@builder.io/dev-tools 1.64.2-beta.202606091524.9594880 → 1.64.2-beta.202606091533.72ef003
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/cli/index.cjs +90 -90
- package/cli/index.cjs.map +3 -3
- package/core/index.cjs +1 -1
- package/core/index.mjs +1 -1
- package/node/index.cjs +1 -1
- package/node/index.mjs +1 -1
- package/package.json +1 -1
- package/server/index.cjs +3 -3
- package/server/index.mjs +3 -3
- package/types/tsconfig.tsbuildinfo +1 -1
package/cli/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var sRe=Object.create;var Dy=Object.defineProperty;var oRe=Object.getOwnPropertyDescriptor;var aRe=Object.getOwnPropertyNames;var ARe=Object.getPrototypeOf,cRe=Object.prototype.hasOwnProperty;var L=(t,e)=>()=>(t&&(e=t(t=0)),e);var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wy=(t,e)=>{for(var r in e)Dy(t,r,{get:e[r],enumerable:!0})},tY=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aRe(e))!cRe.call(t,i)&&i!==r&&Dy(t,i,{get:()=>e[i],enumerable:!(n=oRe(e,i))||n.enumerable});return t};var z=(t,e,r)=>(r=t!=null?sRe(ARe(t)):{},tY(e||!t||!t.__esModule?Dy(r,"default",{value:t,enumerable:!0}):r,t)),Wr=t=>tY(Dy({},"__esModule",{value:!0}),t);var h=L(()=>{(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"
|
|
1
|
+
var sRe=Object.create;var Dy=Object.defineProperty;var oRe=Object.getOwnPropertyDescriptor;var aRe=Object.getOwnPropertyNames;var ARe=Object.getPrototypeOf,cRe=Object.prototype.hasOwnProperty;var L=(t,e)=>()=>(t&&(e=t(t=0)),e);var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wy=(t,e)=>{for(var r in e)Dy(t,r,{get:e[r],enumerable:!0})},tY=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aRe(e))!cRe.call(t,i)&&i!==r&&Dy(t,i,{get:()=>e[i],enumerable:!(n=oRe(e,i))||n.enumerable});return t};var z=(t,e,r)=>(r=t!=null?sRe(ARe(t)):{},tY(e||!t||!t.__esModule?Dy(r,"default",{value:t,enumerable:!0}):r,t)),Wr=t=>tY(Dy({},"__esModule",{value:!0}),t);var h=L(()=>{(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"72ef0039d167be4501aa688110d487f97f8f31ee"}}catch{}})()});function uu(t){let e=t[t.length-1];return e&&typeof e=="object"&&!(e instanceof Error)&&!Array.isArray(e)&&"loggerOptions"in e?{callArgs:t.slice(0,-1),options:e.loggerOptions}:{callArgs:t,options:{}}}function uRe(t,e){return`[${t.toUpperCase()}]`+e.map(r=>{if(r instanceof Error)return r.stack??r.message;if(typeof r=="object"&&r!==null)try{return JSON.stringify(r)}catch{return String(r)}return String(r)}).join(" ")}function nY(){let t=process.env.FUSION_ENVIRONMENT;return t==="cloud"||t==="cloud-v2"}function by(t,e,r,n){let i={severity:e,message:uRe(r,n),timestamp:new Date().toISOString()};r&&(i.context=r),t.write(JSON.stringify(i)+`
|
|
2
2
|
`)}function lRe(t,e,r){return{debug(...n){if(!e())return;let{callArgs:i,options:s}=uu(n);by(s.stderr?process.stderr:process.stdout,"DEBUG",r,i)},info(...n){if(t>lu.info)return;let{callArgs:i,options:s}=uu(n);s.debug&&!e()||by(s.stderr?process.stderr:process.stdout,"INFO",r,i)},warn(...n){if(t>lu.warn)return;let{callArgs:i,options:s}=uu(n);s.debug&&!e()||by(process.stderr,"WARNING",r,i)},error(...n){if(t>lu.error)return;let{callArgs:i,options:s}=uu(n);s.debug&&!e()||by(process.stderr,"ERROR",r,i)}}}function Xp(t){return t?`[${t}]`:""}function gRe(t,e,r){return{debug(...n){if(!e())return;let{callArgs:i,options:s}=uu(n);s.stderr?console.error(Xp(r),...i):console.debug(Xp(r),...i)},info(...n){if(lu.info<t)return;let{callArgs:i,options:s}=uu(n);s.debug&&!e()||(s.stderr?console.error(Xp(r),...i):console.log(Xp(r),...i))},warn(...n){if(lu.warn<t)return;let{callArgs:i,options:s}=uu(n);s.debug&&!e()||console.warn(Xp(r),...i)},error(...n){if(lu.error<t)return;let{callArgs:i,options:s}=uu(n);s.debug&&!e()||console.error(Xp(r),...i)}}}function sY(t){iY=t}function ve(t,e){let r=typeof e?.debug=="function"?e.debug:e?.debug!==void 0?()=>e.debug:()=>iY||!!process.env.DEBUG,n=e?.level??process.env.LOG_LEVEL?.toLowerCase();return nY()?lRe(rY(n??"info"),r,t):gRe(rY(n??"info"),r,t)}function rY(t){return lu[t]??lu.info}function oY(){if(!nY())return;let t=process.stderr.write.bind(process.stderr);process.stderr.write=function(e,r,n){let i=typeof r=="function"?r:n,s=typeof r=="string"?r:void 0,o=typeof e=="string"?e:Buffer.from(e).toString("utf8"),a=o.trim();if(a.startsWith("{"))try{if(typeof JSON.parse(a).severity=="string")return s?t(e,s,i):t(e,i)}catch{}let A={severity:"ERROR",message:a||o,timestamp:new Date().toISOString(),stream:"stderr"},c=JSON.stringify(A)+`
|
|
3
3
|
`;return i?t(c,i):t(c)}}function aY(t="process",e=r=>process.exit(r)){let r=ve(t),n=i=>Promise.resolve(e(i)).catch(()=>{}).finally(()=>process.exit(i));process.on("uncaughtException",i=>{r.error("Uncaught exception:",i),n(1)}),process.on("unhandledRejection",i=>{r.error("Unhandled rejection:",i instanceof Error?i:String(i)),n(1)})}var lu,iY,Bt=L(()=>{"use strict";h();lu={debug:0,info:1,warn:2,error:3};iY=!1});var cY=N((Wbt,AY)=>{h();function vk(t){return t==null?[]:Array.isArray(t)?t:[t]}function pRe(t,e,r,n){var i,s=t[e],o=~n.string.indexOf(e)?r==null||r===!0?"":String(r):typeof r=="boolean"?r:~n.boolean.indexOf(e)?r==="false"?!1:r==="true"||(t._.push((i=+r,i*0===0?i:r)),!!r):(i=+r,i*0===0?i:r);t[e]=s==null?o:Array.isArray(s)?s.concat(o):[s,o]}AY.exports=function(t,e){t=t||[],e=e||{};var r,n,i,s,o,a={_:[]},A=0,c=0,u=0,l=t.length;let d=e.alias!==void 0,g=e.unknown!==void 0,p=e.default!==void 0;if(e.alias=e.alias||{},e.string=vk(e.string),e.boolean=vk(e.boolean),d)for(r in e.alias)for(n=e.alias[r]=vk(e.alias[r]),A=0;A<n.length;A++)(e.alias[n[A]]=n.concat(r)).splice(A,1);for(A=e.boolean.length;A-- >0;)for(n=e.alias[e.boolean[A]]||[],c=n.length;c-- >0;)e.boolean.push(n[c]);for(A=e.string.length;A-- >0;)for(n=e.alias[e.string[A]]||[],c=n.length;c-- >0;)e.string.push(n[c]);if(p){for(r in e.default)if(s=typeof e.default[r],n=e.alias[r]=e.alias[r]||[],e[s]!==void 0)for(e[s].push(r),A=0;A<n.length;A++)e[s].push(n[A])}let f=g?Object.keys(e.alias):[];for(A=0;A<l;A++){if(i=t[A],i==="--"){a._=a._.concat(t.slice(++A));break}for(c=0;c<i.length&&i.charCodeAt(c)===45;c++);if(c===0)a._.push(i);else if(i.substring(c,c+3)==="no-"){if(s=i.substring(c+3),g&&!~f.indexOf(s))return e.unknown(i);a[s]=!1}else{for(u=c+1;u<i.length&&i.charCodeAt(u)!==61;u++);for(s=i.substring(c,u),o=i.substring(++u)||A+1===l||(""+t[A+1]).charCodeAt(0)===45||t[++A],n=c===2?[s]:s,u=0;u<n.length;u++){if(s=n[u],g&&!~f.indexOf(s))return e.unknown("-".repeat(c)+s);pRe(a,s,u+1<n.length||o,e)}}}if(p)for(r in e.default)a[r]===void 0&&(a[r]=e.default[r]);if(d)for(r in a)for(n=e.alias[r]||[];n.length>0;)a[n.shift()]=a[r];return a}});function dRe(){if(Nm!==void 0)return Nm;try{return Nm=require("prettier"),Nm}catch{return Nm=null,null}}function fRe(t){let e=[],r=zl.default.dirname(t);for(;r!==zl.default.dirname(r);){let n=zl.default.join(r,".prettierignore");Sk.default.existsSync(n)&&e.push(n);let i=zl.default.join(r,".git");if(Sk.default.existsSync(i))break;r=zl.default.dirname(r)}return e}function hRe(t){if(t)try{let r=(0,uY.createRequire)(t)("prettier");if(r)return r}catch{}return dRe()}async function ZA(t,e,r,n){try{let i=zl.default.resolve(t,n??"file.tsx"),s=hRe(i);if(!s)return e;if(n){let A=fRe(i);if((await s.getFileInfo(i,{ignorePath:A.length>0?A:void 0})).ignored)return e}let o=await s.resolveConfig(i);return await s.format(e,{...o,filepath:n,parser:r})}catch{return e}}var uY,zl,Sk,Nm,xk=L(()=>{"use strict";h();uY=require("node:module"),zl=z(require("node:path"),1),Sk=z(require("node:fs"),1)});var Fk,Zp,vy,Sy,lY,Xl,kk,Rk,Zl,gY,ed=L(()=>{"use strict";h();Fk="preview-url",Zp="framework",vy="platform",Sy="node",lY="/~builder-connect",Xl="/~builder-connected",kk="/~builder-dev-tools",Rk="/~builder-dev-tools.js",Zl="/~builder-dev-tools-close",gY="/mappings"});var xy=N((rvt,pY)=>{"use strict";h();var Tk={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},mRe={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},CRe={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?Tk.up():"");return t&&(e+=Tk.left),e}};pY.exports={cursor:Tk,scroll:mRe,erase:CRe,beep:"\x07"}});var Ir=N((ivt,Nk)=>{h();var ky=process||{},dY=ky.argv||[],Fy=ky.env||{},IRe=!(Fy.NO_COLOR||dY.includes("--no-color"))&&(!!Fy.FORCE_COLOR||dY.includes("--color")||ky.platform==="win32"||(ky.stdout||{}).isTTY&&Fy.TERM!=="dumb"||!!Fy.CI),ERe=(t,e,r=t)=>n=>{let i=""+n,s=i.indexOf(e,t.length);return~s?t+BRe(i,e,r,s)+e:t+i+e},BRe=(t,e,r,n)=>{let i="",s=0;do i+=t.substring(s,n)+r,s=n+e.length,n=t.indexOf(e,s);while(~n);return i+t.substring(s)},fY=(t=IRe)=>{let e=t?ERe:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Nk.exports=fY();Nk.exports.createColors=fY});function yRe({onlyFirst:t=!1}={}){let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(e,t?void 0:"g")}function bY(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(QRe,"")}function vY(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Mm(t,e={}){if(typeof t!="string"||t.length===0||(e={ambiguousIsNarrow:!0,...e},t=bY(t),t.length===0))return 0;t=t.replace(vRe()," ");let r=e.ambiguousIsNarrow?1:2,n=0;for(let i of t){let s=i.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(wRe.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function FRe(){let t=new Map;for(let[e,r]of Object.entries(Mr)){for(let[n,i]of Object.entries(r))Mr[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Mr[n],t.set(i[0],i[1]);Object.defineProperty(Mr,e,{value:r,enumerable:!1})}return Object.defineProperty(Mr,"codes",{value:t,enumerable:!1}),Mr.color.close="\x1B[39m",Mr.bgColor.close="\x1B[49m",Mr.color.ansi=hY(),Mr.color.ansi256=mY(),Mr.color.ansi16m=CY(),Mr.bgColor.ansi=hY(Mk),Mr.bgColor.ansi256=mY(Mk),Mr.bgColor.ansi16m=CY(Mk),Object.defineProperties(Mr,{rgbToAnsi256:{value:(e,r,n)=>e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(s=>s+s).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:e=>Mr.rgbToAnsi256(...Mr.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,n,i;if(e>=232)r=((e-232)*10+8)/255,n=r,i=r;else{e-=16;let a=e%36;r=Math.floor(e/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let s=Math.max(r,n,i)*2;if(s===0)return 30;let o=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return s===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,r,n)=>Mr.ansi256ToAnsi(Mr.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>Mr.ansi256ToAnsi(Mr.hexToAnsi256(e)),enumerable:!1}}),Mr}function BY(t,e,r){return String(t).normalize().replace(/\r\n/g,`
|
|
4
4
|
`).split(`
|
|
@@ -75,7 +75,7 @@ ${MY}${n.trimStart()}`),r=3+(0,eg.stripVTControlCharacters)(n.trimStart()).lengt
|
|
|
75
75
|
`),p(),i()};return{start:I,stop:y,message:(B="")=>{a=m(B??a)}}}});function $t(t,e=""){return t.ts.createSourceFile("module.tsx",typeof e=="string"?e:"",t.ts.ScriptTarget.Latest,void 0)}function Gy(t,e=""){let r=$t(t,e?.trim());if(r.statements.length===0)throw new Error(`No statements found in code: ${e}`);return r.statements[0]}function On(t,e,r){if(e){let n=t.ts.createPrinter({newLine:t.ts.NewLineKind.LineFeed,removeComments:r});return t.ts.isSourceFile(e)?n.printFile(e).trim()+`
|
|
76
76
|
`:n.printNode(t.ts.EmitHint.Unspecified,e,t.ts.createSourceFile("module.tsx","",t.ts.ScriptTarget.Latest)).trim()+`
|
|
77
77
|
`}return""}var Jr=L(()=>{"use strict";h()});var HY=N((Evt,KY)=>{"use strict";h();KY.exports=function(){if(process.env.npm_config_user_agent)return tTe(process.env.npm_config_user_agent)};function tTe(t){let e=t.split(" ")[0],r=e.lastIndexOf("/"),n=e.substring(0,r);return{name:n==="npminstall"?"cnpm":n,version:e.substring(r+1)}}});function eo(t){return t.endsWith(".mapper.tsx")||t.endsWith(".mapper.jsx")||t.endsWith(".mapper.ts")||t.endsWith(".mapper.js")||t.endsWith(".mapper.mjs")}function Vt(t,e,r){e=Wo(e),r=Wo(r),e=t.dirname(e);let n=t.basename(r,t.extname(r));r=t.dirname(r);let i;return n==="index"?i=t.relative(e,r):i=t.relative(e,t.join(r,n)),i=Wo(t.normalize(i)),i.startsWith(".")||(i="./"+i),i}function Wo(t){return t.startsWith("\\\\?\\")?t:t.replace(/\\/g,"/")}function rg(t,e){let r=t.extname(e),n=t.basename(e,r).split(/[\/\\]/),i=n[n.length-1];return JY(i==="index"?t.basename(t.dirname(e)):i)}function JY(t){return Er(t).replace(/ /g,"")}function to(t,e){let r=t.extname(e),n=Wo(t.basename(e,r)).split("/").pop();return Er(n==="index"?t.basename(t.dirname(e)):n)}function Br(t,e){let r=Wo(t.relative(t.getAppRootDir(),e));r=r.split("/").filter(i=>i!=="."&&i!==".."&&i!=="").join("/"),r.endsWith(".tsx")||r.endsWith(".jsx")?r=r.slice(0,-4):(r.endsWith(".ts")||r.endsWith(".js"))&&(r=r.slice(0,-3));let n=t.getFrameworks();return r.startsWith("src/")&&(r=r.slice(4)),n.some(i=>i.name.includes("next"))?"@/"+r:"~/"+r}function or(t,e){let r=e,n=[];for(let i=0;i<2;i++){let s=t.basename(r);if(!s||s==="components")break;n.unshift(s),r=t.dirname(r)}return n.join("/")}function Er(t){for(t=t.replace(/([A-Z])/g," $1").replace(/\./g," ").replace(/_/g," ").replace(/-/g," ").replace(/\s/g," ").trim();t.includes(" ");)t=t.replace(/ /g," ");return t.split(" ").map(e=>e.length>2?e[0].toUpperCase()+e.slice(1):e).join("").trim()}function ss(t){return t.sort((e,r)=>e.name.toLocaleLowerCase().localeCompare(r.name.toLocaleLowerCase()))}async function fr(t,e,r,n){if(typeof r!="string"||r==="")throw new Error(`getComponentId(), exportName must be a non-empty string, received: ${r}, ${e}`);return n&&(e=n),e=t.normalize(e),(await t.hash(e+"#"+r)).substring(0,8)}async function YY(t){return(await t.hash(t.getAppRootDir())).substring(0,8)}function Lm(t){return typeof t=="number"}function id(t){return typeof t=="boolean"}function Oi(t){return typeof t=="string"}function sd(t){return typeof t=="string"?/^[A-Z][A-Za-z0-9]*$/.test(t):!1}function Rs(t){return JSON.parse(JSON.stringify(t))}function Oy(t,e,r){for(let n of e)if(t.dirname(r).includes(n))return!0;return!1}function qY(){try{let t=(0,jY.default)();if(t?.name)return t.name}catch{}return"npm"}function rTe(){return process.platform.startsWith("win")}function it(){return process.pkg?"@builder.io/agent":rTe()?'"@builder.io/dev-tools"':"builder.io"}function qk(t){return t.replace(/[^a-zA-Z0-9-_]/g,"_")}var jY,xt=L(()=>{"use strict";h();jY=z(HY(),1)});function Ki(t){let e=t.join(t.getAppRootDir(),"tsconfig.json");return t.exists(e)}async function os(t,e){async function r(i,s){if(s>10)return;let o=await t.readdir(i);for(let a of o){if(nTe.includes(a))continue;let A=t.join(i,a),c=await t.stat(A);if(c){if(c.isFile()&&a.startsWith("builder-registry."))return A;if(c.isDirectory()){let u=await r(A,s+1);if(u)return u}}}}let n=await r(t.getAppRootDir(),0);if(!n){let s=`builder-registry.${await Ki(t)?"ts":"js"}`;return t.join(e,s)}return n}async function zo(t,e){let r=t.resolve("/");for(let n=0;n<20;n++){let i=t.join(e,"package.json"),s=await t.readFile(i);if(s)return JSON.parse(s);if(e===r)break;e=t.dirname(e)}return null}async function $Y(t,e){for(let r=0;r<20;r++){let n=t.dirname(e),i=t.join(n,"node_modules");if(await t.exists(i))return i;if(e===t.getAppRootDir())break;e=t.dirname(e)}return t.join(t.getAppRootDir(),"node_modules")}async function _m(t,e,r){let n=await t.readdir(e);return n.includes(r)?t.join(e,r):(await Promise.all(n.map(async s=>{if(s.startsWith(".")||s==="node_modules")return;let o=t.join(e,s);if((await t.stat(o)).isDirectory()){let A=await _m(t,o,r);if(A)return A}}))).find(s=>typeof s=="string")}var nTe,bi=L(()=>{"use strict";h();nTe=["node_modules","dist","build","public"]});async function vn(t,e,r){if(!Array.isArray(e)||e.length===0)throw new Error(`createTsProgram() Invalid filePaths: ${e}`);let n=await $Y(t,e[0]),i=t.join(n,"typescript","lib"),s=new Map,o={fileExists:a=>{if(a=t.normalize(a),a.includes("node_modules")){let A=Um.get(a);if(!A){try{t.statSync(a).isFile()?A={exists:!0,content:t.readFileSync(a)}:A={exists:!1}}catch{A={exists:!1}}Um.set(a,A)}return A.exists}if(!s.has(a))if(t.existsSync(a)){let c=t.statSync(a);s.set(a,c.isFile())}else s.set(a,!1);return s.get(a)},getCanonicalFileName:a=>t.normalize(a),getCurrentDirectory:()=>t.cwd(),getDefaultLibFileName:()=>t.join(i,"lib.d.ts"),getDefaultLibLocation:()=>i,getNewLine:()=>`
|
|
78
|
-
`,getSourceFile:a=>{if(a=t.normalize(a),a.includes("node_modules")){let c=Um.get(a);if(c)return $t(t,c.content)}let A;try{A=t.readFileSync(a)}catch{console.error(`Could not read: ${a}`),A==null}if(A==null){let c=t.basename(a),u=t.extname(c).toLowerCase();if(a.startsWith(i)&&u===".ts"&&(A=WY.get(c),A==null&&typeof self<"u"&&typeof fetch=="function"))throw new Hy(c)}return a.includes("node_modules")&&(A?Um.set(a,{exists:!0,content:A}):Um.set(a,{exists:!1})),$t(t,A)},readFile:a=>{let A=t.readFileSync(a);return typeof A=="string"?A:void 0},useCaseSensitiveFileNames:()=>!1,writeFile:()=>{}};for(;;)try{return iTe(t,o,e,r)}catch(a){if(a instanceof Hy){await sTe(t,a.libName);continue}throw t.Sentry?.captureException(a),new Error(`createTsProgram() Could not create program for: ${e[0]}`,{cause:a})}}function iTe(t,e,r,n){let i={rootNames:[...r],host:e,options:{}},s=t.ts.findConfigFile(t.dirname(r[0]),o=>t.existsSync(o));if(s){let o=VY.get(s);if(!o){let a=t.ts.readConfigFile(s,A=>{let c=t.readFileSync(A);return typeof c=="string"?c:void 0});a.error?t.Sentry?.captureException(new Error("Error reading tsconfig for createTsProgram"),{extra:{error:a.error,tsConfigPath:s}}):(o=t.ts.parseJsonConfigFileContent(a.config,t.ts.sys||{useCaseSensitiveFileNames:!1,readDirectory:(c,u)=>t.readdirSync(c),fileExists:c=>t.existsSync(c),readFile:c=>t.readFileSync(c)||void 0},t.dirname(s),void 0,s).options,VY.set(s,o))}o&&(i.options=Rs(o))}return i.options.noEmit=!0,i.options.isolatedModules=!1,i.options.strict=!1,i.options.jsx=t.ts.JsxEmit.Preserve,i.options.allowJs=!0,Object.assign(i.options,n),t.ts.createProgram(i)}async function od(t,e,r){r||(r=await vn(t,[e]));let n=r.getSourceFile(e);if(!n)throw new Error(`getTypeChecker() Could not find source file: ${e}`);return{typeChecker:r.getTypeChecker(),sourceFile:n}}async function sTe(t,e){let r=`https://cdn.jsdelivr.net/npm/typescript@${t.ts.version}/lib/${e}`;Ky.has(e)||Ky.set(e,fetch(r).then(n=>n.text()).then(n=>{WY.set(e,n)})),await Ky.get(e),Ky.delete(e)}async function zY(t,e){let r=await t.readFile(e.filePath);return r==null?{diagnostics:[{messageText:`Error reading: ${e.filePath}`}],code:null,output:null}:$k(t,{code:r,filePath:e.filePath,compilerOptions:e.compilerOptions})}function $k(t,e){let r={diagnostics:[],code:e.code,output:null};try{let n=t.ts.transpileModule(e.code,{compilerOptions:e.compilerOptions,fileName:e.filePath??"module.tsx",reportDiagnostics:!0});n.diagnostics?.forEach(i=>{r.diagnostics.push({messageText:String(i.messageText)})}),r.output=n.outputText}catch(n){console.error("transpileModule",n),r.diagnostics.push({messageText:String(n)})}return r}var Hy,WY,Ky,Um,VY,ro=L(()=>{"use strict";h();Jr();xt();bi();Hy=class{libName;constructor(e){this.libName=e}};WY=new Map,Ky=new Map,Um=new Map,VY=new Map});var oTe,ht,zr=L(()=>{"use strict";h();oTe="1.64.2-beta.
|
|
78
|
+
`,getSourceFile:a=>{if(a=t.normalize(a),a.includes("node_modules")){let c=Um.get(a);if(c)return $t(t,c.content)}let A;try{A=t.readFileSync(a)}catch{console.error(`Could not read: ${a}`),A==null}if(A==null){let c=t.basename(a),u=t.extname(c).toLowerCase();if(a.startsWith(i)&&u===".ts"&&(A=WY.get(c),A==null&&typeof self<"u"&&typeof fetch=="function"))throw new Hy(c)}return a.includes("node_modules")&&(A?Um.set(a,{exists:!0,content:A}):Um.set(a,{exists:!1})),$t(t,A)},readFile:a=>{let A=t.readFileSync(a);return typeof A=="string"?A:void 0},useCaseSensitiveFileNames:()=>!1,writeFile:()=>{}};for(;;)try{return iTe(t,o,e,r)}catch(a){if(a instanceof Hy){await sTe(t,a.libName);continue}throw t.Sentry?.captureException(a),new Error(`createTsProgram() Could not create program for: ${e[0]}`,{cause:a})}}function iTe(t,e,r,n){let i={rootNames:[...r],host:e,options:{}},s=t.ts.findConfigFile(t.dirname(r[0]),o=>t.existsSync(o));if(s){let o=VY.get(s);if(!o){let a=t.ts.readConfigFile(s,A=>{let c=t.readFileSync(A);return typeof c=="string"?c:void 0});a.error?t.Sentry?.captureException(new Error("Error reading tsconfig for createTsProgram"),{extra:{error:a.error,tsConfigPath:s}}):(o=t.ts.parseJsonConfigFileContent(a.config,t.ts.sys||{useCaseSensitiveFileNames:!1,readDirectory:(c,u)=>t.readdirSync(c),fileExists:c=>t.existsSync(c),readFile:c=>t.readFileSync(c)||void 0},t.dirname(s),void 0,s).options,VY.set(s,o))}o&&(i.options=Rs(o))}return i.options.noEmit=!0,i.options.isolatedModules=!1,i.options.strict=!1,i.options.jsx=t.ts.JsxEmit.Preserve,i.options.allowJs=!0,Object.assign(i.options,n),t.ts.createProgram(i)}async function od(t,e,r){r||(r=await vn(t,[e]));let n=r.getSourceFile(e);if(!n)throw new Error(`getTypeChecker() Could not find source file: ${e}`);return{typeChecker:r.getTypeChecker(),sourceFile:n}}async function sTe(t,e){let r=`https://cdn.jsdelivr.net/npm/typescript@${t.ts.version}/lib/${e}`;Ky.has(e)||Ky.set(e,fetch(r).then(n=>n.text()).then(n=>{WY.set(e,n)})),await Ky.get(e),Ky.delete(e)}async function zY(t,e){let r=await t.readFile(e.filePath);return r==null?{diagnostics:[{messageText:`Error reading: ${e.filePath}`}],code:null,output:null}:$k(t,{code:r,filePath:e.filePath,compilerOptions:e.compilerOptions})}function $k(t,e){let r={diagnostics:[],code:e.code,output:null};try{let n=t.ts.transpileModule(e.code,{compilerOptions:e.compilerOptions,fileName:e.filePath??"module.tsx",reportDiagnostics:!0});n.diagnostics?.forEach(i=>{r.diagnostics.push({messageText:String(i.messageText)})}),r.output=n.outputText}catch(n){console.error("transpileModule",n),r.diagnostics.push({messageText:String(n)})}return r}var Hy,WY,Ky,Um,VY,ro=L(()=>{"use strict";h();Jr();xt();bi();Hy=class{libName;constructor(e){this.libName=e}};WY=new Map,Ky=new Map,Um=new Map,VY=new Map});var oTe,ht,zr=L(()=>{"use strict";h();oTe="1.64.2-beta.202606091533.72ef003",ht=process.env.OVERRIDE_VERSION??oTe});async function ng(t){let e=[],r=await zo(t,t.getRepoRootDir());if(r){let n=await ZY(r,t);e.push(...n)}return e}async function ZY(t,e){let r=[];if(t&&typeof t=="object"){let n=new Set(Object.keys({...t.dependencies,...t.devDependencies}));for(let i of aTe)if(n.has(i)&&!r.some(s=>s.name===i)){let s={name:i};XY.has(i)&&(s.version=await XY.get(i)(e)),r.push(s)}}return r}function Vk(t){let e=parseInt(t);return Number.isNaN(e)?void 0:e}var XY,aTe,ig=L(()=>{"use strict";h();bi();xt();XY=new Map([["next",async t=>{if(!t.spawnSync)return;let e=qY(),r=e==="npm"?"npx":e,{stdout:n}=t.spawnSync(r,["next","-v"],{encoding:"utf8"});if(!n)return;let i=n.match(/(Next.js v)([\d.]+)/g);if(!i)return;let s=i[0].split("Next.js v")[1],[o,a,A]=s.split(".");return{major:Vk(o),minor:Vk(a),patch:Vk(A)}}]]),aTe=["@shopify/remix-oxygen","@shopify/hydrogen","@builder.io/qwik-city","@remix-run/react","@sveltejs/kit","astro","gatsby","next","nuxt","@builder.io/qwik","@angular/core","react","solid-js","svelte","vue"]});async function no(t){let e=e9(t),r=await t.readFile(e);return typeof r=="string"?JSON.parse(r):{}}async function io(t,e){e=typeof e=="object"&&e!=null?e:{};let r=e9(t);await t.writeFile(r,JSON.stringify(e??{},null,2))}function e9(t){let e=t.getAppRootDir();return t.join(e,"node_modules",".builder","builder-cache.json")}var sg=L(()=>{"use strict";h()});async function Ka(t,e,r){let n={envKey:r,envValue:null,file:""};for(let i of e){let s=t.join(t.getAppRootDir(),i),o=await ATe(t,s);if(o){let a=o[r];if(typeof a=="string"&&a.length>0&&a!=="YOUR_API_KEY")return n.envValue=a,n.file=s,n}}return n.file=t.join(t.getAppRootDir(),e[e.length-1]),n}async function ATe(t,e){let r=await t.readFile(e);return typeof r=="string"?t9(r):null}function t9(t){let e={},r=t.replace(/\r\n?/gm,`
|
|
79
79
|
`),n;for(;(n=cTe.exec(r))!=null;){let i=n[1],s=n[2]||"";s=s.trim();let o=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),o==='"'&&(s=s.replace(/\\n/g,`
|
|
80
80
|
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}async function Ha(t,e,r,n){let i="# https://www.builder.io/c/docs/using-your-api-key",s=await t.readFile(e);try{if(s)if(s.includes(r))if(s.includes(n))t.debug(`"${r}" with "${n}" already set in ${e}`);else return t.debug(`Replace "${r}" in ${e}`),s=s.replace(new RegExp(`${r}=.*`),`${r}=${n}`),await t.writeFile(e,s),"update";else return t.debug(`Append "${r}" to ${e}`),s+=`
|
|
81
81
|
|
|
@@ -1257,7 +1257,7 @@ The file content is empty.
|
|
|
1257
1257
|
`).trimEnd();let r=[],n=[];for(let i of t)i===""?n.length>0&&(r.push(n.join(" ")),n=[]):n.push(i);return n.length>0&&r.push(n.join(" ")),r.join(`
|
|
1258
1258
|
`).trim()}function j3e(t){let e={},r=null,n=[],i=null,s=null,o=[];for(let a of t.split(`
|
|
1259
1259
|
`)){let A=a.trim();if(i!==null){if(a.startsWith(" ")||a.startsWith(" ")||A===""){o.push(A);continue}e[i]=DZ(o,s),i=null,s=null,o=[]}if(!A||A.startsWith("#"))continue;if(A.startsWith("-")){let u=A.substring(1).trim();r&&n.push(QZ(u));continue}let c=a.indexOf(":");if(c!==-1){r&&n.length>0&&(e[r]=n,n=[]);let u=a.substring(0,c).trim(),l=a.substring(c+1).trim();if(/^[>|][+-]?$/.test(l)){i=u,s=l[0],o=[],r=null;continue}let d=l?QZ(l):"";r=u,d&&(e[u]=d,r=null)}}return i!==null&&(e[i]=DZ(o,s)),r&&n.length>0&&(e[r]=n),e}function Y3e(t){if(!wZ(t))return null;let e=t.split(/^---$/m);if(e.length<3)return null;let r=e[1].trim(),n=e.slice(2).join("---").trim();return{frontmatterContent:r,body:n}}function af(t){let e=Y3e(t);return e?{frontmatter:j3e(e.frontmatterContent),body:e.body}:{frontmatter:{},body:t.trim()}}var gw=L(()=>{"use strict";h()});function bZ(t){let e=t.replace(/"/g,"");return e=e.trim(),e}function vZ(t,e,r){try{if(!t||!t.trim())return null;let n;e.startsWith("https://")||e.startsWith("http://")?n=eI.default.basename(new URL(e).pathname):n=eI.default.basename(e);let i,s=n.toUpperCase();if(s==="SKILL.MD"||s==="RULE.MD"){let C=eI.default.dirname(e);i=eI.default.basename(C)}else i=n.split(".")[0];let o=i,a=af(t);if(!a.frontmatter||Object.keys(a.frontmatter).length===0)return{id:r?`hash-${r(t)}`:`hash-${Date.now()}`,name:bZ(o),content:t.trim(),filePath:e};let A=a.body;if(!A)return null;let c=bZ(a.frontmatter.name||o),u="agent-mode";if(a.frontmatter.type)u=a.frontmatter.type;else if(a.frontmatter.alwaysApply!==void 0){let C=a.frontmatter.alwaysApply;u=C===!0||C==="true"?"always":"agent-mode"}let l=a.frontmatter.glob||a.frontmatter.globs||a.frontmatter.paths,d=Array.isArray(l)?l.join(","):l,g;if(a.frontmatter["allowed-tools"]){let C=a.frontmatter["allowed-tools"].trim();C&&(g=C.split(",").map(I=>I.trim()).filter(I=>I.length>0))}let p=r?`hash-${r(t)}`:`hash-${Date.now()}`,f=a.frontmatter["disable-model-invocation"]==="true"?!0:void 0,m=a.frontmatter["user-invocable"]==="false"?!1:void 0;return{id:p,name:c,content:A,description:a.frontmatter.description,filePath:e,glob:d,type:u,allowedTools:g,disableModelInvocation:f,userInvocable:m}}catch{return null}}var eI,SZ=L(()=>{"use strict";h();eI=z(require("node:path"),1);gw()});function fP(t){if(!Array.isArray(t))throw new TypeError(`Expected an array, got \`${typeof t}\`.`);for(let i of t)gP(i);let e=t.some(({readableObjectMode:i})=>i),r=q3e(t,e),n=new lP({objectMode:e,writableHighWaterMark:r,readableHighWaterMark:r});for(let i of t)n.add(i);return t.length===0&&NZ(n),n}var dw,kZ,dP,q3e,lP,$3e,V3e,W3e,gP,z3e,RZ,X3e,Z3e,eKe,TZ,NZ,pP,MZ,tKe,pw,xZ,FZ,PZ=L(()=>{h();dw=require("node:events"),kZ=require("node:stream"),dP=require("node:stream/promises");q3e=(t,e)=>{if(t.length===0)return 16384;let r=t.filter(({readableObjectMode:n})=>n===e).map(({readableHighWaterMark:n})=>n);return Math.max(...r)},lP=class extends kZ.PassThrough{#n=new Set([]);#c=new Set([]);#s=new Set([]);#t;add(e){gP(e),!this.#n.has(e)&&(this.#n.add(e),this.#t??=$3e(this,this.#n),z3e({passThroughStream:this,stream:e,streams:this.#n,ended:this.#c,aborted:this.#s,onFinished:this.#t}),e.pipe(this,{end:!1}))}remove(e){return gP(e),this.#n.has(e)?(e.unpipe(this),!0):!1}},$3e=async(t,e)=>{pw(t,xZ);let r=new AbortController;try{await Promise.race([V3e(t,r),W3e(t,e,r)])}finally{r.abort(),pw(t,-xZ)}},V3e=async(t,{signal:e})=>{await(0,dP.finished)(t,{signal:e,cleanup:!0})},W3e=async(t,e,{signal:r})=>{for await(let[n]of(0,dw.on)(t,"unpipe",{signal:r}))e.has(n)&&n.emit(TZ)},gP=t=>{if(typeof t?.pipe!="function")throw new TypeError(`Expected a readable stream, got: \`${typeof t}\`.`)},z3e=async({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,onFinished:s})=>{pw(t,FZ);let o=new AbortController;try{await Promise.race([X3e(s,e),Z3e({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:o}),eKe({stream:e,streams:r,ended:n,aborted:i,controller:o})])}finally{o.abort(),pw(t,-FZ)}r.size===n.size+i.size&&(n.size===0&&i.size>0?pP(t):NZ(t))},RZ=t=>t?.code==="ERR_STREAM_PREMATURE_CLOSE",X3e=async(t,e)=>{try{await t,pP(e)}catch(r){RZ(r)?pP(e):MZ(e,r)}},Z3e=async({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:{signal:s}})=>{try{await(0,dP.finished)(e,{signal:s,cleanup:!0,readable:!0,writable:!1}),r.has(e)&&n.add(e)}catch(o){if(s.aborted||!r.has(e))return;RZ(o)?i.add(e):MZ(t,o)}},eKe=async({stream:t,streams:e,ended:r,aborted:n,controller:{signal:i}})=>{await(0,dw.once)(t,TZ,{signal:i}),e.delete(t),r.delete(t),n.delete(t)},TZ=Symbol("unpipe"),NZ=t=>{t.writable&&t.end()},pP=t=>{(t.readable||t.writable)&&t.destroy()},MZ=(t,e)=>{t.destroyed||(t.once("error",tKe),t.destroy(e))},tKe=()=>{},pw=(t,e)=>{let r=t.getMaxListeners();r!==0&&r!==Number.POSITIVE_INFINITY&&t.setMaxListeners(r+e)},xZ=2,FZ=1});var LZ=N(Af=>{"use strict";h();Object.defineProperty(Af,"__esModule",{value:!0});Af.splitWhen=Af.flatten=void 0;function rKe(t){return t.reduce((e,r)=>[].concat(e,r),[])}Af.flatten=rKe;function nKe(t,e){let r=[[]],n=0;for(let i of t)e(i)?(n++,r[n]=[]):r[n].push(i);return r}Af.splitWhen=nKe});var _Z=N(fw=>{"use strict";h();Object.defineProperty(fw,"__esModule",{value:!0});fw.isEnoentCodeError=void 0;function iKe(t){return t.code==="ENOENT"}fw.isEnoentCodeError=iKe});var UZ=N(hw=>{"use strict";h();Object.defineProperty(hw,"__esModule",{value:!0});hw.createDirentFromStats=void 0;var hP=class{constructor(e,r){this.name=e,this.isBlockDevice=r.isBlockDevice.bind(r),this.isCharacterDevice=r.isCharacterDevice.bind(r),this.isDirectory=r.isDirectory.bind(r),this.isFIFO=r.isFIFO.bind(r),this.isFile=r.isFile.bind(r),this.isSocket=r.isSocket.bind(r),this.isSymbolicLink=r.isSymbolicLink.bind(r)}};function sKe(t,e){return new hP(t,e)}hw.createDirentFromStats=sKe});var HZ=N(yn=>{"use strict";h();Object.defineProperty(yn,"__esModule",{value:!0});yn.convertPosixPathToPattern=yn.convertWindowsPathToPattern=yn.convertPathToPattern=yn.escapePosixPath=yn.escapeWindowsPath=yn.escape=yn.removeLeadingDotSegment=yn.makeAbsolute=yn.unixify=void 0;var oKe=require("os"),aKe=require("path"),GZ=oKe.platform()==="win32",AKe=2,cKe=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,uKe=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,lKe=/^\\\\([.?])/,gKe=/\\(?![!()+@[\]{}])/g;function pKe(t){return t.replace(/\\/g,"/")}yn.unixify=pKe;function dKe(t,e){return aKe.resolve(t,e)}yn.makeAbsolute=dKe;function fKe(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(AKe)}return t}yn.removeLeadingDotSegment=fKe;yn.escape=GZ?mP:CP;function mP(t){return t.replace(uKe,"\\$2")}yn.escapeWindowsPath=mP;function CP(t){return t.replace(cKe,"\\$2")}yn.escapePosixPath=CP;yn.convertPathToPattern=GZ?OZ:KZ;function OZ(t){return mP(t).replace(lKe,"//$1").replace(gKe,"/")}yn.convertWindowsPathToPattern=OZ;function KZ(t){return CP(t)}yn.convertPosixPathToPattern=KZ});var jZ=N((xOt,JZ)=>{h();JZ.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var r;r=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(r[2])return!0;e=e.slice(r.index+r[0].length)}return!1}});var $Z=N((kOt,qZ)=>{h();var hKe=jZ(),YZ={"{":"}","(":")","[":"]"},mKe=function(t){if(t[0]==="!")return!0;for(var e=0,r=-2,n=-2,i=-2,s=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||n!==-1&&t[e]==="["&&t[e+1]!=="]"&&(n<e&&(n=t.indexOf("]",e)),n>e&&(o===-1||o>n||(o=t.indexOf("\\",e),o===-1||o>n)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||s!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(s=t.indexOf(")",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||r!==-1&&t[e]==="("&&t[e+1]!=="|"&&(r<e&&(r=t.indexOf("|",e)),r!==-1&&t[r+1]!==")"&&(s=t.indexOf(")",r),s>r&&(o=t.indexOf("\\",r),o===-1||o>s))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var A=YZ[a];if(A){var c=t.indexOf(A,e);c!==-1&&(e=c+1)}if(t[e]==="!")return!0}else e++}return!1},CKe=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var r=t[e+1];e+=2;var n=YZ[r];if(n){var i=t.indexOf(n,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};qZ.exports=function(e,r){if(typeof e!="string"||e==="")return!1;if(hKe(e))return!0;var n=mKe;return r&&r.strict===!1&&(n=CKe),n(e)}});var WZ=N((TOt,VZ)=>{"use strict";h();var IKe=$Z(),EKe=require("path").posix.dirname,BKe=require("os").platform()==="win32",IP="/",yKe=/\\/g,QKe=/[\{\[].*[\}\]]$/,DKe=/(^|[^\\])([\{\[]|\([^\)]+$)/,wKe=/\\([\!\*\?\|\[\]\(\)\{\}])/g;VZ.exports=function(e,r){var n=Object.assign({flipBackslashes:!0},r);n.flipBackslashes&&BKe&&e.indexOf(IP)<0&&(e=e.replace(yKe,IP)),QKe.test(e)&&(e+=IP),e+="a";do e=EKe(e);while(IKe(e)||DKe.test(e));return e.replace(wKe,"$1")}});var mw=N(go=>{"use strict";h();go.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;go.find=(t,e)=>t.nodes.find(r=>r.type===e);go.exceedsLimit=(t,e,r=1,n)=>n===!1||!go.isInteger(t)||!go.isInteger(e)?!1:(Number(e)-Number(t))/Number(r)>=n;go.escapeNode=(t,e=0,r)=>{let n=t.nodes[e];n&&(r&&n.type===r||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};go.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;go.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;go.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;go.reduce=t=>t.reduce((e,r)=>(r.type==="text"&&e.push(r.value),r.type==="range"&&(r.type="text"),e),[]);go.flatten=(...t)=>{let e=[],r=n=>{for(let i=0;i<n.length;i++){let s=n[i];if(Array.isArray(s)){r(s);continue}s!==void 0&&e.push(s)}return e};return r(t),e}});var Cw=N((LOt,XZ)=>{"use strict";h();var zZ=mw();XZ.exports=(t,e={})=>{let r=(n,i={})=>{let s=e.escapeInvalid&&zZ.isInvalidBrace(i),o=n.invalid===!0&&e.escapeInvalid===!0,a="";if(n.value)return(s||o)&&zZ.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let A of n.nodes)a+=r(A);return a};return r(t)}});var eee=N((UOt,ZZ)=>{"use strict";h();ZZ.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var cee=N((OOt,Aee)=>{"use strict";h();var tee=eee(),Tg=(t,e,r)=>{if(tee(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(tee(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...r};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let i=String(n.relaxZeros),s=String(n.shorthand),o=String(n.capture),a=String(n.wrap),A=t+":"+e+"="+i+s+o+a;if(Tg.cache.hasOwnProperty(A))return Tg.cache[A].result;let c=Math.min(t,e),u=Math.max(t,e);if(Math.abs(c-u)===1){let f=t+"|"+e;return n.capture?`(${f})`:n.wrap===!1?f:`(?:${f})`}let l=aee(t)||aee(e),d={min:t,max:e,a:c,b:u},g=[],p=[];if(l&&(d.isPadded=l,d.maxLen=String(d.max).length),c<0){let f=u<0?Math.abs(u):1;p=ree(f,Math.abs(c),d,n),c=d.a=0}return u>=0&&(g=ree(c,u,d,n)),d.negatives=p,d.positives=g,d.result=bKe(p,g,n),n.capture===!0?d.result=`(${d.result})`:n.wrap!==!1&&g.length+p.length>1&&(d.result=`(?:${d.result})`),Tg.cache[A]=d,d.result};function bKe(t,e,r){let n=EP(t,e,"-",!1,r)||[],i=EP(e,t,"",!1,r)||[],s=EP(t,e,"-?",!0,r)||[];return n.concat(s).concat(i).join("|")}function vKe(t,e){let r=1,n=1,i=iee(t,r),s=new Set([e]);for(;t<=i&&i<=e;)s.add(i),r+=1,i=iee(t,r);for(i=see(e+1,n)-1;t<i&&i<=e;)s.add(i),n+=1,i=see(e+1,n)-1;return s=[...s],s.sort(FKe),s}function SKe(t,e,r){if(t===e)return{pattern:t,count:[],digits:0};let n=xKe(t,e),i=n.length,s="",o=0;for(let a=0;a<i;a++){let[A,c]=n[a];A===c?s+=A:A!=="0"||c!=="9"?s+=kKe(A,c,r):o++}return o&&(s+=r.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function ree(t,e,r,n){let i=vKe(t,e),s=[],o=t,a;for(let A=0;A<i.length;A++){let c=i[A],u=SKe(String(o),String(c),n),l="";if(!r.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+oee(a.count),o=c+1;continue}r.isPadded&&(l=RKe(c,r,n)),u.string=l+u.pattern+oee(u.count),s.push(u),o=c+1,a=u}return s}function EP(t,e,r,n,i){let s=[];for(let o of t){let{string:a}=o;!n&&!nee(e,"string",a)&&s.push(r+a),n&&nee(e,"string",a)&&s.push(r+a)}return s}function xKe(t,e){let r=[];for(let n=0;n<t.length;n++)r.push([t[n],e[n]]);return r}function FKe(t,e){return t>e?1:e>t?-1:0}function nee(t,e,r){return t.some(n=>n[e]===r)}function iee(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function see(t,e){return t-t%Math.pow(10,e)}function oee(t){let[e=0,r=""]=t;return r||e>1?`{${e+(r?","+r:"")}}`:""}function kKe(t,e,r){return`[${t}${e-t===1?"":"-"}${e}]`}function aee(t){return/^-?(0+)\d/.test(t)}function RKe(t,e,r){if(!e.isPadded)return t;let n=Math.abs(e.maxLen-String(t).length),i=r.relaxZeros!==!1;switch(n){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${n}}`:`0{${n}}`}}Tg.cache={};Tg.clearCache=()=>Tg.cache={};Aee.exports=Tg});var QP=N((HOt,hee)=>{"use strict";h();var TKe=require("util"),lee=cee(),uee=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),NKe=t=>e=>t===!0?Number(e):String(e),BP=t=>typeof t=="number"||typeof t=="string"&&t!=="",tI=t=>Number.isInteger(+t),yP=t=>{let e=`${t}`,r=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++r]==="0";);return r>0},MKe=(t,e,r)=>typeof t=="string"||typeof e=="string"?!0:r.stringify===!0,PKe=(t,e,r)=>{if(e>0){let n=t[0]==="-"?"-":"";n&&(t=t.slice(1)),t=n+t.padStart(n?e-1:e,"0")}return r===!1?String(t):t},Ew=(t,e)=>{let r=t[0]==="-"?"-":"";for(r&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return r?"-"+t:t},LKe=(t,e,r)=>{t.negatives.sort((a,A)=>a<A?-1:a>A?1:0),t.positives.sort((a,A)=>a<A?-1:a>A?1:0);let n=e.capture?"":"?:",i="",s="",o;return t.positives.length&&(i=t.positives.map(a=>Ew(String(a),r)).join("|")),t.negatives.length&&(s=`-(${n}${t.negatives.map(a=>Ew(String(a),r)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${n}${o})`:o},gee=(t,e,r,n)=>{if(r)return lee(t,e,{wrap:!1,...n});let i=String.fromCharCode(t);if(t===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},pee=(t,e,r)=>{if(Array.isArray(t)){let n=r.wrap===!0,i=r.capture?"":"?:";return n?`(${i}${t.join("|")})`:t.join("|")}return lee(t,e,r)},dee=(...t)=>new RangeError("Invalid range arguments: "+TKe.inspect(...t)),fee=(t,e,r)=>{if(r.strictRanges===!0)throw dee([t,e]);return[]},_Ke=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},UKe=(t,e,r=1,n={})=>{let i=Number(t),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(n.strictRanges===!0)throw dee([t,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(t),A=String(e),c=String(r);r=Math.max(Math.abs(r),1);let u=yP(a)||yP(A)||yP(c),l=u?Math.max(a.length,A.length,c.length):0,d=u===!1&&MKe(t,e,n)===!1,g=n.transform||NKe(d);if(n.toRegex&&r===1)return gee(Ew(t,l),Ew(e,l),!0,n);let p={negatives:[],positives:[]},f=I=>p[I<0?"negatives":"positives"].push(Math.abs(I)),m=[],C=0;for(;o?i>=s:i<=s;)n.toRegex===!0&&r>1?f(i):m.push(PKe(g(i,C),l,d)),i=o?i-r:i+r,C++;return n.toRegex===!0?r>1?LKe(p,n,l):pee(m,null,{wrap:!1,...n}):m},GKe=(t,e,r=1,n={})=>{if(!tI(t)&&t.length>1||!tI(e)&&e.length>1)return fee(t,e,n);let i=n.transform||(d=>String.fromCharCode(d)),s=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,A=Math.min(s,o),c=Math.max(s,o);if(n.toRegex&&r===1)return gee(A,c,!1,n);let u=[],l=0;for(;a?s>=o:s<=o;)u.push(i(s,l)),s=a?s-r:s+r,l++;return n.toRegex===!0?pee(u,null,{wrap:!1,options:n}):u},Iw=(t,e,r,n={})=>{if(e==null&&BP(t))return[t];if(!BP(t)||!BP(e))return fee(t,e,n);if(typeof r=="function")return Iw(t,e,1,{transform:r});if(uee(r))return Iw(t,e,0,r);let i={...n};return i.capture===!0&&(i.wrap=!0),r=r||i.step||1,tI(r)?tI(t)&&tI(e)?UKe(t,e,r,i):GKe(t,e,Math.max(Math.abs(r),1),i):r!=null&&!uee(r)?_Ke(r,i):Iw(t,e,1,r)};hee.exports=Iw});var Iee=N((jOt,Cee)=>{"use strict";h();var OKe=QP(),mee=mw(),KKe=(t,e={})=>{let r=(n,i={})=>{let s=mee.isInvalidBrace(i),o=n.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,A=e.escapeInvalid===!0?"\\":"",c="";if(n.isOpen===!0)return A+n.value;if(n.isClose===!0)return console.log("node.isClose",A,n.value),A+n.value;if(n.type==="open")return a?A+n.value:"(";if(n.type==="close")return a?A+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":a?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let u=mee.reduce(n.nodes),l=OKe(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(l.length!==0)return u.length>1&&l.length>1?`(${l})`:l}if(n.nodes)for(let u of n.nodes)c+=r(u,n);return c};return r(t)};Cee.exports=KKe});var yee=N((qOt,Bee)=>{"use strict";h();var HKe=QP(),Eee=Cw(),cf=mw(),Ng=(t="",e="",r=!1)=>{let n=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return r?cf.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let s of i)n.push(Ng(s,e,r));else for(let s of e)r===!0&&typeof s=="string"&&(s=`{${s}}`),n.push(Array.isArray(s)?Ng(i,s,r):i+s);return cf.flatten(n)},JKe=(t,e={})=>{let r=e.rangeLimit===void 0?1e3:e.rangeLimit,n=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(Ng(a.pop(),Eee(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Ng(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let l=cf.reduce(i.nodes);if(cf.exceedsLimit(...l,e.step,r))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let d=HKe(...l,e);d.length===0&&(d=Eee(i,e)),a.push(Ng(a.pop(),d)),i.nodes=[];return}let A=cf.encloseBrace(i),c=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,c=u.queue;for(let l=0;l<i.nodes.length;l++){let d=i.nodes[l];if(d.type==="comma"&&i.type==="brace"){l===1&&c.push(""),c.push("");continue}if(d.type==="close"){a.push(Ng(a.pop(),c,A));continue}if(d.value&&d.type!=="open"){c.push(Ng(c.pop(),d.value));continue}d.nodes&&n(d,i)}return c};return cf.flatten(n(t))};Bee.exports=JKe});var Dee=N((VOt,Qee)=>{"use strict";h();Qee.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
|
|
1260
|
-
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var xee=N((zOt,See)=>{"use strict";h();var jKe=Cw(),{MAX_LENGTH:wee,CHAR_BACKSLASH:DP,CHAR_BACKTICK:YKe,CHAR_COMMA:qKe,CHAR_DOT:$Ke,CHAR_LEFT_PARENTHESES:VKe,CHAR_RIGHT_PARENTHESES:WKe,CHAR_LEFT_CURLY_BRACE:zKe,CHAR_RIGHT_CURLY_BRACE:XKe,CHAR_LEFT_SQUARE_BRACKET:bee,CHAR_RIGHT_SQUARE_BRACKET:vee,CHAR_DOUBLE_QUOTE:ZKe,CHAR_SINGLE_QUOTE:eHe,CHAR_NO_BREAK_SPACE:tHe,CHAR_ZERO_WIDTH_NOBREAK_SPACE:rHe}=Dee(),nHe=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let r=e||{},n=typeof r.maxLength=="number"?Math.min(wee,r.maxLength):wee;if(t.length>n)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${n})`);let i={type:"root",input:t,nodes:[]},s=[i],o=i,a=i,A=0,c=t.length,u=0,l=0,d,g=()=>t[u++],p=f=>{if(f.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&f.type==="text"){a.value+=f.value;return}return o.nodes.push(f),f.parent=o,f.prev=a,a=f,f};for(p({type:"bos"});u<c;)if(o=s[s.length-1],d=g(),!(d===rHe||d===tHe)){if(d===DP){p({type:"text",value:(e.keepEscaping?d:"")+g()});continue}if(d===vee){p({type:"text",value:"\\"+d});continue}if(d===bee){A++;let f;for(;u<c&&(f=g());){if(d+=f,f===bee){A++;continue}if(f===DP){d+=g();continue}if(f===vee&&(A--,A===0))break}p({type:"text",value:d});continue}if(d===VKe){o=p({type:"paren",nodes:[]}),s.push(o),p({type:"text",value:d});continue}if(d===WKe){if(o.type!=="paren"){p({type:"text",value:d});continue}o=s.pop(),p({type:"text",value:d}),o=s[s.length-1];continue}if(d===ZKe||d===eHe||d===YKe){let f=d,m;for(e.keepQuotes!==!0&&(d="");u<c&&(m=g());){if(m===DP){d+=m+g();continue}if(m===f){e.keepQuotes===!0&&(d+=m);break}d+=m}p({type:"text",value:d});continue}if(d===zKe){l++;let m={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:l,commas:0,ranges:0,nodes:[]};o=p(m),s.push(o),p({type:"open",value:d});continue}if(d===XKe){if(o.type!=="brace"){p({type:"text",value:d});continue}let f="close";o=s.pop(),o.close=!0,p({type:f,value:d}),l--,o=s[s.length-1];continue}if(d===qKe&&l>0){if(o.ranges>0){o.ranges=0;let f=o.nodes.shift();o.nodes=[f,{type:"text",value:jKe(o)}]}p({type:"comma",value:d}),o.commas++;continue}if(d===$Ke&&l>0&&o.commas===0){let f=o.nodes;if(l===0||f.length===0){p({type:"text",value:d});continue}if(a.type==="dot"){if(o.range=[],a.value+=d,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){f.pop();let m=f[f.length-1];m.value+=a.value+d,a=m,o.ranges--;continue}p({type:"dot",value:d});continue}p({type:"text",value:d})}do if(o=s.pop(),o.type!=="root"){o.nodes.forEach(C=>{C.nodes||(C.type==="open"&&(C.isOpen=!0),C.type==="close"&&(C.isClose=!0),C.nodes||(C.type="text"),C.invalid=!0)});let f=s[s.length-1],m=f.nodes.indexOf(o);f.nodes.splice(m,1,...o.nodes)}while(s.length>0);return p({type:"eos"}),i};See.exports=nHe});var Ree=N((ZOt,kee)=>{"use strict";h();var Fee=Cw(),iHe=Iee(),sHe=yee(),oHe=xee(),Us=(t,e={})=>{let r=[];if(Array.isArray(t))for(let n of t){let i=Us.create(n,e);Array.isArray(i)?r.push(...i):r.push(i)}else r=[].concat(Us.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(r=[...new Set(r)]),r};Us.parse=(t,e={})=>oHe(t,e);Us.stringify=(t,e={})=>Fee(typeof t=="string"?Us.parse(t,e):t,e);Us.compile=(t,e={})=>(typeof t=="string"&&(t=Us.parse(t,e)),iHe(t,e));Us.expand=(t,e={})=>{typeof t=="string"&&(t=Us.parse(t,e));let r=sHe(t,e);return e.noempty===!0&&(r=r.filter(Boolean)),e.nodupes===!0&&(r=[...new Set(r)]),r};Us.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Us.compile(t,e):Us.expand(t,e);kee.exports=Us});var rI=N((t8t,Lee)=>{"use strict";h();var aHe=require("path"),pA="\\\\/",Tee=`[^${pA}]`,fc="\\.",AHe="\\+",cHe="\\?",Bw="\\/",uHe="(?=.)",Nee="[^/]",wP=`(?:${Bw}|$)`,Mee=`(?:^|${Bw})`,bP=`${fc}{1,2}${wP}`,lHe=`(?!${fc})`,gHe=`(?!${Mee}${bP})`,pHe=`(?!${fc}{0,1}${wP})`,dHe=`(?!${bP})`,fHe=`[^.${Bw}]`,hHe=`${Nee}*?`,Pee={DOT_LITERAL:fc,PLUS_LITERAL:AHe,QMARK_LITERAL:cHe,SLASH_LITERAL:Bw,ONE_CHAR:uHe,QMARK:Nee,END_ANCHOR:wP,DOTS_SLASH:bP,NO_DOT:lHe,NO_DOTS:gHe,NO_DOT_SLASH:pHe,NO_DOTS_SLASH:dHe,QMARK_NO_DOT:fHe,STAR:hHe,START_ANCHOR:Mee},mHe={...Pee,SLASH_LITERAL:`[${pA}]`,QMARK:Tee,STAR:`${Tee}*?`,DOTS_SLASH:`${fc}{1,2}(?:[${pA}]|$)`,NO_DOT:`(?!${fc})`,NO_DOTS:`(?!(?:^|[${pA}])${fc}{1,2}(?:[${pA}]|$))`,NO_DOT_SLASH:`(?!${fc}{0,1}(?:[${pA}]|$))`,NO_DOTS_SLASH:`(?!${fc}{1,2}(?:[${pA}]|$))`,QMARK_NO_DOT:`[^.${pA}]`,START_ANCHOR:`(?:^|[${pA}])`,END_ANCHOR:`(?:[${pA}]|$)`},CHe={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Lee.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:CHe,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:aHe.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?mHe:Pee}}});var nI=N(ls=>{"use strict";h();var IHe=require("path"),EHe=process.platform==="win32",{REGEX_BACKSLASH:BHe,REGEX_REMOVE_BACKSLASH:yHe,REGEX_SPECIAL_CHARS:QHe,REGEX_SPECIAL_CHARS_GLOBAL:DHe}=rI();ls.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);ls.hasRegexChars=t=>QHe.test(t);ls.isRegexChar=t=>t.length===1&&ls.hasRegexChars(t);ls.escapeRegex=t=>t.replace(DHe,"\\$1");ls.toPosixSlashes=t=>t.replace(BHe,"/");ls.removeBackslashes=t=>t.replace(yHe,e=>e==="\\"?"":e);ls.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};ls.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:EHe===!0||IHe.sep==="\\";ls.escapeLast=(t,e,r)=>{let n=t.lastIndexOf(e,r);return n===-1?t:t[n-1]==="\\"?ls.escapeLast(t,e,n-1):`${t.slice(0,n)}\\${t.slice(n)}`};ls.removePrefix=(t,e={})=>{let r=t;return r.startsWith("./")&&(r=r.slice(2),e.prefix="./"),r};ls.wrapOutput=(t,e={},r={})=>{let n=r.contains?"":"^",i=r.contains?"":"$",s=`${n}(?:${t})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var jee=N((s8t,Jee)=>{"use strict";h();var _ee=nI(),{CHAR_ASTERISK:vP,CHAR_AT:wHe,CHAR_BACKWARD_SLASH:iI,CHAR_COMMA:bHe,CHAR_DOT:SP,CHAR_EXCLAMATION_MARK:xP,CHAR_FORWARD_SLASH:Hee,CHAR_LEFT_CURLY_BRACE:FP,CHAR_LEFT_PARENTHESES:kP,CHAR_LEFT_SQUARE_BRACKET:vHe,CHAR_PLUS:SHe,CHAR_QUESTION_MARK:Uee,CHAR_RIGHT_CURLY_BRACE:xHe,CHAR_RIGHT_PARENTHESES:Gee,CHAR_RIGHT_SQUARE_BRACKET:FHe}=rI(),Oee=t=>t===Hee||t===iI,Kee=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},kHe=(t,e)=>{let r=e||{},n=t.length-1,i=r.parts===!0||r.scanToEnd===!0,s=[],o=[],a=[],A=t,c=-1,u=0,l=0,d=!1,g=!1,p=!1,f=!1,m=!1,C=!1,I=!1,y=!1,B=!1,E=!1,Q=0,v,D,S={value:"",depth:0,isGlob:!1},b=()=>c>=n,x=()=>A.charCodeAt(c+1),P=()=>(v=D,A.charCodeAt(++c));for(;c<n;){D=P();let j;if(D===iI){I=S.backslashes=!0,D=P(),D===FP&&(C=!0);continue}if(C===!0||D===FP){for(Q++;b()!==!0&&(D=P());){if(D===iI){I=S.backslashes=!0,P();continue}if(D===FP){Q++;continue}if(C!==!0&&D===SP&&(D=P())===SP){if(d=S.isBrace=!0,p=S.isGlob=!0,E=!0,i===!0)continue;break}if(C!==!0&&D===bHe){if(d=S.isBrace=!0,p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===xHe&&(Q--,Q===0)){C=!1,d=S.isBrace=!0,E=!0;break}}if(i===!0)continue;break}if(D===Hee){if(s.push(c),o.push(S),S={value:"",depth:0,isGlob:!1},E===!0)continue;if(v===SP&&c===u+1){u+=2;continue}l=c+1;continue}if(r.noext!==!0&&(D===SHe||D===wHe||D===vP||D===Uee||D===xP)===!0&&x()===kP){if(p=S.isGlob=!0,f=S.isExtglob=!0,E=!0,D===xP&&c===u&&(B=!0),i===!0){for(;b()!==!0&&(D=P());){if(D===iI){I=S.backslashes=!0,D=P();continue}if(D===Gee){p=S.isGlob=!0,E=!0;break}}continue}break}if(D===vP){if(v===vP&&(m=S.isGlobstar=!0),p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===Uee){if(p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===vHe){for(;b()!==!0&&(j=P());){if(j===iI){I=S.backslashes=!0,P();continue}if(j===FHe){g=S.isBracket=!0,p=S.isGlob=!0,E=!0;break}}if(i===!0)continue;break}if(r.nonegate!==!0&&D===xP&&c===u){y=S.negated=!0,u++;continue}if(r.noparen!==!0&&D===kP){if(p=S.isGlob=!0,i===!0){for(;b()!==!0&&(D=P());){if(D===kP){I=S.backslashes=!0,D=P();continue}if(D===Gee){E=!0;break}}continue}break}if(p===!0){if(E=!0,i===!0)continue;break}}r.noext===!0&&(f=!1,p=!1);let O=A,J="",_="";u>0&&(J=A.slice(0,u),A=A.slice(u),l-=u),O&&p===!0&&l>0?(O=A.slice(0,l),_=A.slice(l)):p===!0?(O="",_=A):O=A,O&&O!==""&&O!=="/"&&O!==A&&Oee(O.charCodeAt(O.length-1))&&(O=O.slice(0,-1)),r.unescape===!0&&(_&&(_=_ee.removeBackslashes(_)),O&&I===!0&&(O=_ee.removeBackslashes(O)));let K={prefix:J,input:t,start:u,base:O,glob:_,isBrace:d,isBracket:g,isGlob:p,isExtglob:f,isGlobstar:m,negated:y,negatedExtglob:B};if(r.tokens===!0&&(K.maxDepth=0,Oee(D)||o.push(S),K.tokens=o),r.parts===!0||r.tokens===!0){let j;for(let ee=0;ee<s.length;ee++){let U=j?j+1:u,Y=s[ee],H=t.slice(U,Y);r.tokens&&(ee===0&&u!==0?(o[ee].isPrefix=!0,o[ee].value=J):o[ee].value=H,Kee(o[ee]),K.maxDepth+=o[ee].depth),(ee!==0||H!=="")&&a.push(H),j=Y}if(j&&j+1<t.length){let ee=t.slice(j+1);a.push(ee),r.tokens&&(o[o.length-1].value=ee,Kee(o[o.length-1]),K.maxDepth+=o[o.length-1].depth)}K.slashes=s,K.parts=a}return K};Jee.exports=kHe});var $ee=N((a8t,qee)=>{"use strict";h();var yw=rI(),Gs=nI(),{MAX_LENGTH:Qw,POSIX_REGEX_SOURCE:RHe,REGEX_NON_SPECIAL_CHARS:THe,REGEX_SPECIAL_CHARS_BACKREF:NHe,REPLACEMENTS:Yee}=yw,MHe=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let r=`[${t.join("-")}]`;try{new RegExp(r)}catch{return t.map(i=>Gs.escapeRegex(i)).join("..")}return r},uf=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,RP=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Yee[t]||t;let r={...e},n=typeof r.maxLength=="number"?Math.min(Qw,r.maxLength):Qw,i=t.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:r.prepend||""},o=[s],a=r.capture?"":"?:",A=Gs.isWindows(e),c=yw.globChars(A),u=yw.extglobChars(c),{DOT_LITERAL:l,PLUS_LITERAL:d,SLASH_LITERAL:g,ONE_CHAR:p,DOTS_SLASH:f,NO_DOT:m,NO_DOT_SLASH:C,NO_DOTS_SLASH:I,QMARK:y,QMARK_NO_DOT:B,STAR:E,START_ANCHOR:Q}=c,v=le=>`(${a}(?:(?!${Q}${le.dot?f:l}).)*?)`,D=r.dot?"":m,S=r.dot?y:B,b=r.bash===!0?v(r):E;r.capture&&(b=`(${b})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let x={input:t,index:-1,start:0,dot:r.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=Gs.removePrefix(t,x),i=t.length;let P=[],O=[],J=[],_=s,K,j=()=>x.index===i-1,ee=x.peek=(le=1)=>t[x.index+le],U=x.advance=()=>t[++x.index]||"",Y=()=>t.slice(x.index+1),H=(le="",be=0)=>{x.consumed+=le,x.index+=be},Z=le=>{x.output+=le.output!=null?le.output:le.value,H(le.value)},ue=()=>{let le=1;for(;ee()==="!"&&(ee(2)!=="("||ee(3)==="?");)U(),x.start++,le++;return le%2===0?!1:(x.negated=!0,x.start++,!0)},ge=le=>{x[le]++,J.push(le)},he=le=>{x[le]--,J.pop()},X=le=>{if(_.type==="globstar"){let be=x.braces>0&&(le.type==="comma"||le.type==="brace"),de=le.extglob===!0||P.length&&(le.type==="pipe"||le.type==="paren");le.type!=="slash"&&le.type!=="paren"&&!be&&!de&&(x.output=x.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=b,x.output+=_.output)}if(P.length&&le.type!=="paren"&&(P[P.length-1].inner+=le.value),(le.value||le.output)&&Z(le),_&&_.type==="text"&&le.type==="text"){_.value+=le.value,_.output=(_.output||"")+le.value;return}le.prev=_,o.push(le),_=le},we=(le,be)=>{let de={...u[be],conditions:1,inner:""};de.prev=_,de.parens=x.parens,de.output=x.output;let ke=(r.capture?"(":"")+de.open;ge("parens"),X({type:le,value:be,output:x.output?"":p}),X({type:"paren",extglob:!0,value:U(),output:ke}),P.push(de)},Je=le=>{let be=le.close+(r.capture?")":""),de;if(le.type==="negate"){let ke=b;if(le.inner&&le.inner.length>1&&le.inner.includes("/")&&(ke=v(r)),(ke!==b||j()||/^\)+$/.test(Y()))&&(be=le.close=`)$))${ke}`),le.inner.includes("*")&&(de=Y())&&/^\.[^\\/.]+$/.test(de)){let Qe=RP(de,{...e,fastpaths:!1}).output;be=le.close=`)${Qe})${ke})`}le.prev.type==="bos"&&(x.negatedExtglob=!0)}X({type:"paren",extglob:!0,value:K,output:be}),he("parens")};if(r.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let le=!1,be=t.replace(NHe,(de,ke,Qe,rt,nt,Ut)=>rt==="\\"?(le=!0,de):rt==="?"?ke?ke+rt+(nt?y.repeat(nt.length):""):Ut===0?S+(nt?y.repeat(nt.length):""):y.repeat(Qe.length):rt==="."?l.repeat(Qe.length):rt==="*"?ke?ke+rt+(nt?b:""):b:ke?de:`\\${de}`);return le===!0&&(r.unescape===!0?be=be.replace(/\\/g,""):be=be.replace(/\\+/g,de=>de.length%2===0?"\\\\":de?"\\":"")),be===t&&r.contains===!0?(x.output=t,x):(x.output=Gs.wrapOutput(be,x,e),x)}for(;!j();){if(K=U(),K==="\0")continue;if(K==="\\"){let de=ee();if(de==="/"&&r.bash!==!0||de==="."||de===";")continue;if(!de){K+="\\",X({type:"text",value:K});continue}let ke=/^\\+/.exec(Y()),Qe=0;if(ke&&ke[0].length>2&&(Qe=ke[0].length,x.index+=Qe,Qe%2!==0&&(K+="\\")),r.unescape===!0?K=U():K+=U(),x.brackets===0){X({type:"text",value:K});continue}}if(x.brackets>0&&(K!=="]"||_.value==="["||_.value==="[^")){if(r.posix!==!1&&K===":"){let de=_.value.slice(1);if(de.includes("[")&&(_.posix=!0,de.includes(":"))){let ke=_.value.lastIndexOf("["),Qe=_.value.slice(0,ke),rt=_.value.slice(ke+2),nt=RHe[rt];if(nt){_.value=Qe+nt,x.backtrack=!0,U(),!s.output&&o.indexOf(_)===1&&(s.output=p);continue}}}(K==="["&&ee()!==":"||K==="-"&&ee()==="]")&&(K=`\\${K}`),K==="]"&&(_.value==="["||_.value==="[^")&&(K=`\\${K}`),r.posix===!0&&K==="!"&&_.value==="["&&(K="^"),_.value+=K,Z({value:K});continue}if(x.quotes===1&&K!=='"'){K=Gs.escapeRegex(K),_.value+=K,Z({value:K});continue}if(K==='"'){x.quotes=x.quotes===1?0:1,r.keepQuotes===!0&&X({type:"text",value:K});continue}if(K==="("){ge("parens"),X({type:"paren",value:K});continue}if(K===")"){if(x.parens===0&&r.strictBrackets===!0)throw new SyntaxError(uf("opening","("));let de=P[P.length-1];if(de&&x.parens===de.parens+1){Je(P.pop());continue}X({type:"paren",value:K,output:x.parens?")":"\\)"}),he("parens");continue}if(K==="["){if(r.nobracket===!0||!Y().includes("]")){if(r.nobracket!==!0&&r.strictBrackets===!0)throw new SyntaxError(uf("closing","]"));K=`\\${K}`}else ge("brackets");X({type:"bracket",value:K});continue}if(K==="]"){if(r.nobracket===!0||_&&_.type==="bracket"&&_.value.length===1){X({type:"text",value:K,output:`\\${K}`});continue}if(x.brackets===0){if(r.strictBrackets===!0)throw new SyntaxError(uf("opening","["));X({type:"text",value:K,output:`\\${K}`});continue}he("brackets");let de=_.value.slice(1);if(_.posix!==!0&&de[0]==="^"&&!de.includes("/")&&(K=`/${K}`),_.value+=K,Z({value:K}),r.literalBrackets===!1||Gs.hasRegexChars(de))continue;let ke=Gs.escapeRegex(_.value);if(x.output=x.output.slice(0,-_.value.length),r.literalBrackets===!0){x.output+=ke,_.value=ke;continue}_.value=`(${a}${ke}|${_.value})`,x.output+=_.value;continue}if(K==="{"&&r.nobrace!==!0){ge("braces");let de={type:"brace",value:K,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};O.push(de),X(de);continue}if(K==="}"){let de=O[O.length-1];if(r.nobrace===!0||!de){X({type:"text",value:K,output:K});continue}let ke=")";if(de.dots===!0){let Qe=o.slice(),rt=[];for(let nt=Qe.length-1;nt>=0&&(o.pop(),Qe[nt].type!=="brace");nt--)Qe[nt].type!=="dots"&&rt.unshift(Qe[nt].value);ke=MHe(rt,r),x.backtrack=!0}if(de.comma!==!0&&de.dots!==!0){let Qe=x.output.slice(0,de.outputIndex),rt=x.tokens.slice(de.tokensIndex);de.value=de.output="\\{",K=ke="\\}",x.output=Qe;for(let nt of rt)x.output+=nt.output||nt.value}X({type:"brace",value:K,output:ke}),he("braces"),O.pop();continue}if(K==="|"){P.length>0&&P[P.length-1].conditions++,X({type:"text",value:K});continue}if(K===","){let de=K,ke=O[O.length-1];ke&&J[J.length-1]==="braces"&&(ke.comma=!0,de="|"),X({type:"comma",value:K,output:de});continue}if(K==="/"){if(_.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),_=s;continue}X({type:"slash",value:K,output:g});continue}if(K==="."){if(x.braces>0&&_.type==="dot"){_.value==="."&&(_.output=l);let de=O[O.length-1];_.type="dots",_.output+=K,_.value+=K,de.dots=!0;continue}if(x.braces+x.parens===0&&_.type!=="bos"&&_.type!=="slash"){X({type:"text",value:K,output:l});continue}X({type:"dot",value:K,output:l});continue}if(K==="?"){if(!(_&&_.value==="(")&&r.noextglob!==!0&&ee()==="("&&ee(2)!=="?"){we("qmark",K);continue}if(_&&_.type==="paren"){let ke=ee(),Qe=K;if(ke==="<"&&!Gs.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(_.value==="("&&!/[!=<:]/.test(ke)||ke==="<"&&!/<([!=]|\w+>)/.test(Y()))&&(Qe=`\\${K}`),X({type:"text",value:K,output:Qe});continue}if(r.dot!==!0&&(_.type==="slash"||_.type==="bos")){X({type:"qmark",value:K,output:B});continue}X({type:"qmark",value:K,output:y});continue}if(K==="!"){if(r.noextglob!==!0&&ee()==="("&&(ee(2)!=="?"||!/[!=<:]/.test(ee(3)))){we("negate",K);continue}if(r.nonegate!==!0&&x.index===0){ue();continue}}if(K==="+"){if(r.noextglob!==!0&&ee()==="("&&ee(2)!=="?"){we("plus",K);continue}if(_&&_.value==="("||r.regex===!1){X({type:"plus",value:K,output:d});continue}if(_&&(_.type==="bracket"||_.type==="paren"||_.type==="brace")||x.parens>0){X({type:"plus",value:K});continue}X({type:"plus",value:d});continue}if(K==="@"){if(r.noextglob!==!0&&ee()==="("&&ee(2)!=="?"){X({type:"at",extglob:!0,value:K,output:""});continue}X({type:"text",value:K});continue}if(K!=="*"){(K==="$"||K==="^")&&(K=`\\${K}`);let de=THe.exec(Y());de&&(K+=de[0],x.index+=de[0].length),X({type:"text",value:K});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=K,_.output=b,x.backtrack=!0,x.globstar=!0,H(K);continue}let le=Y();if(r.noextglob!==!0&&/^\([^?]/.test(le)){we("star",K);continue}if(_.type==="star"){if(r.noglobstar===!0){H(K);continue}let de=_.prev,ke=de.prev,Qe=de.type==="slash"||de.type==="bos",rt=ke&&(ke.type==="star"||ke.type==="globstar");if(r.bash===!0&&(!Qe||le[0]&&le[0]!=="/")){X({type:"star",value:K,output:""});continue}let nt=x.braces>0&&(de.type==="comma"||de.type==="brace"),Ut=P.length&&(de.type==="pipe"||de.type==="paren");if(!Qe&&de.type!=="paren"&&!nt&&!Ut){X({type:"star",value:K,output:""});continue}for(;le.slice(0,3)==="/**";){let $r=t[x.index+4];if($r&&$r!=="/")break;le=le.slice(3),H("/**",3)}if(de.type==="bos"&&j()){_.type="globstar",_.value+=K,_.output=v(r),x.output=_.output,x.globstar=!0,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&!rt&&j()){x.output=x.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=v(r)+(r.strictSlashes?")":"|$)"),_.value+=K,x.globstar=!0,x.output+=de.output+_.output,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&le[0]==="/"){let $r=le[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=`${v(r)}${g}|${g}${$r})`,_.value+=K,x.output+=de.output+_.output,x.globstar=!0,H(K+U()),X({type:"slash",value:"/",output:""});continue}if(de.type==="bos"&&le[0]==="/"){_.type="globstar",_.value+=K,_.output=`(?:^|${g}|${v(r)}${g})`,x.output=_.output,x.globstar=!0,H(K+U()),X({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-_.output.length),_.type="globstar",_.output=v(r),_.value+=K,x.output+=_.output,x.globstar=!0,H(K);continue}let be={type:"star",value:K,output:b};if(r.bash===!0){be.output=".*?",(_.type==="bos"||_.type==="slash")&&(be.output=D+be.output),X(be);continue}if(_&&(_.type==="bracket"||_.type==="paren")&&r.regex===!0){be.output=K,X(be);continue}(x.index===x.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(x.output+=C,_.output+=C):r.dot===!0?(x.output+=I,_.output+=I):(x.output+=D,_.output+=D),ee()!=="*"&&(x.output+=p,_.output+=p)),X(be)}for(;x.brackets>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","]"));x.output=Gs.escapeLast(x.output,"["),he("brackets")}for(;x.parens>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing",")"));x.output=Gs.escapeLast(x.output,"("),he("parens")}for(;x.braces>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","}"));x.output=Gs.escapeLast(x.output,"{"),he("braces")}if(r.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${g}?`}),x.backtrack===!0){x.output="";for(let le of x.tokens)x.output+=le.output!=null?le.output:le.value,le.suffix&&(x.output+=le.suffix)}return x};RP.fastpaths=(t,e)=>{let r={...e},n=typeof r.maxLength=="number"?Math.min(Qw,r.maxLength):Qw,i=t.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);t=Yee[t]||t;let s=Gs.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:A,DOTS_SLASH:c,NO_DOT:u,NO_DOTS:l,NO_DOTS_SLASH:d,STAR:g,START_ANCHOR:p}=yw.globChars(s),f=r.dot?l:u,m=r.dot?d:u,C=r.capture?"":"?:",I={negated:!1,prefix:""},y=r.bash===!0?".*?":g;r.capture&&(y=`(${y})`);let B=D=>D.noglobstar===!0?y:`(${C}(?:(?!${p}${D.dot?c:o}).)*?)`,E=D=>{switch(D){case"*":return`${f}${A}${y}`;case".*":return`${o}${A}${y}`;case"*.*":return`${f}${y}${o}${A}${y}`;case"*/*":return`${f}${y}${a}${A}${m}${y}`;case"**":return f+B(r);case"**/*":return`(?:${f}${B(r)}${a})?${m}${A}${y}`;case"**/*.*":return`(?:${f}${B(r)}${a})?${m}${y}${o}${A}${y}`;case"**/.*":return`(?:${f}${B(r)}${a})?${o}${A}${y}`;default:{let S=/^(.*?)\.(\w+)$/.exec(D);if(!S)return;let b=E(S[1]);return b?b+o+S[2]:void 0}}},Q=Gs.removePrefix(t,I),v=E(Q);return v&&r.strictSlashes!==!0&&(v+=`${a}?`),v};qee.exports=RP});var Wee=N((c8t,Vee)=>{"use strict";h();var PHe=require("path"),LHe=jee(),TP=$ee(),NP=nI(),_He=rI(),UHe=t=>t&&typeof t=="object"&&!Array.isArray(t),cn=(t,e,r=!1)=>{if(Array.isArray(t)){let u=t.map(d=>cn(d,e,r));return d=>{for(let g of u){let p=g(d);if(p)return p}return!1}}let n=UHe(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=NP.isWindows(e),o=n?cn.compileRe(t,e):cn.makeRe(t,e,!1,!0),a=o.state;delete o.state;let A=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};A=cn(i.ignore,u,r)}let c=(u,l=!1)=>{let{isMatch:d,match:g,output:p}=cn.test(u,o,e,{glob:t,posix:s}),f={glob:t,state:a,regex:o,posix:s,input:u,output:p,match:g,isMatch:d};return typeof i.onResult=="function"&&i.onResult(f),d===!1?(f.isMatch=!1,l?f:!1):A(u)?(typeof i.onIgnore=="function"&&i.onIgnore(f),f.isMatch=!1,l?f:!1):(typeof i.onMatch=="function"&&i.onMatch(f),l?f:!0)};return r&&(c.state=a),c};cn.test=(t,e,r,{glob:n,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let s=r||{},o=s.format||(i?NP.toPosixSlashes:null),a=t===n,A=a&&o?o(t):t;return a===!1&&(A=o?o(t):t,a=A===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=cn.matchBase(t,e,r,i):a=e.exec(A)),{isMatch:!!a,match:a,output:A}};cn.matchBase=(t,e,r,n=NP.isWindows(r))=>(e instanceof RegExp?e:cn.makeRe(e,r)).test(PHe.basename(t));cn.isMatch=(t,e,r)=>cn(e,r)(t);cn.parse=(t,e)=>Array.isArray(t)?t.map(r=>cn.parse(r,e)):TP(t,{...e,fastpaths:!1});cn.scan=(t,e)=>LHe(t,e);cn.compileRe=(t,e,r=!1,n=!1)=>{if(r===!0)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let A=cn.toRegex(a,e);return n===!0&&(A.state=t),A};cn.makeRe=(t,e={},r=!1,n=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=TP.fastpaths(t,e)),i.output||(i=TP(t,e)),cn.compileRe(i,e,r,n)};cn.toRegex=(t,e)=>{try{let r=e||{};return new RegExp(t,r.flags||(r.nocase?"i":""))}catch(r){if(e&&e.debug===!0)throw r;return/$^/}};cn.constants=_He;Vee.exports=cn});var Xee=N((l8t,zee)=>{"use strict";h();zee.exports=Wee()});var Dw=N((p8t,nte)=>{"use strict";h();var ete=require("util"),tte=Ree(),dA=Xee(),MP=nI(),Zee=t=>t===""||t==="./",rte=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},Fr=(t,e,r)=>{e=[].concat(e),t=[].concat(t);let n=new Set,i=new Set,s=new Set,o=0,a=u=>{s.add(u.output),r&&r.onResult&&r.onResult(u)};for(let u=0;u<e.length;u++){let l=dA(String(e[u]),{...r,onResult:a},!0),d=l.state.negated||l.state.negatedExtglob;d&&o++;for(let g of t){let p=l(g,!0);(d?!p.isMatch:p.isMatch)&&(d?n.add(p.output):(n.delete(p.output),i.add(p.output)))}}let c=(o===e.length?[...s]:[...i]).filter(u=>!n.has(u));if(r&&c.length===0){if(r.failglob===!0)throw new Error(`No matches found for "${e.join(", ")}"`);if(r.nonull===!0||r.nullglob===!0)return r.unescape?e.map(u=>u.replace(/\\/g,"")):e}return c};Fr.match=Fr;Fr.matcher=(t,e)=>dA(t,e);Fr.isMatch=(t,e,r)=>dA(e,r)(t);Fr.any=Fr.isMatch;Fr.not=(t,e,r={})=>{e=[].concat(e).map(String);let n=new Set,i=[],s=a=>{r.onResult&&r.onResult(a),i.push(a.output)},o=new Set(Fr(t,e,{...r,onResult:s}));for(let a of i)o.has(a)||n.add(a);return[...n]};Fr.contains=(t,e,r)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${ete.inspect(t)}"`);if(Array.isArray(e))return e.some(n=>Fr.contains(t,n,r));if(typeof e=="string"){if(Zee(t)||Zee(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return Fr.isMatch(t,e,{...r,contains:!0})};Fr.matchKeys=(t,e,r)=>{if(!MP.isObject(t))throw new TypeError("Expected the first argument to be an object");let n=Fr(Object.keys(t),e,r),i={};for(let s of n)i[s]=t[s];return i};Fr.some=(t,e,r)=>{let n=[].concat(t);for(let i of[].concat(e)){let s=dA(String(i),r);if(n.some(o=>s(o)))return!0}return!1};Fr.every=(t,e,r)=>{let n=[].concat(t);for(let i of[].concat(e)){let s=dA(String(i),r);if(!n.every(o=>s(o)))return!1}return!0};Fr.all=(t,e,r)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${ete.inspect(t)}"`);return[].concat(e).every(n=>dA(n,r)(t))};Fr.capture=(t,e,r)=>{let n=MP.isWindows(r),s=dA.makeRe(String(t),{...r,capture:!0}).exec(n?MP.toPosixSlashes(e):e);if(s)return s.slice(1).map(o=>o===void 0?"":o)};Fr.makeRe=(...t)=>dA.makeRe(...t);Fr.scan=(...t)=>dA.scan(...t);Fr.parse=(t,e)=>{let r=[];for(let n of[].concat(t||[]))for(let i of tte(String(n),e))r.push(dA.parse(i,e));return r};Fr.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!rte(t)?[t]:tte(t,e)};Fr.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return Fr.braces(t,{...e,expand:!0})};Fr.hasBraces=rte;nte.exports=Fr});var pte=N(tt=>{"use strict";h();Object.defineProperty(tt,"__esModule",{value:!0});tt.isAbsolute=tt.partitionAbsoluteAndRelative=tt.removeDuplicateSlashes=tt.matchAny=tt.convertPatternsToRe=tt.makeRe=tt.getPatternParts=tt.expandBraceExpansion=tt.expandPatternsWithBraceExpansion=tt.isAffectDepthOfReadingPattern=tt.endsWithSlashGlobStar=tt.hasGlobStar=tt.getBaseDirectory=tt.isPatternRelatedToParentDirectory=tt.getPatternsOutsideCurrentDirectory=tt.getPatternsInsideCurrentDirectory=tt.getPositivePatterns=tt.getNegativePatterns=tt.isPositivePattern=tt.isNegativePattern=tt.convertToNegativePattern=tt.convertToPositivePattern=tt.isDynamicPattern=tt.isStaticPattern=void 0;var ite=require("path"),GHe=WZ(),PP=Dw(),ste="**",OHe="\\",KHe=/[*?]|^!/,HHe=/\[[^[]*]/,JHe=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,jHe=/[!*+?@]\([^(]*\)/,YHe=/,|\.\./,qHe=/(?!^)\/{2,}/g;function ote(t,e={}){return!ate(t,e)}tt.isStaticPattern=ote;function ate(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(OHe)||KHe.test(t)||HHe.test(t)||JHe.test(t)||e.extglob!==!1&&jHe.test(t)||e.braceExpansion!==!1&&$He(t))}tt.isDynamicPattern=ate;function $He(t){let e=t.indexOf("{");if(e===-1)return!1;let r=t.indexOf("}",e+1);if(r===-1)return!1;let n=t.slice(e,r);return YHe.test(n)}function VHe(t){return ww(t)?t.slice(1):t}tt.convertToPositivePattern=VHe;function WHe(t){return"!"+t}tt.convertToNegativePattern=WHe;function ww(t){return t.startsWith("!")&&t[1]!=="("}tt.isNegativePattern=ww;function Ate(t){return!ww(t)}tt.isPositivePattern=Ate;function zHe(t){return t.filter(ww)}tt.getNegativePatterns=zHe;function XHe(t){return t.filter(Ate)}tt.getPositivePatterns=XHe;function ZHe(t){return t.filter(e=>!LP(e))}tt.getPatternsInsideCurrentDirectory=ZHe;function e4e(t){return t.filter(LP)}tt.getPatternsOutsideCurrentDirectory=e4e;function LP(t){return t.startsWith("..")||t.startsWith("./..")}tt.isPatternRelatedToParentDirectory=LP;function t4e(t){return GHe(t,{flipBackslashes:!1})}tt.getBaseDirectory=t4e;function r4e(t){return t.includes(ste)}tt.hasGlobStar=r4e;function cte(t){return t.endsWith("/"+ste)}tt.endsWithSlashGlobStar=cte;function n4e(t){let e=ite.basename(t);return cte(t)||ote(e)}tt.isAffectDepthOfReadingPattern=n4e;function i4e(t){return t.reduce((e,r)=>e.concat(ute(r)),[])}tt.expandPatternsWithBraceExpansion=i4e;function ute(t){let e=PP.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((r,n)=>r.length-n.length),e.filter(r=>r!=="")}tt.expandBraceExpansion=ute;function s4e(t,e){let{parts:r}=PP.scan(t,Object.assign(Object.assign({},e),{parts:!0}));return r.length===0&&(r=[t]),r[0].startsWith("/")&&(r[0]=r[0].slice(1),r.unshift("")),r}tt.getPatternParts=s4e;function lte(t,e){return PP.makeRe(t,e)}tt.makeRe=lte;function o4e(t,e){return t.map(r=>lte(r,e))}tt.convertPatternsToRe=o4e;function a4e(t,e){return e.some(r=>r.test(t))}tt.matchAny=a4e;function A4e(t){return t.replace(qHe,"/")}tt.removeDuplicateSlashes=A4e;function c4e(t){let e=[],r=[];for(let n of t)gte(n)?e.push(n):r.push(n);return[e,r]}tt.partitionAbsoluteAndRelative=c4e;function gte(t){return ite.isAbsolute(t)}tt.isAbsolute=gte});var mte=N((m8t,hte)=>{"use strict";h();var u4e=require("stream"),dte=u4e.PassThrough,l4e=Array.prototype.slice;hte.exports=g4e;function g4e(){let t=[],e=l4e.call(arguments),r=!1,n=e[e.length-1];n&&!Array.isArray(n)&&n.pipe==null?e.pop():n={};let i=n.end!==!1,s=n.pipeError===!0;n.objectMode==null&&(n.objectMode=!0),n.highWaterMark==null&&(n.highWaterMark=64*1024);let o=dte(n);function a(){for(let u=0,l=arguments.length;u<l;u++)t.push(fte(arguments[u],n));return A(),this}function A(){if(r)return;r=!0;let u=t.shift();if(!u){process.nextTick(c);return}Array.isArray(u)||(u=[u]);let l=u.length+1;function d(){--l>0||(r=!1,A())}function g(p){function f(){p.removeListener("merge2UnpipeEnd",f),p.removeListener("end",f),s&&p.removeListener("error",m),d()}function m(C){o.emit("error",C)}if(p._readableState.endEmitted)return d();p.on("merge2UnpipeEnd",f),p.on("end",f),s&&p.on("error",m),p.pipe(o,{end:!1}),p.resume()}for(let p=0;p<u.length;p++)g(u[p]);d()}function c(){r=!1,o.emit("queueDrain"),i&&o.end()}return o.setMaxListeners(0),o.add=a,o.on("unpipe",function(u){u.emit("merge2UnpipeEnd")}),e.length&&a.apply(null,e),o}function fte(t,e){if(Array.isArray(t))for(let r=0,n=t.length;r<n;r++)t[r]=fte(t[r],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(dte(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var Ite=N(bw=>{"use strict";h();Object.defineProperty(bw,"__esModule",{value:!0});bw.merge=void 0;var p4e=mte();function d4e(t){let e=p4e(t);return t.forEach(r=>{r.once("error",n=>e.emit("error",n))}),e.once("close",()=>Cte(t)),e.once("end",()=>Cte(t)),e}bw.merge=d4e;function Cte(t){t.forEach(e=>e.emit("close"))}});var Ete=N(lf=>{"use strict";h();Object.defineProperty(lf,"__esModule",{value:!0});lf.isEmpty=lf.isString=void 0;function f4e(t){return typeof t=="string"}lf.isString=f4e;function h4e(t){return t===""}lf.isEmpty=h4e});var hc=N(Ri=>{"use strict";h();Object.defineProperty(Ri,"__esModule",{value:!0});Ri.string=Ri.stream=Ri.pattern=Ri.path=Ri.fs=Ri.errno=Ri.array=void 0;var m4e=LZ();Ri.array=m4e;var C4e=_Z();Ri.errno=C4e;var I4e=UZ();Ri.fs=I4e;var E4e=HZ();Ri.path=E4e;var B4e=pte();Ri.pattern=B4e;var y4e=Ite();Ri.stream=y4e;var Q4e=Ete();Ri.string=Q4e});var Dte=N(Ti=>{"use strict";h();Object.defineProperty(Ti,"__esModule",{value:!0});Ti.convertPatternGroupToTask=Ti.convertPatternGroupsToTasks=Ti.groupPatternsByBaseDirectory=Ti.getNegativePatternsAsPositive=Ti.getPositivePatterns=Ti.convertPatternsToTasks=Ti.generate=void 0;var la=hc();function D4e(t,e){let r=Bte(t,e),n=Bte(e.ignore,e),i=yte(r),s=Qte(r,n),o=i.filter(u=>la.pattern.isStaticPattern(u,e)),a=i.filter(u=>la.pattern.isDynamicPattern(u,e)),A=_P(o,s,!1),c=_P(a,s,!0);return A.concat(c)}Ti.generate=D4e;function Bte(t,e){let r=t;return e.braceExpansion&&(r=la.pattern.expandPatternsWithBraceExpansion(r)),e.baseNameMatch&&(r=r.map(n=>n.includes("/")?n:`**/${n}`)),r.map(n=>la.pattern.removeDuplicateSlashes(n))}function _P(t,e,r){let n=[],i=la.pattern.getPatternsOutsideCurrentDirectory(t),s=la.pattern.getPatternsInsideCurrentDirectory(t),o=UP(i),a=UP(s);return n.push(...GP(o,e,r)),"."in a?n.push(OP(".",s,e,r)):n.push(...GP(a,e,r)),n}Ti.convertPatternsToTasks=_P;function yte(t){return la.pattern.getPositivePatterns(t)}Ti.getPositivePatterns=yte;function Qte(t,e){return la.pattern.getNegativePatterns(t).concat(e).map(la.pattern.convertToPositivePattern)}Ti.getNegativePatternsAsPositive=Qte;function UP(t){let e={};return t.reduce((r,n)=>{let i=la.pattern.getBaseDirectory(n);return i in r?r[i].push(n):r[i]=[n],r},e)}Ti.groupPatternsByBaseDirectory=UP;function GP(t,e,r){return Object.keys(t).map(n=>OP(n,t[n],e,r))}Ti.convertPatternGroupsToTasks=GP;function OP(t,e,r,n){return{dynamic:n,positive:e,negative:r,base:t,patterns:[].concat(e,r.map(la.pattern.convertToNegativePattern))}}Ti.convertPatternGroupToTask=OP});var bte=N(vw=>{"use strict";h();Object.defineProperty(vw,"__esModule",{value:!0});vw.read=void 0;function w4e(t,e,r){e.fs.lstat(t,(n,i)=>{if(n!==null){wte(r,n);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){KP(r,i);return}e.fs.stat(t,(s,o)=>{if(s!==null){if(e.throwErrorOnBrokenSymbolicLink){wte(r,s);return}KP(r,i);return}e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),KP(r,o)})})}vw.read=w4e;function wte(t,e){t(e)}function KP(t,e){t(null,e)}});var vte=N(Sw=>{"use strict";h();Object.defineProperty(Sw,"__esModule",{value:!0});Sw.read=void 0;function b4e(t,e){let r=e.fs.lstatSync(t);if(!r.isSymbolicLink()||!e.followSymbolicLink)return r;try{let n=e.fs.statSync(t);return e.markSymbolicLink&&(n.isSymbolicLink=()=>!0),n}catch(n){if(!e.throwErrorOnBrokenSymbolicLink)return r;throw n}}Sw.read=b4e});var Ste=N(Nu=>{"use strict";h();Object.defineProperty(Nu,"__esModule",{value:!0});Nu.createFileSystemAdapter=Nu.FILE_SYSTEM_ADAPTER=void 0;var xw=require("fs");Nu.FILE_SYSTEM_ADAPTER={lstat:xw.lstat,stat:xw.stat,lstatSync:xw.lstatSync,statSync:xw.statSync};function v4e(t){return t===void 0?Nu.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Nu.FILE_SYSTEM_ADAPTER),t)}Nu.createFileSystemAdapter=v4e});var xte=N(JP=>{"use strict";h();Object.defineProperty(JP,"__esModule",{value:!0});var S4e=Ste(),HP=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=S4e.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue(e,r){return e??r}};JP.default=HP});var Mg=N(Mu=>{"use strict";h();Object.defineProperty(Mu,"__esModule",{value:!0});Mu.statSync=Mu.stat=Mu.Settings=void 0;var Fte=bte(),x4e=vte(),jP=xte();Mu.Settings=jP.default;function F4e(t,e,r){if(typeof e=="function"){Fte.read(t,YP(),e);return}Fte.read(t,YP(e),r)}Mu.stat=F4e;function k4e(t,e){let r=YP(e);return x4e.read(t,r)}Mu.statSync=k4e;function YP(t={}){return t instanceof jP.default?t:new jP.default(t)}});var Tte=N((L8t,Rte)=>{h();var kte;Rte.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(kte||(kte=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var Mte=N((U8t,Nte)=>{h();Nte.exports=T4e;var R4e=Tte();function T4e(t,e){let r,n,i,s=!0;Array.isArray(t)?(r=[],n=t.length):(i=Object.keys(t),r={},n=i.length);function o(A){function c(){e&&e(A,r),e=null}s?R4e(c):c()}function a(A,c,u){r[A]=u,(--n===0||c)&&o(c)}n?i?i.forEach(function(A){t[A](function(c,u){a(A,c,u)})}):t.forEach(function(A,c){A(function(u,l){a(c,u,l)})}):o(null),s=!1}});var qP=N(kw=>{"use strict";h();Object.defineProperty(kw,"__esModule",{value:!0});kw.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var Fw=process.versions.node.split(".");if(Fw[0]===void 0||Fw[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var Pte=Number.parseInt(Fw[0],10),N4e=Number.parseInt(Fw[1],10),Lte=10,M4e=10,P4e=Pte>Lte,L4e=Pte===Lte&&N4e>=M4e;kw.IS_SUPPORT_READDIR_WITH_FILE_TYPES=P4e||L4e});var _te=N(Rw=>{"use strict";h();Object.defineProperty(Rw,"__esModule",{value:!0});Rw.createDirentFromStats=void 0;var $P=class{constructor(e,r){this.name=e,this.isBlockDevice=r.isBlockDevice.bind(r),this.isCharacterDevice=r.isCharacterDevice.bind(r),this.isDirectory=r.isDirectory.bind(r),this.isFIFO=r.isFIFO.bind(r),this.isFile=r.isFile.bind(r),this.isSocket=r.isSocket.bind(r),this.isSymbolicLink=r.isSymbolicLink.bind(r)}};function _4e(t,e){return new $P(t,e)}Rw.createDirentFromStats=_4e});var VP=N(Tw=>{"use strict";h();Object.defineProperty(Tw,"__esModule",{value:!0});Tw.fs=void 0;var U4e=_te();Tw.fs=U4e});var WP=N(Nw=>{"use strict";h();Object.defineProperty(Nw,"__esModule",{value:!0});Nw.joinPathSegments=void 0;function G4e(t,e,r){return t.endsWith(r)?t+e:t+r+e}Nw.joinPathSegments=G4e});var Jte=N(Pu=>{"use strict";h();Object.defineProperty(Pu,"__esModule",{value:!0});Pu.readdir=Pu.readdirWithFileTypes=Pu.read=void 0;var O4e=Mg(),Ute=Mte(),K4e=qP(),Gte=VP(),Ote=WP();function H4e(t,e,r){if(!e.stats&&K4e.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Kte(t,e,r);return}Hte(t,e,r)}Pu.read=H4e;function Kte(t,e,r){e.fs.readdir(t,{withFileTypes:!0},(n,i)=>{if(n!==null){Mw(r,n);return}let s=i.map(a=>({dirent:a,name:a.name,path:Ote.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){zP(r,s);return}let o=s.map(a=>J4e(a,e));Ute(o,(a,A)=>{if(a!==null){Mw(r,a);return}zP(r,A)})})}Pu.readdirWithFileTypes=Kte;function J4e(t,e){return r=>{if(!t.dirent.isSymbolicLink()){r(null,t);return}e.fs.stat(t.path,(n,i)=>{if(n!==null){if(e.throwErrorOnBrokenSymbolicLink){r(n);return}r(null,t);return}t.dirent=Gte.fs.createDirentFromStats(t.name,i),r(null,t)})}}function Hte(t,e,r){e.fs.readdir(t,(n,i)=>{if(n!==null){Mw(r,n);return}let s=i.map(o=>{let a=Ote.joinPathSegments(t,o,e.pathSegmentSeparator);return A=>{O4e.stat(a,e.fsStatSettings,(c,u)=>{if(c!==null){A(c);return}let l={name:o,path:a,dirent:Gte.fs.createDirentFromStats(o,u)};e.stats&&(l.stats=u),A(null,l)})}});Ute(s,(o,a)=>{if(o!==null){Mw(r,o);return}zP(r,a)})})}Pu.readdir=Hte;function Mw(t,e){t(e)}function zP(t,e){t(null,e)}});var Vte=N(Lu=>{"use strict";h();Object.defineProperty(Lu,"__esModule",{value:!0});Lu.readdir=Lu.readdirWithFileTypes=Lu.read=void 0;var j4e=Mg(),Y4e=qP(),jte=VP(),Yte=WP();function q4e(t,e){return!e.stats&&Y4e.IS_SUPPORT_READDIR_WITH_FILE_TYPES?qte(t,e):$te(t,e)}Lu.read=q4e;function qte(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(n=>{let i={dirent:n,name:n.name,path:Yte.joinPathSegments(t,n.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let s=e.fs.statSync(i.path);i.dirent=jte.fs.createDirentFromStats(i.name,s)}catch(s){if(e.throwErrorOnBrokenSymbolicLink)throw s}return i})}Lu.readdirWithFileTypes=qte;function $te(t,e){return e.fs.readdirSync(t).map(n=>{let i=Yte.joinPathSegments(t,n,e.pathSegmentSeparator),s=j4e.statSync(i,e.fsStatSettings),o={name:n,path:i,dirent:jte.fs.createDirentFromStats(n,s)};return e.stats&&(o.stats=s),o})}Lu.readdir=$te});var Wte=N(_u=>{"use strict";h();Object.defineProperty(_u,"__esModule",{value:!0});_u.createFileSystemAdapter=_u.FILE_SYSTEM_ADAPTER=void 0;var gf=require("fs");_u.FILE_SYSTEM_ADAPTER={lstat:gf.lstat,stat:gf.stat,lstatSync:gf.lstatSync,statSync:gf.statSync,readdir:gf.readdir,readdirSync:gf.readdirSync};function $4e(t){return t===void 0?_u.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},_u.FILE_SYSTEM_ADAPTER),t)}_u.createFileSystemAdapter=$4e});var zte=N(ZP=>{"use strict";h();Object.defineProperty(ZP,"__esModule",{value:!0});var V4e=require("path"),W4e=Mg(),z4e=Wte(),XP=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=z4e.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,V4e.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new W4e.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,r){return e??r}};ZP.default=XP});var Pw=N(Uu=>{"use strict";h();Object.defineProperty(Uu,"__esModule",{value:!0});Uu.Settings=Uu.scandirSync=Uu.scandir=void 0;var Xte=Jte(),X4e=Vte(),e1=zte();Uu.Settings=e1.default;function Z4e(t,e,r){if(typeof e=="function"){Xte.read(t,t1(),e);return}Xte.read(t,t1(e),r)}Uu.scandir=Z4e;function eJe(t,e){let r=t1(e);return X4e.read(t,r)}Uu.scandirSync=eJe;function t1(t={}){return t instanceof e1.default?t:new e1.default(t)}});var ere=N((s3t,Zte)=>{"use strict";h();function tJe(t){var e=new t,r=e;function n(){var s=e;return s.next?e=s.next:(e=new t,r=e),s.next=null,s}function i(s){r.next=s,r=s}return{get:n,release:i}}Zte.exports=tJe});var rre=N((a3t,r1)=>{"use strict";h();var rJe=ere();function tre(t,e,r){if(typeof t=="function"&&(r=e,e=t,t=null),!(r>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var n=rJe(nJe),i=null,s=null,o=0,a=null,A={push:f,drain:gs,saturated:gs,pause:u,paused:!1,get concurrency(){return r},set concurrency(Q){if(!(Q>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(r=Q,!A.paused)for(;i&&o<r;)o++,C()},running:c,resume:g,idle:p,length:l,getQueue:d,unshift:m,empty:gs,kill:I,killAndDrain:y,error:E,abort:B};return A;function c(){return o}function u(){A.paused=!0}function l(){for(var Q=i,v=0;Q;)Q=Q.next,v++;return v}function d(){for(var Q=i,v=[];Q;)v.push(Q.value),Q=Q.next;return v}function g(){if(A.paused){if(A.paused=!1,i===null){o++,C();return}for(;i&&o<r;)o++,C()}}function p(){return o===0&&A.length()===0}function f(Q,v){var D=n.get();D.context=t,D.release=C,D.value=Q,D.callback=v||gs,D.errorHandler=a,o>=r||A.paused?s?(s.next=D,s=D):(i=D,s=D,A.saturated()):(o++,e.call(t,D.value,D.worked))}function m(Q,v){var D=n.get();D.context=t,D.release=C,D.value=Q,D.callback=v||gs,D.errorHandler=a,o>=r||A.paused?i?(D.next=i,i=D):(i=D,s=D,A.saturated()):(o++,e.call(t,D.value,D.worked))}function C(Q){Q&&n.release(Q);var v=i;v&&o<=r?A.paused?o--:(s===i&&(s=null),i=v.next,v.next=null,e.call(t,v.value,v.worked),s===null&&A.empty()):--o===0&&A.drain()}function I(){i=null,s=null,A.drain=gs}function y(){i=null,s=null,A.drain(),A.drain=gs}function B(){var Q=i;for(i=null,s=null;Q;){var v=Q.next,D=Q.callback,S=Q.errorHandler,b=Q.value,x=Q.context;Q.value=null,Q.callback=gs,Q.errorHandler=null,S&&S(new Error("abort"),b),D.call(x,new Error("abort")),Q.release(Q),Q=v}A.drain=gs}function E(Q){a=Q}}function gs(){}function nJe(){this.value=null,this.callback=gs,this.next=null,this.release=gs,this.context=null,this.errorHandler=null;var t=this;this.worked=function(r,n){var i=t.callback,s=t.errorHandler,o=t.value;t.value=null,t.callback=gs,t.errorHandler&&s(r,o),i.call(t.context,r,n),t.release(t)}}function iJe(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(u,l){e.call(this,u).then(function(d){l(null,d)},l)}var i=tre(t,n,r),s=i.push,o=i.unshift;return i.push=a,i.unshift=A,i.drained=c,i;function a(u){var l=new Promise(function(d,g){s(u,function(p,f){if(p){g(p);return}d(f)})});return l.catch(gs),l}function A(u){var l=new Promise(function(d,g){o(u,function(p,f){if(p){g(p);return}d(f)})});return l.catch(gs),l}function c(){var u=new Promise(function(l){process.nextTick(function(){if(i.idle())l();else{var d=i.drain;i.drain=function(){typeof d=="function"&&d(),l(),i.drain=d}}})});return u}}r1.exports=tre;r1.exports.promise=iJe});var Lw=N(fA=>{"use strict";h();Object.defineProperty(fA,"__esModule",{value:!0});fA.joinPathSegments=fA.replacePathSegmentSeparator=fA.isAppliedFilter=fA.isFatalError=void 0;function sJe(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}fA.isFatalError=sJe;function oJe(t,e){return t===null||t(e)}fA.isAppliedFilter=oJe;function aJe(t,e){return t.split(/[/\\]/).join(e)}fA.replacePathSegmentSeparator=aJe;function AJe(t,e,r){return t===""?e:t.endsWith(r)?t+e:t+r+e}fA.joinPathSegments=AJe});var s1=N(i1=>{"use strict";h();Object.defineProperty(i1,"__esModule",{value:!0});var cJe=Lw(),n1=class{constructor(e,r){this._root=e,this._settings=r,this._root=cJe.replacePathSegmentSeparator(e,r.pathSegmentSeparator)}};i1.default=n1});var A1=N(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});var uJe=require("events"),lJe=Pw(),gJe=rre(),_w=Lw(),pJe=s1(),o1=class extends pJe.default{constructor(e,r){super(e,r),this._settings=r,this._scandir=lJe.scandir,this._emitter=new uJe.EventEmitter,this._queue=gJe(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit("end")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw new Error("The reader is already destroyed");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on("entry",e)}onError(e){this._emitter.once("error",e)}onEnd(e){this._emitter.once("end",e)}_pushToQueue(e,r){let n={directory:e,base:r};this._queue.push(n,i=>{i!==null&&this._handleError(i)})}_worker(e,r){this._scandir(e.directory,this._settings.fsScandirSettings,(n,i)=>{if(n!==null){r(n,void 0);return}for(let s of i)this._handleEntry(s,e.base);r(null,void 0)})}_handleError(e){this._isDestroyed||!_w.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit("error",e))}_handleEntry(e,r){if(this._isDestroyed||this._isFatalError)return;let n=e.path;r!==void 0&&(e.path=_w.joinPathSegments(r,e.name,this._settings.pathSegmentSeparator)),_w.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&_w.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(n,r===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};a1.default=o1});var nre=N(u1=>{"use strict";h();Object.defineProperty(u1,"__esModule",{value:!0});var dJe=A1(),c1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new dJe.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(r=>{fJe(e,r)}),this._reader.onEntry(r=>{this._storage.push(r)}),this._reader.onEnd(()=>{hJe(e,this._storage)}),this._reader.read()}};u1.default=c1;function fJe(t,e){t(e)}function hJe(t,e){t(null,e)}});var ire=N(g1=>{"use strict";h();Object.defineProperty(g1,"__esModule",{value:!0});var mJe=require("stream"),CJe=A1(),l1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new CJe.default(this._root,this._settings),this._stream=new mJe.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit("error",e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}};g1.default=l1});var sre=N(d1=>{"use strict";h();Object.defineProperty(d1,"__esModule",{value:!0});var IJe=Pw(),Uw=Lw(),EJe=s1(),p1=class extends EJe.default{constructor(){super(...arguments),this._scandir=IJe.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,r){this._queue.add({directory:e,base:r})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,r){try{let n=this._scandir(e,this._settings.fsScandirSettings);for(let i of n)this._handleEntry(i,r)}catch(n){this._handleError(n)}}_handleError(e){if(Uw.isFatalError(this._settings,e))throw e}_handleEntry(e,r){let n=e.path;r!==void 0&&(e.path=Uw.joinPathSegments(r,e.name,this._settings.pathSegmentSeparator)),Uw.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&Uw.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(n,r===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};d1.default=p1});var ore=N(h1=>{"use strict";h();Object.defineProperty(h1,"__esModule",{value:!0});var BJe=sre(),f1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new BJe.default(this._root,this._settings)}read(){return this._reader.read()}};h1.default=f1});var are=N(C1=>{"use strict";h();Object.defineProperty(C1,"__esModule",{value:!0});var yJe=require("path"),QJe=Pw(),m1=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,yJe.sep),this.fsScandirSettings=new QJe.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,r){return e??r}};C1.default=m1});var Ow=N(hA=>{"use strict";h();Object.defineProperty(hA,"__esModule",{value:!0});hA.Settings=hA.walkStream=hA.walkSync=hA.walk=void 0;var Are=nre(),DJe=ire(),wJe=ore(),I1=are();hA.Settings=I1.default;function bJe(t,e,r){if(typeof e=="function"){new Are.default(t,Gw()).read(e);return}new Are.default(t,Gw(e)).read(r)}hA.walk=bJe;function vJe(t,e){let r=Gw(e);return new wJe.default(t,r).read()}hA.walkSync=vJe;function SJe(t,e){let r=Gw(e);return new DJe.default(t,r).read()}hA.walkStream=SJe;function Gw(t={}){return t instanceof I1.default?t:new I1.default(t)}});var Kw=N(B1=>{"use strict";h();Object.defineProperty(B1,"__esModule",{value:!0});var xJe=require("path"),FJe=Mg(),cre=hc(),E1=class{constructor(e){this._settings=e,this._fsStatSettings=new FJe.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return xJe.resolve(this._settings.cwd,e)}_makeEntry(e,r){let n={name:r,path:r,dirent:cre.fs.createDirentFromStats(r,e)};return this._settings.stats&&(n.stats=e),n}_isFatalError(e){return!cre.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};B1.default=E1});var D1=N(Q1=>{"use strict";h();Object.defineProperty(Q1,"__esModule",{value:!0});var kJe=require("stream"),RJe=Mg(),TJe=Ow(),NJe=Kw(),y1=class extends NJe.default{constructor(){super(...arguments),this._walkStream=TJe.walkStream,this._stat=RJe.stat}dynamic(e,r){return this._walkStream(e,r)}static(e,r){let n=e.map(this._getFullEntryPath,this),i=new kJe.PassThrough({objectMode:!0});i._write=(s,o,a)=>this._getEntry(n[s],e[s],r).then(A=>{A!==null&&r.entryFilter(A)&&i.push(A),s===n.length-1&&i.end(),a()}).catch(a);for(let s=0;s<n.length;s++)i.write(s);return i}_getEntry(e,r,n){return this._getStat(e).then(i=>this._makeEntry(i,r)).catch(i=>{if(n.errorFilter(i))return null;throw i})}_getStat(e){return new Promise((r,n)=>{this._stat(e,this._fsStatSettings,(i,s)=>i===null?r(s):n(i))})}};Q1.default=y1});var ure=N(b1=>{"use strict";h();Object.defineProperty(b1,"__esModule",{value:!0});var MJe=Ow(),PJe=Kw(),LJe=D1(),w1=class extends PJe.default{constructor(){super(...arguments),this._walkAsync=MJe.walk,this._readerStream=new LJe.default(this._settings)}dynamic(e,r){return new Promise((n,i)=>{this._walkAsync(e,r,(s,o)=>{s===null?n(o):i(s)})})}async static(e,r){let n=[],i=this._readerStream.static(e,r);return new Promise((s,o)=>{i.once("error",o),i.on("data",a=>n.push(a)),i.once("end",()=>s(n))})}};b1.default=w1});var lre=N(S1=>{"use strict";h();Object.defineProperty(S1,"__esModule",{value:!0});var sI=hc(),v1=class{constructor(e,r,n){this._patterns=e,this._settings=r,this._micromatchOptions=n,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let r=this._getPatternSegments(e),n=this._splitSegmentsIntoSections(r);this._storage.push({complete:n.length<=1,pattern:e,segments:r,sections:n})}}_getPatternSegments(e){return sI.pattern.getPatternParts(e,this._micromatchOptions).map(n=>sI.pattern.isDynamicPattern(n,this._settings)?{dynamic:!0,pattern:n,patternRe:sI.pattern.makeRe(n,this._micromatchOptions)}:{dynamic:!1,pattern:n})}_splitSegmentsIntoSections(e){return sI.array.splitWhen(e,r=>r.dynamic&&sI.pattern.hasGlobStar(r.pattern))}};S1.default=v1});var gre=N(F1=>{"use strict";h();Object.defineProperty(F1,"__esModule",{value:!0});var _Je=lre(),x1=class extends _Je.default{match(e){let r=e.split("/"),n=r.length,i=this._storage.filter(s=>!s.complete||s.segments.length>n);for(let s of i){let o=s.sections[0];if(!s.complete&&n>o.length||r.every((A,c)=>{let u=s.segments[c];return!!(u.dynamic&&u.patternRe.test(A)||!u.dynamic&&u.pattern===A)}))return!0}return!1}};F1.default=x1});var pre=N(R1=>{"use strict";h();Object.defineProperty(R1,"__esModule",{value:!0});var Hw=hc(),UJe=gre(),k1=class{constructor(e,r){this._settings=e,this._micromatchOptions=r}getFilter(e,r,n){let i=this._getMatcher(r),s=this._getNegativePatternsRe(n);return o=>this._filter(e,o,i,s)}_getMatcher(e){return new UJe.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let r=e.filter(Hw.pattern.isAffectDepthOfReadingPattern);return Hw.pattern.convertPatternsToRe(r,this._micromatchOptions)}_filter(e,r,n,i){if(this._isSkippedByDeep(e,r.path)||this._isSkippedSymbolicLink(r))return!1;let s=Hw.path.removeLeadingDotSegment(r.path);return this._isSkippedByPositivePatterns(s,n)?!1:this._isSkippedByNegativePatterns(s,i)}_isSkippedByDeep(e,r){return this._settings.deep===1/0?!1:this._getEntryLevel(e,r)>=this._settings.deep}_getEntryLevel(e,r){let n=r.split("/").length;if(e==="")return n;let i=e.split("/").length;return n-i}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,r){return!this._settings.baseNameMatch&&!r.match(e)}_isSkippedByNegativePatterns(e,r){return!Hw.pattern.matchAny(e,r)}};R1.default=k1});var dre=N(N1=>{"use strict";h();Object.defineProperty(N1,"__esModule",{value:!0});var Gu=hc(),T1=class{constructor(e,r){this._settings=e,this._micromatchOptions=r,this.index=new Map}getFilter(e,r){let[n,i]=Gu.pattern.partitionAbsoluteAndRelative(r),s={positive:{all:Gu.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:Gu.pattern.convertPatternsToRe(n,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:Gu.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return o=>this._filter(o,s)}_filter(e,r){let n=Gu.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(n)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let i=this._isMatchToPatternsSet(n,r,e.dirent.isDirectory());return this._settings.unique&&i&&this._createIndexRecord(n),i}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isMatchToPatternsSet(e,r,n){return!(!this._isMatchToPatterns(e,r.positive.all,n)||this._isMatchToPatterns(e,r.negative.relative,n)||this._isMatchToAbsoluteNegative(e,r.negative.absolute,n))}_isMatchToAbsoluteNegative(e,r,n){if(r.length===0)return!1;let i=Gu.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,r,n)}_isMatchToPatterns(e,r,n){if(r.length===0)return!1;let i=Gu.pattern.matchAny(e,r);return!i&&n?Gu.pattern.matchAny(e+"/",r):i}};N1.default=T1});var fre=N(P1=>{"use strict";h();Object.defineProperty(P1,"__esModule",{value:!0});var GJe=hc(),M1=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return GJe.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};P1.default=M1});var mre=N(_1=>{"use strict";h();Object.defineProperty(_1,"__esModule",{value:!0});var hre=hc(),L1=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let r=e.path;return this._settings.absolute&&(r=hre.path.makeAbsolute(this._settings.cwd,r),r=hre.path.unixify(r)),this._settings.markDirectories&&e.dirent.isDirectory()&&(r+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:r}):r}};_1.default=L1});var Jw=N(G1=>{"use strict";h();Object.defineProperty(G1,"__esModule",{value:!0});var OJe=require("path"),KJe=pre(),HJe=dre(),JJe=fre(),jJe=mre(),U1=class{constructor(e){this._settings=e,this.errorFilter=new JJe.default(this._settings),this.entryFilter=new HJe.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new KJe.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new jJe.default(this._settings)}_getRootDirectory(e){return OJe.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let r=e.base==="."?"":e.base;return{basePath:r,pathSegmentSeparator:"/",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(r,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}};G1.default=U1});var Cre=N(K1=>{"use strict";h();Object.defineProperty(K1,"__esModule",{value:!0});var YJe=ure(),qJe=Jw(),O1=class extends qJe.default{constructor(){super(...arguments),this._reader=new YJe.default(this._settings)}async read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e);return(await this.api(r,e,n)).map(s=>n.transform(s))}api(e,r,n){return r.dynamic?this._reader.dynamic(e,n):this._reader.static(r.patterns,n)}};K1.default=O1});var Ire=N(J1=>{"use strict";h();Object.defineProperty(J1,"__esModule",{value:!0});var $Je=require("stream"),VJe=D1(),WJe=Jw(),H1=class extends WJe.default{constructor(){super(...arguments),this._reader=new VJe.default(this._settings)}read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e),i=this.api(r,e,n),s=new $Je.Readable({objectMode:!0,read:()=>{}});return i.once("error",o=>s.emit("error",o)).on("data",o=>s.emit("data",n.transform(o))).once("end",()=>s.emit("end")),s.once("close",()=>i.destroy()),s}api(e,r,n){return r.dynamic?this._reader.dynamic(e,n):this._reader.static(r.patterns,n)}};J1.default=H1});var Ere=N(Y1=>{"use strict";h();Object.defineProperty(Y1,"__esModule",{value:!0});var zJe=Mg(),XJe=Ow(),ZJe=Kw(),j1=class extends ZJe.default{constructor(){super(...arguments),this._walkSync=XJe.walkSync,this._statSync=zJe.statSync}dynamic(e,r){return this._walkSync(e,r)}static(e,r){let n=[];for(let i of e){let s=this._getFullEntryPath(i),o=this._getEntry(s,i,r);o===null||!r.entryFilter(o)||n.push(o)}return n}_getEntry(e,r,n){try{let i=this._getStat(e);return this._makeEntry(i,r)}catch(i){if(n.errorFilter(i))return null;throw i}}_getStat(e){return this._statSync(e,this._fsStatSettings)}};Y1.default=j1});var Bre=N($1=>{"use strict";h();Object.defineProperty($1,"__esModule",{value:!0});var eje=Ere(),tje=Jw(),q1=class extends tje.default{constructor(){super(...arguments),this._reader=new eje.default(this._settings)}read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e);return this.api(r,e,n).map(n.transform)}api(e,r,n){return r.dynamic?this._reader.dynamic(e,n):this._reader.static(r.patterns,n)}};$1.default=q1});var yre=N(df=>{"use strict";h();Object.defineProperty(df,"__esModule",{value:!0});df.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var pf=require("fs"),rje=require("os"),nje=Math.max(rje.cpus().length,1);df.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:pf.lstat,lstatSync:pf.lstatSync,stat:pf.stat,statSync:pf.statSync,readdir:pf.readdir,readdirSync:pf.readdirSync};var V1=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,nje),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,r){return e===void 0?r:e}_getFileSystemMethods(e={}){return Object.assign(Object.assign({},df.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};df.default=V1});var Z1=N((nKt,Dre)=>{"use strict";h();var Qre=Dte(),ije=Cre(),sje=Ire(),oje=Bre(),W1=yre(),po=hc();async function z1(t,e){ga(t);let r=X1(t,ije.default,e),n=await Promise.all(r);return po.array.flatten(n)}(function(t){t.glob=t,t.globSync=e,t.globStream=r,t.async=t;function e(c,u){ga(c);let l=X1(c,oje.default,u);return po.array.flatten(l)}t.sync=e;function r(c,u){ga(c);let l=X1(c,sje.default,u);return po.stream.merge(l)}t.stream=r;function n(c,u){ga(c);let l=[].concat(c),d=new W1.default(u);return Qre.generate(l,d)}t.generateTasks=n;function i(c,u){ga(c);let l=new W1.default(u);return po.pattern.isDynamicPattern(c,l)}t.isDynamicPattern=i;function s(c){return ga(c),po.path.escape(c)}t.escapePath=s;function o(c){return ga(c),po.path.convertPathToPattern(c)}t.convertPathToPattern=o;let a;(function(c){function u(d){return ga(d),po.path.escapePosixPath(d)}c.escapePath=u;function l(d){return ga(d),po.path.convertPosixPathToPattern(d)}c.convertPathToPattern=l})(a=t.posix||(t.posix={}));let A;(function(c){function u(d){return ga(d),po.path.escapeWindowsPath(d)}c.escapePath=u;function l(d){return ga(d),po.path.convertWindowsPathToPattern(d)}c.convertPathToPattern=l})(A=t.win32||(t.win32={}))})(z1||(z1={}));function X1(t,e,r){let n=[].concat(t),i=new W1.default(r),s=Qre.generate(n,i),o=new e(i);return s.map(o.read,o)}function ga(t){if(![].concat(t).every(n=>po.string.isString(n)&&!po.string.isEmpty(n)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}Dre.exports=z1});async function eL(t,e,r){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);try{return(await bre.default[t](r))[e]()}catch(n){if(n.code==="ENOENT")return!1;throw n}}function tL(t,e,r){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);try{return wre.default[t](r)[e]()}catch(n){if(n.code==="ENOENT")return!1;throw n}}var wre,bre,sKt,vre,oKt,aKt,Sre,AKt,xre=L(()=>{h();wre=z(require("node:fs"),1),bre=z(require("node:fs/promises"),1);sKt=eL.bind(void 0,"stat","isFile"),vre=eL.bind(void 0,"stat","isDirectory"),oKt=eL.bind(void 0,"lstat","isSymbolicLink"),aKt=tL.bind(void 0,"statSync","isFile"),Sre=tL.bind(void 0,"statSync","isDirectory"),AKt=tL.bind(void 0,"lstatSync","isSymbolicLink")});var Fre=L(()=>{h()});function mc(t){return t instanceof URL?(0,Rre.fileURLToPath)(t):t}function Tre(t){return{*[Symbol.iterator](){let e=rL.default.resolve(mc(t)),r;for(;r!==e;)yield e,r=e,e=rL.default.resolve(e,"..")}}}var kre,nL,rL,Rre,pKt,dKt,jw=L(()=>{h();kre=require("node:util"),nL=require("node:child_process"),rL=z(require("node:path"),1),Rre=require("node:url");Fre();pKt=(0,kre.promisify)(nL.execFile);dKt=10*1024*1024});function ff(t){return t.startsWith("\\\\?\\")?t:t.replace(/\\/g,"/")}var Nre=L(()=>{h()});var oI,iL=L(()=>{h();oI=t=>t[0]==="!"});var Mre,Pre,Lre,Pg,sL,_re,aje,Ure,Gre,Aje,cje,uje,Ore,Kre,Hre,Jre,jre=L(()=>{h();Mre=z(require("node:process"),1),Pre=z(require("node:fs"),1),Lre=z(require("node:fs/promises"),1),Pg=z(require("node:path"),1),sL=z(Z1(),1),_re=z(require("ignore"),1);Nre();jw();iL();aje=["**/node_modules","**/flow-typed","**/coverage","**/.git"],Ure={absolute:!0,dot:!0},Gre="**/.gitignore",Aje=(t,e)=>oI(t)?"!"+Pg.default.posix.join(e,t.slice(1)):Pg.default.posix.join(e,t),cje=(t,e)=>{let r=ff(Pg.default.relative(e,Pg.default.dirname(t.filePath)));return t.content.split(/\r?\n/).filter(n=>n&&!n.startsWith("#")).map(n=>Aje(n,r))},uje=(t,e)=>{if(e=ff(e),Pg.default.isAbsolute(t)){if(ff(t).startsWith(e))return Pg.default.relative(e,t);throw new Error(`Path ${t} is not in cwd ${e}`)}return t},Ore=(t,e)=>{let r=t.flatMap(i=>cje(i,e)),n=(0,_re.default)().add(r);return i=>(i=mc(i),i=uje(i,e),i?n.ignores(ff(i)):!1)},Kre=(t={})=>({cwd:mc(t.cwd)??Mre.default.cwd(),suppressErrors:!!t.suppressErrors,deep:typeof t.deep=="number"?t.deep:Number.POSITIVE_INFINITY,ignore:[...t.ignore??[],...aje]}),Hre=async(t,e)=>{let{cwd:r,suppressErrors:n,deep:i,ignore:s}=Kre(e),o=await(0,sL.default)(t,{cwd:r,suppressErrors:n,deep:i,ignore:s,...Ure}),a=await Promise.all(o.map(async A=>({filePath:A,content:await Lre.default.readFile(A,"utf8")})));return Ore(a,r)},Jre=(t,e)=>{let{cwd:r,suppressErrors:n,deep:i,ignore:s}=Kre(e),a=sL.default.sync(t,{cwd:r,suppressErrors:n,deep:i,ignore:s,...Ure}).map(A=>({filePath:A,content:Pre.default.readFileSync(A,"utf8")}));return Ore(a,r)}});var oL,$re,Lg,hf,lje,Vre,Wre,Yre,qre,aL,gje,zre,Xre,Yw,Zre,pje,ene,tne,rne,nne,ine,sne,AL,qw,RKt,TKt,NKt,MKt,PKt,LKt,one=L(()=>{h();oL=z(require("node:process"),1),$re=z(require("node:fs"),1),Lg=z(require("node:path"),1);PZ();hf=z(Z1(),1);xre();jw();jre();iL();lje=t=>{if(t.some(e=>typeof e!="string"))throw new TypeError("Patterns must be a string or an array of strings")},Vre=(t,e)=>{let r=oI(t)?t.slice(1):t;return Lg.default.isAbsolute(r)?r:Lg.default.join(e,r)},Wre=({directoryPath:t,files:e,extensions:r})=>{let n=r?.length>0?`.${r.length>1?`{${r.join(",")}}`:r[0]}`:"";return e?e.map(i=>Lg.default.posix.join(t,`**/${Lg.default.extname(i)?i:`${i}${n}`}`)):[Lg.default.posix.join(t,`**${n?`/*${n}`:""}`)]},Yre=async(t,{cwd:e=oL.default.cwd(),files:r,extensions:n}={})=>(await Promise.all(t.map(async s=>await vre(Vre(s,e))?Wre({directoryPath:s,files:r,extensions:n}):s))).flat(),qre=(t,{cwd:e=oL.default.cwd(),files:r,extensions:n}={})=>t.flatMap(i=>Sre(Vre(i,e))?Wre({directoryPath:i,files:r,extensions:n}):i),aL=t=>(t=[...new Set([t].flat())],lje(t),t),gje=t=>{if(!t)return;let e;try{e=$re.default.statSync(t)}catch{return}if(!e.isDirectory())throw new Error("The `cwd` option must be a path to a directory")},zre=(t={})=>(t={...t,ignore:t.ignore??[],expandDirectories:t.expandDirectories??!0,cwd:mc(t.cwd)},gje(t.cwd),t),Xre=t=>async(e,r)=>t(aL(e),zre(r)),Yw=t=>(e,r)=>t(aL(e),zre(r)),Zre=t=>{let{ignoreFiles:e,gitignore:r}=t,n=e?aL(e):[];return r&&n.push(Gre),n},pje=async t=>{let e=Zre(t);return tne(e.length>0&&await Hre(e,t))},ene=t=>{let e=Zre(t);return tne(e.length>0&&Jre(e,t))},tne=t=>{let e=new Set;return r=>{let n=Lg.default.normalize(r.path??r);return e.has(n)||t&&t(n)?!1:(e.add(n),!0)}},rne=(t,e)=>t.flat().filter(r=>e(r)),nne=(t,e)=>{let r=[];for(;t.length>0;){let n=t.findIndex(s=>oI(s));if(n===-1){r.push({patterns:t,options:e});break}let i=t[n].slice(1);for(let s of r)s.options.ignore.push(i);n!==0&&r.push({patterns:t.slice(0,n),options:{...e,ignore:[...e.ignore,i]}}),t=t.slice(n+1)}return r},ine=(t,e)=>({...e?{cwd:e}:{},...Array.isArray(t)?{files:t}:t}),sne=async(t,e)=>{let r=nne(t,e),{cwd:n,expandDirectories:i}=e;if(!i)return r;let s=ine(i,n);return Promise.all(r.map(async o=>{let{patterns:a,options:A}=o;return[a,A.ignore]=await Promise.all([Yre(a,s),Yre(A.ignore,{cwd:n})]),{patterns:a,options:A}}))},AL=(t,e)=>{let r=nne(t,e),{cwd:n,expandDirectories:i}=e;if(!i)return r;let s=ine(i,n);return r.map(o=>{let{patterns:a,options:A}=o;return a=qre(a,s),A.ignore=qre(A.ignore,{cwd:n}),{patterns:a,options:A}})},qw=Xre(async(t,e)=>{let[r,n]=await Promise.all([sne(t,e),pje(e)]),i=await Promise.all(r.map(s=>(0,hf.default)(s.patterns,s.options)));return rne(i,n)}),RKt=Yw((t,e)=>{let r=AL(t,e),n=ene(e),i=r.map(s=>hf.default.sync(s.patterns,s.options));return rne(i,n)}),TKt=Yw((t,e)=>{let r=AL(t,e),n=ene(e),i=r.map(o=>hf.default.stream(o.patterns,o.options));return fP(i).filter(o=>n(o))}),NKt=Yw((t,e)=>t.some(r=>hf.default.isDynamicPattern(r,e))),MKt=Xre(sne),PKt=Yw(AL),{convertPathToPattern:LKt}=hf.default});function mf(t){let e=Date.now();return new Promise((r,n)=>{let s=dje(t.url)({protocol:t.url.protocol,host:t.url.host,port:t.url.port,path:t.url.pathname+t.url.search,method:t.method,headers:t.headers},o=>{let a="";o.on("data",A=>{a+=A}),o.on("end",()=>{if((0,ane.debug)(`${t.method} ${t.url.href}, duration: ${Date.now()-e}ms`),typeof o.statusCode=="number"&&o.statusCode>=200&&o.statusCode<300)if(typeof o.headers["content-type"]!="string"||!o.headers["content-type"].includes("application/json"))n(`Response from ${t.url.href} content-type is ${o.headers["content-type"]}`);else try{r(JSON.parse(a))}catch(A){n(`Response from ${t.url.href} is not valid JSON: ${a}
|
|
1260
|
+
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var xee=N((zOt,See)=>{"use strict";h();var jKe=Cw(),{MAX_LENGTH:wee,CHAR_BACKSLASH:DP,CHAR_BACKTICK:YKe,CHAR_COMMA:qKe,CHAR_DOT:$Ke,CHAR_LEFT_PARENTHESES:VKe,CHAR_RIGHT_PARENTHESES:WKe,CHAR_LEFT_CURLY_BRACE:zKe,CHAR_RIGHT_CURLY_BRACE:XKe,CHAR_LEFT_SQUARE_BRACKET:bee,CHAR_RIGHT_SQUARE_BRACKET:vee,CHAR_DOUBLE_QUOTE:ZKe,CHAR_SINGLE_QUOTE:e4e,CHAR_NO_BREAK_SPACE:t4e,CHAR_ZERO_WIDTH_NOBREAK_SPACE:r4e}=Dee(),n4e=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let r=e||{},n=typeof r.maxLength=="number"?Math.min(wee,r.maxLength):wee;if(t.length>n)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${n})`);let i={type:"root",input:t,nodes:[]},s=[i],o=i,a=i,A=0,c=t.length,u=0,l=0,d,g=()=>t[u++],p=f=>{if(f.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&f.type==="text"){a.value+=f.value;return}return o.nodes.push(f),f.parent=o,f.prev=a,a=f,f};for(p({type:"bos"});u<c;)if(o=s[s.length-1],d=g(),!(d===r4e||d===t4e)){if(d===DP){p({type:"text",value:(e.keepEscaping?d:"")+g()});continue}if(d===vee){p({type:"text",value:"\\"+d});continue}if(d===bee){A++;let f;for(;u<c&&(f=g());){if(d+=f,f===bee){A++;continue}if(f===DP){d+=g();continue}if(f===vee&&(A--,A===0))break}p({type:"text",value:d});continue}if(d===VKe){o=p({type:"paren",nodes:[]}),s.push(o),p({type:"text",value:d});continue}if(d===WKe){if(o.type!=="paren"){p({type:"text",value:d});continue}o=s.pop(),p({type:"text",value:d}),o=s[s.length-1];continue}if(d===ZKe||d===e4e||d===YKe){let f=d,m;for(e.keepQuotes!==!0&&(d="");u<c&&(m=g());){if(m===DP){d+=m+g();continue}if(m===f){e.keepQuotes===!0&&(d+=m);break}d+=m}p({type:"text",value:d});continue}if(d===zKe){l++;let m={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:l,commas:0,ranges:0,nodes:[]};o=p(m),s.push(o),p({type:"open",value:d});continue}if(d===XKe){if(o.type!=="brace"){p({type:"text",value:d});continue}let f="close";o=s.pop(),o.close=!0,p({type:f,value:d}),l--,o=s[s.length-1];continue}if(d===qKe&&l>0){if(o.ranges>0){o.ranges=0;let f=o.nodes.shift();o.nodes=[f,{type:"text",value:jKe(o)}]}p({type:"comma",value:d}),o.commas++;continue}if(d===$Ke&&l>0&&o.commas===0){let f=o.nodes;if(l===0||f.length===0){p({type:"text",value:d});continue}if(a.type==="dot"){if(o.range=[],a.value+=d,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){f.pop();let m=f[f.length-1];m.value+=a.value+d,a=m,o.ranges--;continue}p({type:"dot",value:d});continue}p({type:"text",value:d})}do if(o=s.pop(),o.type!=="root"){o.nodes.forEach(C=>{C.nodes||(C.type==="open"&&(C.isOpen=!0),C.type==="close"&&(C.isClose=!0),C.nodes||(C.type="text"),C.invalid=!0)});let f=s[s.length-1],m=f.nodes.indexOf(o);f.nodes.splice(m,1,...o.nodes)}while(s.length>0);return p({type:"eos"}),i};See.exports=n4e});var Ree=N((ZOt,kee)=>{"use strict";h();var Fee=Cw(),i4e=Iee(),s4e=yee(),o4e=xee(),Us=(t,e={})=>{let r=[];if(Array.isArray(t))for(let n of t){let i=Us.create(n,e);Array.isArray(i)?r.push(...i):r.push(i)}else r=[].concat(Us.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(r=[...new Set(r)]),r};Us.parse=(t,e={})=>o4e(t,e);Us.stringify=(t,e={})=>Fee(typeof t=="string"?Us.parse(t,e):t,e);Us.compile=(t,e={})=>(typeof t=="string"&&(t=Us.parse(t,e)),i4e(t,e));Us.expand=(t,e={})=>{typeof t=="string"&&(t=Us.parse(t,e));let r=s4e(t,e);return e.noempty===!0&&(r=r.filter(Boolean)),e.nodupes===!0&&(r=[...new Set(r)]),r};Us.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Us.compile(t,e):Us.expand(t,e);kee.exports=Us});var rI=N((t8t,Lee)=>{"use strict";h();var a4e=require("path"),pA="\\\\/",Tee=`[^${pA}]`,fc="\\.",A4e="\\+",c4e="\\?",Bw="\\/",u4e="(?=.)",Nee="[^/]",wP=`(?:${Bw}|$)`,Mee=`(?:^|${Bw})`,bP=`${fc}{1,2}${wP}`,l4e=`(?!${fc})`,g4e=`(?!${Mee}${bP})`,p4e=`(?!${fc}{0,1}${wP})`,d4e=`(?!${bP})`,f4e=`[^.${Bw}]`,h4e=`${Nee}*?`,Pee={DOT_LITERAL:fc,PLUS_LITERAL:A4e,QMARK_LITERAL:c4e,SLASH_LITERAL:Bw,ONE_CHAR:u4e,QMARK:Nee,END_ANCHOR:wP,DOTS_SLASH:bP,NO_DOT:l4e,NO_DOTS:g4e,NO_DOT_SLASH:p4e,NO_DOTS_SLASH:d4e,QMARK_NO_DOT:f4e,STAR:h4e,START_ANCHOR:Mee},m4e={...Pee,SLASH_LITERAL:`[${pA}]`,QMARK:Tee,STAR:`${Tee}*?`,DOTS_SLASH:`${fc}{1,2}(?:[${pA}]|$)`,NO_DOT:`(?!${fc})`,NO_DOTS:`(?!(?:^|[${pA}])${fc}{1,2}(?:[${pA}]|$))`,NO_DOT_SLASH:`(?!${fc}{0,1}(?:[${pA}]|$))`,NO_DOTS_SLASH:`(?!${fc}{1,2}(?:[${pA}]|$))`,QMARK_NO_DOT:`[^.${pA}]`,START_ANCHOR:`(?:^|[${pA}])`,END_ANCHOR:`(?:[${pA}]|$)`},C4e={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Lee.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:C4e,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:a4e.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?m4e:Pee}}});var nI=N(ls=>{"use strict";h();var I4e=require("path"),E4e=process.platform==="win32",{REGEX_BACKSLASH:B4e,REGEX_REMOVE_BACKSLASH:y4e,REGEX_SPECIAL_CHARS:Q4e,REGEX_SPECIAL_CHARS_GLOBAL:D4e}=rI();ls.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);ls.hasRegexChars=t=>Q4e.test(t);ls.isRegexChar=t=>t.length===1&&ls.hasRegexChars(t);ls.escapeRegex=t=>t.replace(D4e,"\\$1");ls.toPosixSlashes=t=>t.replace(B4e,"/");ls.removeBackslashes=t=>t.replace(y4e,e=>e==="\\"?"":e);ls.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};ls.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:E4e===!0||I4e.sep==="\\";ls.escapeLast=(t,e,r)=>{let n=t.lastIndexOf(e,r);return n===-1?t:t[n-1]==="\\"?ls.escapeLast(t,e,n-1):`${t.slice(0,n)}\\${t.slice(n)}`};ls.removePrefix=(t,e={})=>{let r=t;return r.startsWith("./")&&(r=r.slice(2),e.prefix="./"),r};ls.wrapOutput=(t,e={},r={})=>{let n=r.contains?"":"^",i=r.contains?"":"$",s=`${n}(?:${t})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var jee=N((s8t,Jee)=>{"use strict";h();var _ee=nI(),{CHAR_ASTERISK:vP,CHAR_AT:w4e,CHAR_BACKWARD_SLASH:iI,CHAR_COMMA:b4e,CHAR_DOT:SP,CHAR_EXCLAMATION_MARK:xP,CHAR_FORWARD_SLASH:Hee,CHAR_LEFT_CURLY_BRACE:FP,CHAR_LEFT_PARENTHESES:kP,CHAR_LEFT_SQUARE_BRACKET:v4e,CHAR_PLUS:S4e,CHAR_QUESTION_MARK:Uee,CHAR_RIGHT_CURLY_BRACE:x4e,CHAR_RIGHT_PARENTHESES:Gee,CHAR_RIGHT_SQUARE_BRACKET:F4e}=rI(),Oee=t=>t===Hee||t===iI,Kee=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},k4e=(t,e)=>{let r=e||{},n=t.length-1,i=r.parts===!0||r.scanToEnd===!0,s=[],o=[],a=[],A=t,c=-1,u=0,l=0,d=!1,g=!1,p=!1,f=!1,m=!1,C=!1,I=!1,y=!1,B=!1,E=!1,Q=0,v,D,S={value:"",depth:0,isGlob:!1},b=()=>c>=n,x=()=>A.charCodeAt(c+1),P=()=>(v=D,A.charCodeAt(++c));for(;c<n;){D=P();let j;if(D===iI){I=S.backslashes=!0,D=P(),D===FP&&(C=!0);continue}if(C===!0||D===FP){for(Q++;b()!==!0&&(D=P());){if(D===iI){I=S.backslashes=!0,P();continue}if(D===FP){Q++;continue}if(C!==!0&&D===SP&&(D=P())===SP){if(d=S.isBrace=!0,p=S.isGlob=!0,E=!0,i===!0)continue;break}if(C!==!0&&D===b4e){if(d=S.isBrace=!0,p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===x4e&&(Q--,Q===0)){C=!1,d=S.isBrace=!0,E=!0;break}}if(i===!0)continue;break}if(D===Hee){if(s.push(c),o.push(S),S={value:"",depth:0,isGlob:!1},E===!0)continue;if(v===SP&&c===u+1){u+=2;continue}l=c+1;continue}if(r.noext!==!0&&(D===S4e||D===w4e||D===vP||D===Uee||D===xP)===!0&&x()===kP){if(p=S.isGlob=!0,f=S.isExtglob=!0,E=!0,D===xP&&c===u&&(B=!0),i===!0){for(;b()!==!0&&(D=P());){if(D===iI){I=S.backslashes=!0,D=P();continue}if(D===Gee){p=S.isGlob=!0,E=!0;break}}continue}break}if(D===vP){if(v===vP&&(m=S.isGlobstar=!0),p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===Uee){if(p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===v4e){for(;b()!==!0&&(j=P());){if(j===iI){I=S.backslashes=!0,P();continue}if(j===F4e){g=S.isBracket=!0,p=S.isGlob=!0,E=!0;break}}if(i===!0)continue;break}if(r.nonegate!==!0&&D===xP&&c===u){y=S.negated=!0,u++;continue}if(r.noparen!==!0&&D===kP){if(p=S.isGlob=!0,i===!0){for(;b()!==!0&&(D=P());){if(D===kP){I=S.backslashes=!0,D=P();continue}if(D===Gee){E=!0;break}}continue}break}if(p===!0){if(E=!0,i===!0)continue;break}}r.noext===!0&&(f=!1,p=!1);let O=A,J="",_="";u>0&&(J=A.slice(0,u),A=A.slice(u),l-=u),O&&p===!0&&l>0?(O=A.slice(0,l),_=A.slice(l)):p===!0?(O="",_=A):O=A,O&&O!==""&&O!=="/"&&O!==A&&Oee(O.charCodeAt(O.length-1))&&(O=O.slice(0,-1)),r.unescape===!0&&(_&&(_=_ee.removeBackslashes(_)),O&&I===!0&&(O=_ee.removeBackslashes(O)));let K={prefix:J,input:t,start:u,base:O,glob:_,isBrace:d,isBracket:g,isGlob:p,isExtglob:f,isGlobstar:m,negated:y,negatedExtglob:B};if(r.tokens===!0&&(K.maxDepth=0,Oee(D)||o.push(S),K.tokens=o),r.parts===!0||r.tokens===!0){let j;for(let ee=0;ee<s.length;ee++){let U=j?j+1:u,Y=s[ee],H=t.slice(U,Y);r.tokens&&(ee===0&&u!==0?(o[ee].isPrefix=!0,o[ee].value=J):o[ee].value=H,Kee(o[ee]),K.maxDepth+=o[ee].depth),(ee!==0||H!=="")&&a.push(H),j=Y}if(j&&j+1<t.length){let ee=t.slice(j+1);a.push(ee),r.tokens&&(o[o.length-1].value=ee,Kee(o[o.length-1]),K.maxDepth+=o[o.length-1].depth)}K.slashes=s,K.parts=a}return K};Jee.exports=k4e});var $ee=N((a8t,qee)=>{"use strict";h();var yw=rI(),Gs=nI(),{MAX_LENGTH:Qw,POSIX_REGEX_SOURCE:R4e,REGEX_NON_SPECIAL_CHARS:T4e,REGEX_SPECIAL_CHARS_BACKREF:N4e,REPLACEMENTS:Yee}=yw,M4e=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let r=`[${t.join("-")}]`;try{new RegExp(r)}catch{return t.map(i=>Gs.escapeRegex(i)).join("..")}return r},uf=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,RP=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Yee[t]||t;let r={...e},n=typeof r.maxLength=="number"?Math.min(Qw,r.maxLength):Qw,i=t.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:r.prepend||""},o=[s],a=r.capture?"":"?:",A=Gs.isWindows(e),c=yw.globChars(A),u=yw.extglobChars(c),{DOT_LITERAL:l,PLUS_LITERAL:d,SLASH_LITERAL:g,ONE_CHAR:p,DOTS_SLASH:f,NO_DOT:m,NO_DOT_SLASH:C,NO_DOTS_SLASH:I,QMARK:y,QMARK_NO_DOT:B,STAR:E,START_ANCHOR:Q}=c,v=le=>`(${a}(?:(?!${Q}${le.dot?f:l}).)*?)`,D=r.dot?"":m,S=r.dot?y:B,b=r.bash===!0?v(r):E;r.capture&&(b=`(${b})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let x={input:t,index:-1,start:0,dot:r.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=Gs.removePrefix(t,x),i=t.length;let P=[],O=[],J=[],_=s,K,j=()=>x.index===i-1,ee=x.peek=(le=1)=>t[x.index+le],U=x.advance=()=>t[++x.index]||"",Y=()=>t.slice(x.index+1),H=(le="",be=0)=>{x.consumed+=le,x.index+=be},Z=le=>{x.output+=le.output!=null?le.output:le.value,H(le.value)},ue=()=>{let le=1;for(;ee()==="!"&&(ee(2)!=="("||ee(3)==="?");)U(),x.start++,le++;return le%2===0?!1:(x.negated=!0,x.start++,!0)},ge=le=>{x[le]++,J.push(le)},he=le=>{x[le]--,J.pop()},X=le=>{if(_.type==="globstar"){let be=x.braces>0&&(le.type==="comma"||le.type==="brace"),de=le.extglob===!0||P.length&&(le.type==="pipe"||le.type==="paren");le.type!=="slash"&&le.type!=="paren"&&!be&&!de&&(x.output=x.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=b,x.output+=_.output)}if(P.length&&le.type!=="paren"&&(P[P.length-1].inner+=le.value),(le.value||le.output)&&Z(le),_&&_.type==="text"&&le.type==="text"){_.value+=le.value,_.output=(_.output||"")+le.value;return}le.prev=_,o.push(le),_=le},we=(le,be)=>{let de={...u[be],conditions:1,inner:""};de.prev=_,de.parens=x.parens,de.output=x.output;let ke=(r.capture?"(":"")+de.open;ge("parens"),X({type:le,value:be,output:x.output?"":p}),X({type:"paren",extglob:!0,value:U(),output:ke}),P.push(de)},Je=le=>{let be=le.close+(r.capture?")":""),de;if(le.type==="negate"){let ke=b;if(le.inner&&le.inner.length>1&&le.inner.includes("/")&&(ke=v(r)),(ke!==b||j()||/^\)+$/.test(Y()))&&(be=le.close=`)$))${ke}`),le.inner.includes("*")&&(de=Y())&&/^\.[^\\/.]+$/.test(de)){let Qe=RP(de,{...e,fastpaths:!1}).output;be=le.close=`)${Qe})${ke})`}le.prev.type==="bos"&&(x.negatedExtglob=!0)}X({type:"paren",extglob:!0,value:K,output:be}),he("parens")};if(r.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let le=!1,be=t.replace(N4e,(de,ke,Qe,rt,nt,Ut)=>rt==="\\"?(le=!0,de):rt==="?"?ke?ke+rt+(nt?y.repeat(nt.length):""):Ut===0?S+(nt?y.repeat(nt.length):""):y.repeat(Qe.length):rt==="."?l.repeat(Qe.length):rt==="*"?ke?ke+rt+(nt?b:""):b:ke?de:`\\${de}`);return le===!0&&(r.unescape===!0?be=be.replace(/\\/g,""):be=be.replace(/\\+/g,de=>de.length%2===0?"\\\\":de?"\\":"")),be===t&&r.contains===!0?(x.output=t,x):(x.output=Gs.wrapOutput(be,x,e),x)}for(;!j();){if(K=U(),K==="\0")continue;if(K==="\\"){let de=ee();if(de==="/"&&r.bash!==!0||de==="."||de===";")continue;if(!de){K+="\\",X({type:"text",value:K});continue}let ke=/^\\+/.exec(Y()),Qe=0;if(ke&&ke[0].length>2&&(Qe=ke[0].length,x.index+=Qe,Qe%2!==0&&(K+="\\")),r.unescape===!0?K=U():K+=U(),x.brackets===0){X({type:"text",value:K});continue}}if(x.brackets>0&&(K!=="]"||_.value==="["||_.value==="[^")){if(r.posix!==!1&&K===":"){let de=_.value.slice(1);if(de.includes("[")&&(_.posix=!0,de.includes(":"))){let ke=_.value.lastIndexOf("["),Qe=_.value.slice(0,ke),rt=_.value.slice(ke+2),nt=R4e[rt];if(nt){_.value=Qe+nt,x.backtrack=!0,U(),!s.output&&o.indexOf(_)===1&&(s.output=p);continue}}}(K==="["&&ee()!==":"||K==="-"&&ee()==="]")&&(K=`\\${K}`),K==="]"&&(_.value==="["||_.value==="[^")&&(K=`\\${K}`),r.posix===!0&&K==="!"&&_.value==="["&&(K="^"),_.value+=K,Z({value:K});continue}if(x.quotes===1&&K!=='"'){K=Gs.escapeRegex(K),_.value+=K,Z({value:K});continue}if(K==='"'){x.quotes=x.quotes===1?0:1,r.keepQuotes===!0&&X({type:"text",value:K});continue}if(K==="("){ge("parens"),X({type:"paren",value:K});continue}if(K===")"){if(x.parens===0&&r.strictBrackets===!0)throw new SyntaxError(uf("opening","("));let de=P[P.length-1];if(de&&x.parens===de.parens+1){Je(P.pop());continue}X({type:"paren",value:K,output:x.parens?")":"\\)"}),he("parens");continue}if(K==="["){if(r.nobracket===!0||!Y().includes("]")){if(r.nobracket!==!0&&r.strictBrackets===!0)throw new SyntaxError(uf("closing","]"));K=`\\${K}`}else ge("brackets");X({type:"bracket",value:K});continue}if(K==="]"){if(r.nobracket===!0||_&&_.type==="bracket"&&_.value.length===1){X({type:"text",value:K,output:`\\${K}`});continue}if(x.brackets===0){if(r.strictBrackets===!0)throw new SyntaxError(uf("opening","["));X({type:"text",value:K,output:`\\${K}`});continue}he("brackets");let de=_.value.slice(1);if(_.posix!==!0&&de[0]==="^"&&!de.includes("/")&&(K=`/${K}`),_.value+=K,Z({value:K}),r.literalBrackets===!1||Gs.hasRegexChars(de))continue;let ke=Gs.escapeRegex(_.value);if(x.output=x.output.slice(0,-_.value.length),r.literalBrackets===!0){x.output+=ke,_.value=ke;continue}_.value=`(${a}${ke}|${_.value})`,x.output+=_.value;continue}if(K==="{"&&r.nobrace!==!0){ge("braces");let de={type:"brace",value:K,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};O.push(de),X(de);continue}if(K==="}"){let de=O[O.length-1];if(r.nobrace===!0||!de){X({type:"text",value:K,output:K});continue}let ke=")";if(de.dots===!0){let Qe=o.slice(),rt=[];for(let nt=Qe.length-1;nt>=0&&(o.pop(),Qe[nt].type!=="brace");nt--)Qe[nt].type!=="dots"&&rt.unshift(Qe[nt].value);ke=M4e(rt,r),x.backtrack=!0}if(de.comma!==!0&&de.dots!==!0){let Qe=x.output.slice(0,de.outputIndex),rt=x.tokens.slice(de.tokensIndex);de.value=de.output="\\{",K=ke="\\}",x.output=Qe;for(let nt of rt)x.output+=nt.output||nt.value}X({type:"brace",value:K,output:ke}),he("braces"),O.pop();continue}if(K==="|"){P.length>0&&P[P.length-1].conditions++,X({type:"text",value:K});continue}if(K===","){let de=K,ke=O[O.length-1];ke&&J[J.length-1]==="braces"&&(ke.comma=!0,de="|"),X({type:"comma",value:K,output:de});continue}if(K==="/"){if(_.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),_=s;continue}X({type:"slash",value:K,output:g});continue}if(K==="."){if(x.braces>0&&_.type==="dot"){_.value==="."&&(_.output=l);let de=O[O.length-1];_.type="dots",_.output+=K,_.value+=K,de.dots=!0;continue}if(x.braces+x.parens===0&&_.type!=="bos"&&_.type!=="slash"){X({type:"text",value:K,output:l});continue}X({type:"dot",value:K,output:l});continue}if(K==="?"){if(!(_&&_.value==="(")&&r.noextglob!==!0&&ee()==="("&&ee(2)!=="?"){we("qmark",K);continue}if(_&&_.type==="paren"){let ke=ee(),Qe=K;if(ke==="<"&&!Gs.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(_.value==="("&&!/[!=<:]/.test(ke)||ke==="<"&&!/<([!=]|\w+>)/.test(Y()))&&(Qe=`\\${K}`),X({type:"text",value:K,output:Qe});continue}if(r.dot!==!0&&(_.type==="slash"||_.type==="bos")){X({type:"qmark",value:K,output:B});continue}X({type:"qmark",value:K,output:y});continue}if(K==="!"){if(r.noextglob!==!0&&ee()==="("&&(ee(2)!=="?"||!/[!=<:]/.test(ee(3)))){we("negate",K);continue}if(r.nonegate!==!0&&x.index===0){ue();continue}}if(K==="+"){if(r.noextglob!==!0&&ee()==="("&&ee(2)!=="?"){we("plus",K);continue}if(_&&_.value==="("||r.regex===!1){X({type:"plus",value:K,output:d});continue}if(_&&(_.type==="bracket"||_.type==="paren"||_.type==="brace")||x.parens>0){X({type:"plus",value:K});continue}X({type:"plus",value:d});continue}if(K==="@"){if(r.noextglob!==!0&&ee()==="("&&ee(2)!=="?"){X({type:"at",extglob:!0,value:K,output:""});continue}X({type:"text",value:K});continue}if(K!=="*"){(K==="$"||K==="^")&&(K=`\\${K}`);let de=T4e.exec(Y());de&&(K+=de[0],x.index+=de[0].length),X({type:"text",value:K});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=K,_.output=b,x.backtrack=!0,x.globstar=!0,H(K);continue}let le=Y();if(r.noextglob!==!0&&/^\([^?]/.test(le)){we("star",K);continue}if(_.type==="star"){if(r.noglobstar===!0){H(K);continue}let de=_.prev,ke=de.prev,Qe=de.type==="slash"||de.type==="bos",rt=ke&&(ke.type==="star"||ke.type==="globstar");if(r.bash===!0&&(!Qe||le[0]&&le[0]!=="/")){X({type:"star",value:K,output:""});continue}let nt=x.braces>0&&(de.type==="comma"||de.type==="brace"),Ut=P.length&&(de.type==="pipe"||de.type==="paren");if(!Qe&&de.type!=="paren"&&!nt&&!Ut){X({type:"star",value:K,output:""});continue}for(;le.slice(0,3)==="/**";){let $r=t[x.index+4];if($r&&$r!=="/")break;le=le.slice(3),H("/**",3)}if(de.type==="bos"&&j()){_.type="globstar",_.value+=K,_.output=v(r),x.output=_.output,x.globstar=!0,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&!rt&&j()){x.output=x.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=v(r)+(r.strictSlashes?")":"|$)"),_.value+=K,x.globstar=!0,x.output+=de.output+_.output,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&le[0]==="/"){let $r=le[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=`${v(r)}${g}|${g}${$r})`,_.value+=K,x.output+=de.output+_.output,x.globstar=!0,H(K+U()),X({type:"slash",value:"/",output:""});continue}if(de.type==="bos"&&le[0]==="/"){_.type="globstar",_.value+=K,_.output=`(?:^|${g}|${v(r)}${g})`,x.output=_.output,x.globstar=!0,H(K+U()),X({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-_.output.length),_.type="globstar",_.output=v(r),_.value+=K,x.output+=_.output,x.globstar=!0,H(K);continue}let be={type:"star",value:K,output:b};if(r.bash===!0){be.output=".*?",(_.type==="bos"||_.type==="slash")&&(be.output=D+be.output),X(be);continue}if(_&&(_.type==="bracket"||_.type==="paren")&&r.regex===!0){be.output=K,X(be);continue}(x.index===x.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(x.output+=C,_.output+=C):r.dot===!0?(x.output+=I,_.output+=I):(x.output+=D,_.output+=D),ee()!=="*"&&(x.output+=p,_.output+=p)),X(be)}for(;x.brackets>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","]"));x.output=Gs.escapeLast(x.output,"["),he("brackets")}for(;x.parens>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing",")"));x.output=Gs.escapeLast(x.output,"("),he("parens")}for(;x.braces>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","}"));x.output=Gs.escapeLast(x.output,"{"),he("braces")}if(r.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${g}?`}),x.backtrack===!0){x.output="";for(let le of x.tokens)x.output+=le.output!=null?le.output:le.value,le.suffix&&(x.output+=le.suffix)}return x};RP.fastpaths=(t,e)=>{let r={...e},n=typeof r.maxLength=="number"?Math.min(Qw,r.maxLength):Qw,i=t.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);t=Yee[t]||t;let s=Gs.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:A,DOTS_SLASH:c,NO_DOT:u,NO_DOTS:l,NO_DOTS_SLASH:d,STAR:g,START_ANCHOR:p}=yw.globChars(s),f=r.dot?l:u,m=r.dot?d:u,C=r.capture?"":"?:",I={negated:!1,prefix:""},y=r.bash===!0?".*?":g;r.capture&&(y=`(${y})`);let B=D=>D.noglobstar===!0?y:`(${C}(?:(?!${p}${D.dot?c:o}).)*?)`,E=D=>{switch(D){case"*":return`${f}${A}${y}`;case".*":return`${o}${A}${y}`;case"*.*":return`${f}${y}${o}${A}${y}`;case"*/*":return`${f}${y}${a}${A}${m}${y}`;case"**":return f+B(r);case"**/*":return`(?:${f}${B(r)}${a})?${m}${A}${y}`;case"**/*.*":return`(?:${f}${B(r)}${a})?${m}${y}${o}${A}${y}`;case"**/.*":return`(?:${f}${B(r)}${a})?${o}${A}${y}`;default:{let S=/^(.*?)\.(\w+)$/.exec(D);if(!S)return;let b=E(S[1]);return b?b+o+S[2]:void 0}}},Q=Gs.removePrefix(t,I),v=E(Q);return v&&r.strictSlashes!==!0&&(v+=`${a}?`),v};qee.exports=RP});var Wee=N((c8t,Vee)=>{"use strict";h();var P4e=require("path"),L4e=jee(),TP=$ee(),NP=nI(),_4e=rI(),U4e=t=>t&&typeof t=="object"&&!Array.isArray(t),cn=(t,e,r=!1)=>{if(Array.isArray(t)){let u=t.map(d=>cn(d,e,r));return d=>{for(let g of u){let p=g(d);if(p)return p}return!1}}let n=U4e(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=NP.isWindows(e),o=n?cn.compileRe(t,e):cn.makeRe(t,e,!1,!0),a=o.state;delete o.state;let A=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};A=cn(i.ignore,u,r)}let c=(u,l=!1)=>{let{isMatch:d,match:g,output:p}=cn.test(u,o,e,{glob:t,posix:s}),f={glob:t,state:a,regex:o,posix:s,input:u,output:p,match:g,isMatch:d};return typeof i.onResult=="function"&&i.onResult(f),d===!1?(f.isMatch=!1,l?f:!1):A(u)?(typeof i.onIgnore=="function"&&i.onIgnore(f),f.isMatch=!1,l?f:!1):(typeof i.onMatch=="function"&&i.onMatch(f),l?f:!0)};return r&&(c.state=a),c};cn.test=(t,e,r,{glob:n,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let s=r||{},o=s.format||(i?NP.toPosixSlashes:null),a=t===n,A=a&&o?o(t):t;return a===!1&&(A=o?o(t):t,a=A===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=cn.matchBase(t,e,r,i):a=e.exec(A)),{isMatch:!!a,match:a,output:A}};cn.matchBase=(t,e,r,n=NP.isWindows(r))=>(e instanceof RegExp?e:cn.makeRe(e,r)).test(P4e.basename(t));cn.isMatch=(t,e,r)=>cn(e,r)(t);cn.parse=(t,e)=>Array.isArray(t)?t.map(r=>cn.parse(r,e)):TP(t,{...e,fastpaths:!1});cn.scan=(t,e)=>L4e(t,e);cn.compileRe=(t,e,r=!1,n=!1)=>{if(r===!0)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let A=cn.toRegex(a,e);return n===!0&&(A.state=t),A};cn.makeRe=(t,e={},r=!1,n=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=TP.fastpaths(t,e)),i.output||(i=TP(t,e)),cn.compileRe(i,e,r,n)};cn.toRegex=(t,e)=>{try{let r=e||{};return new RegExp(t,r.flags||(r.nocase?"i":""))}catch(r){if(e&&e.debug===!0)throw r;return/$^/}};cn.constants=_4e;Vee.exports=cn});var Xee=N((l8t,zee)=>{"use strict";h();zee.exports=Wee()});var Dw=N((p8t,nte)=>{"use strict";h();var ete=require("util"),tte=Ree(),dA=Xee(),MP=nI(),Zee=t=>t===""||t==="./",rte=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},Fr=(t,e,r)=>{e=[].concat(e),t=[].concat(t);let n=new Set,i=new Set,s=new Set,o=0,a=u=>{s.add(u.output),r&&r.onResult&&r.onResult(u)};for(let u=0;u<e.length;u++){let l=dA(String(e[u]),{...r,onResult:a},!0),d=l.state.negated||l.state.negatedExtglob;d&&o++;for(let g of t){let p=l(g,!0);(d?!p.isMatch:p.isMatch)&&(d?n.add(p.output):(n.delete(p.output),i.add(p.output)))}}let c=(o===e.length?[...s]:[...i]).filter(u=>!n.has(u));if(r&&c.length===0){if(r.failglob===!0)throw new Error(`No matches found for "${e.join(", ")}"`);if(r.nonull===!0||r.nullglob===!0)return r.unescape?e.map(u=>u.replace(/\\/g,"")):e}return c};Fr.match=Fr;Fr.matcher=(t,e)=>dA(t,e);Fr.isMatch=(t,e,r)=>dA(e,r)(t);Fr.any=Fr.isMatch;Fr.not=(t,e,r={})=>{e=[].concat(e).map(String);let n=new Set,i=[],s=a=>{r.onResult&&r.onResult(a),i.push(a.output)},o=new Set(Fr(t,e,{...r,onResult:s}));for(let a of i)o.has(a)||n.add(a);return[...n]};Fr.contains=(t,e,r)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${ete.inspect(t)}"`);if(Array.isArray(e))return e.some(n=>Fr.contains(t,n,r));if(typeof e=="string"){if(Zee(t)||Zee(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return Fr.isMatch(t,e,{...r,contains:!0})};Fr.matchKeys=(t,e,r)=>{if(!MP.isObject(t))throw new TypeError("Expected the first argument to be an object");let n=Fr(Object.keys(t),e,r),i={};for(let s of n)i[s]=t[s];return i};Fr.some=(t,e,r)=>{let n=[].concat(t);for(let i of[].concat(e)){let s=dA(String(i),r);if(n.some(o=>s(o)))return!0}return!1};Fr.every=(t,e,r)=>{let n=[].concat(t);for(let i of[].concat(e)){let s=dA(String(i),r);if(!n.every(o=>s(o)))return!1}return!0};Fr.all=(t,e,r)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${ete.inspect(t)}"`);return[].concat(e).every(n=>dA(n,r)(t))};Fr.capture=(t,e,r)=>{let n=MP.isWindows(r),s=dA.makeRe(String(t),{...r,capture:!0}).exec(n?MP.toPosixSlashes(e):e);if(s)return s.slice(1).map(o=>o===void 0?"":o)};Fr.makeRe=(...t)=>dA.makeRe(...t);Fr.scan=(...t)=>dA.scan(...t);Fr.parse=(t,e)=>{let r=[];for(let n of[].concat(t||[]))for(let i of tte(String(n),e))r.push(dA.parse(i,e));return r};Fr.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!rte(t)?[t]:tte(t,e)};Fr.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return Fr.braces(t,{...e,expand:!0})};Fr.hasBraces=rte;nte.exports=Fr});var pte=N(tt=>{"use strict";h();Object.defineProperty(tt,"__esModule",{value:!0});tt.isAbsolute=tt.partitionAbsoluteAndRelative=tt.removeDuplicateSlashes=tt.matchAny=tt.convertPatternsToRe=tt.makeRe=tt.getPatternParts=tt.expandBraceExpansion=tt.expandPatternsWithBraceExpansion=tt.isAffectDepthOfReadingPattern=tt.endsWithSlashGlobStar=tt.hasGlobStar=tt.getBaseDirectory=tt.isPatternRelatedToParentDirectory=tt.getPatternsOutsideCurrentDirectory=tt.getPatternsInsideCurrentDirectory=tt.getPositivePatterns=tt.getNegativePatterns=tt.isPositivePattern=tt.isNegativePattern=tt.convertToNegativePattern=tt.convertToPositivePattern=tt.isDynamicPattern=tt.isStaticPattern=void 0;var ite=require("path"),G4e=WZ(),PP=Dw(),ste="**",O4e="\\",K4e=/[*?]|^!/,H4e=/\[[^[]*]/,J4e=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,j4e=/[!*+?@]\([^(]*\)/,Y4e=/,|\.\./,q4e=/(?!^)\/{2,}/g;function ote(t,e={}){return!ate(t,e)}tt.isStaticPattern=ote;function ate(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(O4e)||K4e.test(t)||H4e.test(t)||J4e.test(t)||e.extglob!==!1&&j4e.test(t)||e.braceExpansion!==!1&&$4e(t))}tt.isDynamicPattern=ate;function $4e(t){let e=t.indexOf("{");if(e===-1)return!1;let r=t.indexOf("}",e+1);if(r===-1)return!1;let n=t.slice(e,r);return Y4e.test(n)}function V4e(t){return ww(t)?t.slice(1):t}tt.convertToPositivePattern=V4e;function W4e(t){return"!"+t}tt.convertToNegativePattern=W4e;function ww(t){return t.startsWith("!")&&t[1]!=="("}tt.isNegativePattern=ww;function Ate(t){return!ww(t)}tt.isPositivePattern=Ate;function z4e(t){return t.filter(ww)}tt.getNegativePatterns=z4e;function X4e(t){return t.filter(Ate)}tt.getPositivePatterns=X4e;function Z4e(t){return t.filter(e=>!LP(e))}tt.getPatternsInsideCurrentDirectory=Z4e;function eHe(t){return t.filter(LP)}tt.getPatternsOutsideCurrentDirectory=eHe;function LP(t){return t.startsWith("..")||t.startsWith("./..")}tt.isPatternRelatedToParentDirectory=LP;function tHe(t){return G4e(t,{flipBackslashes:!1})}tt.getBaseDirectory=tHe;function rHe(t){return t.includes(ste)}tt.hasGlobStar=rHe;function cte(t){return t.endsWith("/"+ste)}tt.endsWithSlashGlobStar=cte;function nHe(t){let e=ite.basename(t);return cte(t)||ote(e)}tt.isAffectDepthOfReadingPattern=nHe;function iHe(t){return t.reduce((e,r)=>e.concat(ute(r)),[])}tt.expandPatternsWithBraceExpansion=iHe;function ute(t){let e=PP.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((r,n)=>r.length-n.length),e.filter(r=>r!=="")}tt.expandBraceExpansion=ute;function sHe(t,e){let{parts:r}=PP.scan(t,Object.assign(Object.assign({},e),{parts:!0}));return r.length===0&&(r=[t]),r[0].startsWith("/")&&(r[0]=r[0].slice(1),r.unshift("")),r}tt.getPatternParts=sHe;function lte(t,e){return PP.makeRe(t,e)}tt.makeRe=lte;function oHe(t,e){return t.map(r=>lte(r,e))}tt.convertPatternsToRe=oHe;function aHe(t,e){return e.some(r=>r.test(t))}tt.matchAny=aHe;function AHe(t){return t.replace(q4e,"/")}tt.removeDuplicateSlashes=AHe;function cHe(t){let e=[],r=[];for(let n of t)gte(n)?e.push(n):r.push(n);return[e,r]}tt.partitionAbsoluteAndRelative=cHe;function gte(t){return ite.isAbsolute(t)}tt.isAbsolute=gte});var mte=N((m8t,hte)=>{"use strict";h();var uHe=require("stream"),dte=uHe.PassThrough,lHe=Array.prototype.slice;hte.exports=gHe;function gHe(){let t=[],e=lHe.call(arguments),r=!1,n=e[e.length-1];n&&!Array.isArray(n)&&n.pipe==null?e.pop():n={};let i=n.end!==!1,s=n.pipeError===!0;n.objectMode==null&&(n.objectMode=!0),n.highWaterMark==null&&(n.highWaterMark=64*1024);let o=dte(n);function a(){for(let u=0,l=arguments.length;u<l;u++)t.push(fte(arguments[u],n));return A(),this}function A(){if(r)return;r=!0;let u=t.shift();if(!u){process.nextTick(c);return}Array.isArray(u)||(u=[u]);let l=u.length+1;function d(){--l>0||(r=!1,A())}function g(p){function f(){p.removeListener("merge2UnpipeEnd",f),p.removeListener("end",f),s&&p.removeListener("error",m),d()}function m(C){o.emit("error",C)}if(p._readableState.endEmitted)return d();p.on("merge2UnpipeEnd",f),p.on("end",f),s&&p.on("error",m),p.pipe(o,{end:!1}),p.resume()}for(let p=0;p<u.length;p++)g(u[p]);d()}function c(){r=!1,o.emit("queueDrain"),i&&o.end()}return o.setMaxListeners(0),o.add=a,o.on("unpipe",function(u){u.emit("merge2UnpipeEnd")}),e.length&&a.apply(null,e),o}function fte(t,e){if(Array.isArray(t))for(let r=0,n=t.length;r<n;r++)t[r]=fte(t[r],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(dte(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var Ite=N(bw=>{"use strict";h();Object.defineProperty(bw,"__esModule",{value:!0});bw.merge=void 0;var pHe=mte();function dHe(t){let e=pHe(t);return t.forEach(r=>{r.once("error",n=>e.emit("error",n))}),e.once("close",()=>Cte(t)),e.once("end",()=>Cte(t)),e}bw.merge=dHe;function Cte(t){t.forEach(e=>e.emit("close"))}});var Ete=N(lf=>{"use strict";h();Object.defineProperty(lf,"__esModule",{value:!0});lf.isEmpty=lf.isString=void 0;function fHe(t){return typeof t=="string"}lf.isString=fHe;function hHe(t){return t===""}lf.isEmpty=hHe});var hc=N(Ri=>{"use strict";h();Object.defineProperty(Ri,"__esModule",{value:!0});Ri.string=Ri.stream=Ri.pattern=Ri.path=Ri.fs=Ri.errno=Ri.array=void 0;var mHe=LZ();Ri.array=mHe;var CHe=_Z();Ri.errno=CHe;var IHe=UZ();Ri.fs=IHe;var EHe=HZ();Ri.path=EHe;var BHe=pte();Ri.pattern=BHe;var yHe=Ite();Ri.stream=yHe;var QHe=Ete();Ri.string=QHe});var Dte=N(Ti=>{"use strict";h();Object.defineProperty(Ti,"__esModule",{value:!0});Ti.convertPatternGroupToTask=Ti.convertPatternGroupsToTasks=Ti.groupPatternsByBaseDirectory=Ti.getNegativePatternsAsPositive=Ti.getPositivePatterns=Ti.convertPatternsToTasks=Ti.generate=void 0;var la=hc();function DHe(t,e){let r=Bte(t,e),n=Bte(e.ignore,e),i=yte(r),s=Qte(r,n),o=i.filter(u=>la.pattern.isStaticPattern(u,e)),a=i.filter(u=>la.pattern.isDynamicPattern(u,e)),A=_P(o,s,!1),c=_P(a,s,!0);return A.concat(c)}Ti.generate=DHe;function Bte(t,e){let r=t;return e.braceExpansion&&(r=la.pattern.expandPatternsWithBraceExpansion(r)),e.baseNameMatch&&(r=r.map(n=>n.includes("/")?n:`**/${n}`)),r.map(n=>la.pattern.removeDuplicateSlashes(n))}function _P(t,e,r){let n=[],i=la.pattern.getPatternsOutsideCurrentDirectory(t),s=la.pattern.getPatternsInsideCurrentDirectory(t),o=UP(i),a=UP(s);return n.push(...GP(o,e,r)),"."in a?n.push(OP(".",s,e,r)):n.push(...GP(a,e,r)),n}Ti.convertPatternsToTasks=_P;function yte(t){return la.pattern.getPositivePatterns(t)}Ti.getPositivePatterns=yte;function Qte(t,e){return la.pattern.getNegativePatterns(t).concat(e).map(la.pattern.convertToPositivePattern)}Ti.getNegativePatternsAsPositive=Qte;function UP(t){let e={};return t.reduce((r,n)=>{let i=la.pattern.getBaseDirectory(n);return i in r?r[i].push(n):r[i]=[n],r},e)}Ti.groupPatternsByBaseDirectory=UP;function GP(t,e,r){return Object.keys(t).map(n=>OP(n,t[n],e,r))}Ti.convertPatternGroupsToTasks=GP;function OP(t,e,r,n){return{dynamic:n,positive:e,negative:r,base:t,patterns:[].concat(e,r.map(la.pattern.convertToNegativePattern))}}Ti.convertPatternGroupToTask=OP});var bte=N(vw=>{"use strict";h();Object.defineProperty(vw,"__esModule",{value:!0});vw.read=void 0;function wHe(t,e,r){e.fs.lstat(t,(n,i)=>{if(n!==null){wte(r,n);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){KP(r,i);return}e.fs.stat(t,(s,o)=>{if(s!==null){if(e.throwErrorOnBrokenSymbolicLink){wte(r,s);return}KP(r,i);return}e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),KP(r,o)})})}vw.read=wHe;function wte(t,e){t(e)}function KP(t,e){t(null,e)}});var vte=N(Sw=>{"use strict";h();Object.defineProperty(Sw,"__esModule",{value:!0});Sw.read=void 0;function bHe(t,e){let r=e.fs.lstatSync(t);if(!r.isSymbolicLink()||!e.followSymbolicLink)return r;try{let n=e.fs.statSync(t);return e.markSymbolicLink&&(n.isSymbolicLink=()=>!0),n}catch(n){if(!e.throwErrorOnBrokenSymbolicLink)return r;throw n}}Sw.read=bHe});var Ste=N(Nu=>{"use strict";h();Object.defineProperty(Nu,"__esModule",{value:!0});Nu.createFileSystemAdapter=Nu.FILE_SYSTEM_ADAPTER=void 0;var xw=require("fs");Nu.FILE_SYSTEM_ADAPTER={lstat:xw.lstat,stat:xw.stat,lstatSync:xw.lstatSync,statSync:xw.statSync};function vHe(t){return t===void 0?Nu.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Nu.FILE_SYSTEM_ADAPTER),t)}Nu.createFileSystemAdapter=vHe});var xte=N(JP=>{"use strict";h();Object.defineProperty(JP,"__esModule",{value:!0});var SHe=Ste(),HP=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=SHe.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue(e,r){return e??r}};JP.default=HP});var Mg=N(Mu=>{"use strict";h();Object.defineProperty(Mu,"__esModule",{value:!0});Mu.statSync=Mu.stat=Mu.Settings=void 0;var Fte=bte(),xHe=vte(),jP=xte();Mu.Settings=jP.default;function FHe(t,e,r){if(typeof e=="function"){Fte.read(t,YP(),e);return}Fte.read(t,YP(e),r)}Mu.stat=FHe;function kHe(t,e){let r=YP(e);return xHe.read(t,r)}Mu.statSync=kHe;function YP(t={}){return t instanceof jP.default?t:new jP.default(t)}});var Tte=N((L8t,Rte)=>{h();var kte;Rte.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(kte||(kte=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var Mte=N((U8t,Nte)=>{h();Nte.exports=THe;var RHe=Tte();function THe(t,e){let r,n,i,s=!0;Array.isArray(t)?(r=[],n=t.length):(i=Object.keys(t),r={},n=i.length);function o(A){function c(){e&&e(A,r),e=null}s?RHe(c):c()}function a(A,c,u){r[A]=u,(--n===0||c)&&o(c)}n?i?i.forEach(function(A){t[A](function(c,u){a(A,c,u)})}):t.forEach(function(A,c){A(function(u,l){a(c,u,l)})}):o(null),s=!1}});var qP=N(kw=>{"use strict";h();Object.defineProperty(kw,"__esModule",{value:!0});kw.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var Fw=process.versions.node.split(".");if(Fw[0]===void 0||Fw[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var Pte=Number.parseInt(Fw[0],10),NHe=Number.parseInt(Fw[1],10),Lte=10,MHe=10,PHe=Pte>Lte,LHe=Pte===Lte&&NHe>=MHe;kw.IS_SUPPORT_READDIR_WITH_FILE_TYPES=PHe||LHe});var _te=N(Rw=>{"use strict";h();Object.defineProperty(Rw,"__esModule",{value:!0});Rw.createDirentFromStats=void 0;var $P=class{constructor(e,r){this.name=e,this.isBlockDevice=r.isBlockDevice.bind(r),this.isCharacterDevice=r.isCharacterDevice.bind(r),this.isDirectory=r.isDirectory.bind(r),this.isFIFO=r.isFIFO.bind(r),this.isFile=r.isFile.bind(r),this.isSocket=r.isSocket.bind(r),this.isSymbolicLink=r.isSymbolicLink.bind(r)}};function _He(t,e){return new $P(t,e)}Rw.createDirentFromStats=_He});var VP=N(Tw=>{"use strict";h();Object.defineProperty(Tw,"__esModule",{value:!0});Tw.fs=void 0;var UHe=_te();Tw.fs=UHe});var WP=N(Nw=>{"use strict";h();Object.defineProperty(Nw,"__esModule",{value:!0});Nw.joinPathSegments=void 0;function GHe(t,e,r){return t.endsWith(r)?t+e:t+r+e}Nw.joinPathSegments=GHe});var Jte=N(Pu=>{"use strict";h();Object.defineProperty(Pu,"__esModule",{value:!0});Pu.readdir=Pu.readdirWithFileTypes=Pu.read=void 0;var OHe=Mg(),Ute=Mte(),KHe=qP(),Gte=VP(),Ote=WP();function HHe(t,e,r){if(!e.stats&&KHe.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Kte(t,e,r);return}Hte(t,e,r)}Pu.read=HHe;function Kte(t,e,r){e.fs.readdir(t,{withFileTypes:!0},(n,i)=>{if(n!==null){Mw(r,n);return}let s=i.map(a=>({dirent:a,name:a.name,path:Ote.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){zP(r,s);return}let o=s.map(a=>JHe(a,e));Ute(o,(a,A)=>{if(a!==null){Mw(r,a);return}zP(r,A)})})}Pu.readdirWithFileTypes=Kte;function JHe(t,e){return r=>{if(!t.dirent.isSymbolicLink()){r(null,t);return}e.fs.stat(t.path,(n,i)=>{if(n!==null){if(e.throwErrorOnBrokenSymbolicLink){r(n);return}r(null,t);return}t.dirent=Gte.fs.createDirentFromStats(t.name,i),r(null,t)})}}function Hte(t,e,r){e.fs.readdir(t,(n,i)=>{if(n!==null){Mw(r,n);return}let s=i.map(o=>{let a=Ote.joinPathSegments(t,o,e.pathSegmentSeparator);return A=>{OHe.stat(a,e.fsStatSettings,(c,u)=>{if(c!==null){A(c);return}let l={name:o,path:a,dirent:Gte.fs.createDirentFromStats(o,u)};e.stats&&(l.stats=u),A(null,l)})}});Ute(s,(o,a)=>{if(o!==null){Mw(r,o);return}zP(r,a)})})}Pu.readdir=Hte;function Mw(t,e){t(e)}function zP(t,e){t(null,e)}});var Vte=N(Lu=>{"use strict";h();Object.defineProperty(Lu,"__esModule",{value:!0});Lu.readdir=Lu.readdirWithFileTypes=Lu.read=void 0;var jHe=Mg(),YHe=qP(),jte=VP(),Yte=WP();function qHe(t,e){return!e.stats&&YHe.IS_SUPPORT_READDIR_WITH_FILE_TYPES?qte(t,e):$te(t,e)}Lu.read=qHe;function qte(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(n=>{let i={dirent:n,name:n.name,path:Yte.joinPathSegments(t,n.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let s=e.fs.statSync(i.path);i.dirent=jte.fs.createDirentFromStats(i.name,s)}catch(s){if(e.throwErrorOnBrokenSymbolicLink)throw s}return i})}Lu.readdirWithFileTypes=qte;function $te(t,e){return e.fs.readdirSync(t).map(n=>{let i=Yte.joinPathSegments(t,n,e.pathSegmentSeparator),s=jHe.statSync(i,e.fsStatSettings),o={name:n,path:i,dirent:jte.fs.createDirentFromStats(n,s)};return e.stats&&(o.stats=s),o})}Lu.readdir=$te});var Wte=N(_u=>{"use strict";h();Object.defineProperty(_u,"__esModule",{value:!0});_u.createFileSystemAdapter=_u.FILE_SYSTEM_ADAPTER=void 0;var gf=require("fs");_u.FILE_SYSTEM_ADAPTER={lstat:gf.lstat,stat:gf.stat,lstatSync:gf.lstatSync,statSync:gf.statSync,readdir:gf.readdir,readdirSync:gf.readdirSync};function $He(t){return t===void 0?_u.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},_u.FILE_SYSTEM_ADAPTER),t)}_u.createFileSystemAdapter=$He});var zte=N(ZP=>{"use strict";h();Object.defineProperty(ZP,"__esModule",{value:!0});var VHe=require("path"),WHe=Mg(),zHe=Wte(),XP=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=zHe.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,VHe.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new WHe.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,r){return e??r}};ZP.default=XP});var Pw=N(Uu=>{"use strict";h();Object.defineProperty(Uu,"__esModule",{value:!0});Uu.Settings=Uu.scandirSync=Uu.scandir=void 0;var Xte=Jte(),XHe=Vte(),e1=zte();Uu.Settings=e1.default;function ZHe(t,e,r){if(typeof e=="function"){Xte.read(t,t1(),e);return}Xte.read(t,t1(e),r)}Uu.scandir=ZHe;function eJe(t,e){let r=t1(e);return XHe.read(t,r)}Uu.scandirSync=eJe;function t1(t={}){return t instanceof e1.default?t:new e1.default(t)}});var ere=N((s3t,Zte)=>{"use strict";h();function tJe(t){var e=new t,r=e;function n(){var s=e;return s.next?e=s.next:(e=new t,r=e),s.next=null,s}function i(s){r.next=s,r=s}return{get:n,release:i}}Zte.exports=tJe});var rre=N((a3t,r1)=>{"use strict";h();var rJe=ere();function tre(t,e,r){if(typeof t=="function"&&(r=e,e=t,t=null),!(r>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var n=rJe(nJe),i=null,s=null,o=0,a=null,A={push:f,drain:gs,saturated:gs,pause:u,paused:!1,get concurrency(){return r},set concurrency(Q){if(!(Q>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(r=Q,!A.paused)for(;i&&o<r;)o++,C()},running:c,resume:g,idle:p,length:l,getQueue:d,unshift:m,empty:gs,kill:I,killAndDrain:y,error:E,abort:B};return A;function c(){return o}function u(){A.paused=!0}function l(){for(var Q=i,v=0;Q;)Q=Q.next,v++;return v}function d(){for(var Q=i,v=[];Q;)v.push(Q.value),Q=Q.next;return v}function g(){if(A.paused){if(A.paused=!1,i===null){o++,C();return}for(;i&&o<r;)o++,C()}}function p(){return o===0&&A.length()===0}function f(Q,v){var D=n.get();D.context=t,D.release=C,D.value=Q,D.callback=v||gs,D.errorHandler=a,o>=r||A.paused?s?(s.next=D,s=D):(i=D,s=D,A.saturated()):(o++,e.call(t,D.value,D.worked))}function m(Q,v){var D=n.get();D.context=t,D.release=C,D.value=Q,D.callback=v||gs,D.errorHandler=a,o>=r||A.paused?i?(D.next=i,i=D):(i=D,s=D,A.saturated()):(o++,e.call(t,D.value,D.worked))}function C(Q){Q&&n.release(Q);var v=i;v&&o<=r?A.paused?o--:(s===i&&(s=null),i=v.next,v.next=null,e.call(t,v.value,v.worked),s===null&&A.empty()):--o===0&&A.drain()}function I(){i=null,s=null,A.drain=gs}function y(){i=null,s=null,A.drain(),A.drain=gs}function B(){var Q=i;for(i=null,s=null;Q;){var v=Q.next,D=Q.callback,S=Q.errorHandler,b=Q.value,x=Q.context;Q.value=null,Q.callback=gs,Q.errorHandler=null,S&&S(new Error("abort"),b),D.call(x,new Error("abort")),Q.release(Q),Q=v}A.drain=gs}function E(Q){a=Q}}function gs(){}function nJe(){this.value=null,this.callback=gs,this.next=null,this.release=gs,this.context=null,this.errorHandler=null;var t=this;this.worked=function(r,n){var i=t.callback,s=t.errorHandler,o=t.value;t.value=null,t.callback=gs,t.errorHandler&&s(r,o),i.call(t.context,r,n),t.release(t)}}function iJe(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(u,l){e.call(this,u).then(function(d){l(null,d)},l)}var i=tre(t,n,r),s=i.push,o=i.unshift;return i.push=a,i.unshift=A,i.drained=c,i;function a(u){var l=new Promise(function(d,g){s(u,function(p,f){if(p){g(p);return}d(f)})});return l.catch(gs),l}function A(u){var l=new Promise(function(d,g){o(u,function(p,f){if(p){g(p);return}d(f)})});return l.catch(gs),l}function c(){var u=new Promise(function(l){process.nextTick(function(){if(i.idle())l();else{var d=i.drain;i.drain=function(){typeof d=="function"&&d(),l(),i.drain=d}}})});return u}}r1.exports=tre;r1.exports.promise=iJe});var Lw=N(fA=>{"use strict";h();Object.defineProperty(fA,"__esModule",{value:!0});fA.joinPathSegments=fA.replacePathSegmentSeparator=fA.isAppliedFilter=fA.isFatalError=void 0;function sJe(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}fA.isFatalError=sJe;function oJe(t,e){return t===null||t(e)}fA.isAppliedFilter=oJe;function aJe(t,e){return t.split(/[/\\]/).join(e)}fA.replacePathSegmentSeparator=aJe;function AJe(t,e,r){return t===""?e:t.endsWith(r)?t+e:t+r+e}fA.joinPathSegments=AJe});var s1=N(i1=>{"use strict";h();Object.defineProperty(i1,"__esModule",{value:!0});var cJe=Lw(),n1=class{constructor(e,r){this._root=e,this._settings=r,this._root=cJe.replacePathSegmentSeparator(e,r.pathSegmentSeparator)}};i1.default=n1});var A1=N(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});var uJe=require("events"),lJe=Pw(),gJe=rre(),_w=Lw(),pJe=s1(),o1=class extends pJe.default{constructor(e,r){super(e,r),this._settings=r,this._scandir=lJe.scandir,this._emitter=new uJe.EventEmitter,this._queue=gJe(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit("end")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw new Error("The reader is already destroyed");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on("entry",e)}onError(e){this._emitter.once("error",e)}onEnd(e){this._emitter.once("end",e)}_pushToQueue(e,r){let n={directory:e,base:r};this._queue.push(n,i=>{i!==null&&this._handleError(i)})}_worker(e,r){this._scandir(e.directory,this._settings.fsScandirSettings,(n,i)=>{if(n!==null){r(n,void 0);return}for(let s of i)this._handleEntry(s,e.base);r(null,void 0)})}_handleError(e){this._isDestroyed||!_w.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit("error",e))}_handleEntry(e,r){if(this._isDestroyed||this._isFatalError)return;let n=e.path;r!==void 0&&(e.path=_w.joinPathSegments(r,e.name,this._settings.pathSegmentSeparator)),_w.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&_w.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(n,r===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};a1.default=o1});var nre=N(u1=>{"use strict";h();Object.defineProperty(u1,"__esModule",{value:!0});var dJe=A1(),c1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new dJe.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(r=>{fJe(e,r)}),this._reader.onEntry(r=>{this._storage.push(r)}),this._reader.onEnd(()=>{hJe(e,this._storage)}),this._reader.read()}};u1.default=c1;function fJe(t,e){t(e)}function hJe(t,e){t(null,e)}});var ire=N(g1=>{"use strict";h();Object.defineProperty(g1,"__esModule",{value:!0});var mJe=require("stream"),CJe=A1(),l1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new CJe.default(this._root,this._settings),this._stream=new mJe.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit("error",e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}};g1.default=l1});var sre=N(d1=>{"use strict";h();Object.defineProperty(d1,"__esModule",{value:!0});var IJe=Pw(),Uw=Lw(),EJe=s1(),p1=class extends EJe.default{constructor(){super(...arguments),this._scandir=IJe.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,r){this._queue.add({directory:e,base:r})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,r){try{let n=this._scandir(e,this._settings.fsScandirSettings);for(let i of n)this._handleEntry(i,r)}catch(n){this._handleError(n)}}_handleError(e){if(Uw.isFatalError(this._settings,e))throw e}_handleEntry(e,r){let n=e.path;r!==void 0&&(e.path=Uw.joinPathSegments(r,e.name,this._settings.pathSegmentSeparator)),Uw.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&Uw.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(n,r===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};d1.default=p1});var ore=N(h1=>{"use strict";h();Object.defineProperty(h1,"__esModule",{value:!0});var BJe=sre(),f1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new BJe.default(this._root,this._settings)}read(){return this._reader.read()}};h1.default=f1});var are=N(C1=>{"use strict";h();Object.defineProperty(C1,"__esModule",{value:!0});var yJe=require("path"),QJe=Pw(),m1=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,yJe.sep),this.fsScandirSettings=new QJe.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,r){return e??r}};C1.default=m1});var Ow=N(hA=>{"use strict";h();Object.defineProperty(hA,"__esModule",{value:!0});hA.Settings=hA.walkStream=hA.walkSync=hA.walk=void 0;var Are=nre(),DJe=ire(),wJe=ore(),I1=are();hA.Settings=I1.default;function bJe(t,e,r){if(typeof e=="function"){new Are.default(t,Gw()).read(e);return}new Are.default(t,Gw(e)).read(r)}hA.walk=bJe;function vJe(t,e){let r=Gw(e);return new wJe.default(t,r).read()}hA.walkSync=vJe;function SJe(t,e){let r=Gw(e);return new DJe.default(t,r).read()}hA.walkStream=SJe;function Gw(t={}){return t instanceof I1.default?t:new I1.default(t)}});var Kw=N(B1=>{"use strict";h();Object.defineProperty(B1,"__esModule",{value:!0});var xJe=require("path"),FJe=Mg(),cre=hc(),E1=class{constructor(e){this._settings=e,this._fsStatSettings=new FJe.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return xJe.resolve(this._settings.cwd,e)}_makeEntry(e,r){let n={name:r,path:r,dirent:cre.fs.createDirentFromStats(r,e)};return this._settings.stats&&(n.stats=e),n}_isFatalError(e){return!cre.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};B1.default=E1});var D1=N(Q1=>{"use strict";h();Object.defineProperty(Q1,"__esModule",{value:!0});var kJe=require("stream"),RJe=Mg(),TJe=Ow(),NJe=Kw(),y1=class extends NJe.default{constructor(){super(...arguments),this._walkStream=TJe.walkStream,this._stat=RJe.stat}dynamic(e,r){return this._walkStream(e,r)}static(e,r){let n=e.map(this._getFullEntryPath,this),i=new kJe.PassThrough({objectMode:!0});i._write=(s,o,a)=>this._getEntry(n[s],e[s],r).then(A=>{A!==null&&r.entryFilter(A)&&i.push(A),s===n.length-1&&i.end(),a()}).catch(a);for(let s=0;s<n.length;s++)i.write(s);return i}_getEntry(e,r,n){return this._getStat(e).then(i=>this._makeEntry(i,r)).catch(i=>{if(n.errorFilter(i))return null;throw i})}_getStat(e){return new Promise((r,n)=>{this._stat(e,this._fsStatSettings,(i,s)=>i===null?r(s):n(i))})}};Q1.default=y1});var ure=N(b1=>{"use strict";h();Object.defineProperty(b1,"__esModule",{value:!0});var MJe=Ow(),PJe=Kw(),LJe=D1(),w1=class extends PJe.default{constructor(){super(...arguments),this._walkAsync=MJe.walk,this._readerStream=new LJe.default(this._settings)}dynamic(e,r){return new Promise((n,i)=>{this._walkAsync(e,r,(s,o)=>{s===null?n(o):i(s)})})}async static(e,r){let n=[],i=this._readerStream.static(e,r);return new Promise((s,o)=>{i.once("error",o),i.on("data",a=>n.push(a)),i.once("end",()=>s(n))})}};b1.default=w1});var lre=N(S1=>{"use strict";h();Object.defineProperty(S1,"__esModule",{value:!0});var sI=hc(),v1=class{constructor(e,r,n){this._patterns=e,this._settings=r,this._micromatchOptions=n,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let r=this._getPatternSegments(e),n=this._splitSegmentsIntoSections(r);this._storage.push({complete:n.length<=1,pattern:e,segments:r,sections:n})}}_getPatternSegments(e){return sI.pattern.getPatternParts(e,this._micromatchOptions).map(n=>sI.pattern.isDynamicPattern(n,this._settings)?{dynamic:!0,pattern:n,patternRe:sI.pattern.makeRe(n,this._micromatchOptions)}:{dynamic:!1,pattern:n})}_splitSegmentsIntoSections(e){return sI.array.splitWhen(e,r=>r.dynamic&&sI.pattern.hasGlobStar(r.pattern))}};S1.default=v1});var gre=N(F1=>{"use strict";h();Object.defineProperty(F1,"__esModule",{value:!0});var _Je=lre(),x1=class extends _Je.default{match(e){let r=e.split("/"),n=r.length,i=this._storage.filter(s=>!s.complete||s.segments.length>n);for(let s of i){let o=s.sections[0];if(!s.complete&&n>o.length||r.every((A,c)=>{let u=s.segments[c];return!!(u.dynamic&&u.patternRe.test(A)||!u.dynamic&&u.pattern===A)}))return!0}return!1}};F1.default=x1});var pre=N(R1=>{"use strict";h();Object.defineProperty(R1,"__esModule",{value:!0});var Hw=hc(),UJe=gre(),k1=class{constructor(e,r){this._settings=e,this._micromatchOptions=r}getFilter(e,r,n){let i=this._getMatcher(r),s=this._getNegativePatternsRe(n);return o=>this._filter(e,o,i,s)}_getMatcher(e){return new UJe.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let r=e.filter(Hw.pattern.isAffectDepthOfReadingPattern);return Hw.pattern.convertPatternsToRe(r,this._micromatchOptions)}_filter(e,r,n,i){if(this._isSkippedByDeep(e,r.path)||this._isSkippedSymbolicLink(r))return!1;let s=Hw.path.removeLeadingDotSegment(r.path);return this._isSkippedByPositivePatterns(s,n)?!1:this._isSkippedByNegativePatterns(s,i)}_isSkippedByDeep(e,r){return this._settings.deep===1/0?!1:this._getEntryLevel(e,r)>=this._settings.deep}_getEntryLevel(e,r){let n=r.split("/").length;if(e==="")return n;let i=e.split("/").length;return n-i}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,r){return!this._settings.baseNameMatch&&!r.match(e)}_isSkippedByNegativePatterns(e,r){return!Hw.pattern.matchAny(e,r)}};R1.default=k1});var dre=N(N1=>{"use strict";h();Object.defineProperty(N1,"__esModule",{value:!0});var Gu=hc(),T1=class{constructor(e,r){this._settings=e,this._micromatchOptions=r,this.index=new Map}getFilter(e,r){let[n,i]=Gu.pattern.partitionAbsoluteAndRelative(r),s={positive:{all:Gu.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:Gu.pattern.convertPatternsToRe(n,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:Gu.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return o=>this._filter(o,s)}_filter(e,r){let n=Gu.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(n)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let i=this._isMatchToPatternsSet(n,r,e.dirent.isDirectory());return this._settings.unique&&i&&this._createIndexRecord(n),i}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isMatchToPatternsSet(e,r,n){return!(!this._isMatchToPatterns(e,r.positive.all,n)||this._isMatchToPatterns(e,r.negative.relative,n)||this._isMatchToAbsoluteNegative(e,r.negative.absolute,n))}_isMatchToAbsoluteNegative(e,r,n){if(r.length===0)return!1;let i=Gu.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,r,n)}_isMatchToPatterns(e,r,n){if(r.length===0)return!1;let i=Gu.pattern.matchAny(e,r);return!i&&n?Gu.pattern.matchAny(e+"/",r):i}};N1.default=T1});var fre=N(P1=>{"use strict";h();Object.defineProperty(P1,"__esModule",{value:!0});var GJe=hc(),M1=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return GJe.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};P1.default=M1});var mre=N(_1=>{"use strict";h();Object.defineProperty(_1,"__esModule",{value:!0});var hre=hc(),L1=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let r=e.path;return this._settings.absolute&&(r=hre.path.makeAbsolute(this._settings.cwd,r),r=hre.path.unixify(r)),this._settings.markDirectories&&e.dirent.isDirectory()&&(r+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:r}):r}};_1.default=L1});var Jw=N(G1=>{"use strict";h();Object.defineProperty(G1,"__esModule",{value:!0});var OJe=require("path"),KJe=pre(),HJe=dre(),JJe=fre(),jJe=mre(),U1=class{constructor(e){this._settings=e,this.errorFilter=new JJe.default(this._settings),this.entryFilter=new HJe.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new KJe.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new jJe.default(this._settings)}_getRootDirectory(e){return OJe.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let r=e.base==="."?"":e.base;return{basePath:r,pathSegmentSeparator:"/",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(r,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}};G1.default=U1});var Cre=N(K1=>{"use strict";h();Object.defineProperty(K1,"__esModule",{value:!0});var YJe=ure(),qJe=Jw(),O1=class extends qJe.default{constructor(){super(...arguments),this._reader=new YJe.default(this._settings)}async read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e);return(await this.api(r,e,n)).map(s=>n.transform(s))}api(e,r,n){return r.dynamic?this._reader.dynamic(e,n):this._reader.static(r.patterns,n)}};K1.default=O1});var Ire=N(J1=>{"use strict";h();Object.defineProperty(J1,"__esModule",{value:!0});var $Je=require("stream"),VJe=D1(),WJe=Jw(),H1=class extends WJe.default{constructor(){super(...arguments),this._reader=new VJe.default(this._settings)}read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e),i=this.api(r,e,n),s=new $Je.Readable({objectMode:!0,read:()=>{}});return i.once("error",o=>s.emit("error",o)).on("data",o=>s.emit("data",n.transform(o))).once("end",()=>s.emit("end")),s.once("close",()=>i.destroy()),s}api(e,r,n){return r.dynamic?this._reader.dynamic(e,n):this._reader.static(r.patterns,n)}};J1.default=H1});var Ere=N(Y1=>{"use strict";h();Object.defineProperty(Y1,"__esModule",{value:!0});var zJe=Mg(),XJe=Ow(),ZJe=Kw(),j1=class extends ZJe.default{constructor(){super(...arguments),this._walkSync=XJe.walkSync,this._statSync=zJe.statSync}dynamic(e,r){return this._walkSync(e,r)}static(e,r){let n=[];for(let i of e){let s=this._getFullEntryPath(i),o=this._getEntry(s,i,r);o===null||!r.entryFilter(o)||n.push(o)}return n}_getEntry(e,r,n){try{let i=this._getStat(e);return this._makeEntry(i,r)}catch(i){if(n.errorFilter(i))return null;throw i}}_getStat(e){return this._statSync(e,this._fsStatSettings)}};Y1.default=j1});var Bre=N($1=>{"use strict";h();Object.defineProperty($1,"__esModule",{value:!0});var eje=Ere(),tje=Jw(),q1=class extends tje.default{constructor(){super(...arguments),this._reader=new eje.default(this._settings)}read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e);return this.api(r,e,n).map(n.transform)}api(e,r,n){return r.dynamic?this._reader.dynamic(e,n):this._reader.static(r.patterns,n)}};$1.default=q1});var yre=N(df=>{"use strict";h();Object.defineProperty(df,"__esModule",{value:!0});df.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var pf=require("fs"),rje=require("os"),nje=Math.max(rje.cpus().length,1);df.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:pf.lstat,lstatSync:pf.lstatSync,stat:pf.stat,statSync:pf.statSync,readdir:pf.readdir,readdirSync:pf.readdirSync};var V1=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,nje),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,r){return e===void 0?r:e}_getFileSystemMethods(e={}){return Object.assign(Object.assign({},df.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};df.default=V1});var Z1=N((nKt,Dre)=>{"use strict";h();var Qre=Dte(),ije=Cre(),sje=Ire(),oje=Bre(),W1=yre(),po=hc();async function z1(t,e){ga(t);let r=X1(t,ije.default,e),n=await Promise.all(r);return po.array.flatten(n)}(function(t){t.glob=t,t.globSync=e,t.globStream=r,t.async=t;function e(c,u){ga(c);let l=X1(c,oje.default,u);return po.array.flatten(l)}t.sync=e;function r(c,u){ga(c);let l=X1(c,sje.default,u);return po.stream.merge(l)}t.stream=r;function n(c,u){ga(c);let l=[].concat(c),d=new W1.default(u);return Qre.generate(l,d)}t.generateTasks=n;function i(c,u){ga(c);let l=new W1.default(u);return po.pattern.isDynamicPattern(c,l)}t.isDynamicPattern=i;function s(c){return ga(c),po.path.escape(c)}t.escapePath=s;function o(c){return ga(c),po.path.convertPathToPattern(c)}t.convertPathToPattern=o;let a;(function(c){function u(d){return ga(d),po.path.escapePosixPath(d)}c.escapePath=u;function l(d){return ga(d),po.path.convertPosixPathToPattern(d)}c.convertPathToPattern=l})(a=t.posix||(t.posix={}));let A;(function(c){function u(d){return ga(d),po.path.escapeWindowsPath(d)}c.escapePath=u;function l(d){return ga(d),po.path.convertWindowsPathToPattern(d)}c.convertPathToPattern=l})(A=t.win32||(t.win32={}))})(z1||(z1={}));function X1(t,e,r){let n=[].concat(t),i=new W1.default(r),s=Qre.generate(n,i),o=new e(i);return s.map(o.read,o)}function ga(t){if(![].concat(t).every(n=>po.string.isString(n)&&!po.string.isEmpty(n)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}Dre.exports=z1});async function eL(t,e,r){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);try{return(await bre.default[t](r))[e]()}catch(n){if(n.code==="ENOENT")return!1;throw n}}function tL(t,e,r){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);try{return wre.default[t](r)[e]()}catch(n){if(n.code==="ENOENT")return!1;throw n}}var wre,bre,sKt,vre,oKt,aKt,Sre,AKt,xre=L(()=>{h();wre=z(require("node:fs"),1),bre=z(require("node:fs/promises"),1);sKt=eL.bind(void 0,"stat","isFile"),vre=eL.bind(void 0,"stat","isDirectory"),oKt=eL.bind(void 0,"lstat","isSymbolicLink"),aKt=tL.bind(void 0,"statSync","isFile"),Sre=tL.bind(void 0,"statSync","isDirectory"),AKt=tL.bind(void 0,"lstatSync","isSymbolicLink")});var Fre=L(()=>{h()});function mc(t){return t instanceof URL?(0,Rre.fileURLToPath)(t):t}function Tre(t){return{*[Symbol.iterator](){let e=rL.default.resolve(mc(t)),r;for(;r!==e;)yield e,r=e,e=rL.default.resolve(e,"..")}}}var kre,nL,rL,Rre,pKt,dKt,jw=L(()=>{h();kre=require("node:util"),nL=require("node:child_process"),rL=z(require("node:path"),1),Rre=require("node:url");Fre();pKt=(0,kre.promisify)(nL.execFile);dKt=10*1024*1024});function ff(t){return t.startsWith("\\\\?\\")?t:t.replace(/\\/g,"/")}var Nre=L(()=>{h()});var oI,iL=L(()=>{h();oI=t=>t[0]==="!"});var Mre,Pre,Lre,Pg,sL,_re,aje,Ure,Gre,Aje,cje,uje,Ore,Kre,Hre,Jre,jre=L(()=>{h();Mre=z(require("node:process"),1),Pre=z(require("node:fs"),1),Lre=z(require("node:fs/promises"),1),Pg=z(require("node:path"),1),sL=z(Z1(),1),_re=z(require("ignore"),1);Nre();jw();iL();aje=["**/node_modules","**/flow-typed","**/coverage","**/.git"],Ure={absolute:!0,dot:!0},Gre="**/.gitignore",Aje=(t,e)=>oI(t)?"!"+Pg.default.posix.join(e,t.slice(1)):Pg.default.posix.join(e,t),cje=(t,e)=>{let r=ff(Pg.default.relative(e,Pg.default.dirname(t.filePath)));return t.content.split(/\r?\n/).filter(n=>n&&!n.startsWith("#")).map(n=>Aje(n,r))},uje=(t,e)=>{if(e=ff(e),Pg.default.isAbsolute(t)){if(ff(t).startsWith(e))return Pg.default.relative(e,t);throw new Error(`Path ${t} is not in cwd ${e}`)}return t},Ore=(t,e)=>{let r=t.flatMap(i=>cje(i,e)),n=(0,_re.default)().add(r);return i=>(i=mc(i),i=uje(i,e),i?n.ignores(ff(i)):!1)},Kre=(t={})=>({cwd:mc(t.cwd)??Mre.default.cwd(),suppressErrors:!!t.suppressErrors,deep:typeof t.deep=="number"?t.deep:Number.POSITIVE_INFINITY,ignore:[...t.ignore??[],...aje]}),Hre=async(t,e)=>{let{cwd:r,suppressErrors:n,deep:i,ignore:s}=Kre(e),o=await(0,sL.default)(t,{cwd:r,suppressErrors:n,deep:i,ignore:s,...Ure}),a=await Promise.all(o.map(async A=>({filePath:A,content:await Lre.default.readFile(A,"utf8")})));return Ore(a,r)},Jre=(t,e)=>{let{cwd:r,suppressErrors:n,deep:i,ignore:s}=Kre(e),a=sL.default.sync(t,{cwd:r,suppressErrors:n,deep:i,ignore:s,...Ure}).map(A=>({filePath:A,content:Pre.default.readFileSync(A,"utf8")}));return Ore(a,r)}});var oL,$re,Lg,hf,lje,Vre,Wre,Yre,qre,aL,gje,zre,Xre,Yw,Zre,pje,ene,tne,rne,nne,ine,sne,AL,qw,RKt,TKt,NKt,MKt,PKt,LKt,one=L(()=>{h();oL=z(require("node:process"),1),$re=z(require("node:fs"),1),Lg=z(require("node:path"),1);PZ();hf=z(Z1(),1);xre();jw();jre();iL();lje=t=>{if(t.some(e=>typeof e!="string"))throw new TypeError("Patterns must be a string or an array of strings")},Vre=(t,e)=>{let r=oI(t)?t.slice(1):t;return Lg.default.isAbsolute(r)?r:Lg.default.join(e,r)},Wre=({directoryPath:t,files:e,extensions:r})=>{let n=r?.length>0?`.${r.length>1?`{${r.join(",")}}`:r[0]}`:"";return e?e.map(i=>Lg.default.posix.join(t,`**/${Lg.default.extname(i)?i:`${i}${n}`}`)):[Lg.default.posix.join(t,`**${n?`/*${n}`:""}`)]},Yre=async(t,{cwd:e=oL.default.cwd(),files:r,extensions:n}={})=>(await Promise.all(t.map(async s=>await vre(Vre(s,e))?Wre({directoryPath:s,files:r,extensions:n}):s))).flat(),qre=(t,{cwd:e=oL.default.cwd(),files:r,extensions:n}={})=>t.flatMap(i=>Sre(Vre(i,e))?Wre({directoryPath:i,files:r,extensions:n}):i),aL=t=>(t=[...new Set([t].flat())],lje(t),t),gje=t=>{if(!t)return;let e;try{e=$re.default.statSync(t)}catch{return}if(!e.isDirectory())throw new Error("The `cwd` option must be a path to a directory")},zre=(t={})=>(t={...t,ignore:t.ignore??[],expandDirectories:t.expandDirectories??!0,cwd:mc(t.cwd)},gje(t.cwd),t),Xre=t=>async(e,r)=>t(aL(e),zre(r)),Yw=t=>(e,r)=>t(aL(e),zre(r)),Zre=t=>{let{ignoreFiles:e,gitignore:r}=t,n=e?aL(e):[];return r&&n.push(Gre),n},pje=async t=>{let e=Zre(t);return tne(e.length>0&&await Hre(e,t))},ene=t=>{let e=Zre(t);return tne(e.length>0&&Jre(e,t))},tne=t=>{let e=new Set;return r=>{let n=Lg.default.normalize(r.path??r);return e.has(n)||t&&t(n)?!1:(e.add(n),!0)}},rne=(t,e)=>t.flat().filter(r=>e(r)),nne=(t,e)=>{let r=[];for(;t.length>0;){let n=t.findIndex(s=>oI(s));if(n===-1){r.push({patterns:t,options:e});break}let i=t[n].slice(1);for(let s of r)s.options.ignore.push(i);n!==0&&r.push({patterns:t.slice(0,n),options:{...e,ignore:[...e.ignore,i]}}),t=t.slice(n+1)}return r},ine=(t,e)=>({...e?{cwd:e}:{},...Array.isArray(t)?{files:t}:t}),sne=async(t,e)=>{let r=nne(t,e),{cwd:n,expandDirectories:i}=e;if(!i)return r;let s=ine(i,n);return Promise.all(r.map(async o=>{let{patterns:a,options:A}=o;return[a,A.ignore]=await Promise.all([Yre(a,s),Yre(A.ignore,{cwd:n})]),{patterns:a,options:A}}))},AL=(t,e)=>{let r=nne(t,e),{cwd:n,expandDirectories:i}=e;if(!i)return r;let s=ine(i,n);return r.map(o=>{let{patterns:a,options:A}=o;return a=qre(a,s),A.ignore=qre(A.ignore,{cwd:n}),{patterns:a,options:A}})},qw=Xre(async(t,e)=>{let[r,n]=await Promise.all([sne(t,e),pje(e)]),i=await Promise.all(r.map(s=>(0,hf.default)(s.patterns,s.options)));return rne(i,n)}),RKt=Yw((t,e)=>{let r=AL(t,e),n=ene(e),i=r.map(s=>hf.default.sync(s.patterns,s.options));return rne(i,n)}),TKt=Yw((t,e)=>{let r=AL(t,e),n=ene(e),i=r.map(o=>hf.default.stream(o.patterns,o.options));return fP(i).filter(o=>n(o))}),NKt=Yw((t,e)=>t.some(r=>hf.default.isDynamicPattern(r,e))),MKt=Xre(sne),PKt=Yw(AL),{convertPathToPattern:LKt}=hf.default});function mf(t){let e=Date.now();return new Promise((r,n)=>{let s=dje(t.url)({protocol:t.url.protocol,host:t.url.host,port:t.url.port,path:t.url.pathname+t.url.search,method:t.method,headers:t.headers},o=>{let a="";o.on("data",A=>{a+=A}),o.on("end",()=>{if((0,ane.debug)(`${t.method} ${t.url.href}, duration: ${Date.now()-e}ms`),typeof o.statusCode=="number"&&o.statusCode>=200&&o.statusCode<300)if(typeof o.headers["content-type"]!="string"||!o.headers["content-type"].includes("application/json"))n(`Response from ${t.url.href} content-type is ${o.headers["content-type"]}`);else try{r(JSON.parse(a))}catch(A){n(`Response from ${t.url.href} is not valid JSON: ${a}
|
|
1261
1261
|
${A}`)}else n(`Request to ${t.url.href} failed with status ${o.statusCode}: ${a}`)})}).on("error",o=>{n(`Error fetching ${t.url.href}, ${o}`)});t.body&&(s.setHeader("Content-Type","application/json"),s.write(t.body)),s.end()})}function dje(t){if(t.protocol==="https:")return cne.request;if(t.protocol==="http:")return Ane.request;throw new Error(`Unsupported protocol ${t.protocol}`)}var ane,Ane,cne,une=L(()=>{"use strict";h();ane=require("node:console"),Ane=require("node:http"),cne=require("node:https")});async function lne(t){let e=new URL(`https://cdn.builder.io/api/v3/query/${t.publicApiKey}/${t.model}`);return e.searchParams.set("omit","meta.componentsUsed"),e.searchParams.set("apiKey",t.publicApiKey),e.searchParams.set("userAttributes.urlPath",t.pageUrl),e.searchParams.set("options.page.model",`"${t.model}"`),e.searchParams.set("cachebust","true"),(await mf({url:e,method:"GET"}))[t.model]}async function gne(t,e){if(e.kind===Km.VCP)return!0;let r=new URL("https://cdn.builder.io/api/v2/admin"),n={query:`query {
|
|
1262
1262
|
models {
|
|
1263
1263
|
id
|
|
@@ -1276,7 +1276,7 @@ Restarting server after Builder Devtools update...
|
|
|
1276
1276
|
<h3>How's Devtools working for you?</h3>
|
|
1277
1277
|
<p>We'd love your feedback!</p>
|
|
1278
1278
|
</div>
|
|
1279
|
-
\`,t.appendChild(e),setTimeout(()=>{e.classList.add("menu-toggle-tooltip-show"),e.addEventListener("click",()=>{e.classList.remove("menu-toggle-tooltip-show")})},1e3)};function ui(t){t.getElementById("go-to-builder").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Ee(t,!1),window.open(Ur(),"builder")}),t.getElementById("components-link").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation();let c=t.querySelector(".nav-cmp-list .section-content");c.scrollTop=0,oe(t,"nav-cmp-list"),ai(t)}),t.getElementById("settings-link").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),oe(t,"nav-settings")}),t.getElementById("add-page-link").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Ee(t,!1),window.open(je(),"builder")}),t.getElementById("import-from-figma").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Ee(t,!1),window.open("https://www.figma.com/community/plugin/747985167520967365/builder-io-ai-powered-figma-to-code-react-vue-tailwind-more")})}function ci(t){let e=t.getElementById("enable-edit");e.addEventListener("change",r=>{r.stopPropagation(),Ht(e.checked)}),e.checked=it(),Ht(e.checked)}var Dt=class extends HTMLElement{constructor(){super()}connectedCallback(){let e=this.attachShadow({mode:"open"});e.innerHTML=\`<style>*,*:before,*:after{box-sizing:border-box}:host{--background-color: rgba(40, 40, 40, 1);--primary-color: rgba(72, 161, 255, 1);--primary-color-subdued: rgb(72, 161, 255, .6);--primary-color-highlight: rgb(126, 188, 255);--primary-contrast-color: white;--edit-color: #1d74e2;--edit-color-highlight: #1c6bd1;--edit-color-alpha: rgb(72, 161, 255, .15);--error-color: #ff2b55;--text-color: white;--text-color-highlight: white;--border-color: #454545;--button-background-color-hover: rgba(255, 255, 255, .1);--menu-width: 320px;--transition-time: .15s;--font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-family:var(--font-family);line-height:1.6}button{cursor:pointer;color:var(--text-color);-webkit-tap-highlight-color:transparent}input,select,button{font-family:var(--font-family)}.menu-toggle{position:absolute;right:0;bottom:0;pointer-events:auto;padding:8px;background:transparent;border:none;appearance:none}.menu-toggle div{position:relative;width:64px;height:64px;pointer-events:none;border-radius:50%;background:#000;border:1px solid white;box-shadow:#00000054 0 0 8px}.menu-toggle:hover div{background-color:var(--background-color);border:1px solid rgb(220,220,220)}.menu-toggle svg{position:absolute;top:15px;left:15px;width:33px;height:32px}div.highlight-bg{position:absolute;top:-1px;left:-1px;background-color:#1a1a1a;pointer-events:none;transition:all .4s ease-out;opacity:0}.menu-toggle-highlight-no-transition div.highlight-bg{transition:none}.menu-toggle-highlight div.highlight-bg{opacity:1}.menu-toggle-tooltip{position:absolute;bottom:0;right:0;width:382px;height:72px;padding:0;text-align:left;appearance:none;background-color:transparent;border:none;pointer-events:none;transform:translate3d(320px,0,0);opacity:0;transition:all .15s ease-in-out;color:#fff}.menu-toggle-tooltip.menu-toggle-tooltip-show{pointer-events:auto;opacity:1;transform:translateZ(0)}.menu-toggle-tooltip-content{position:absolute;inset:0 95px 10px 0;padding:8px 12px;background-color:var(--primary-color);box-shadow:#00000054 0 0 20px;border-radius:2px}.menu-toggle-tooltip-content:before{content:"";position:absolute;bottom:15px;right:-6px;width:30px;height:30px;background-color:var(--primary-color);transform:rotate(45deg)}.menu-toggle-tooltip:hover .menu-toggle-tooltip-content,.menu-toggle-tooltip:hover .menu-toggle-tooltip-content:before{background-color:var(--primary-color-highlight)}.menu-toggle-tooltip-content h3{margin:0;font-size:16px}.menu-toggle-tooltip-content p{margin:0;font-size:12px}section{position:absolute;display:grid;grid-template-rows:64px auto 64px;top:0;left:0;width:100%;height:100%;padding:0;pointer-events:none}.section-content{margin:0;padding:0 0 10px;font-weight:300;transform:translate3d(105%,0,0);transition:transform var(--transition-time) ease-in-out;overflow-y:auto}.section-content .error{color:var(--error-color);font-weight:700}section a{text-decoration:none;color:var(--text-color)}section h3,section p{margin-left:16px;margin-right:16px}.info{font-size:12px}ul.list{list-style:none;padding:0;margin:0}ul.list li{display:block;padding:0;margin:0}ul.list a,ul.list button{display:grid;grid-template-columns:24px auto;grid-gap:16px;padding:12px;margin:8px 0;border:none;background:transparent;appearance:none;width:100%;font-weight:300;text-align:left;text-decoration:none;color:var(--text-color)}ul.list a:hover,ul.list button:hover{text-decoration:none;color:var(--text-color);background-color:var(--button-background-color-hover)}ul.list a span,ul.list button span{display:block;font-size:16px;font-weight:500;line-height:1.5;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}header{position:relative;display:grid;grid-template-columns:44px 1fr;gap:8px;padding-left:8px;border-bottom:1px solid var(--border-color);transition:opacity var(--transition-time) ease-in-out;opacity:0;pointer-events:none}header>div{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nav-home header>div{margin-right:56px}header h2{margin:7px 0 0;font-size:18px;font-weight:500;line-height:1.5;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}header p{margin:2px 0 0;font-size:12px;font-weight:300;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}header p button{display:block;margin:0;padding:0;width:100%;font-size:12px;font-weight:300;text-decoration:none;appearance:none;text-align:left;background-color:transparent;border:none;color:var(--primary-color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}header p button:hover{text-decoration:underline;color:var(--primary-color)}.builder-logo{margin:12px 0 0 8px}#close{display:block;position:absolute;appearance:none;background:transparent;border:none;border-radius:50%;margin:0;padding:0;right:4px;top:8px;width:48px;height:48px;z-index:1;opacity:.7}#close:hover{opacity:1;background-color:var(--button-background-color-hover)}#close svg{position:absolute;top:12px;left:12px;width:24px;height:24px;fill:currentColor;pointer-events:none}.back-button{position:relative;display:block;margin:7px 0 0 -2px;width:48px;height:48px;background:transparent;border:none;appearance:none;border-radius:50%}.back-button:hover{background-color:var(--button-background-color-hover)}.back-button svg{position:absolute;top:12px;left:12px;width:24px;height:24px;fill:currentColor;pointer-events:none}footer{border-top:1px solid var(--border-color);transition:opacity var(--transition-time) ease-in-out;opacity:0;pointer-events:none}section.nav-cmp-list{grid-template-rows:64px auto 120px}footer a{text-decoration:underline;color:var(--primary-color)}footer a:hover{color:var(--primary-color);text-decoration:none}.nav-list{padding:2px 0}.nav-loading{pointer-events:none}.nav-loading-icon{position:absolute;display:inline-block;top:170px;left:0;width:100%;transform:translateZ(0);pointer-events:auto;opacity:0;transition:all 50ms ease-in-out;transition-delay:50ms;pointer-events:none}.nav-loading .nav-loading-icon{opacity:.5}.nav-list h4{margin:8px 8px 8px 10px;font-size:14px;font-weight:600}.nav-list .nav-list-item+h4{margin-top:30px}.nav-list-item{display:grid;grid-template-columns:1fr 1fr;gap:8px;position:relative;margin:2px 0;padding:8px 28px 8px 46px;width:100%;font-size:14px;font-weight:300;text-align:left;border:none;background:transparent;appearance:none}.nav-list-item:hover{background-color:var(--button-background-color-hover)}.nav-list-item-icon{position:absolute;top:4px;left:10px;width:24px;height:24px;object-fit:contain;filter:invert(100%);background-size:24px 24px;background-repeat:no-repeat;background-position:center center}.nav-list-item span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none}.nav-list-item:after{display:block;position:absolute;content:"";background-image:url('data:image/svg+xml,<svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L7 7L1 13" stroke="%23F2F2F2" stroke-opacity="0.5" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/></svg>');background-repeat:no-repeat;background-position:12px 9px;top:0;right:0;width:32px;height:32px;pointer-events:none}.nav-list-item-note{opacity:0;font-size:12px;padding-top:1px;text-align:right}.nav-list-item:hover .nav-list-item-note{opacity:.5}.ui-select{display:block;margin:8px 0 16px;padding:8px 16px;cursor:pointer}.ui-select h3{margin:0;font-size:14px;font-weight:500}.ui-select p{margin:8px 0;font-size:12px;font-weight:300}.ui-select .select{position:relative;margin:8px 0;border-radius:4px;padding:0;line-height:1.1;overflow:hidden;border:1px solid var(--border-color)}.ui-select select{appearance:none;background-color:transparent;border:none;outline:none;padding:8px 32px 8px 8px;margin:0;width:100%;font-size:14px;cursor:pointer;text-overflow:ellipsis;opacity:.6;color:var(--text-color)}.ui-select .select:after{content:"";top:6px;right:5px;width:24px;height:24px;position:absolute;background-image:url('data:image/svg+xml,<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="%23F2F2F2" d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/></svg>');background-repeat:no-repeat;background-position:center;pointer-events:none;opacity:.6}.ui-select .select:hover{border-color:var(--primary-color-subdued)}.ui-text-input .select:focus-within{border-color:var(--primary-color)}.ui-text-input .select:focus-within select{opacity:1}.spinner:after{content:" ";display:block;width:32px;height:32px;margin:0 auto;pointer-events:auto;border-radius:50%;border:3px solid var(--text-color);border-color:var(--text-color) transparent var(--text-color) transparent;animation:spinner .75s linear infinite}@keyframes spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.ui-switch{display:grid;grid-template-columns:auto 48px;grid-gap:20px;margin:8px 0 16px;padding:8px 0 8px 16px;cursor:pointer}.ui-switch>*{pointer-events:none}.ui-switch input{display:none;visibility:hidden}.ui-switch .switcher{display:inline-block;border-radius:100px;width:35px;height:14px;background-color:#ccc;position:relative;top:6px;vertical-align:middle;cursor:pointer}.ui-switch input[type=checkbox]:checked+.switcher{background-color:var(--primary-color-subdued)}.ui-switch .switcher:before{content:"";display:block;width:20px;height:20px;background-color:var(--text-color);box-shadow:0 1px 3px #0009;border-radius:50%;position:absolute;top:-3px;left:0;margin-right:0;transition:all .15s}.ui-switch input[type=checkbox]:checked+.switcher:before{left:100%;margin-left:-20px;background-color:var(--primary-color)}.ui-switch h3{margin:0;font-size:14px;font-weight:500}.ui-switch p{margin:4px 0 0;font-size:12px;font-weight:300}.ui-text-input{display:block;margin:8px 0 16px;padding:8px 16px;cursor:pointer}.ui-text-input h3{margin:0;font-size:14px;font-weight:500}.ui-text-input p{margin:8px 0;font-size:12px;font-weight:300}.ui-text-input .input{position:relative;margin:8px 0;border:1px solid var(--border-color);border-radius:4px;background:transparent;padding:2px;overflow:hidden}.ui-text-input input{display:block;width:235px;font-size:14px;border:none;background:transparent;padding:6px;appearance:none;color:var(--text-color);opacity:.6;outline:none}.ui-text-input .input:hover{border-color:var(--primary-color-subdued)}.ui-text-input .input:focus-within{border-color:var(--primary-color)}.ui-text-input .input:focus-within input{opacity:1}.ui-text-input .input:after{content:"";position:absolute;top:5px;right:14px;width:8px;height:17px;border:2px solid rgba(51,181,51,1);border-top:none;border-left:none;transform:rotate(45deg);opacity:0;transition:opacity 80ms ease-in-out;pointer-events:none}.ui-text-input.saved .input:after{opacity:1}.ui-toast{position:fixed;bottom:8px;left:8px;right:8px;padding:6px 12px;font-size:14px;border-radius:4px;transform:translate3d(0,150%,0);opacity:0;transition:all var(--transition-time) ease-in-out;background-color:var(--primary-color-subdued);color:var(--text-color);pointer-events:none}.ui-toast.ui-toast-show{transform:translateZ(0);opacity:1;pointer-events:auto}[data-view=nav-home] .nav-home .section-content,[data-view=nav-cmp-list] .nav-cmp-list .section-content,[data-view=nav-cmp-detail] .nav-cmp-detail .section-content,[data-view=nav-cmp-input] .nav-cmp-input .section-content,[data-view=nav-settings] .nav-settings .section-content{transform:translateZ(0);pointer-events:auto}[data-view=nav-home] .nav-home header,[data-view=nav-home] .nav-home footer,[data-view=nav-cmp-list] .nav-cmp-list header,[data-view=nav-cmp-list] .nav-cmp-list footer,[data-view=nav-cmp-detail] .nav-cmp-detail header,[data-view=nav-cmp-detail] .nav-cmp-detail footer,[data-view=nav-cmp-input] .nav-cmp-input header,[data-view=nav-cmp-input] .nav-cmp-input footer,[data-view=nav-settings] .nav-settings header,[data-view=nav-settings] .nav-settings footer{opacity:1;pointer-events:auto}[data-view=nav-cmp-list] .nav-home .section-content,[data-view=nav-cmp-detail] .nav-home .section-content,[data-view=nav-cmp-detail] .nav-cmp-list .section-content,[data-view=nav-cmp-input] .nav-home .section-content,[data-view=nav-cmp-input] .nav-cmp-list .section-content,[data-view=nav-cmp-input] .nav-cmp-detail .section-content,[data-view=nav-settings] .nav-home .section-content{transform:translate3d(-105%,0,0)}.cmp-item .nav-list-item-icon{background-image:url('data:image/svg+xml,<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20.83 16.809C20.94 16.561 21 16.289 21 16.008V7.99001C20.9994 7.64108 20.9066 7.29851 20.731 6.99699C20.5554 6.69547 20.3032 6.44571 20 6.27301L13 2.26501C12.6954 2.09103 12.3508 1.99951 12 1.99951C11.6492 1.99951 11.3046 2.09103 11 2.26501L7.988 3.99001M5.441 5.44801L4 6.27301C3.381 6.62801 3 7.28301 3 7.99101V16.009C3 16.718 3.381 17.372 4 17.726L11 21.734C11.3046 21.908 11.6492 21.9995 12 21.9995C12.3508 21.9995 12.6954 21.908 13 21.734L18.544 18.56" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 22V12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.532 10.538L20.73 6.95996" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.27002 6.95996L12 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M3 3L21 21" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/></svg>');opacity:.3}.cmp-item.registered .nav-list-item-icon{background-image:url('data:image/svg+xml,<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M21 16.008V7.99001C20.9994 7.64108 20.9066 7.29851 20.731 6.99699C20.5554 6.69547 20.3032 6.44571 20 6.27301L13 2.26501C12.6954 2.09103 12.3508 1.99951 12 1.99951C11.6492 1.99951 11.3046 2.09103 11 2.26501L4 6.27301C3.381 6.62801 3 7.28301 3 7.99101V16.009C3 16.718 3.381 17.372 4 17.726L11 21.734C11.3046 21.908 11.6492 21.9995 12 21.9995C12.3508 21.9995 12.6954 21.908 13 21.734L20 17.726C20.619 17.371 21 16.716 21 16.008Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 22V12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 12L20.73 6.95996" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M3.26999 6.95996L12 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /></svg>');opacity:.8}.search-highlight{background-color:var(--primary-color-alpha);padding:0 2px;border-radius:2px;font-weight:500}.search-container{position:sticky;top:0;z-index:10;padding:12px 16px;background:var(--background-color);border-bottom:1px solid var(--border-color)}.search-input-wrapper{position:relative;display:flex;align-items:center}.search-icon{position:absolute;left:12px;color:var(--text-color-secondary);pointer-events:none}.component-search-input{width:100%;height:36px;padding:8px 36px;border:1px solid var(--border-color);border-radius:6px;background:var(--input-background);color:var(--text-color);font-size:14px;transition:border-color .2s,box-shadow .2s}.component-search-input:focus{outline:none;border-color:var(--primary-color);box-shadow:0 0 0 2px var(--primary-color-alpha)}.component-search-input::placeholder{color:var(--text-color-tertiary)}.clear-search-button{position:absolute;right:8px;padding:4px;color:var(--text-color-secondary);border:none;background:transparent;border-radius:4px;cursor:pointer;opacity:0;transition:opacity .2s,background-color .2s;display:flex;align-items:center;justify-content:center}.clear-search-button:hover{background-color:var(--hover-color)}.component-search-input:not(:placeholder-shown)+.clear-search-button{opacity:1}.no-results{padding:32px 16px;text-align:center;color:var(--text-color-secondary);font-size:14px}#cmp-detail{position:relative}.cmp-loading{pointer-events:none!important}.cmp-loading-icon{position:absolute;display:inline-block;top:170px;left:0;width:100%;transform:translateZ(0);pointer-events:auto;opacity:0;transition:all 50ms ease-in-out;transition-delay:50ms;pointer-events:none}.cmp-loading .cmp-loading-icon{opacity:.5}.cmp-cover{position:absolute;top:160px;left:0;width:100%;height:100vh;background:var(--background-color);transform:translateZ(0);pointer-events:none;display:none}[data-view=nav-cmp-detail] .cmp-cover{display:block;pointer-events:auto}.cmp-enabled .cmp-cover{transform:translate3d(0,105%,0);pointer-events:none}.section-ready .cmp-cover{transition:all var(--transition-time) ease-in-out}.cmp-detail-inputs-container{margin:8px 0 16px;padding:0}.cmp-detail-inputs-container h3{margin:0 0 6px;padding-left:16px;padding-right:8px;font-size:14px;font-weight:500;display:flex;justify-content:space-between;align-items:center}.cmp-detail-inputs-reload{font-weight:300;font-size:.9em;text-decoration:none;appearance:none;text-align:left;background-color:transparent;border:none;color:var(--primary-color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cmp-detail-inputs-reload:hover{text-decoration:underline;color:var(--primary-color)}.cmp-detail-inputs-container .cmp-inputs-empty{padding:0;margin-top:12px;font-size:12px;font-weight:300;opacity:.5;font-style:italic}.cmp-detail-inputs-container .nav-list-item-icon{opacity:.8;background-size:20px 20px;background-position:4px center}.input-icon{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path></svg>')}.input-icon-array{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 16v-6a2 2 0 1 1 4 0v6"></path> <path d="M10 13h4"></path></svg>')}.input-icon-boolean{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 16h2a2 2 0 1 0 0 -4h-2h2a2 2 0 1 0 0 -4h-2v8z"></path></svg>')}.input-icon-number{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 16v-8l4 8v-8"></path></svg>')}.input-icon-object{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M12 8a2 2 0 0 1 2 2v4a2 2 0 1 1 -4 0v-4a2 2 0 0 1 2 -2z"></path></svg>')}.input-icon-string{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 15a1 1 0 0 0 1 1h2a1 1 0 0 0 1 -1v-2a1 1 0 0 0 -1 -1h-2a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1"></path></svg>')}.cmp-input-item-unregistered{opacity:.4}.cmp-input-item-unregistered .input-icon:after{content:"";position:absolute;top:11px;left:4px;width:20px;height:2px;background-color:#000;transform:rotate(-45deg)}.cmp-prop-info{border-bottom:1px solid var(--border-color)}.cmp-input-readonly{margin:16px 0;padding:0 16px;display:grid;grid-template-columns:50% 50%;gap:12px}.cmp-input-readonly h3{margin:0;font-size:14px;font-weight:500}.cmp-input-readonly span{margin-top:2px;font-size:12px;font-weight:300;opacity:.8}.cmp-input-detail{margin:16px 0}.cmp-input-detail a{color:var(--primary-color);text-decoration:none}.cmp-input-detail a:hover{text-decoration:underline}.input-cover{position:absolute;top:175px;left:0;width:100%;height:100%;background:var(--background-color);transform:translateZ(0);transition:all var(--transition-time) ease-in-out;pointer-events:auto}.input-enabled .input-cover{transform:translate3d(0,105%,0);pointer-events:none}.input-loading-icon{position:absolute;display:inline-block;top:190px;left:0;width:100%;transform:translateZ(0);pointer-events:auto;opacity:0;transition:all 50ms ease-in-out;transition-delay:50ms;pointer-events:none}.input-loading .input-loading-icon{opacity:.5}:host{position:fixed;inset:0;z-index:2147483646;user-select:none;pointer-events:none;color:var(--text-color)}aside{position:absolute;top:0;right:0;width:var(--menu-width);height:100%;transform:translate3d(105%,0,0);transition:transform var(--transition-time) ease-in-out;background:var(--background-color);box-shadow:#000000c9 5px 0 20px;overflow:hidden;z-index:1}:host(.show-builder-menu) aside{pointer-events:auto;transform:translateZ(0)}#hit{position:absolute;inset:0;display:none}:host(.show-builder-menu) #hit{display:block;pointer-events:auto}#version{position:absolute;bottom:6px;right:6px;font-size:8px;color:#9b9b9b}</style><div id="hit"></div> <aside data-view="nav-home"> <section class="nav-home"> <header> <svg class="builder-logo" viewBox="0 0 31 36" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M31 9.96854C31.0016 11.4553 30.6701 12.9236 30.03 14.2654C29.3898 15.6072 28.4572 16.7884 27.3007 17.7221L0.702841 2.61812C0.601104 2.56012 0.506714 2.49008 0.421705 2.40951C0.288323 2.27871 0.182333 2.12263 0.109928 1.95039C0.0375215 1.77814 0.000151253 1.59319 0 1.40633C0 1.03335 0.148098 0.675643 0.411715 0.411905C0.675332 0.148167 1.03287 0 1.40568 0L21.036 0C23.6786 0 26.213 1.05025 28.0816 2.91972C29.9502 4.78918 31 7.32472 31 9.96854Z" fill="#18B4F4" /> <path d="M31 25.4757C31.0004 26.7849 30.7429 28.0815 30.2423 29.2912C29.7417 30.5009 29.0078 31.6001 28.0825 32.526C27.1572 33.4519 26.0587 34.1864 24.8497 34.6875C23.6406 35.1886 22.3448 35.4465 21.0361 35.4465H1.40573C1.12766 35.4436 0.856725 35.3581 0.627199 35.201C0.397672 35.044 0.219871 34.8223 0.116289 34.5641C0.0127078 34.3059 -0.011999 34.0228 0.0452946 33.7505C0.102588 33.4783 0.239308 33.2292 0.438156 33.0347C0.517415 32.9551 0.606358 32.8858 0.702893 32.8284L11.1705 26.8843L27.2984 17.7244C28.4548 18.6579 29.3874 19.8387 30.028 21.18C30.6685 22.5213 31.0007 23.9891 31 25.4757Z" fill="#FD6B3C" /> <path d="M27.3011 17.7221L11.1709 26.8843L0.703209 32.8284C0.602697 32.8843 0.509784 32.9528 0.426758 33.0323C4.41799 28.9369 6.6496 23.442 6.64456 17.7221C6.65208 12.0015 4.42111 6.50517 0.429101 2.40948C0.51411 2.49005 0.6085 2.56009 0.710237 2.61809L27.3011 17.7221Z" fill="#A97FF2" /> </svg> <div> <h2 class="builder-home-title">Builder Devtools</h2> <p><button id="go-to-builder">Go to Builder</button></p> </div> <button id="close" aria-label="Close Menu"> <svg viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M18 6l-12 12" /> <path d="M6 6l12 12" /> </svg> </button> </header> <div class="section-content"> <ul class="list"> <li> <button id="components-link"> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M21 16.008V7.99001C20.9994 7.64108 20.9066 7.29851 20.731 6.99699C20.5554 6.69547 20.3032 6.44571 20 6.27301L13 2.26501C12.6954 2.09103 12.3508 1.99951 12 1.99951C11.6492 1.99951 11.3046 2.09103 11 2.26501L4 6.27301C3.381 6.62801 3 7.28301 3 7.99101V16.009C3 16.718 3.381 17.372 4 17.726L11 21.734C11.3046 21.908 11.6492 21.9995 12 21.9995C12.3508 21.9995 12.6954 21.908 13 21.734L20 17.726C20.619 17.371 21 16.716 21 16.008Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 22V12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 12L20.73 6.95996" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M3.26999 6.95996L12 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> </svg> <span>Components</span> </button> </li> <li> <button id="settings-link"> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M10.325 4.317C10.751 2.561 13.249 2.561 13.675 4.317C13.7389 4.5808 13.8642 4.82578 14.0407 5.032C14.2172 5.23822 14.4399 5.39985 14.6907 5.50375C14.9414 5.60764 15.2132 5.65085 15.4838 5.62987C15.7544 5.60889 16.0162 5.5243 16.248 5.383C17.791 4.443 19.558 6.209 18.618 7.753C18.4769 7.98466 18.3924 8.24634 18.3715 8.51677C18.3506 8.78721 18.3938 9.05877 18.4975 9.30938C18.6013 9.55999 18.7627 9.78258 18.9687 9.95905C19.1747 10.1355 19.4194 10.2609 19.683 10.325C21.439 10.751 21.439 13.249 19.683 13.675C19.4192 13.7389 19.1742 13.8642 18.968 14.0407C18.7618 14.2172 18.6001 14.4399 18.4963 14.6907C18.3924 14.9414 18.3491 15.2132 18.3701 15.4838C18.3911 15.7544 18.4757 16.0162 18.617 16.248C19.557 17.791 17.791 19.558 16.247 18.618C16.0153 18.4769 15.7537 18.3924 15.4832 18.3715C15.2128 18.3506 14.9412 18.3938 14.6906 18.4975C14.44 18.6013 14.2174 18.7627 14.0409 18.9687C13.8645 19.1747 13.7391 19.4194 13.675 19.683C13.249 21.439 10.751 21.439 10.325 19.683C10.2611 19.4192 10.1358 19.1742 9.95929 18.968C9.7828 18.7618 9.56011 18.6001 9.30935 18.4963C9.05859 18.3924 8.78683 18.3491 8.51621 18.3701C8.24559 18.3911 7.98375 18.4757 7.752 18.617C6.209 19.557 4.442 17.791 5.382 16.247C5.5231 16.0153 5.60755 15.7537 5.62848 15.4832C5.64942 15.2128 5.60624 14.9412 5.50247 14.6906C5.3987 14.44 5.23726 14.2174 5.03127 14.0409C4.82529 13.8645 4.58056 13.7391 4.317 13.675C2.561 13.249 2.561 10.751 4.317 10.325C4.5808 10.2611 4.82578 10.1358 5.032 9.95929C5.23822 9.7828 5.39985 9.56011 5.50375 9.30935C5.60764 9.05859 5.65085 8.78683 5.62987 8.51621C5.60889 8.24559 5.5243 7.98375 5.383 7.752C4.443 6.209 6.209 4.442 7.753 5.382C8.753 5.99 10.049 5.452 10.325 4.317Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M9 12C9 12.7956 9.31607 13.5587 9.87868 14.1213C10.4413 14.6839 11.2044 15 12 15C12.7956 15 13.5587 14.6839 14.1213 14.1213C14.6839 13.5587 15 12.7956 15 12C15 11.2044 14.6839 10.4413 14.1213 9.87868C13.5587 9.31607 12.7956 9 12 9C11.2044 9 10.4413 9.31607 9.87868 9.87868C9.31607 10.4413 9 11.2044 9 12Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> </svg> <span>Settings</span> </button> </li> <li> <button id="add-page-link"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M14 3v4a1 1 0 0 0 1 1h4" /> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z" /> <path d="M12 11l0 6" /> <path d="M9 14l6 0" /> </svg> <span>Add Builder Page</span> </button> </li> <li> <button id="import-from-figma"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-figma" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M15 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" /> <path d="M6 3m0 3a3 3 0 0 1 3 -3h6a3 3 0 0 1 3 3v0a3 3 0 0 1 -3 3h-6a3 3 0 0 1 -3 -3z" /> <path d="M9 9a3 3 0 0 0 0 6h3m-3 0a3 3 0 1 0 3 3v-15" /> </svg> <span>Import From Figma</span> </button> </li> </ul> </div> <footer> <ul class="list"> <li> <a href="https://docs.google.com/forms/d/e/1FAIpQLSdqZcJpRtm_Ia5DTHP6SDY9Xa6LID3KiTjRWkjMzWyJRUtSHw/viewform" target="_blank" > <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M11.013 17.0114L10.013 18.0114L2.513 10.5834C2.0183 10.102 1.62864 9.52342 1.36854 8.88404C1.10845 8.24466 0.983558 7.55836 1.00173 6.86834C1.01991 6.17832 1.18076 5.49954 1.47415 4.87474C1.76755 4.24994 2.18713 3.69266 2.70648 3.23799C3.22583 2.78331 3.8337 2.4411 4.49181 2.23289C5.14991 2.02468 5.844 1.95499 6.53036 2.02821C7.21673 2.10143 7.8805 2.31596 8.47987 2.65831C9.07925 3.00066 9.60124 3.46341 10.013 4.01741C10.8086 2.95654 11.9931 2.2552 13.3059 2.06766C14.6186 1.88012 15.9521 2.22176 17.013 3.01741C18.0739 3.81306 18.7752 4.99755 18.9627 6.3103C19.1503 7.62305 18.8086 8.95654 18.013 10.0174" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> <path d="M18.2006 19.8175L16.0286 20.9555C15.9642 20.989 15.8917 21.004 15.8192 20.9987C15.7467 20.9934 15.6771 20.9681 15.6182 20.9256C15.5593 20.8831 15.5134 20.825 15.4855 20.7579C15.4577 20.6907 15.4491 20.6172 15.4606 20.5455L15.8756 18.1345L14.1186 16.4275C14.0662 16.3768 14.0291 16.3123 14.0115 16.2416C13.9939 16.1708 13.9966 16.0965 14.0192 16.0271C14.0418 15.9578 14.0835 15.8962 14.1394 15.8494C14.1954 15.8026 14.2634 15.7725 14.3356 15.7625L16.7636 15.4105L17.8496 13.2175C17.8821 13.1521 17.9322 13.0972 17.9942 13.0588C18.0562 13.0204 18.1277 13 18.2006 13C18.2736 13 18.3451 13.0204 18.4071 13.0588C18.4691 13.0972 18.5191 13.1521 18.5516 13.2175L19.6376 15.4105L22.0656 15.7625C22.1377 15.7728 22.2054 15.8031 22.2611 15.85C22.3168 15.8968 22.3583 15.9583 22.3809 16.0275C22.4034 16.0967 22.4062 16.1708 22.3888 16.2415C22.3715 16.3122 22.3347 16.3766 22.2826 16.4275L20.5256 18.1345L20.9396 20.5445C20.9521 20.6163 20.9441 20.6902 20.9166 20.7578C20.8891 20.8254 20.8433 20.8839 20.7842 20.9267C20.7252 20.9695 20.6553 20.9949 20.5825 21C20.5098 21.005 20.4371 20.9896 20.3726 20.9555L18.2006 19.8175Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> </svg> <span>Give Feedback</span> </a> </li> </ul> <div id="version"></div> </footer> </section> <section class="nav-cmp-list"> <header> <button class="back-button"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div class="search-container"> <div class="search-input-wrapper"> <svg class="search-icon" viewBox="0 0 24 24" width="16" height="16"> <path fill="none" stroke="currentColor" stroke-width="2" d="M15.5 15.5L20 20M10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10C17 13.866 13.866 17 10 17Z" /> </svg> <input type="text" id="component-search" class="component-search-input" placeholder="Search components..." autocomplete="off" spellcheck="false" /> <button id="clear-search" class="clear-search-button" type="button" aria-label="Clear search" > <svg viewBox="0 0 24 24" width="16" height="16"> <path fill="none" stroke="currentColor" stroke-width="2" d="M6 6l12 12M6 18L18 6" /> </svg> </button> </div> </div> <div> <h2>Custom Components</h2> <p> <button id="open-builder-registry"></button> </p> </div> </header> <div class="section-content"> <div id="cmp-list" class="cmp-list nav-list"></div> </div> <div class="nav-loading-icon spinner"></div> <footer> <p class="info"> Expand on Builder's selection of built-in blocks by <a target="_blank" href="https://www.builder.io/c/docs/custom-components-intro" >registering components</a > from your codebase. This way, teammates can drag and drop your components within Builder's Visual Editor just like any other block. </p> </footer> </section> <section class="nav-cmp-detail"> <header> <button class="back-button" data-back="nav-cmp-list"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div> <h2 id="cmp-detail-title"></h2> <p> <button id="cmp-open-source"></button> </p> </div> </header> <div class="section-content"> <div id="cmp-error"></div> <label class="ui-switch"> <div> <h3>Register Component</h3> <p> Registers this component so it can be used within Builder Visual CMS </p> </div> <input type="checkbox" role="switch" id="cmp-register" /> <span class="switcher"></span> </label> <div id="cmp-detail"> <label class="ui-text-input"> <h3>Component Name</h3> <div class="input"> <input type="text" id="cmp-name" autocapitalize="off" autocorrect="off" spellcheck="false" autocomplete="off" minlength="2" maxlength="30" required placeholder="e.g. My Counter" /> </div> <p> Unique name to identify this custom component within Builder. Press ESC to cancel </p> </label> <div class="cmp-detail-inputs-container"> <h3> <span>Builder Inputs (Props)</span> <button class="cmp-detail-inputs-reload" id="btn-inputs-reload"> Reload </button> </h3> <div id="cmp-detail-inputs"></div> </div> </div> </div> <div class="cmp-cover"></div> <div class="cmp-loading-icon spinner"></div> </section> <section class="nav-cmp-input"> <header> <button class="back-button" data-back="nav-cmp-detail"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div> <h2 id="cmp-input-title"></h2> <p> <button id="input-open-source"></button> </p> </div> </header> <div class="section-content"> <label class="ui-switch"> <div> <h3>Enable Input</h3> <p>Add this component prop as a Builder input</p> </div> <input type="checkbox" role="switch" id="input-register" /> <span class="switcher"></span> </label> <div class="cmp-prop-info"> <div class="cmp-input-readonly"> <h3>Prop Name</h3> <span id="cmp-prop-name"></span> </div> <div class="cmp-input-readonly"> <h3>Prop Type</h3> <span id="cmp-prop-type"></span> </div> </div> <div class="cmp-input-detail"> <label class="ui-text-input"> <h3>Builder Input Name</h3> <div class="input"> <input type="text" id="input-name" autocapitalize="off" autocorrect="off" spellcheck="false" autocomplete="off" minlength="1" maxlength="30" required placeholder="e.g. Text" /> </div> <p> Friendly name to identify this component prop as a Builder input. Press ESC to cancel </p> </label> <label class="ui-select"> <h3>Builder Input Type</h3> <div class="select"> <select id="input-type"></select> </div> <p> Correlate to what editing UI is appropriate for this Builder input. <a href="https://www.builder.io/c/docs/custom-components-input-types" target="_blank" >Read more about input types.</a > </p> </label> </div> <div class="input-cover"></div> <div class="input-loading-icon spinner"></div> </div> </section> <section class="nav-settings"> <header> <button class="back-button"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div> <h2>Settings</h2> <p>Configure Builder's Devtools</p> </div> </header> <div class="section-content"> <label class="ui-switch"> <div> <h3>Enable edit button in UI</h3> <p>Enables the edit button so you can edit content in Builder</p> </div> <input type="checkbox" role="switch" id="enable-edit" /> <span class="switcher"></span> </label> </div> </section> <div class="ui-toast" id="toast"></div> </aside> <button class="menu-toggle" aria-label="Toggle Builder Devtools"> <div> <div class="highlight-bg"></div> <svg viewBox="0 0 31 36" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M31 9.96854C31.0016 11.4553 30.6701 12.9236 30.03 14.2654C29.3898 15.6072 28.4572 16.7884 27.3007 17.7221L0.702841 2.61812C0.601104 2.56012 0.506714 2.49008 0.421705 2.40951C0.288323 2.27871 0.182333 2.12263 0.109928 1.95039C0.0375215 1.77814 0.000151253 1.59319 0 1.40633C0 1.03335 0.148098 0.675643 0.411715 0.411905C0.675332 0.148167 1.03287 0 1.40568 0L21.036 0C23.6786 0 26.213 1.05025 28.0816 2.91972C29.9502 4.78918 31 7.32472 31 9.96854Z" fill="#18B4F4" /> <path d="M31 25.4757C31.0004 26.7849 30.7429 28.0815 30.2423 29.2912C29.7417 30.5009 29.0078 31.6001 28.0825 32.526C27.1572 33.4519 26.0587 34.1864 24.8497 34.6875C23.6406 35.1886 22.3448 35.4465 21.0361 35.4465H1.40573C1.12766 35.4436 0.856725 35.3581 0.627199 35.201C0.397672 35.044 0.219871 34.8223 0.116289 34.5641C0.0127078 34.3059 -0.011999 34.0228 0.0452946 33.7505C0.102588 33.4783 0.239308 33.2292 0.438156 33.0347C0.517415 32.9551 0.606358 32.8858 0.702893 32.8284L11.1705 26.8843L27.2984 17.7244C28.4548 18.6579 29.3874 19.8387 30.028 21.18C30.6685 22.5213 31.0007 23.9891 31 25.4757Z" fill="#FD6B3C" /> <path d="M27.3011 17.7221L11.1709 26.8843L0.703209 32.8284C0.602697 32.8843 0.509784 32.9528 0.426758 33.0323C4.41799 28.9369 6.6496 23.442 6.64456 17.7221C6.65208 12.0015 4.42111 6.50517 0.429101 2.40948C0.51411 2.49005 0.6085 2.56009 0.710237 2.61809L27.3011 17.7221Z" fill="#A97FF2" /> </svg> </div> </button>\`,si(e),ui(e),oi(e),ri(e),ti(e),ci(e),this.setAttribute("aria-hidden","true"),e.getElementById("version").textContent="v1.64.2-beta.202606091524.9594880"}highlightOpener(){let e=this.shadowRoot.querySelector(".menu-toggle");e.classList.add("menu-toggle-highlight"),e.classList.add("menu-toggle-highlight-no-transition"),setTimeout(()=>{e.classList.remove("menu-toggle-highlight-no-transition"),setTimeout(()=>{e.classList.remove("menu-toggle-highlight")},20)},20)}};var lo=\`<style>*,*:before,*:after{box-sizing:border-box}html,body,:host{position:fixed;top:0;left:0;width:100%;height:100vh;z-index:2147483646;margin:0;padding:0;line-height:1.8;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";background-color:#252525;color:#fff;transition:opacity .25s ease-in-out}:host([aria-hidden="true"]){opacity:0;pointer-events:none}main{position:absolute;top:0;left:0;width:100%;height:100vh}h1{margin-top:0;font-size:24px;font-weight:300;line-height:1.4}p{margin:20px 0;font-weight:300}button{cursor:pointer}aside{position:absolute;top:0;left:0;width:350px;height:100vh;padding:60px 0 0 50px;background-color:#121212}aside ul{margin:30px 0 0;padding:0;list-style:none}aside li{position:relative;margin:0;padding:20px 10px;font-weight:300}aside li.highlight{color:#48a1ff}aside li.active{font-weight:700}aside li .circle{position:absolute;top:20px;left:10px;width:24px;height:24px;border:3px solid white;border-radius:50%;font-size:14px}aside li.highlight .circle{border-color:#48a1ff}aside li.active .circle:after{content:"";position:absolute;top:3px;left:3px;width:12px;height:12px;border-radius:50%;background-color:#48a1ff}aside li.completed .circle{background-color:#48a1ff}aside li.completed .circle:after{content:"";position:absolute;top:2px;left:6px;width:6px;height:13px;border:3px solid black;border-top:none;border-left:none;transform:rotate(45deg)}aside li .line{position:absolute;top:44px;left:21px;width:3px;height:45px;background-color:#fff}aside li.completed .line{background-color:#48a1ff}aside li span{display:block;margin-left:44px}nav{margin-top:30px}section{position:absolute;top:135px;left:350px;padding:0 80px 0 140px;transition:opacity .15s ease-in-out}section[aria-hidden=true]{pointer-events:none;opacity:0}section h1,section p{min-width:300px;max-width:600px}.button{position:relative;display:inline-block;color:#fff;background-color:#48a1ff;border-radius:4px;text-decoration:none;padding:10px 40px 10px 20px;white-space:nowrap}.button:hover{background-color:#48a1ffd9}#button-icon{position:absolute;top:1px;right:5px;bottom:0;width:30px;background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="none" stroke="white" stroke-linecap="square" stroke-miterlimit="10" stroke-width="48" d="M184 112l144 144-144 144"/></svg>');background-repeat:no-repeat;background-position:center;background-size:24px 24px}.button[aria-disabled=true]{opacity:.9;background-color:#ffffff4d;pointer-events:none;padding-right:60px}.button[aria-disabled=true] #button-icon{top:21px;right:29px;width:8px;height:8px;border-radius:4px;background:#fff;color:#fff;animation:dot-flashing .5s infinite linear alternate;animation-delay:.25s}.button[aria-disabled=true] #button-icon:before,.button[aria-disabled=true] #button-icon:after{content:"";display:inline-block;position:absolute;top:0}.button[aria-disabled=true] #button-icon:before{left:-12px;width:8px;height:8px;border-radius:4px;background-color:#fff;color:#fff;animation:dot-flashing .5s infinite alternate;animation-delay:0s}.button[aria-disabled=true] #button-icon:after{left:12px;width:8px;height:8px;border-radius:4px;background-color:#fff;color:#fff;animation:dot-flashing .5s infinite alternate;animation-delay:.5s}@keyframes dot-flashing{0%{background-color:#fff}50%,to{background-color:#ffffff4d}}.logo{margin-left:9px;background:url('data:image/svg+xml,<svg viewBox="0 0 150 32" fill="none" xmlns="http://www.w3.org/2000/svg" > <g clip-path="url(%23clip0_4_304)"> <path d="M27.9858 8.99927C27.9872 10.3415 27.688 11.667 27.1101 12.8783C26.5321 14.0896 25.6902 15.156 24.6462 15.9989V15.9989L0.634502 2.36355C0.542657 2.31119 0.457444 2.24796 0.380701 2.17523C0.260289 2.05715 0.164605 1.91624 0.0992389 1.76075C0.0338732 1.60525 0.000136546 1.43828 0 1.26959C0 0.932873 0.133698 0.609948 0.371683 0.371854C0.609667 0.13376 0.932443 0 1.269 0L18.9906 0C21.3763 0 23.6642 0.948135 25.3512 2.63583C27.0381 4.32352 27.9858 6.61252 27.9858 8.99927V8.99927Z" fill="%2318B4F4" /> <path d="M27.9858 22.9986C27.9861 24.1806 27.7536 25.351 27.3017 26.4431C26.8498 27.5352 26.1873 28.5275 25.352 29.3634C24.5167 30.1993 23.5249 30.8624 22.4335 31.3147C21.342 31.7671 20.1721 32 18.9907 32H1.26906C1.01802 31.9973 0.77343 31.9202 0.566221 31.7784C0.359012 31.6366 0.198499 31.4364 0.104989 31.2034C0.0114791 30.9703 -0.0108254 30.7147 0.0408974 30.4689C0.0926201 30.2231 0.216046 29.9982 0.395559 29.8226V29.8226C0.467112 29.7508 0.547407 29.6882 0.634555 29.6364L10.0844 24.2703L24.6441 16.001C25.688 16.8438 26.53 17.9097 27.1083 19.1206C27.6866 20.3315 27.9864 21.6566 27.9858 22.9986V22.9986Z" fill="%23FD6B3C" /> <path d="M24.6461 15.9989L10.0843 24.2703L0.634458 29.6365C0.54372 29.6868 0.459841 29.7487 0.384888 29.8205C3.98804 26.1233 6.00266 21.1627 5.99812 15.9989C6.0049 10.8346 3.99085 5.87268 0.387003 2.17523C0.463746 2.24796 0.548959 2.31119 0.640803 2.36355L24.6461 15.9989Z" fill="%23A97FF2" /> <path d="M47.6659 11.7352C51.8177 11.7352 54.1632 15.0531 54.1632 19.0714C54.1632 23.0896 51.8177 26.3821 47.6659 26.3821C45.5086 26.3821 43.8589 25.5188 42.9473 24.0545L42.5709 26.052H39.9736V6.77115H43.1884V13.8914C43.971 12.6959 45.5086 11.7352 47.6659 11.7352ZM47.0187 23.5488C49.4446 23.5488 50.9547 21.5809 50.9547 19.0714C50.9547 16.5089 49.4446 14.5664 47.0187 14.5664C44.5928 14.5664 43.0806 16.5047 43.0806 19.0714C43.0806 21.583 44.5653 23.5488 47.0187 23.5488V23.5488Z" fill="white" /> <path d="M65.4595 20.2859V12.0611H68.668V20.123C68.668 23.7202 67.0246 26.3821 62.4943 26.3821C57.9639 26.3821 56.3206 23.7117 56.3206 20.123V12.0611H59.529V20.2859C59.529 22.4696 60.5527 23.5488 62.49 23.5488C64.4274 23.5488 65.4595 22.4696 65.4595 20.2859Z" fill="white" /> <path d="M71.2355 7.74451C71.2247 7.46284 71.2724 7.18199 71.3755 6.91968C71.4787 6.65737 71.6351 6.41929 71.8348 6.22047C72.0345 6.02165 72.2732 5.8664 72.5359 5.76452C72.7986 5.66264 73.0796 5.61633 73.3611 5.62853C74.5793 5.62853 75.4571 6.50666 75.4571 7.75509C75.4571 9.00352 74.5793 9.8224 73.3611 9.8224C72.1428 9.8224 71.2355 8.9612 71.2355 7.74451Z" fill="white" /> <path d="M128.476 7.74451C128.465 7.46376 128.513 7.18383 128.615 6.92227C128.718 6.66071 128.873 6.42315 129.072 6.22449C129.27 6.02583 129.508 5.87035 129.769 5.7678C130.031 5.66524 130.31 5.61783 130.591 5.62852C131.809 5.62852 132.687 6.50666 132.687 7.75509C132.687 9.00352 131.809 9.8224 130.591 9.8224C129.373 9.8224 128.476 8.9612 128.476 7.74451Z" fill="white" /> <path d="M122.302 24.1031C122.291 23.8223 122.339 23.5422 122.441 23.2805C122.543 23.0188 122.699 22.7811 122.897 22.5824C123.096 22.3837 123.334 22.2282 123.595 22.1258C123.857 22.0233 124.137 21.9761 124.417 21.9872C125.636 21.9872 126.513 22.8653 126.513 24.1031C126.513 25.341 125.636 26.1726 124.417 26.1726C123.199 26.1726 122.302 25.3219 122.302 24.1031Z" fill="white" /> <path d="M74.9516 12.059H71.7432V26.0583H74.9516V12.059Z" fill="white" /> <path d="M78.16 26.0583V6.77115H81.3685V26.0626L78.16 26.0583Z" fill="white" /> <path d="M94.6063 6.77115H97.8148V26.0626H95.2239L94.8474 24.0651C93.9591 25.523 92.3094 26.3927 90.131 26.3927C86.0046 26.3927 83.6591 23.0748 83.6591 19.0819C83.6591 15.0891 86.0046 11.7458 90.131 11.7458C92.3137 11.7458 93.8238 12.7149 94.6063 13.902V6.77115ZM90.7993 14.5707C88.3734 14.5707 86.8633 16.5131 86.8633 19.0756C86.8633 21.5851 88.3734 23.553 90.7993 23.553C93.2252 23.553 94.7354 21.5851 94.7354 19.0756C94.7396 16.5047 93.257 14.5664 90.8036 14.5664L90.7993 14.5707Z" fill="white" /> <path d="M113.479 22.2284C112.482 24.7359 110.162 26.3821 107.117 26.3821C102.887 26.3821 100.137 23.225 100.137 19.0439C100.137 14.9706 102.942 11.7353 107.093 11.7353C111.245 11.7353 113.969 14.8902 113.969 18.991C113.982 19.3255 113.953 19.6604 113.883 19.9876H103.288C103.53 22.2009 104.959 23.6292 107.197 23.6292C108.735 23.6292 110.001 22.8738 110.594 21.473L113.479 22.2284ZM103.341 17.6156H110.784C110.513 15.6731 109.166 14.3506 107.089 14.3506C105.012 14.3506 103.665 15.7006 103.341 17.6156V17.6156Z" fill="white" /> <path d="M123.779 14.9452C123.538 14.9117 123.295 14.8933 123.051 14.8902C120.786 14.8902 119.439 16.0772 119.439 18.7751V26.0583H116.23V12.0611H118.821L119.195 14.0014C119.707 13.1127 120.887 11.9257 123.322 11.9257C123.455 11.9257 123.779 11.9532 123.779 11.9532V14.9452Z" fill="white" /> <path d="M132.192 12.059H128.984V26.0583H132.192V12.059Z" fill="white" /> <path d="M134.483 19.0714C134.483 15.1335 137.287 11.7353 141.735 11.7353C146.183 11.7353 149.015 15.1335 149.015 19.0714C149.015 23.0092 146.213 26.3821 141.735 26.3821C137.258 26.3821 134.483 23.0092 134.483 19.0714ZM141.735 23.5488C144.083 23.5488 145.806 21.7692 145.806 19.0714C145.806 16.3735 144.083 14.5664 141.735 14.5664C139.387 14.5664 137.687 16.346 137.687 19.0714C137.687 21.7968 139.417 23.5488 141.735 23.5488V23.5488Z" fill="white" /> </g> <defs> <clipPath id="clip0_4_304"> <rect width="149.015" height="32" fill="white" /> </clipPath> </defs> </svg>');background-repeat:no-repeat;width:150px;height:32px}@media(max-width:840px){aside{width:250px;padding:60px 0 0 20px}section{left:250px;padding:0 80px}}@media(max-width:590px){aside{width:230px;padding:60px 0 0 10px}section{left:230px;padding:0 40px}}#modified-files-message a{color:#cbcbcb;font-weight:300;text-decoration:underline}#modified-files-message a:hover{color:#fff;text-decoration:none}#restart-warning{border-radius:4px;padding:8px 16px;border:1px solid #fd6b3c;background:#fd6b3c1a}#react-router-steps{margin:0 0 5px;padding:0 20px}#need-help{color:#48a1ff;text-decoration:none}#router-message{border-radius:4px;padding:16px;border:1px solid #48a1ff}#router-finish-button{margin-top:12px}#router-checkbox-div{display:flex;align-items:center}#router-checkbox{margin-right:10px;width:15px;height:15px}#success-title{display:flex;align-items:center;gap:10px}#success-title .check-icon{display:inline-block;width:24px;height:24px;border:2px solid #28a745;border-radius:50%;position:relative}#success-title .check-icon:before{content:"";position:absolute;top:50%;left:50%;width:6px;height:12px;border:solid #28a745;border-width:0 2px 2px 0;transform:translate(-50%,-60%) rotate(45deg)}
|
|
1279
|
+
\`,t.appendChild(e),setTimeout(()=>{e.classList.add("menu-toggle-tooltip-show"),e.addEventListener("click",()=>{e.classList.remove("menu-toggle-tooltip-show")})},1e3)};function ui(t){t.getElementById("go-to-builder").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Ee(t,!1),window.open(Ur(),"builder")}),t.getElementById("components-link").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation();let c=t.querySelector(".nav-cmp-list .section-content");c.scrollTop=0,oe(t,"nav-cmp-list"),ai(t)}),t.getElementById("settings-link").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),oe(t,"nav-settings")}),t.getElementById("add-page-link").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Ee(t,!1),window.open(je(),"builder")}),t.getElementById("import-from-figma").addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Ee(t,!1),window.open("https://www.figma.com/community/plugin/747985167520967365/builder-io-ai-powered-figma-to-code-react-vue-tailwind-more")})}function ci(t){let e=t.getElementById("enable-edit");e.addEventListener("change",r=>{r.stopPropagation(),Ht(e.checked)}),e.checked=it(),Ht(e.checked)}var Dt=class extends HTMLElement{constructor(){super()}connectedCallback(){let e=this.attachShadow({mode:"open"});e.innerHTML=\`<style>*,*:before,*:after{box-sizing:border-box}:host{--background-color: rgba(40, 40, 40, 1);--primary-color: rgba(72, 161, 255, 1);--primary-color-subdued: rgb(72, 161, 255, .6);--primary-color-highlight: rgb(126, 188, 255);--primary-contrast-color: white;--edit-color: #1d74e2;--edit-color-highlight: #1c6bd1;--edit-color-alpha: rgb(72, 161, 255, .15);--error-color: #ff2b55;--text-color: white;--text-color-highlight: white;--border-color: #454545;--button-background-color-hover: rgba(255, 255, 255, .1);--menu-width: 320px;--transition-time: .15s;--font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-family:var(--font-family);line-height:1.6}button{cursor:pointer;color:var(--text-color);-webkit-tap-highlight-color:transparent}input,select,button{font-family:var(--font-family)}.menu-toggle{position:absolute;right:0;bottom:0;pointer-events:auto;padding:8px;background:transparent;border:none;appearance:none}.menu-toggle div{position:relative;width:64px;height:64px;pointer-events:none;border-radius:50%;background:#000;border:1px solid white;box-shadow:#00000054 0 0 8px}.menu-toggle:hover div{background-color:var(--background-color);border:1px solid rgb(220,220,220)}.menu-toggle svg{position:absolute;top:15px;left:15px;width:33px;height:32px}div.highlight-bg{position:absolute;top:-1px;left:-1px;background-color:#1a1a1a;pointer-events:none;transition:all .4s ease-out;opacity:0}.menu-toggle-highlight-no-transition div.highlight-bg{transition:none}.menu-toggle-highlight div.highlight-bg{opacity:1}.menu-toggle-tooltip{position:absolute;bottom:0;right:0;width:382px;height:72px;padding:0;text-align:left;appearance:none;background-color:transparent;border:none;pointer-events:none;transform:translate3d(320px,0,0);opacity:0;transition:all .15s ease-in-out;color:#fff}.menu-toggle-tooltip.menu-toggle-tooltip-show{pointer-events:auto;opacity:1;transform:translateZ(0)}.menu-toggle-tooltip-content{position:absolute;inset:0 95px 10px 0;padding:8px 12px;background-color:var(--primary-color);box-shadow:#00000054 0 0 20px;border-radius:2px}.menu-toggle-tooltip-content:before{content:"";position:absolute;bottom:15px;right:-6px;width:30px;height:30px;background-color:var(--primary-color);transform:rotate(45deg)}.menu-toggle-tooltip:hover .menu-toggle-tooltip-content,.menu-toggle-tooltip:hover .menu-toggle-tooltip-content:before{background-color:var(--primary-color-highlight)}.menu-toggle-tooltip-content h3{margin:0;font-size:16px}.menu-toggle-tooltip-content p{margin:0;font-size:12px}section{position:absolute;display:grid;grid-template-rows:64px auto 64px;top:0;left:0;width:100%;height:100%;padding:0;pointer-events:none}.section-content{margin:0;padding:0 0 10px;font-weight:300;transform:translate3d(105%,0,0);transition:transform var(--transition-time) ease-in-out;overflow-y:auto}.section-content .error{color:var(--error-color);font-weight:700}section a{text-decoration:none;color:var(--text-color)}section h3,section p{margin-left:16px;margin-right:16px}.info{font-size:12px}ul.list{list-style:none;padding:0;margin:0}ul.list li{display:block;padding:0;margin:0}ul.list a,ul.list button{display:grid;grid-template-columns:24px auto;grid-gap:16px;padding:12px;margin:8px 0;border:none;background:transparent;appearance:none;width:100%;font-weight:300;text-align:left;text-decoration:none;color:var(--text-color)}ul.list a:hover,ul.list button:hover{text-decoration:none;color:var(--text-color);background-color:var(--button-background-color-hover)}ul.list a span,ul.list button span{display:block;font-size:16px;font-weight:500;line-height:1.5;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}header{position:relative;display:grid;grid-template-columns:44px 1fr;gap:8px;padding-left:8px;border-bottom:1px solid var(--border-color);transition:opacity var(--transition-time) ease-in-out;opacity:0;pointer-events:none}header>div{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nav-home header>div{margin-right:56px}header h2{margin:7px 0 0;font-size:18px;font-weight:500;line-height:1.5;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}header p{margin:2px 0 0;font-size:12px;font-weight:300;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}header p button{display:block;margin:0;padding:0;width:100%;font-size:12px;font-weight:300;text-decoration:none;appearance:none;text-align:left;background-color:transparent;border:none;color:var(--primary-color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}header p button:hover{text-decoration:underline;color:var(--primary-color)}.builder-logo{margin:12px 0 0 8px}#close{display:block;position:absolute;appearance:none;background:transparent;border:none;border-radius:50%;margin:0;padding:0;right:4px;top:8px;width:48px;height:48px;z-index:1;opacity:.7}#close:hover{opacity:1;background-color:var(--button-background-color-hover)}#close svg{position:absolute;top:12px;left:12px;width:24px;height:24px;fill:currentColor;pointer-events:none}.back-button{position:relative;display:block;margin:7px 0 0 -2px;width:48px;height:48px;background:transparent;border:none;appearance:none;border-radius:50%}.back-button:hover{background-color:var(--button-background-color-hover)}.back-button svg{position:absolute;top:12px;left:12px;width:24px;height:24px;fill:currentColor;pointer-events:none}footer{border-top:1px solid var(--border-color);transition:opacity var(--transition-time) ease-in-out;opacity:0;pointer-events:none}section.nav-cmp-list{grid-template-rows:64px auto 120px}footer a{text-decoration:underline;color:var(--primary-color)}footer a:hover{color:var(--primary-color);text-decoration:none}.nav-list{padding:2px 0}.nav-loading{pointer-events:none}.nav-loading-icon{position:absolute;display:inline-block;top:170px;left:0;width:100%;transform:translateZ(0);pointer-events:auto;opacity:0;transition:all 50ms ease-in-out;transition-delay:50ms;pointer-events:none}.nav-loading .nav-loading-icon{opacity:.5}.nav-list h4{margin:8px 8px 8px 10px;font-size:14px;font-weight:600}.nav-list .nav-list-item+h4{margin-top:30px}.nav-list-item{display:grid;grid-template-columns:1fr 1fr;gap:8px;position:relative;margin:2px 0;padding:8px 28px 8px 46px;width:100%;font-size:14px;font-weight:300;text-align:left;border:none;background:transparent;appearance:none}.nav-list-item:hover{background-color:var(--button-background-color-hover)}.nav-list-item-icon{position:absolute;top:4px;left:10px;width:24px;height:24px;object-fit:contain;filter:invert(100%);background-size:24px 24px;background-repeat:no-repeat;background-position:center center}.nav-list-item span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none}.nav-list-item:after{display:block;position:absolute;content:"";background-image:url('data:image/svg+xml,<svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L7 7L1 13" stroke="%23F2F2F2" stroke-opacity="0.5" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/></svg>');background-repeat:no-repeat;background-position:12px 9px;top:0;right:0;width:32px;height:32px;pointer-events:none}.nav-list-item-note{opacity:0;font-size:12px;padding-top:1px;text-align:right}.nav-list-item:hover .nav-list-item-note{opacity:.5}.ui-select{display:block;margin:8px 0 16px;padding:8px 16px;cursor:pointer}.ui-select h3{margin:0;font-size:14px;font-weight:500}.ui-select p{margin:8px 0;font-size:12px;font-weight:300}.ui-select .select{position:relative;margin:8px 0;border-radius:4px;padding:0;line-height:1.1;overflow:hidden;border:1px solid var(--border-color)}.ui-select select{appearance:none;background-color:transparent;border:none;outline:none;padding:8px 32px 8px 8px;margin:0;width:100%;font-size:14px;cursor:pointer;text-overflow:ellipsis;opacity:.6;color:var(--text-color)}.ui-select .select:after{content:"";top:6px;right:5px;width:24px;height:24px;position:absolute;background-image:url('data:image/svg+xml,<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="%23F2F2F2" d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/></svg>');background-repeat:no-repeat;background-position:center;pointer-events:none;opacity:.6}.ui-select .select:hover{border-color:var(--primary-color-subdued)}.ui-text-input .select:focus-within{border-color:var(--primary-color)}.ui-text-input .select:focus-within select{opacity:1}.spinner:after{content:" ";display:block;width:32px;height:32px;margin:0 auto;pointer-events:auto;border-radius:50%;border:3px solid var(--text-color);border-color:var(--text-color) transparent var(--text-color) transparent;animation:spinner .75s linear infinite}@keyframes spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.ui-switch{display:grid;grid-template-columns:auto 48px;grid-gap:20px;margin:8px 0 16px;padding:8px 0 8px 16px;cursor:pointer}.ui-switch>*{pointer-events:none}.ui-switch input{display:none;visibility:hidden}.ui-switch .switcher{display:inline-block;border-radius:100px;width:35px;height:14px;background-color:#ccc;position:relative;top:6px;vertical-align:middle;cursor:pointer}.ui-switch input[type=checkbox]:checked+.switcher{background-color:var(--primary-color-subdued)}.ui-switch .switcher:before{content:"";display:block;width:20px;height:20px;background-color:var(--text-color);box-shadow:0 1px 3px #0009;border-radius:50%;position:absolute;top:-3px;left:0;margin-right:0;transition:all .15s}.ui-switch input[type=checkbox]:checked+.switcher:before{left:100%;margin-left:-20px;background-color:var(--primary-color)}.ui-switch h3{margin:0;font-size:14px;font-weight:500}.ui-switch p{margin:4px 0 0;font-size:12px;font-weight:300}.ui-text-input{display:block;margin:8px 0 16px;padding:8px 16px;cursor:pointer}.ui-text-input h3{margin:0;font-size:14px;font-weight:500}.ui-text-input p{margin:8px 0;font-size:12px;font-weight:300}.ui-text-input .input{position:relative;margin:8px 0;border:1px solid var(--border-color);border-radius:4px;background:transparent;padding:2px;overflow:hidden}.ui-text-input input{display:block;width:235px;font-size:14px;border:none;background:transparent;padding:6px;appearance:none;color:var(--text-color);opacity:.6;outline:none}.ui-text-input .input:hover{border-color:var(--primary-color-subdued)}.ui-text-input .input:focus-within{border-color:var(--primary-color)}.ui-text-input .input:focus-within input{opacity:1}.ui-text-input .input:after{content:"";position:absolute;top:5px;right:14px;width:8px;height:17px;border:2px solid rgba(51,181,51,1);border-top:none;border-left:none;transform:rotate(45deg);opacity:0;transition:opacity 80ms ease-in-out;pointer-events:none}.ui-text-input.saved .input:after{opacity:1}.ui-toast{position:fixed;bottom:8px;left:8px;right:8px;padding:6px 12px;font-size:14px;border-radius:4px;transform:translate3d(0,150%,0);opacity:0;transition:all var(--transition-time) ease-in-out;background-color:var(--primary-color-subdued);color:var(--text-color);pointer-events:none}.ui-toast.ui-toast-show{transform:translateZ(0);opacity:1;pointer-events:auto}[data-view=nav-home] .nav-home .section-content,[data-view=nav-cmp-list] .nav-cmp-list .section-content,[data-view=nav-cmp-detail] .nav-cmp-detail .section-content,[data-view=nav-cmp-input] .nav-cmp-input .section-content,[data-view=nav-settings] .nav-settings .section-content{transform:translateZ(0);pointer-events:auto}[data-view=nav-home] .nav-home header,[data-view=nav-home] .nav-home footer,[data-view=nav-cmp-list] .nav-cmp-list header,[data-view=nav-cmp-list] .nav-cmp-list footer,[data-view=nav-cmp-detail] .nav-cmp-detail header,[data-view=nav-cmp-detail] .nav-cmp-detail footer,[data-view=nav-cmp-input] .nav-cmp-input header,[data-view=nav-cmp-input] .nav-cmp-input footer,[data-view=nav-settings] .nav-settings header,[data-view=nav-settings] .nav-settings footer{opacity:1;pointer-events:auto}[data-view=nav-cmp-list] .nav-home .section-content,[data-view=nav-cmp-detail] .nav-home .section-content,[data-view=nav-cmp-detail] .nav-cmp-list .section-content,[data-view=nav-cmp-input] .nav-home .section-content,[data-view=nav-cmp-input] .nav-cmp-list .section-content,[data-view=nav-cmp-input] .nav-cmp-detail .section-content,[data-view=nav-settings] .nav-home .section-content{transform:translate3d(-105%,0,0)}.cmp-item .nav-list-item-icon{background-image:url('data:image/svg+xml,<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20.83 16.809C20.94 16.561 21 16.289 21 16.008V7.99001C20.9994 7.64108 20.9066 7.29851 20.731 6.99699C20.5554 6.69547 20.3032 6.44571 20 6.27301L13 2.26501C12.6954 2.09103 12.3508 1.99951 12 1.99951C11.6492 1.99951 11.3046 2.09103 11 2.26501L7.988 3.99001M5.441 5.44801L4 6.27301C3.381 6.62801 3 7.28301 3 7.99101V16.009C3 16.718 3.381 17.372 4 17.726L11 21.734C11.3046 21.908 11.6492 21.9995 12 21.9995C12.3508 21.9995 12.6954 21.908 13 21.734L18.544 18.56" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 22V12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.532 10.538L20.73 6.95996" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.27002 6.95996L12 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/><path d="M3 3L21 21" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/></svg>');opacity:.3}.cmp-item.registered .nav-list-item-icon{background-image:url('data:image/svg+xml,<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M21 16.008V7.99001C20.9994 7.64108 20.9066 7.29851 20.731 6.99699C20.5554 6.69547 20.3032 6.44571 20 6.27301L13 2.26501C12.6954 2.09103 12.3508 1.99951 12 1.99951C11.6492 1.99951 11.3046 2.09103 11 2.26501L4 6.27301C3.381 6.62801 3 7.28301 3 7.99101V16.009C3 16.718 3.381 17.372 4 17.726L11 21.734C11.3046 21.908 11.6492 21.9995 12 21.9995C12.3508 21.9995 12.6954 21.908 13 21.734L20 17.726C20.619 17.371 21 16.716 21 16.008Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 22V12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 12L20.73 6.95996" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M3.26999 6.95996L12 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /></svg>');opacity:.8}.search-highlight{background-color:var(--primary-color-alpha);padding:0 2px;border-radius:2px;font-weight:500}.search-container{position:sticky;top:0;z-index:10;padding:12px 16px;background:var(--background-color);border-bottom:1px solid var(--border-color)}.search-input-wrapper{position:relative;display:flex;align-items:center}.search-icon{position:absolute;left:12px;color:var(--text-color-secondary);pointer-events:none}.component-search-input{width:100%;height:36px;padding:8px 36px;border:1px solid var(--border-color);border-radius:6px;background:var(--input-background);color:var(--text-color);font-size:14px;transition:border-color .2s,box-shadow .2s}.component-search-input:focus{outline:none;border-color:var(--primary-color);box-shadow:0 0 0 2px var(--primary-color-alpha)}.component-search-input::placeholder{color:var(--text-color-tertiary)}.clear-search-button{position:absolute;right:8px;padding:4px;color:var(--text-color-secondary);border:none;background:transparent;border-radius:4px;cursor:pointer;opacity:0;transition:opacity .2s,background-color .2s;display:flex;align-items:center;justify-content:center}.clear-search-button:hover{background-color:var(--hover-color)}.component-search-input:not(:placeholder-shown)+.clear-search-button{opacity:1}.no-results{padding:32px 16px;text-align:center;color:var(--text-color-secondary);font-size:14px}#cmp-detail{position:relative}.cmp-loading{pointer-events:none!important}.cmp-loading-icon{position:absolute;display:inline-block;top:170px;left:0;width:100%;transform:translateZ(0);pointer-events:auto;opacity:0;transition:all 50ms ease-in-out;transition-delay:50ms;pointer-events:none}.cmp-loading .cmp-loading-icon{opacity:.5}.cmp-cover{position:absolute;top:160px;left:0;width:100%;height:100vh;background:var(--background-color);transform:translateZ(0);pointer-events:none;display:none}[data-view=nav-cmp-detail] .cmp-cover{display:block;pointer-events:auto}.cmp-enabled .cmp-cover{transform:translate3d(0,105%,0);pointer-events:none}.section-ready .cmp-cover{transition:all var(--transition-time) ease-in-out}.cmp-detail-inputs-container{margin:8px 0 16px;padding:0}.cmp-detail-inputs-container h3{margin:0 0 6px;padding-left:16px;padding-right:8px;font-size:14px;font-weight:500;display:flex;justify-content:space-between;align-items:center}.cmp-detail-inputs-reload{font-weight:300;font-size:.9em;text-decoration:none;appearance:none;text-align:left;background-color:transparent;border:none;color:var(--primary-color);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cmp-detail-inputs-reload:hover{text-decoration:underline;color:var(--primary-color)}.cmp-detail-inputs-container .cmp-inputs-empty{padding:0;margin-top:12px;font-size:12px;font-weight:300;opacity:.5;font-style:italic}.cmp-detail-inputs-container .nav-list-item-icon{opacity:.8;background-size:20px 20px;background-position:4px center}.input-icon{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path></svg>')}.input-icon-array{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 16v-6a2 2 0 1 1 4 0v6"></path> <path d="M10 13h4"></path></svg>')}.input-icon-boolean{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 16h2a2 2 0 1 0 0 -4h-2h2a2 2 0 1 0 0 -4h-2v8z"></path></svg>')}.input-icon-number{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 16v-8l4 8v-8"></path></svg>')}.input-icon-object{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M12 8a2 2 0 0 1 2 2v4a2 2 0 1 1 -4 0v-4a2 2 0 0 1 2 -2z"></path></svg>')}.input-icon-string{background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path> <path d="M10 15a1 1 0 0 0 1 1h2a1 1 0 0 0 1 -1v-2a1 1 0 0 0 -1 -1h-2a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1"></path></svg>')}.cmp-input-item-unregistered{opacity:.4}.cmp-input-item-unregistered .input-icon:after{content:"";position:absolute;top:11px;left:4px;width:20px;height:2px;background-color:#000;transform:rotate(-45deg)}.cmp-prop-info{border-bottom:1px solid var(--border-color)}.cmp-input-readonly{margin:16px 0;padding:0 16px;display:grid;grid-template-columns:50% 50%;gap:12px}.cmp-input-readonly h3{margin:0;font-size:14px;font-weight:500}.cmp-input-readonly span{margin-top:2px;font-size:12px;font-weight:300;opacity:.8}.cmp-input-detail{margin:16px 0}.cmp-input-detail a{color:var(--primary-color);text-decoration:none}.cmp-input-detail a:hover{text-decoration:underline}.input-cover{position:absolute;top:175px;left:0;width:100%;height:100%;background:var(--background-color);transform:translateZ(0);transition:all var(--transition-time) ease-in-out;pointer-events:auto}.input-enabled .input-cover{transform:translate3d(0,105%,0);pointer-events:none}.input-loading-icon{position:absolute;display:inline-block;top:190px;left:0;width:100%;transform:translateZ(0);pointer-events:auto;opacity:0;transition:all 50ms ease-in-out;transition-delay:50ms;pointer-events:none}.input-loading .input-loading-icon{opacity:.5}:host{position:fixed;inset:0;z-index:2147483646;user-select:none;pointer-events:none;color:var(--text-color)}aside{position:absolute;top:0;right:0;width:var(--menu-width);height:100%;transform:translate3d(105%,0,0);transition:transform var(--transition-time) ease-in-out;background:var(--background-color);box-shadow:#000000c9 5px 0 20px;overflow:hidden;z-index:1}:host(.show-builder-menu) aside{pointer-events:auto;transform:translateZ(0)}#hit{position:absolute;inset:0;display:none}:host(.show-builder-menu) #hit{display:block;pointer-events:auto}#version{position:absolute;bottom:6px;right:6px;font-size:8px;color:#9b9b9b}</style><div id="hit"></div> <aside data-view="nav-home"> <section class="nav-home"> <header> <svg class="builder-logo" viewBox="0 0 31 36" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M31 9.96854C31.0016 11.4553 30.6701 12.9236 30.03 14.2654C29.3898 15.6072 28.4572 16.7884 27.3007 17.7221L0.702841 2.61812C0.601104 2.56012 0.506714 2.49008 0.421705 2.40951C0.288323 2.27871 0.182333 2.12263 0.109928 1.95039C0.0375215 1.77814 0.000151253 1.59319 0 1.40633C0 1.03335 0.148098 0.675643 0.411715 0.411905C0.675332 0.148167 1.03287 0 1.40568 0L21.036 0C23.6786 0 26.213 1.05025 28.0816 2.91972C29.9502 4.78918 31 7.32472 31 9.96854Z" fill="#18B4F4" /> <path d="M31 25.4757C31.0004 26.7849 30.7429 28.0815 30.2423 29.2912C29.7417 30.5009 29.0078 31.6001 28.0825 32.526C27.1572 33.4519 26.0587 34.1864 24.8497 34.6875C23.6406 35.1886 22.3448 35.4465 21.0361 35.4465H1.40573C1.12766 35.4436 0.856725 35.3581 0.627199 35.201C0.397672 35.044 0.219871 34.8223 0.116289 34.5641C0.0127078 34.3059 -0.011999 34.0228 0.0452946 33.7505C0.102588 33.4783 0.239308 33.2292 0.438156 33.0347C0.517415 32.9551 0.606358 32.8858 0.702893 32.8284L11.1705 26.8843L27.2984 17.7244C28.4548 18.6579 29.3874 19.8387 30.028 21.18C30.6685 22.5213 31.0007 23.9891 31 25.4757Z" fill="#FD6B3C" /> <path d="M27.3011 17.7221L11.1709 26.8843L0.703209 32.8284C0.602697 32.8843 0.509784 32.9528 0.426758 33.0323C4.41799 28.9369 6.6496 23.442 6.64456 17.7221C6.65208 12.0015 4.42111 6.50517 0.429101 2.40948C0.51411 2.49005 0.6085 2.56009 0.710237 2.61809L27.3011 17.7221Z" fill="#A97FF2" /> </svg> <div> <h2 class="builder-home-title">Builder Devtools</h2> <p><button id="go-to-builder">Go to Builder</button></p> </div> <button id="close" aria-label="Close Menu"> <svg viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M18 6l-12 12" /> <path d="M6 6l12 12" /> </svg> </button> </header> <div class="section-content"> <ul class="list"> <li> <button id="components-link"> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M21 16.008V7.99001C20.9994 7.64108 20.9066 7.29851 20.731 6.99699C20.5554 6.69547 20.3032 6.44571 20 6.27301L13 2.26501C12.6954 2.09103 12.3508 1.99951 12 1.99951C11.6492 1.99951 11.3046 2.09103 11 2.26501L4 6.27301C3.381 6.62801 3 7.28301 3 7.99101V16.009C3 16.718 3.381 17.372 4 17.726L11 21.734C11.3046 21.908 11.6492 21.9995 12 21.9995C12.3508 21.9995 12.6954 21.908 13 21.734L20 17.726C20.619 17.371 21 16.716 21 16.008Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 22V12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M12 12L20.73 6.95996" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M3.26999 6.95996L12 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> </svg> <span>Components</span> </button> </li> <li> <button id="settings-link"> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M10.325 4.317C10.751 2.561 13.249 2.561 13.675 4.317C13.7389 4.5808 13.8642 4.82578 14.0407 5.032C14.2172 5.23822 14.4399 5.39985 14.6907 5.50375C14.9414 5.60764 15.2132 5.65085 15.4838 5.62987C15.7544 5.60889 16.0162 5.5243 16.248 5.383C17.791 4.443 19.558 6.209 18.618 7.753C18.4769 7.98466 18.3924 8.24634 18.3715 8.51677C18.3506 8.78721 18.3938 9.05877 18.4975 9.30938C18.6013 9.55999 18.7627 9.78258 18.9687 9.95905C19.1747 10.1355 19.4194 10.2609 19.683 10.325C21.439 10.751 21.439 13.249 19.683 13.675C19.4192 13.7389 19.1742 13.8642 18.968 14.0407C18.7618 14.2172 18.6001 14.4399 18.4963 14.6907C18.3924 14.9414 18.3491 15.2132 18.3701 15.4838C18.3911 15.7544 18.4757 16.0162 18.617 16.248C19.557 17.791 17.791 19.558 16.247 18.618C16.0153 18.4769 15.7537 18.3924 15.4832 18.3715C15.2128 18.3506 14.9412 18.3938 14.6906 18.4975C14.44 18.6013 14.2174 18.7627 14.0409 18.9687C13.8645 19.1747 13.7391 19.4194 13.675 19.683C13.249 21.439 10.751 21.439 10.325 19.683C10.2611 19.4192 10.1358 19.1742 9.95929 18.968C9.7828 18.7618 9.56011 18.6001 9.30935 18.4963C9.05859 18.3924 8.78683 18.3491 8.51621 18.3701C8.24559 18.3911 7.98375 18.4757 7.752 18.617C6.209 19.557 4.442 17.791 5.382 16.247C5.5231 16.0153 5.60755 15.7537 5.62848 15.4832C5.64942 15.2128 5.60624 14.9412 5.50247 14.6906C5.3987 14.44 5.23726 14.2174 5.03127 14.0409C4.82529 13.8645 4.58056 13.7391 4.317 13.675C2.561 13.249 2.561 10.751 4.317 10.325C4.5808 10.2611 4.82578 10.1358 5.032 9.95929C5.23822 9.7828 5.39985 9.56011 5.50375 9.30935C5.60764 9.05859 5.65085 8.78683 5.62987 8.51621C5.60889 8.24559 5.5243 7.98375 5.383 7.752C4.443 6.209 6.209 4.442 7.753 5.382C8.753 5.99 10.049 5.452 10.325 4.317Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> <path d="M9 12C9 12.7956 9.31607 13.5587 9.87868 14.1213C10.4413 14.6839 11.2044 15 12 15C12.7956 15 13.5587 14.6839 14.1213 14.1213C14.6839 13.5587 15 12.7956 15 12C15 11.2044 14.6839 10.4413 14.1213 9.87868C13.5587 9.31607 12.7956 9 12 9C11.2044 9 10.4413 9.31607 9.87868 9.87868C9.31607 10.4413 9 11.2044 9 12Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" /> </svg> <span>Settings</span> </button> </li> <li> <button id="add-page-link"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M14 3v4a1 1 0 0 0 1 1h4" /> <path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z" /> <path d="M12 11l0 6" /> <path d="M9 14l6 0" /> </svg> <span>Add Builder Page</span> </button> </li> <li> <button id="import-from-figma"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-brand-figma" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M15 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" /> <path d="M6 3m0 3a3 3 0 0 1 3 -3h6a3 3 0 0 1 3 3v0a3 3 0 0 1 -3 3h-6a3 3 0 0 1 -3 -3z" /> <path d="M9 9a3 3 0 0 0 0 6h3m-3 0a3 3 0 1 0 3 3v-15" /> </svg> <span>Import From Figma</span> </button> </li> </ul> </div> <footer> <ul class="list"> <li> <a href="https://docs.google.com/forms/d/e/1FAIpQLSdqZcJpRtm_Ia5DTHP6SDY9Xa6LID3KiTjRWkjMzWyJRUtSHw/viewform" target="_blank" > <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M11.013 17.0114L10.013 18.0114L2.513 10.5834C2.0183 10.102 1.62864 9.52342 1.36854 8.88404C1.10845 8.24466 0.983558 7.55836 1.00173 6.86834C1.01991 6.17832 1.18076 5.49954 1.47415 4.87474C1.76755 4.24994 2.18713 3.69266 2.70648 3.23799C3.22583 2.78331 3.8337 2.4411 4.49181 2.23289C5.14991 2.02468 5.844 1.95499 6.53036 2.02821C7.21673 2.10143 7.8805 2.31596 8.47987 2.65831C9.07925 3.00066 9.60124 3.46341 10.013 4.01741C10.8086 2.95654 11.9931 2.2552 13.3059 2.06766C14.6186 1.88012 15.9521 2.22176 17.013 3.01741C18.0739 3.81306 18.7752 4.99755 18.9627 6.3103C19.1503 7.62305 18.8086 8.95654 18.013 10.0174" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> <path d="M18.2006 19.8175L16.0286 20.9555C15.9642 20.989 15.8917 21.004 15.8192 20.9987C15.7467 20.9934 15.6771 20.9681 15.6182 20.9256C15.5593 20.8831 15.5134 20.825 15.4855 20.7579C15.4577 20.6907 15.4491 20.6172 15.4606 20.5455L15.8756 18.1345L14.1186 16.4275C14.0662 16.3768 14.0291 16.3123 14.0115 16.2416C13.9939 16.1708 13.9966 16.0965 14.0192 16.0271C14.0418 15.9578 14.0835 15.8962 14.1394 15.8494C14.1954 15.8026 14.2634 15.7725 14.3356 15.7625L16.7636 15.4105L17.8496 13.2175C17.8821 13.1521 17.9322 13.0972 17.9942 13.0588C18.0562 13.0204 18.1277 13 18.2006 13C18.2736 13 18.3451 13.0204 18.4071 13.0588C18.4691 13.0972 18.5191 13.1521 18.5516 13.2175L19.6376 15.4105L22.0656 15.7625C22.1377 15.7728 22.2054 15.8031 22.2611 15.85C22.3168 15.8968 22.3583 15.9583 22.3809 16.0275C22.4034 16.0967 22.4062 16.1708 22.3888 16.2415C22.3715 16.3122 22.3347 16.3766 22.2826 16.4275L20.5256 18.1345L20.9396 20.5445C20.9521 20.6163 20.9441 20.6902 20.9166 20.7578C20.8891 20.8254 20.8433 20.8839 20.7842 20.9267C20.7252 20.9695 20.6553 20.9949 20.5825 21C20.5098 21.005 20.4371 20.9896 20.3726 20.9555L18.2006 19.8175Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> </svg> <span>Give Feedback</span> </a> </li> </ul> <div id="version"></div> </footer> </section> <section class="nav-cmp-list"> <header> <button class="back-button"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div class="search-container"> <div class="search-input-wrapper"> <svg class="search-icon" viewBox="0 0 24 24" width="16" height="16"> <path fill="none" stroke="currentColor" stroke-width="2" d="M15.5 15.5L20 20M10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10C17 13.866 13.866 17 10 17Z" /> </svg> <input type="text" id="component-search" class="component-search-input" placeholder="Search components..." autocomplete="off" spellcheck="false" /> <button id="clear-search" class="clear-search-button" type="button" aria-label="Clear search" > <svg viewBox="0 0 24 24" width="16" height="16"> <path fill="none" stroke="currentColor" stroke-width="2" d="M6 6l12 12M6 18L18 6" /> </svg> </button> </div> </div> <div> <h2>Custom Components</h2> <p> <button id="open-builder-registry"></button> </p> </div> </header> <div class="section-content"> <div id="cmp-list" class="cmp-list nav-list"></div> </div> <div class="nav-loading-icon spinner"></div> <footer> <p class="info"> Expand on Builder's selection of built-in blocks by <a target="_blank" href="https://www.builder.io/c/docs/custom-components-intro" >registering components</a > from your codebase. This way, teammates can drag and drop your components within Builder's Visual Editor just like any other block. </p> </footer> </section> <section class="nav-cmp-detail"> <header> <button class="back-button" data-back="nav-cmp-list"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div> <h2 id="cmp-detail-title"></h2> <p> <button id="cmp-open-source"></button> </p> </div> </header> <div class="section-content"> <div id="cmp-error"></div> <label class="ui-switch"> <div> <h3>Register Component</h3> <p> Registers this component so it can be used within Builder Visual CMS </p> </div> <input type="checkbox" role="switch" id="cmp-register" /> <span class="switcher"></span> </label> <div id="cmp-detail"> <label class="ui-text-input"> <h3>Component Name</h3> <div class="input"> <input type="text" id="cmp-name" autocapitalize="off" autocorrect="off" spellcheck="false" autocomplete="off" minlength="2" maxlength="30" required placeholder="e.g. My Counter" /> </div> <p> Unique name to identify this custom component within Builder. Press ESC to cancel </p> </label> <div class="cmp-detail-inputs-container"> <h3> <span>Builder Inputs (Props)</span> <button class="cmp-detail-inputs-reload" id="btn-inputs-reload"> Reload </button> </h3> <div id="cmp-detail-inputs"></div> </div> </div> </div> <div class="cmp-cover"></div> <div class="cmp-loading-icon spinner"></div> </section> <section class="nav-cmp-input"> <header> <button class="back-button" data-back="nav-cmp-detail"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div> <h2 id="cmp-input-title"></h2> <p> <button id="input-open-source"></button> </p> </div> </header> <div class="section-content"> <label class="ui-switch"> <div> <h3>Enable Input</h3> <p>Add this component prop as a Builder input</p> </div> <input type="checkbox" role="switch" id="input-register" /> <span class="switcher"></span> </label> <div class="cmp-prop-info"> <div class="cmp-input-readonly"> <h3>Prop Name</h3> <span id="cmp-prop-name"></span> </div> <div class="cmp-input-readonly"> <h3>Prop Type</h3> <span id="cmp-prop-type"></span> </div> </div> <div class="cmp-input-detail"> <label class="ui-text-input"> <h3>Builder Input Name</h3> <div class="input"> <input type="text" id="input-name" autocapitalize="off" autocorrect="off" spellcheck="false" autocomplete="off" minlength="1" maxlength="30" required placeholder="e.g. Text" /> </div> <p> Friendly name to identify this component prop as a Builder input. Press ESC to cancel </p> </label> <label class="ui-select"> <h3>Builder Input Type</h3> <div class="select"> <select id="input-type"></select> </div> <p> Correlate to what editing UI is appropriate for this Builder input. <a href="https://www.builder.io/c/docs/custom-components-input-types" target="_blank" >Read more about input types.</a > </p> </label> </div> <div class="input-cover"></div> <div class="input-loading-icon spinner"></div> </div> </section> <section class="nav-settings"> <header> <button class="back-button"> <svg viewBox="0 0 24 24"> <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" /> </svg> </button> <div> <h2>Settings</h2> <p>Configure Builder's Devtools</p> </div> </header> <div class="section-content"> <label class="ui-switch"> <div> <h3>Enable edit button in UI</h3> <p>Enables the edit button so you can edit content in Builder</p> </div> <input type="checkbox" role="switch" id="enable-edit" /> <span class="switcher"></span> </label> </div> </section> <div class="ui-toast" id="toast"></div> </aside> <button class="menu-toggle" aria-label="Toggle Builder Devtools"> <div> <div class="highlight-bg"></div> <svg viewBox="0 0 31 36" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M31 9.96854C31.0016 11.4553 30.6701 12.9236 30.03 14.2654C29.3898 15.6072 28.4572 16.7884 27.3007 17.7221L0.702841 2.61812C0.601104 2.56012 0.506714 2.49008 0.421705 2.40951C0.288323 2.27871 0.182333 2.12263 0.109928 1.95039C0.0375215 1.77814 0.000151253 1.59319 0 1.40633C0 1.03335 0.148098 0.675643 0.411715 0.411905C0.675332 0.148167 1.03287 0 1.40568 0L21.036 0C23.6786 0 26.213 1.05025 28.0816 2.91972C29.9502 4.78918 31 7.32472 31 9.96854Z" fill="#18B4F4" /> <path d="M31 25.4757C31.0004 26.7849 30.7429 28.0815 30.2423 29.2912C29.7417 30.5009 29.0078 31.6001 28.0825 32.526C27.1572 33.4519 26.0587 34.1864 24.8497 34.6875C23.6406 35.1886 22.3448 35.4465 21.0361 35.4465H1.40573C1.12766 35.4436 0.856725 35.3581 0.627199 35.201C0.397672 35.044 0.219871 34.8223 0.116289 34.5641C0.0127078 34.3059 -0.011999 34.0228 0.0452946 33.7505C0.102588 33.4783 0.239308 33.2292 0.438156 33.0347C0.517415 32.9551 0.606358 32.8858 0.702893 32.8284L11.1705 26.8843L27.2984 17.7244C28.4548 18.6579 29.3874 19.8387 30.028 21.18C30.6685 22.5213 31.0007 23.9891 31 25.4757Z" fill="#FD6B3C" /> <path d="M27.3011 17.7221L11.1709 26.8843L0.703209 32.8284C0.602697 32.8843 0.509784 32.9528 0.426758 33.0323C4.41799 28.9369 6.6496 23.442 6.64456 17.7221C6.65208 12.0015 4.42111 6.50517 0.429101 2.40948C0.51411 2.49005 0.6085 2.56009 0.710237 2.61809L27.3011 17.7221Z" fill="#A97FF2" /> </svg> </div> </button>\`,si(e),ui(e),oi(e),ri(e),ti(e),ci(e),this.setAttribute("aria-hidden","true"),e.getElementById("version").textContent="v1.64.2-beta.202606091533.72ef003"}highlightOpener(){let e=this.shadowRoot.querySelector(".menu-toggle");e.classList.add("menu-toggle-highlight"),e.classList.add("menu-toggle-highlight-no-transition"),setTimeout(()=>{e.classList.remove("menu-toggle-highlight-no-transition"),setTimeout(()=>{e.classList.remove("menu-toggle-highlight")},20)},20)}};var lo=\`<style>*,*:before,*:after{box-sizing:border-box}html,body,:host{position:fixed;top:0;left:0;width:100%;height:100vh;z-index:2147483646;margin:0;padding:0;line-height:1.8;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";background-color:#252525;color:#fff;transition:opacity .25s ease-in-out}:host([aria-hidden="true"]){opacity:0;pointer-events:none}main{position:absolute;top:0;left:0;width:100%;height:100vh}h1{margin-top:0;font-size:24px;font-weight:300;line-height:1.4}p{margin:20px 0;font-weight:300}button{cursor:pointer}aside{position:absolute;top:0;left:0;width:350px;height:100vh;padding:60px 0 0 50px;background-color:#121212}aside ul{margin:30px 0 0;padding:0;list-style:none}aside li{position:relative;margin:0;padding:20px 10px;font-weight:300}aside li.highlight{color:#48a1ff}aside li.active{font-weight:700}aside li .circle{position:absolute;top:20px;left:10px;width:24px;height:24px;border:3px solid white;border-radius:50%;font-size:14px}aside li.highlight .circle{border-color:#48a1ff}aside li.active .circle:after{content:"";position:absolute;top:3px;left:3px;width:12px;height:12px;border-radius:50%;background-color:#48a1ff}aside li.completed .circle{background-color:#48a1ff}aside li.completed .circle:after{content:"";position:absolute;top:2px;left:6px;width:6px;height:13px;border:3px solid black;border-top:none;border-left:none;transform:rotate(45deg)}aside li .line{position:absolute;top:44px;left:21px;width:3px;height:45px;background-color:#fff}aside li.completed .line{background-color:#48a1ff}aside li span{display:block;margin-left:44px}nav{margin-top:30px}section{position:absolute;top:135px;left:350px;padding:0 80px 0 140px;transition:opacity .15s ease-in-out}section[aria-hidden=true]{pointer-events:none;opacity:0}section h1,section p{min-width:300px;max-width:600px}.button{position:relative;display:inline-block;color:#fff;background-color:#48a1ff;border-radius:4px;text-decoration:none;padding:10px 40px 10px 20px;white-space:nowrap}.button:hover{background-color:#48a1ffd9}#button-icon{position:absolute;top:1px;right:5px;bottom:0;width:30px;background-image:url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="none" stroke="white" stroke-linecap="square" stroke-miterlimit="10" stroke-width="48" d="M184 112l144 144-144 144"/></svg>');background-repeat:no-repeat;background-position:center;background-size:24px 24px}.button[aria-disabled=true]{opacity:.9;background-color:#ffffff4d;pointer-events:none;padding-right:60px}.button[aria-disabled=true] #button-icon{top:21px;right:29px;width:8px;height:8px;border-radius:4px;background:#fff;color:#fff;animation:dot-flashing .5s infinite linear alternate;animation-delay:.25s}.button[aria-disabled=true] #button-icon:before,.button[aria-disabled=true] #button-icon:after{content:"";display:inline-block;position:absolute;top:0}.button[aria-disabled=true] #button-icon:before{left:-12px;width:8px;height:8px;border-radius:4px;background-color:#fff;color:#fff;animation:dot-flashing .5s infinite alternate;animation-delay:0s}.button[aria-disabled=true] #button-icon:after{left:12px;width:8px;height:8px;border-radius:4px;background-color:#fff;color:#fff;animation:dot-flashing .5s infinite alternate;animation-delay:.5s}@keyframes dot-flashing{0%{background-color:#fff}50%,to{background-color:#ffffff4d}}.logo{margin-left:9px;background:url('data:image/svg+xml,<svg viewBox="0 0 150 32" fill="none" xmlns="http://www.w3.org/2000/svg" > <g clip-path="url(%23clip0_4_304)"> <path d="M27.9858 8.99927C27.9872 10.3415 27.688 11.667 27.1101 12.8783C26.5321 14.0896 25.6902 15.156 24.6462 15.9989V15.9989L0.634502 2.36355C0.542657 2.31119 0.457444 2.24796 0.380701 2.17523C0.260289 2.05715 0.164605 1.91624 0.0992389 1.76075C0.0338732 1.60525 0.000136546 1.43828 0 1.26959C0 0.932873 0.133698 0.609948 0.371683 0.371854C0.609667 0.13376 0.932443 0 1.269 0L18.9906 0C21.3763 0 23.6642 0.948135 25.3512 2.63583C27.0381 4.32352 27.9858 6.61252 27.9858 8.99927V8.99927Z" fill="%2318B4F4" /> <path d="M27.9858 22.9986C27.9861 24.1806 27.7536 25.351 27.3017 26.4431C26.8498 27.5352 26.1873 28.5275 25.352 29.3634C24.5167 30.1993 23.5249 30.8624 22.4335 31.3147C21.342 31.7671 20.1721 32 18.9907 32H1.26906C1.01802 31.9973 0.77343 31.9202 0.566221 31.7784C0.359012 31.6366 0.198499 31.4364 0.104989 31.2034C0.0114791 30.9703 -0.0108254 30.7147 0.0408974 30.4689C0.0926201 30.2231 0.216046 29.9982 0.395559 29.8226V29.8226C0.467112 29.7508 0.547407 29.6882 0.634555 29.6364L10.0844 24.2703L24.6441 16.001C25.688 16.8438 26.53 17.9097 27.1083 19.1206C27.6866 20.3315 27.9864 21.6566 27.9858 22.9986V22.9986Z" fill="%23FD6B3C" /> <path d="M24.6461 15.9989L10.0843 24.2703L0.634458 29.6365C0.54372 29.6868 0.459841 29.7487 0.384888 29.8205C3.98804 26.1233 6.00266 21.1627 5.99812 15.9989C6.0049 10.8346 3.99085 5.87268 0.387003 2.17523C0.463746 2.24796 0.548959 2.31119 0.640803 2.36355L24.6461 15.9989Z" fill="%23A97FF2" /> <path d="M47.6659 11.7352C51.8177 11.7352 54.1632 15.0531 54.1632 19.0714C54.1632 23.0896 51.8177 26.3821 47.6659 26.3821C45.5086 26.3821 43.8589 25.5188 42.9473 24.0545L42.5709 26.052H39.9736V6.77115H43.1884V13.8914C43.971 12.6959 45.5086 11.7352 47.6659 11.7352ZM47.0187 23.5488C49.4446 23.5488 50.9547 21.5809 50.9547 19.0714C50.9547 16.5089 49.4446 14.5664 47.0187 14.5664C44.5928 14.5664 43.0806 16.5047 43.0806 19.0714C43.0806 21.583 44.5653 23.5488 47.0187 23.5488V23.5488Z" fill="white" /> <path d="M65.4595 20.2859V12.0611H68.668V20.123C68.668 23.7202 67.0246 26.3821 62.4943 26.3821C57.9639 26.3821 56.3206 23.7117 56.3206 20.123V12.0611H59.529V20.2859C59.529 22.4696 60.5527 23.5488 62.49 23.5488C64.4274 23.5488 65.4595 22.4696 65.4595 20.2859Z" fill="white" /> <path d="M71.2355 7.74451C71.2247 7.46284 71.2724 7.18199 71.3755 6.91968C71.4787 6.65737 71.6351 6.41929 71.8348 6.22047C72.0345 6.02165 72.2732 5.8664 72.5359 5.76452C72.7986 5.66264 73.0796 5.61633 73.3611 5.62853C74.5793 5.62853 75.4571 6.50666 75.4571 7.75509C75.4571 9.00352 74.5793 9.8224 73.3611 9.8224C72.1428 9.8224 71.2355 8.9612 71.2355 7.74451Z" fill="white" /> <path d="M128.476 7.74451C128.465 7.46376 128.513 7.18383 128.615 6.92227C128.718 6.66071 128.873 6.42315 129.072 6.22449C129.27 6.02583 129.508 5.87035 129.769 5.7678C130.031 5.66524 130.31 5.61783 130.591 5.62852C131.809 5.62852 132.687 6.50666 132.687 7.75509C132.687 9.00352 131.809 9.8224 130.591 9.8224C129.373 9.8224 128.476 8.9612 128.476 7.74451Z" fill="white" /> <path d="M122.302 24.1031C122.291 23.8223 122.339 23.5422 122.441 23.2805C122.543 23.0188 122.699 22.7811 122.897 22.5824C123.096 22.3837 123.334 22.2282 123.595 22.1258C123.857 22.0233 124.137 21.9761 124.417 21.9872C125.636 21.9872 126.513 22.8653 126.513 24.1031C126.513 25.341 125.636 26.1726 124.417 26.1726C123.199 26.1726 122.302 25.3219 122.302 24.1031Z" fill="white" /> <path d="M74.9516 12.059H71.7432V26.0583H74.9516V12.059Z" fill="white" /> <path d="M78.16 26.0583V6.77115H81.3685V26.0626L78.16 26.0583Z" fill="white" /> <path d="M94.6063 6.77115H97.8148V26.0626H95.2239L94.8474 24.0651C93.9591 25.523 92.3094 26.3927 90.131 26.3927C86.0046 26.3927 83.6591 23.0748 83.6591 19.0819C83.6591 15.0891 86.0046 11.7458 90.131 11.7458C92.3137 11.7458 93.8238 12.7149 94.6063 13.902V6.77115ZM90.7993 14.5707C88.3734 14.5707 86.8633 16.5131 86.8633 19.0756C86.8633 21.5851 88.3734 23.553 90.7993 23.553C93.2252 23.553 94.7354 21.5851 94.7354 19.0756C94.7396 16.5047 93.257 14.5664 90.8036 14.5664L90.7993 14.5707Z" fill="white" /> <path d="M113.479 22.2284C112.482 24.7359 110.162 26.3821 107.117 26.3821C102.887 26.3821 100.137 23.225 100.137 19.0439C100.137 14.9706 102.942 11.7353 107.093 11.7353C111.245 11.7353 113.969 14.8902 113.969 18.991C113.982 19.3255 113.953 19.6604 113.883 19.9876H103.288C103.53 22.2009 104.959 23.6292 107.197 23.6292C108.735 23.6292 110.001 22.8738 110.594 21.473L113.479 22.2284ZM103.341 17.6156H110.784C110.513 15.6731 109.166 14.3506 107.089 14.3506C105.012 14.3506 103.665 15.7006 103.341 17.6156V17.6156Z" fill="white" /> <path d="M123.779 14.9452C123.538 14.9117 123.295 14.8933 123.051 14.8902C120.786 14.8902 119.439 16.0772 119.439 18.7751V26.0583H116.23V12.0611H118.821L119.195 14.0014C119.707 13.1127 120.887 11.9257 123.322 11.9257C123.455 11.9257 123.779 11.9532 123.779 11.9532V14.9452Z" fill="white" /> <path d="M132.192 12.059H128.984V26.0583H132.192V12.059Z" fill="white" /> <path d="M134.483 19.0714C134.483 15.1335 137.287 11.7353 141.735 11.7353C146.183 11.7353 149.015 15.1335 149.015 19.0714C149.015 23.0092 146.213 26.3821 141.735 26.3821C137.258 26.3821 134.483 23.0092 134.483 19.0714ZM141.735 23.5488C144.083 23.5488 145.806 21.7692 145.806 19.0714C145.806 16.3735 144.083 14.5664 141.735 14.5664C139.387 14.5664 137.687 16.346 137.687 19.0714C137.687 21.7968 139.417 23.5488 141.735 23.5488V23.5488Z" fill="white" /> </g> <defs> <clipPath id="clip0_4_304"> <rect width="149.015" height="32" fill="white" /> </clipPath> </defs> </svg>');background-repeat:no-repeat;width:150px;height:32px}@media(max-width:840px){aside{width:250px;padding:60px 0 0 20px}section{left:250px;padding:0 80px}}@media(max-width:590px){aside{width:230px;padding:60px 0 0 10px}section{left:230px;padding:0 40px}}#modified-files-message a{color:#cbcbcb;font-weight:300;text-decoration:underline}#modified-files-message a:hover{color:#fff;text-decoration:none}#restart-warning{border-radius:4px;padding:8px 16px;border:1px solid #fd6b3c;background:#fd6b3c1a}#react-router-steps{margin:0 0 5px;padding:0 20px}#need-help{color:#48a1ff;text-decoration:none}#router-message{border-radius:4px;padding:16px;border:1px solid #48a1ff}#router-finish-button{margin-top:12px}#router-checkbox-div{display:flex;align-items:center}#router-checkbox{margin-right:10px;width:15px;height:15px}#success-title{display:flex;align-items:center;gap:10px}#success-title .check-icon{display:inline-block;width:24px;height:24px;border:2px solid #28a745;border-radius:50%;position:relative}#success-title .check-icon:before{content:"";position:absolute;top:50%;left:50%;width:6px;height:12px;border:solid #28a745;border-width:0 2px 2px 0;transform:translate(-50%,-60%) rotate(45deg)}
|
|
1280
1280
|
</style>\`,Nt=class extends HTMLElement{constructor(){super()}connectedCallback(){let e=this.attachShadow({mode:"open"});e.innerHTML=lo+\`<main>
|
|
1281
1281
|
<aside>
|
|
1282
1282
|
<div class="logo"></div>
|
|
@@ -1315,7 +1315,7 @@ Restarting server after Builder Devtools update...
|
|
|
1315
1315
|
</nav>
|
|
1316
1316
|
</section>
|
|
1317
1317
|
</main>
|
|
1318
|
-
\`,po();let r=new URL(Fr,ot);r.searchParams.set(Br,location.href);let n=e.querySelectorAll(".next-step");for(let i of n)i.setAttribute("href",r.href);ye("overview step viewed")}},po=()=>{let t=document.head.querySelector("link[rel='icon'], link[rel='icon shortcut']");t?(t.href="https://cdn.builder.io/favicon.ico",t.removeAttribute("type")):(t=document.createElement("link"),t.rel="icon",t.href="https://cdn.builder.io/favicon.ico",document.head.appendChild(t))};var li=async()=>{(await jr()).isValid||fo()},fo=()=>{customElements.get("builder-dev-tools-overview")||customElements.define("builder-dev-tools-overview",Nt);let t=document.querySelector("builder-dev-tools-overview");t||(t=document.createElement("builder-dev-tools-overview"),t.setAttribute("aria-hidden","true"),document.body.appendChild(t)),setTimeout(()=>{t.removeAttribute("aria-hidden")},32)};var mo=()=>{try{customElements.get("builder-dev-tools-edit")||customElements.define("builder-dev-tools-edit",at),customElements.get("builder-dev-tools-menu")||customElements.define("builder-dev-tools-menu",Dt);let t=document.querySelector("builder-dev-tools-menu");t||(t=document.createElement("builder-dev-tools-menu"),t.setAttribute("data-version","1.64.2-beta.
|
|
1318
|
+
\`,po();let r=new URL(Fr,ot);r.searchParams.set(Br,location.href);let n=e.querySelectorAll(".next-step");for(let i of n)i.setAttribute("href",r.href);ye("overview step viewed")}},po=()=>{let t=document.head.querySelector("link[rel='icon'], link[rel='icon shortcut']");t?(t.href="https://cdn.builder.io/favicon.ico",t.removeAttribute("type")):(t=document.createElement("link"),t.rel="icon",t.href="https://cdn.builder.io/favicon.ico",document.head.appendChild(t))};var li=async()=>{(await jr()).isValid||fo()},fo=()=>{customElements.get("builder-dev-tools-overview")||customElements.define("builder-dev-tools-overview",Nt);let t=document.querySelector("builder-dev-tools-overview");t||(t=document.createElement("builder-dev-tools-overview"),t.setAttribute("aria-hidden","true"),document.body.appendChild(t)),setTimeout(()=>{t.removeAttribute("aria-hidden")},32)};var mo=()=>{try{customElements.get("builder-dev-tools-edit")||customElements.define("builder-dev-tools-edit",at),customElements.get("builder-dev-tools-menu")||customElements.define("builder-dev-tools-menu",Dt);let t=document.querySelector("builder-dev-tools-menu");t||(t=document.createElement("builder-dev-tools-menu"),t.setAttribute("data-version","1.64.2-beta.202606091533.72ef003"),document.body.appendChild(t));let e=document.querySelector("builder-dev-tools-edit");e||(e=document.createElement("builder-dev-tools-edit"),document.body.appendChild(e));let r=document.getElementById("builder-dev-tools-style");r||(r=document.createElement("style"),r.id="builder-dev-tools-style",r.innerHTML=".builder-no-scroll{overflow:hidden !important}",document.head.appendChild(r)),li(),Jn()}catch(t){console.error("Builder Devtools:",t)}};window.location===window.parent.location&&(console.debug("Builder.io Devtools v1.64.2-beta.202606091533.72ef003"),mo());})();`)}async function wne(t){return bne(t,`<!doctype html>
|
|
1319
1319
|
<html lang="en" dir="ltr">
|
|
1320
1320
|
<head>
|
|
1321
1321
|
<meta charset="utf-8" />
|
|
@@ -1487,7 +1487,7 @@ If you are using Windows Git Bash, try a different terminal or wrap the command
|
|
|
1487
1487
|
${a.map(c=>` * ${c}`).join(`
|
|
1488
1488
|
`)}
|
|
1489
1489
|
*/`}
|
|
1490
|
-
${e}`}async function bje(t,e,r){let n,i=Sje(r,e.toLowerCase());switch(e.toLowerCase()){case"react":let s=await vje(t);n=`components/${i||"MyComponent"}.${s?"tsx":"jsx"}`;break;case"angular":n=`app/components/${i||"my-component"}.component.ts`;break;case"vue":n=`components/${i||"MyComponent"}.vue`;break;case"svelte":n=`components/${i||"MyComponent"}.svelte`;break;case"html":n=`${i||"my-design"}.html`;break;case"qwik":n=`components/${i||"MyComponent"}.tsx`;break;default:n=`components/${i||"MyComponent"}.tsx`}return n=(0,ai.existsSync)("./src")?`./src/${n}`:`./${n}`,n}async function vje(t){if((0,ai.existsSync)((0,pa.join)(t,"./tsconfig.json")))return!0;let e=wN(t);return e&&(0,ai.existsSync)((0,pa.join)(e,"./package.json"))?(0,ai.readFileSync)((0,pa.join)(e,"./package.json"),"utf-8").includes("typescript"):!1}function Sje(t,e){let r={vue:/name:\s*'([^']+)'/,react:/function (\w+)\([\w\W]+\)/,qwik:/export const (\w+) = component\$/,angular:/selector:\s*'([^']+)'/};if(!r[e])return null;let n=t.match(r[e]);return e==="react"&&!n?.[1]?t.match(/const (\w+)[\w\W]+=\s*\(/)?.[1]||null:n?.[1]||null}async function Vw(t,e,r,n,i){let s=[];for(let o of r){let a=xje(n,o.path),A=(0,pa.resolve)(t,a);if("code"in o){let c=await kje(t,e,o.code,Fje(o.path),i);(0,ai.existsSync)(A)||(0,ai.mkdirSync)((0,pa.dirname)(A),{recursive:!0}),(0,ai.writeFileSync)(A,c),s.push({...o,path:a,code:c,timestamp:(0,ai.statSync)(A).mtime.getTime()}),$.info(`Writing file to ${A}`)}else(0,ai.mkdirSync)(A,{recursive:!0}),s=s.concat(await Vw(t,e,o.files,a,i))}return s}function xje(t,e){let r=t.replace(/^\.?\/+|\/+$/g,""),n=e.replace(/^\.?\/+|\/+$/g,""),i=r.split("/").filter(Boolean),s=n.split("/").filter(Boolean),o=-1;for(let A=0;A<i.length;A++){let c=s.indexOf(i[A]);c!==-1&&(o=c)}return[...i,...s.slice(o+1)].join("/")}function Fje(t){switch(t.split(".").pop()?.toLowerCase()){case"html":case"svelte":return"html";case"vue":return"vue";case"ts":case"tsx":case"js":case"jsx":return"typescript";case"css":return"css";case"json":return"json";default:return"typescript"}}async function kje(t,e,r,n,i){let s=r;try{s=await ZA(t,r,n,void 0)}catch{}return i?Gne(e,s,n,i):s}function hL(t,e){let n=(0,ai.existsSync)((0,pa.join)(t,"src"))?"src/":"";switch(e.toLowerCase()){case"angular":return`./${n}app/components/`;case"html":return"./";default:return`./${n}components/`}}var pa,ai,Ou,mL=L(()=>{"use strict";h();rr();pa=require("node:path"),ai=require("node:fs");GC();xk();Ou=z(Ir(),1);Ns();hr();zr()});var qne=N((
|
|
1490
|
+
${e}`}async function bje(t,e,r){let n,i=Sje(r,e.toLowerCase());switch(e.toLowerCase()){case"react":let s=await vje(t);n=`components/${i||"MyComponent"}.${s?"tsx":"jsx"}`;break;case"angular":n=`app/components/${i||"my-component"}.component.ts`;break;case"vue":n=`components/${i||"MyComponent"}.vue`;break;case"svelte":n=`components/${i||"MyComponent"}.svelte`;break;case"html":n=`${i||"my-design"}.html`;break;case"qwik":n=`components/${i||"MyComponent"}.tsx`;break;default:n=`components/${i||"MyComponent"}.tsx`}return n=(0,ai.existsSync)("./src")?`./src/${n}`:`./${n}`,n}async function vje(t){if((0,ai.existsSync)((0,pa.join)(t,"./tsconfig.json")))return!0;let e=wN(t);return e&&(0,ai.existsSync)((0,pa.join)(e,"./package.json"))?(0,ai.readFileSync)((0,pa.join)(e,"./package.json"),"utf-8").includes("typescript"):!1}function Sje(t,e){let r={vue:/name:\s*'([^']+)'/,react:/function (\w+)\([\w\W]+\)/,qwik:/export const (\w+) = component\$/,angular:/selector:\s*'([^']+)'/};if(!r[e])return null;let n=t.match(r[e]);return e==="react"&&!n?.[1]?t.match(/const (\w+)[\w\W]+=\s*\(/)?.[1]||null:n?.[1]||null}async function Vw(t,e,r,n,i){let s=[];for(let o of r){let a=xje(n,o.path),A=(0,pa.resolve)(t,a);if("code"in o){let c=await kje(t,e,o.code,Fje(o.path),i);(0,ai.existsSync)(A)||(0,ai.mkdirSync)((0,pa.dirname)(A),{recursive:!0}),(0,ai.writeFileSync)(A,c),s.push({...o,path:a,code:c,timestamp:(0,ai.statSync)(A).mtime.getTime()}),$.info(`Writing file to ${A}`)}else(0,ai.mkdirSync)(A,{recursive:!0}),s=s.concat(await Vw(t,e,o.files,a,i))}return s}function xje(t,e){let r=t.replace(/^\.?\/+|\/+$/g,""),n=e.replace(/^\.?\/+|\/+$/g,""),i=r.split("/").filter(Boolean),s=n.split("/").filter(Boolean),o=-1;for(let A=0;A<i.length;A++){let c=s.indexOf(i[A]);c!==-1&&(o=c)}return[...i,...s.slice(o+1)].join("/")}function Fje(t){switch(t.split(".").pop()?.toLowerCase()){case"html":case"svelte":return"html";case"vue":return"vue";case"ts":case"tsx":case"js":case"jsx":return"typescript";case"css":return"css";case"json":return"json";default:return"typescript"}}async function kje(t,e,r,n,i){let s=r;try{s=await ZA(t,r,n,void 0)}catch{}return i?Gne(e,s,n,i):s}function hL(t,e){let n=(0,ai.existsSync)((0,pa.join)(t,"src"))?"src/":"";switch(e.toLowerCase()){case"angular":return`./${n}app/components/`;case"html":return"./";default:return`./${n}components/`}}var pa,ai,Ou,mL=L(()=>{"use strict";h();rr();pa=require("node:path"),ai=require("node:fs");GC();xk();Ou=z(Ir(),1);Ns();hr();zr()});var qne=N((J4t,Yne)=>{"use strict";h();var Hne=require("child_process"),Rje=Hne.spawn,Tje=Hne.exec;Yne.exports=function(t,e,r){if(typeof e=="function"&&r===void 0&&(r=e,e=void 0),t=parseInt(t),Number.isNaN(t)){if(r)return r(new Error("pid must be a number"));throw new Error("pid must be a number")}var n={},i={};switch(n[t]=[],i[t]=1,process.platform){case"win32":Tje("taskkill /pid "+t+" /T /F",r);break;case"darwin":jne(t,n,i,function(){One(n,e,r)});break;default:Jne(t,n,i,function(s){return Rje("ps",["-o","pid","--no-headers","--ppid",s])},function(){One(n,e,r)});break}};function One(t,e,r){var n={};try{Object.keys(t).forEach(function(i){t[i].forEach(function(s){n[s]||(Kne(s,e),n[s]=1)}),n[i]||(Kne(i,e),n[i]=1)})}catch(i){if(r)return r(i);throw i}if(r)return r()}function Kne(t,e){try{process.kill(parseInt(t,10),e)}catch(r){if(r.code!=="ESRCH")throw r}}function Jne(t,e,r,n,i){var s=n(t),o="";s.stdout.on("data",function(c){var c=c.toString("ascii");o+=c});var a=function(A){if(delete r[t],A!=0){Object.keys(r).length==0&&i();return}o.match(/\d+/g).forEach(function(c){c=parseInt(c,10),e[t].push(c),e[c]=[],r[c]=1,Jne(c,e,r,n,i)})};s.on("close",a)}function jne(t,e,r,n){try{let i="";try{i=execSync("pgrep -P "+t,{encoding:"utf8",timeout:2e3,maxBuffer:1024*1024})}catch(o){if(o.status!==1)throw o}delete r[t];let s=i.trim().split(`
|
|
1491
1491
|
`).filter(Boolean);if(s.length===0){Object.keys(r).length===0&&n();return}s.forEach(function(o){let a=parseInt(o,10);isNaN(a)||(e[t].push(a),e[a]=[],r[a]=1,jne(a,e,r,n))})}catch{delete r[t],Object.keys(r).length===0&&n()}}});function Cc({command:t,args:e,options:r}){let n,i=r?{...r,windowsHide:r.windowsHide!==void 0?r.windowsHide:!0}:process.platform==="win32"?{windowsHide:!0}:void 0;return e!==void 0&&i!==void 0?n=(0,lI.spawn)(t,e,i):e!==void 0?n=(0,lI.spawn)(t,e):i!==void 0?n=(0,lI.spawn)(t,i):n=(0,lI.spawn)(t),Xw.track(n),n}function mA(t,e,r,n){return Cc({command:t,args:yL(e,t,n),options:r})}function Ww(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function Os(t,e,r,n=5e3){if(typeof e!="number"&&(!e||(uI(e)?e.getExitCode()!==null:e.exitCode!==null)))return null;if(r?.aborted)return rn(r.reason);let i=new Promise((A,c)=>{r?.addEventListener("abort",()=>{c(new Error("killProcess aborted by the user"))},{once:!0})}),s,o;if(typeof e=="number"?s=e:(o=e,s=uI(o)?o.getPid():o.pid),!s){if(t?.Sentry?.captureMessage("killProcess: no pid (process never spawned or already exited)",{level:"info",extra:{procType:o?uI(o)?"DevCommandProcess":"ChildProcess":"number"}}),o)try{o.kill("SIGKILL")}catch{}return null}let a=A=>{if(o){if(uI(o)?o.getExitCode()!==null:o.exitCode!==null||o.signalCode!==null){A();return}uI(o)?o.onClose(()=>A()):o.on("close",A)}else{let u=Math.floor(n/100),l=0,d=()=>{if(!Ww(s)){A();return}++l>=u||setTimeout(d,100)};d()}};try{return await Promise.race([new Promise((A,c)=>(0,CL.default)(s,"SIGTERM",u=>{if(u){c(u);return}o?.removeAllListeners(),a(A)})),new Promise((A,c)=>setTimeout(()=>c(new Error("SIGTERM killProcess timeout")),n)),i]),null}catch(A){if(A.code==="ESRCH")return null;t?.Sentry?.captureException(A,{level:"warning"});try{return await Promise.race([new Promise((c,u)=>(0,CL.default)(s,"SIGKILL",l=>{if(l){u(l);return}o?.removeAllListeners(),a(c)})),new Promise((c,u)=>setTimeout(()=>u(new Error("SIGKILL killProcess timeout")),n)),i]),null}catch(c){return c.code==="ESRCH"||!Ww(s)?null:(t?.Sentry?.captureException(c,{level:"warning"}),c instanceof Error?c:new Error("killProcess: failed to kill process: "+String(c)))}}finally{o&&o.removeAllListeners()}}var lI,CL,zw,$ne,Vne,EL,Nje,IL,Xw,_g,Mje,Wne,Pje,Lje,BL,yL,uI,da=L(()=>{"use strict";h();lI=require("node:child_process"),CL=z(qne(),1),zw=z(require("node:fs"),1),$ne=z(require("node:os"),1),Vne=z(require("@sentry/node"),1),EL=z(require("node:path"),1);Bt();Ic();Nje=ve("ProcessTracker"),IL=class{processes=new Set;cleanupHandlersRegistered=!1;constructor(){this.registerCleanupHandlers()}track(e){this.processes.add(e),e.on("exit",()=>{this.processes.delete(e)})}untrack(e){this.processes.delete(e)}async killAll(e){if(this.processes.size===0)return;let r=[];for(let n of this.processes)n.pid&&n.exitCode===null&&r.push(Os(e,n));await Promise.all(r),this.processes.clear()}registerCleanupHandlers(){if(this.cleanupHandlersRegistered)return;this.cleanupHandlersRegistered=!0;let e=async r=>{try{await this.killAll()}catch(n){Nje.error("Error during cleanup:",n)}};process.on("SIGINT",()=>e("SIGINT")),process.on("SIGTERM",()=>e("SIGTERM")),process.on("SIGHUP",()=>e("SIGHUP")),process.on("exit",()=>{for(let r of this.processes)if(r.pid&&r.exitCode===null)try{process.kill(r.pid,"SIGKILL")}catch{}})}get count(){return this.processes.size}},Xw=new IL;Mje=()=>(_g||(_g=EL.default.join($ne.default.tmpdir(),"shell-scripts"),zw.default.mkdirSync(_g,{recursive:!0})),_g),Wne=()=>{try{if(_g)return zw.default.rmSync(_g,{recursive:!0}),_g=void 0,!0}catch(t){Vne.captureException(t)}return!1},Pje=t=>(t=t.trim(),t.includes(`
|
|
1492
1492
|
`)||t.includes(`\r
|
|
1493
1493
|
`)),Lje=(t,e)=>{let r=process.platform==="win32",n,i;if(r)e.includes("powershell")||e.includes("PowerShell")||e.includes("pwsh")?(n=".ps1",i=t.replace(/2>\/dev\/null \|\| true/g,"2>$null; if ($?) {}")):(n=".bat",i=`@echo off
|
|
@@ -1497,7 +1497,7 @@ source ~/.zshrc 2>/dev/null || true
|
|
|
1497
1497
|
set -e
|
|
1498
1498
|
${t}`):(n=".sh",i=`${u}
|
|
1499
1499
|
set -e
|
|
1500
|
-
${t}`)}let s=BL(n);try{return zw.default.writeFileSync(s,i,{mode:493}),s}catch(o){throw new Error(`Failed to create temporary script: ${o}`)}},BL=t=>{let e=Mje(),r=Date.now(),n=Math.random().toString(36).substring(2,8);return EL.default.join(e,`builder_temp_${r}_${n}${t}`)},yL=(t,e,r=!0)=>{if(Pje(t)){let n=Lje(t,e);return e.includes("cmd")||e.includes("CMD")?["/c",n]:e.includes("powershell")||e.includes("PowerShell")||e.includes("pwsh")?["-ExecutionPolicy","Bypass","-File",n]:e.includes("bash")||e.includes("zsh")?r?["-l",n]:[n]:[n]}return e.includes("cmd")||e.includes("CMD")?["/c",t.replace(/2>\/dev\/null \|\| true/g,"2>nul || cd .")]:e.includes("powershell")||e.includes("PowerShell")||e.includes("pwsh")?["-Command",t.replace(/2>\/dev\/null \|\| true/g,"2>$null; if ($?) {}")]:e.includes("zsh")?r?["-l","-c",`source ~/.zshrc 2>/dev/null || true; ${t}`]:["-c",t]:e.includes("bash")?r?["-l","-c",t]:["-c",t]:["-c",t]};uI=t=>"type"in t});var Ef,_je,WHt,zne=L(()=>{"use strict";h();Ef=require("zod"),_je=Ef.z.object({kind:Ef.z.literal("postgres"),migrations:Ef.z.literal("drizzle"),schemaDir:Ef.z.string().default("drizzle")}),WHt=Ef.z.object({database:_je.optional()})});var Xne=L(()=>{"use strict";h()});var Zne,eie,tie,rie,nie,iie=L(()=>{"use strict";h();Zne={eventName:"client.devtools.session.started",version:"1"},eie={eventName:"client.devtools.session.idle",version:"1"},tie={eventName:"client.devtools.tool.call-request",version:"1"},rie={eventName:"client.devtools.tool.call",version:"1"},nie={eventName:"client.devtools.tool.result",version:"1"}});function QL(t){return typeof t=="string"?t:t.map(e=>e.type==="text"?e.text:"").join("")}var ye,Uje,Gje,Oje,Kje,Hje,DL,Jje,jje,Yje,qje,$je,Vje,Wje,zje,Xje,Zje,sie,wL=L(()=>{"use strict";h();ye=require("zod");Uje=ye.z.object({type:ye.z.literal("url"),value:ye.z.string()}).meta({title:"URL"}),Gje=ye.z.object({type:ye.z.literal("upload"),contentType:ye.z.enum(["image/webp","image/png","image/jpeg","image/gif","application/pdf","application/json","text/plain"]),name:ye.z.string(),dataUrl:ye.z.string(),text:ye.z.string().optional(),size:ye.z.number(),id:ye.z.string(),originalUrl:ye.z.string().optional(),ephemeral:ye.z.boolean().optional()}).meta({title:"FileUpload"}),Oje=ye.z.object({type:ye.z.literal("template"),name:ye.z.string(),id:ye.z.number()}).meta({title:"Template"}),Kje=ye.z.object({type:ye.z.literal("builder"),html:ye.z.string()}).meta({title:"BuilderContentAttachment"}),Hje=ye.z.object({type:ye.z.literal("figma"),html:ye.z.string()}).meta({title:"FigmaContentAttachment"}),DL=ye.z.discriminatedUnion("type",[Gje,Oje,Uje,Kje,Hje]).meta({title:"Attachment"}),Jje=ye.z.object({cited_text:ye.z.string(),document_index:ye.z.number(),document_title:ye.z.string().nullable(),end_char_index:ye.z.number(),start_char_index:ye.z.number(),type:ye.z.literal("char_location")}).meta({title:"CitationCharLocationParam"}),jje=ye.z.object({cited_text:ye.z.string(),document_index:ye.z.number(),document_title:ye.z.string().nullable(),end_block_index:ye.z.number(),start_block_index:ye.z.number(),type:ye.z.literal("content_block_location")}).meta({title:"CitationContentBlockLocationParam"}),Yje=ye.z.object({cited_text:ye.z.string(),document_index:ye.z.number(),document_title:ye.z.string().nullable(),end_page_number:ye.z.number(),start_page_number:ye.z.number(),type:ye.z.literal("page_location")}).meta({title:"CitationPageLocationParam"}),qje=ye.z.object({cited_text:ye.z.string(),encrypted_index:ye.z.string(),title:ye.z.string().nullable(),type:ye.z.literal("web_search_result_location"),url:ye.z.string()}).meta({title:"CitationWebSearchResultLocationParam"}),$je=ye.z.discriminatedUnion("type",[Jje,Yje,jje,qje]).meta({title:"TextCitationParam"}),Vje=ye.z.object({type:ye.z.literal("base64"),media_type:ye.z.enum(["image/webp","image/png","image/jpeg","image/gif"]),data:ye.z.string(),original_url:ye.z.string().optional()}).meta({title:"ImageBase64Source"}),Wje=ye.z.object({type:ye.z.literal("url"),url:ye.z.string()}).meta({title:"ImageUrlSource"}),zje=ye.z.object({type:ye.z.literal("text"),text:ye.z.string(),cache:ye.z.boolean().optional(),citations:ye.z.array($je).nullish(),ephemeral:ye.z.boolean().optional(),thoughtSignature:ye.z.string().optional(),tag:ye.z.string().optional()}).meta({title:"ContentMessageItemText"}),Xje=ye.z.object({type:ye.z.literal("image"),source:ye.z.discriminatedUnion("type",[Vje,Wje]),cache:ye.z.boolean().optional(),ephemeral:ye.z.boolean().optional()}).meta({title:"ContentMessageItemImage"}),Zje=ye.z.object({type:ye.z.literal("resource"),resource:ye.z.object({uri:ye.z.string(),mimeType:ye.z.string().optional(),text:ye.z.string().optional(),blob:ye.z.string().optional()})}).meta({title:"ContentMessageItemResource"}),sie=ye.z.object({type:ye.z.literal("tool_result"),tool_use_id:ye.z.string(),tool_name:ye.z.string().optional(),tool_input:ye.z.string().optional(),title:ye.z.string().optional(),content:ye.z.union([ye.z.string(),ye.z.array(ye.z.discriminatedUnion("type",[zje,Xje,Zje]))]),is_error:ye.z.boolean().optional(),cache:ye.z.boolean().optional(),ephemeral:ye.z.boolean().optional(),structured_result:ye.z.record(ye.z.string(),ye.z.any()).optional()}).meta({title:"ContentMessageItemToolResult"})});var oie=L(()=>{"use strict";h()});var Yn,aie,bL=L(()=>{"use strict";h();Yn=require("zod"),aie=Yn.z.object({client:Yn.z.string(),clientVersion:Yn.z.string(),nodeVersion:Yn.z.string(),systemPlatform:Yn.z.string(),frameworks:Yn.z.array(Yn.z.string()),systemEOL:Yn.z.string(),systemArch:Yn.z.string(),systemShell:Yn.z.string().optional(),inGitRepo:Yn.z.boolean().optional()}).catchall(Yn.z.union([Yn.z.string(),Yn.z.array(Yn.z.string()),Yn.z.boolean(),Yn.z.undefined()])).meta({title:"UserContext"})});var qn,Bf,eYe,tYe,Aie,Zw=L(()=>{"use strict";h();qn=require("zod"),Bf=qn.z.object({key:qn.z.string(),value:qn.z.string(),isSecret:qn.z.boolean(),placeholder:qn.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:qn.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"EnvironmentVariable"}),eYe=qn.z.object({key:qn.z.string(),type:qn.z.literal("mise"),tool:qn.z.string(),version:qn.z.string().optional()}).meta({title:"SetupMiseDependency"}),tYe=qn.z.object({key:qn.z.string(),type:qn.z.literal("script"),name:qn.z.string(),script:qn.z.string()}).meta({title:"SetupScriptDependency"}),Aie=qn.z.discriminatedUnion("type",[eYe,tYe]).meta({title:"SetupDependency"})});function die(t){return t==="interrupt"||t==="interrupt-clear"||t==="interrupt-replace"}function xL(t){return t===void 0?{...G9e}:t==="next-turn"?{schedule:"next-turn",coalesce:"merge"}:t==="until-idle"?{schedule:"until-idle",coalesce:"preserve-order"}:{schedule:t.schedule,coalesce:t.coalesce}}var w,rYe,p4t,nYe,iYe,uie,sYe,oYe,aYe,AYe,d4t,t0,cYe,uYe,lYe,gYe,pYe,dYe,f4t,fYe,hYe,mYe,CYe,IYe,EYe,BYe,yYe,QYe,DYe,wYe,bYe,vYe,SYe,xYe,vL,FYe,kYe,RYe,TYe,NYe,MYe,PYe,LYe,_Ye,UYe,GYe,OYe,KYe,HYe,JYe,jYe,YYe,qYe,$Ye,VYe,WYe,zYe,XYe,ZYe,e9e,t9e,r9e,n9e,e0,i9e,s9e,o9e,a9e,A9e,c9e,lie,gie,h4t,m4t,u9e,l9e,g9e,p9e,d9e,f9e,h9e,m9e,C9e,I9e,E9e,B9e,y9e,SL,Q9e,D9e,w9e,b9e,v9e,S9e,x9e,F9e,k9e,R9e,T9e,N9e,M9e,P9e,L9e,_9e,pie,U9e,G9e,O9e,cie,K9e,H9e,J9e,fie,j9e,r0,C4t,Y9e,q9e,$9e,hie,V9e,W9e,z9e,mie,X9e,I4t,Z9e,e6e,E4t,B4t,y4t,Q4t,Cie=L(()=>{"use strict";h();w=require("zod");wL();bL();Zw();rYe=w.z.string().meta({title:"GitSnapshot",description:"Multi-repo git snapshot. Format: 'folder:hash,folder:hash' with URL-encoded folder names. Legacy single-hash form ('abc123') is also accepted. Empty string means no commits."}),p4t=w.z.enum(["named","default"]).meta({title:"ImportType"}),nYe=w.z.object({filePath:w.z.string(),content:w.z.string().optional(),importance:w.z.number().optional(),dropReason:w.z.string().optional(),wasIncluded:w.z.boolean().optional(),virtual:w.z.boolean().optional()}).meta({title:"ProjectFile"}),iYe=w.z.object({id:w.z.string(),name:w.z.string(),content:w.z.string(),type:w.z.enum(["always","agent-mode"]).optional(),filePath:w.z.string().optional(),glob:w.z.string().optional(),description:w.z.string().optional(),allowedTools:w.z.array(w.z.string()).optional(),hideUI:w.z.boolean().optional(),isSkill:w.z.boolean().optional(),disableModelInvocation:w.z.boolean().optional(),userInvocable:w.z.boolean().optional(),scope:w.z.enum(["project","user","plugin"]).optional(),pluginName:w.z.string().optional()}).meta({title:"CustomInstruction"}),uie=w.z.enum(["auto","none","minimal","low","medium","high","xhigh","max"]).meta({title:"ReasoningEffort"}),sYe=w.z.object({name:w.z.string(),description:w.z.string().optional()}).meta({title:"CustomAgentInfo"}),oYe=w.z.record(w.z.string(),w.z.union([w.z.string(),w.z.array(w.z.string())])).meta({title:"AgentModelOverrides"}),aYe=w.z.enum(["react","html","mitosis","react-native","angular","vue","svelte","qwik","solid","marko","swiftui","jetpack-compose","flutter"]).meta({title:"CodeGenFramework"}),AYe=w.z.enum(["tailwind","tailwind-precise","emotion","styled-components","styled-jsx","react-native"]).meta({title:"CodeGenStyleLibrary"}),d4t=w.z.enum(["max_tokens","stop_sequence","tool_use","end_turn","content_filter","error","aborted","pause_turn","refusal","compaction","model_context_window_exceeded"]).nullable().meta({title:"CompletionStopReason"}),t0="The path of the file. Accepts a path relative to the project working directory, an absolute path (`/Users/.../skill.md`), or a tilde path (`~/.builder/skills/.../SKILL.md`). User-level Builder state under `~/.builder/**` is allowed by default for plugin operations; other absolute paths require an explicit ACL policy.",cYe=w.z.object({file_path:w.z.string().meta({description:t0}),offset:w.z.number().nullish().meta({description:"The line number to start reading from."}),limit:w.z.number().nullish().meta({description:"The number of lines to read."})}).meta({title:"ReadToolInput"}),uYe=w.z.object({pattern:w.z.string().meta({description:"The pattern to search for"})}).meta({title:"GlobSearchToolInput"}),lYe=w.z.object({query:w.z.string().meta({description:'A string literal or a JavaScript-flavored regex to search for in all project files. Only escape special characters such as {} and () in string literals to avoid confusion with regex patterns (e.g. "import \\{ foo \\}"). Avoid over-escaping as that will cause errors. Do NOT use inline regex flags like (?i) or (?s) \u2014 they are not supported. The search is case-insensitive by default; use the case_sensitive parameter to control this.'}),include_glob:w.z.string().nullish().meta({description:"An optional single glob pattern to include only specific files (e.g. '**/*.(ts|tsx)' for all TypeScript files)"}),exclude_glob:w.z.string().nullish().meta({description:"Optional glob pattern to exclude specific files or directories"}),case_sensitive:w.z.boolean().nullish().meta({description:"Whether the search should be case-sensitive. Defaults to false (case-insensitive). Set to true for case-sensitive search."})}).meta({title:"GrepSearchToolInput"}),gYe=w.z.object({skill:w.z.string().meta({description:"The name of a skill from the available-skills list. Do not guess names."}),args:w.z.string().nullish().meta({description:"Optional invocation arguments; forwarded with the skill body in the tool result."})}).meta({title:"SkillToolInput"}),pYe=w.z.object({name:w.z.string().meta({description:"The name of the rule to get"})}).meta({title:"GetRuleToolInput"}),dYe=w.z.object({url:w.z.string().meta({description:"The URL of the website to analyze and mimic the style of, for example 'https://airbnb.com' or 'https://instagram.com'"})}).meta({title:"GetStyleInspirationToolInput"}),f4t=w.z.object({}).meta({title:"GetBuildOutputToolInput"}),fYe=w.z.object({restart:w.z.boolean().nullish().meta({description:"Whether to restart the dev server, it will also return the initial logs coming from the dev server. This tool can be very slow, only use as last resort, most of the times file changes do not require a restart."}),set_dev_command:w.z.string().nullish().meta({description:"Use to set the command of the dev server, for example 'npm run dev' or 'cd packages/frontend && yarn dev'. When updating the command, the dev server will be automatically restarted. After changing a command, the proxy port might change, so you need to use the 'set_proxy_port' tool to update the proxy port. Only use if there are explicit issues"}),set_proxy_port:w.z.number().nullish().meta({description:"Used to configure the proxy port of the dev server. For example, if `npm run dev` open a port in 8392, but current proxy server listens 3000, you can use this tool to update the proxy port. Only use if there are explicit issues."}),get_logs:w.z.boolean().nullish().meta({description:"When used standalone, the tool will return logs of the dev server and other status. But don't change or restart anything. It's a read-only operation."}),set_env_variable:w.z.tuple([w.z.string(),w.z.string()]).nullish().meta({description:"Tuple of two strings, the first string is the name of the environment variable, the second string is the value of the environment variable. For example, ['DB_API_KEY', '___PRIVATE_KEY___']"}),set_and_run_setup_command:w.z.string().nullish().meta({description:"Use to set the command of the setup command, for example 'npm install' or 'yarn'. Only use if there are explicit issues."})}).meta({title:"DevServerControlInput"}),hYe=w.z.object({}).meta({title:"DevServerLogsInput"}),mYe=w.z.object({}).meta({title:"GenerateDesignSystemAgentMdInput",description:"Generates and writes `.builder/output/AGENTS.md` from the token and component CSS files produced during DSI approximation indexing. Reads `.builder/sources/figma/manifest.json` for the design system name, `.builder/output/_index/tokens-report.json` for token categories, and globs `.builder/output/tokens/components/*.css` for component slugs. Call this as the final step after all CSS files have been written."}),CYe=w.z.object({}).meta({title:"DevServerRestartInput",description:"Restarts the dev server with current configuration."}),IYe=w.z.object({description:w.z.string().meta({description:"A human readable description of the command to run, for example 'install dependencies' or 'run tests'. This description will be used to explain the command to the user."}),command:w.z.string().meta({description:"The shell command to run, for example 'npm install --save uuid', 'yarn test' or 'npm run build'..."}),timeout:w.z.number().nullish().meta({description:"Optional timeout in milliseconds (max/default 600000)"})}).meta({title:"BashToolInput"}),EYe=w.z.object({command:w.z.string().nullish().meta({description:"The PowerShell command to run, for example 'npm install' or 'yarn test'"}),timeout:w.z.number().nullish().meta({description:"The timeout in milliseconds for the command to run. Choose an appropriate timeout based on the command"}),description:w.z.string().nullish().meta({description:"A human readable description of the command to run, for example 'install dependencies' or 'run tests'. This description will be used to explain the command to the user."})}).meta({title:"PowerShellToolInput"}),BYe=w.z.object({query:w.z.string().meta({description:"The question to search on the internet, be specific and concise."})}).meta({title:"WebSearchToolInput"}),yYe=w.z.object({title:w.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:w.z.string().meta({description:t0}),content:w.z.string().meta({description:"Actual content to write into the file, use an empty string to remove the file"})}).meta({title:"WriteFileInput"}),QYe=w.z.object({title:w.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:w.z.string().meta({description:`${t0} The content of this path must be previously known.`}),old_str:w.z.string().meta({description:"The text to replace"}),new_str:w.z.string().meta({description:"The text to replace it with (must be different from old_str)"}),replace_all:w.z.boolean().optional().meta({description:"Replace all occurences of old_str (default false)"}),apply_with_error:w.z.boolean().optional()}).meta({title:"SearchReplaceInput"}),DYe=w.z.object({title:w.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:w.z.string().meta({description:`${t0} The content of this path must be previously known.`}),edits:w.z.array(w.z.object({old_str:w.z.string().meta({description:"The text to replace (must match the file contents exactly, including all whitespace and indentation)"}),new_str:w.z.string().meta({description:"The edited text to replace the old_str"}),replace_all:w.z.boolean().optional().meta({description:"Replace all occurrences of old_str. This parameter is optional and defaults to false."})})).meta({description:"An array of edit operations to perform, where each edit contains: old_str, new_str, replace_all"}),apply_with_error:w.z.boolean().nullish()}).meta({title:"MultiSearchReplaceInput"}),wYe=w.z.object({query:w.z.string(),type:w.z.enum(["image","video"]),orientation:w.z.enum(["landscape","portrait","square"]).nullish(),hex_color:w.z.string().nullish()}).meta({title:"FindMediaToolInput"}),bYe=w.z.object({query:w.z.string().meta({description:"The text prompt describing the media to find or generate"}),type:w.z.enum(["image","video","gen-image"]).meta({description:"The type of media: 'image' to search images, 'video' to search videos, or 'gen-image' to generate an AI image"}),orientation:w.z.enum(["landscape","portrait","square"]).nullish().meta({description:"The orientation/aspect ratio of the media (landscape=wide, portrait=tall, square=1:1)"}),hex_color:w.z.string().nullish().meta({description:"Optionally use to find images with the predominant specified hex color, for example '#000000' or '#FFFFFF'"}),input_image_urls:w.z.array(w.z.string()).nullish().meta({description:'Reference image URLs for AI image generation (only used with type: "gen-image")'})}).meta({title:"MediaToolInput"}),vYe=w.z.object({content:w.z.string().meta({description:"Markdown content of the memory, keep it factual and to the point. Avoid using line numbers, code snippets as they are likely to change."}),when:w.z.string().meta({description:"The semantic search query that will be used to retrieve this memory later. Describe the situation, task, or context when this memory should be surfaced."}),category:w.z.union([w.z.literal("architecture").meta({description:"System structure, layers, and responsibilities"}),w.z.literal("data-and-sync").meta({description:"Data storage, persistence, synchronization, IPC, and state flow"}),w.z.literal("patterns-and-standards").meta({description:"Canonical ways of doing things in this codebase"}),w.z.literal("coupling-and-duplication").meta({description:"Cross-file, cross-surface, or duplicated logic that must stay aligned"}),w.z.literal("ui-and-ux-contracts").meta({description:"User-visible behavior, UX guarantees, and UI rules"}),w.z.literal("concurrency-and-lifecycle").meta({description:"Async behavior, ordering, lifecycle, and race prevention"}),w.z.literal("invariants").meta({description:"Hard rules that must always remain true"}),w.z.literal("security-and-trust").meta({description:"Security, permissions, and trust boundaries"}),w.z.literal("gotchas").meta({description:"Known sharp edges that will break things if ignored"}),w.z.literal("constraints-and-limits").meta({description:"System limits, assumptions, and non-obvious constraints"}),w.z.literal("rationale-and-history").meta({description:"Why something is the way it is (tradeoffs, history, intent)"})]).meta({description:"The general category that this memory fits into"}),glob:w.z.string().optional().meta({description:"Glob pattern for file-based memory retrieval. Use specific paths (e.g., 'src/components/Button.tsx', 'lib/api/**/*.ts') rather than broad patterns (e.g., '*.tsx'). When files matching this glob are read, this memory will be suggested."}),importance:w.z.number().optional(),glob_auto_include:w.z.boolean().optional().meta({description:"Whenever the memory should be included whenever the glob is matched."})}).meta({title:"MemoryToolInput"}),SYe=w.z.object({query:w.z.string(),limit:w.z.number().optional(),minSimilarity:w.z.number().optional()}).meta({title:"SearchMemoriesToolInput"}),xYe=w.z.object({outcome:w.z.enum(["worked","failed","partial","unknown"]).meta({description:"Overall exchange outcome based on user reaction"}),memory_scores:w.z.object({}).catchall(w.z.enum(["worked","failed","partial","unknown"])).meta({description:"Score for each memory used: { memory_id: outcome }"})}).meta({title:"ScoreMemoriesToolInput"}),vL=w.z.object({label:w.z.string(),description:w.z.string()}).meta({title:"LabelOption"}),FYe=w.z.strictObject({label:w.z.string().meta({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:w.z.string().meta({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}),preview:w.z.string().nullish().meta({description:"Optional preview content rendered when this option is focused. Use for mockups, code snippets, or visual comparisons that help users compare options. See the tool description for the expected content format."})}).meta({title:"AskUserQuestionOption"}),kYe=w.z.strictObject({question:w.z.string().meta({description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:w.z.string().meta({description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:w.z.array(FYe).min(2).max(4).meta({description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically."}),multiSelect:w.z.boolean().optional().meta({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}).meta({title:"AskUserQuestion"}),RYe=w.z.strictObject({questions:w.z.array(kYe).min(1,"Must have at least 1 question").max(4).meta({description:"Questions to ask the user (1-4 questions)"})}).meta({title:"AskUserQuestionToolInput"}),TYe=w.z.object({description:w.z.string().meta({description:"A short (3-5 word) description of the task"}),prompt:w.z.string().meta({description:"The task for the agent to perform"}),subagent_type:w.z.string().optional().meta({description:"The type of specialized agent to use for this task"}),resume:w.z.string().optional().meta({description:"Optional agent ID to resume from"}),origin_channel_id:w.z.string().optional().meta({description:"The original user's channel_id that triggered this work. When provided, it will be included in the worker report so you can route the response back to the correct channel. Always pass this when spawning agents on behalf of a user request."}),attachmentUrls:w.z.array(w.z.string()).optional().meta({description:"URLs of images or files to attach to the agent's context. Useful for providing visual context like screenshots, designs, or reference images."})}).meta({title:"AgentToolInput"}),NYe=w.z.object({checkpoint_id:w.z.string().meta({description:"The checkpoint ID to revert back to. All changes from this checkpoint to HEAD will be reverted."})}).meta({title:"RevertToolInput"}),MYe=w.z.object({}).meta({title:"TodoReadToolInput"}),PYe=w.z.object({}).meta({title:"RunningAgentsToolInput"}),LYe=w.z.object({mode:w.z.enum(["replace","patch"]).meta({description:"Determine how the new todos update the current list: 'patch' means existing items will remain and only the provided items will be updated. The same 'id' must be provided for items you want to update. 'replace' means all existing items will be replaced with the new array of todos."}),todos:w.z.array(w.z.object({content:w.z.string().meta({description:"The imperative form describing what needs to be done"}),status:w.z.enum(["pending","in_progress","completed"]),id:w.z.string()}))}).meta({title:"TodoWriteToolInput"}),_Ye=w.z.object({subject:w.z.string().meta({description:"A brief title for the task"}),description:w.z.string().meta({description:"What needs to be done"}),metadata:w.z.looseObject({}).optional()}).meta({title:"TaskCreateToolInput"}),UYe=w.z.object({taskId:w.z.string().meta({description:"The ID of the task to update"}),subject:w.z.string().optional().meta({description:"New subject for the task"}),description:w.z.string().optional().meta({description:"New description for the task"}),status:w.z.enum(["pending","in_progress","completed","deleted"]).optional().meta({description:"New status for the task"}),owner:w.z.string().optional().meta({description:"New owner for the task"}),addBlocks:w.z.array(w.z.string()).optional().meta({description:"Task IDs that this task blocks"}),addBlockedBy:w.z.array(w.z.string()).optional().meta({description:"Task IDs that block this task"}),metadata:w.z.looseObject({}).optional()}).meta({title:"TaskUpdateToolInput"}),GYe=w.z.object({}).meta({title:"TaskListToolInput"}),OYe=w.z.object({filePath:w.z.string().meta({description:"The path of the Mitosis file to edit (e.g., index.lite.tsx)"}),old_str:w.z.string().meta({description:"Content to be replaced, this substring should appear verbatim in the selected file_path"}),new_str:w.z.string().meta({description:"New content to replace the old content with"})}).meta({title:"BuilderEditToolInput"}),KYe=w.z.object({href:w.z.string().optional(),selector:w.z.string().optional(),width:w.z.number().optional(),height:w.z.number().optional()}).meta({title:"GetScreenshotToolInput"}),HYe=w.z.object({href:w.z.string().meta({description:"The URL or relative path to navigate the preview to (e.g., '/about' or 'https://example.com')"})}).meta({title:"NavigatePreviewToolInput"}),JYe=w.z.object({url:w.z.string().meta({description:"The URL to fetch content from"}),prompt:w.z.string().optional().meta({description:"Optional prompt to describe the content you want to extract from the URL. Leave it blank to fetch images."}),include_styles:w.z.boolean().optional().meta({description:"If true, the computed styles of the page will be extracted, as well as a screenshot. Prompt must be provided"})}).meta({title:"WebFetchToolInput"}),jYe=w.z.object({category:w.z.enum(["reusable_knowledge","one_off","bad_quality"]).optional(),gif_id:w.z.string().optional(),timeline_id:w.z.string().optional(),recording_id:w.z.string().optional(),important_files:w.z.array(w.z.object({file_path:w.z.string().meta({description:"The relative path of the file to read"}),relevance:w.z.enum(["high","medium","low"]).optional().meta({description:"The relevance of the file based on the initial user_prompt"}),offset:w.z.number().optional().meta({description:"The offset of the file to read, in lines"}),limit:w.z.number().optional().meta({description:"The limit of the file to read, in lines"})}))}).meta({title:"ExplorationMetadataToolInput"}),YYe=w.z.object({}).meta({title:"EnterPlanModeToolInput"}),qYe=w.z.object({plan:w.z.string().meta({description:"The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise. Do not include follow up questions in the plan."}),handled:w.z.boolean().optional()}).meta({title:"ExitPlanModeToolInput"}),$Ye=w.z.object({uri:w.z.string().meta({description:"The URI of the resource to read, matching a resource template pattern (e.g., 'file:///path/to/file')"}),serverName:w.z.string().optional().meta({description:"Optional name of the MCP server to use. If not provided, will auto-detect based on URI."})}).meta({title:"ReadMcpResourceToolInput"}),VYe=w.z.enum(["navigation","interaction","assertion","error","milestone","code-change","observation","verified"]).meta({title:"TimelineEventCategory"}),WYe=w.z.enum(["succeeded","couldnt_verify","failed","other"]).meta({title:"TestOutcome"}),zYe=w.z.enum(["env_issue","creds_missing","needs_user_input","server_not_ready","feature_not_reachable","timeout","assertion_failed","unexpected_error","not_applicable","escalated"]).meta({title:"TestCaseFailureCategory"}),XYe=w.z.object({title:w.z.string().meta({description:"A descriptive title for this frame (e.g., 'Login page loaded', 'Form submitted successfully')"}),frame:w.z.literal("last-image").meta({description:"The frame source. Use 'last-image' to record the most recent screenshot."}),category:VYe.optional().meta({description:"Category of this frame for timeline organization. Default: 'milestone'"}),description:w.z.string().optional().meta({description:"Optional longer description providing context about what this frame shows."}),pr_highlight:w.z.boolean().optional().meta({description:"Set true to mark this as a 'verified screenshot' worth showing in the PR description \u2014 i.e. visual proof of how the fix/feature behaves. Use sparingly (1\u20133 per session) for the key moments that demonstrate the feature working. The title is used as the caption."})}).meta({title:"RecordFrameToolInput"}),ZYe=w.z.object({outcome:WYe.meta({description:"The structured test outcome"}),summary:w.z.string().meta({description:"A concise 1\u20132 sentence summary explaining the test outcome"}),details:w.z.string().optional().meta({description:"Optional additional context: error messages, steps attempted, etc."}),test_case_id:w.z.string().optional().meta({description:"Links to a test case ID (e.g., 'TC-01'). If present, this is a per-case report. If absent, this is the session-level summary."}),evidence_frame_count:w.z.number().optional().meta({description:"Number of RecordFrame calls made for this test case. Should be >= 1 for per-case reports."}),failure_category:zYe.optional().meta({description:"Structured failure reason. Required when outcome is failed or couldnt_verify."}),failure_detail:w.z.string().optional().meta({description:"Human-readable failure explanation. E.g., 'Login page returned 403 \u2014 test account may have been disabled'"}),console_errors:w.z.string().optional(),network_failures:w.z.string().optional(),steps_attempted:w.z.string().optional(),urls_tested:w.z.array(w.z.string()).optional()}).meta({title:"ReportTestOutcomeToolInput"}),e9e=w.z.object({projectOverview:w.z.object({framework:w.z.string().nullable(),packageManager:w.z.enum(["npm","yarn","pnpm","bun"]).nullable(),isMonorepo:w.z.boolean(),detectedLanguage:w.z.enum(["typescript","javascript"]).nullable()}),rootDirectory:w.z.object({path:w.z.string(),reason:w.z.string()}).nullable(),installCommand:w.z.object({command:w.z.string(),reason:w.z.string()}).nullable(),runtimeDependencies:w.z.array(w.z.object({tool:w.z.string(),version:w.z.string(),source:w.z.string()})),devServer:w.z.object({command:w.z.string(),url:w.z.string(),port:w.z.number(),reason:w.z.string()}).nullable(),environmentVariables:w.z.array(w.z.object({key:w.z.string(),description:w.z.string(),isRequired:w.z.boolean(),isSecret:w.z.boolean(),defaultValue:w.z.string().nullable(),source:w.z.string()})),validationScript:w.z.object({command:w.z.string(),reason:w.z.string()}).nullable(),npmrcContents:w.z.string().nullable(),hasHotModuleReload:w.z.object({value:w.z.boolean(),reason:w.z.string()}).nullable()}).meta({title:"SetupAnalysisValues"}),t9e=w.z.object({config:e9e,message:w.z.string().optional()}).meta({title:"ProposeConfigToolInput"}),r9e=w.z.enum(["installCommand","devServer","validationScript","environmentVariables"]).meta({title:"SetupValueField"}),n9e=w.z.object({field:r9e.meta({description:"Which field to update"}),value:w.z.object({command:w.z.string().optional().meta({description:"The command to run (for installCommand, devServer, validationScript)"}),url:w.z.string().optional().meta({description:"Dev server URL (only for devServer)"}),port:w.z.number().optional().meta({description:"Dev server port (only for devServer)"}),environmentVariables:w.z.array(w.z.object({key:w.z.string().meta({description:"Variable name"}),description:w.z.string().optional().meta({description:"What this variable is for"}),isRequired:w.z.boolean().optional().meta({description:"Whether this variable is required"}),isSecret:w.z.boolean().optional().meta({description:"Whether this is a secret/credential"}),defaultValue:w.z.string().nullish()})).optional()}),reason:w.z.string()}).meta({title:"UpdateSetupValueToolInput"}),e0=w.z.enum(["verified","no-frontend","empty-project","mobile-project","user-question","code-change-required","other","started","failed"]).meta({title:"ExitState",description:"Current state: verified (all done), no-frontend (project has no dev server), empty-project (project has almost no code), mobile-project (mobile app e.g. Expo/React Native \u2014 recommend desktop local mode), user-question (need input), code-change-required (repo has code issues user must fix), other (other problem), started (Session started but Exit tool was never called (orphaned session)), failed (Session failed before reaching the agent (e.g. branch/container creation failed))"}),i9e=w.z.object({state:e0.meta({description:"Current state: verified (all done), no-frontend (project has no dev server), empty-project (project has almost no code), mobile-project (mobile app e.g. Expo/React Native), user-question (need input), code-change-required (repo has code issues user must fix), other (other problem)"}),summary:w.z.string().meta({description:"Brief summary of configuration outcome (what succeeded or what's needed)"}),questions:w.z.array(w.z.object({question:w.z.string().meta({description:"Full question text"}),context:w.z.string().meta({description:"Why this information is needed"}),header:w.z.string().optional().meta({description:'Short label (e.g., "API Key", "Database URL")'}),type:w.z.enum(["select","multi-select","text"]).optional().meta({description:'Question type: "select" for single-choice, "multi-select" for multiple choices, "text" for free-form input. Defaults to "select" if options are present, "text" if not.'}),placeholder:w.z.string().optional().meta({description:"Placeholder/hint text for 'text' type questions (e.g., 'Enter your API key', 'https://localhost:3000')"}),options:w.z.array(vL).optional().meta({description:"Suggested answer choices (for 'select' and 'multi-select' types). User can always choose 'Other'."})})).optional().meta({description:"Questions for user (only when state is 'user-question'). Include suggested options when possible."}),isMonorepo:w.z.boolean().optional().meta({description:"Repository contains multiple packages/apps"}),isMicrofrontend:w.z.boolean().optional().meta({description:"Frontend code served over multiple ports/servers"}),setupNeedsCredentials:w.z.boolean().optional().meta({description:"Setup requires credentials (e.g., NPM_TOKEN for private packages)"}),devServerNeedsCredentials:w.z.boolean().optional().meta({description:"Dev server needs special environment variables to run"}),needsVPN:w.z.boolean().optional().meta({description:"Setup requires a VPN connection"}),autoReload:w.z.boolean().optional().meta({description:"The dev server is able to reload the page automatically when the code changes, either through HMR or full page reload. Usually vite, webpack etc support this."}),usesBuilderCms:w.z.boolean().optional().meta({description:"The connected app uses Builder CMS (detected via @builder.io/react or @builder.io/sdk-* dependencies, a builder-registry file, or Builder CMS API keys such as BUILDER_PUBLIC_KEY)"}),stack:w.z.array(w.z.string()).optional().meta({description:'Technologies used by the connected application (not monorepo-wide). Include specific, high-confidence signals only, e.g. ["React", "Next.js", "Postgres", "Drizzle", "Tailwind CSS", "Clerk"]. Omit vague or uncertain entries.'}),projectDescription:w.z.string().optional().meta({description:"A human-readable description of what this project is about \u2014 focus on purpose and domain, not technical stack. This helps route user requests to the right project (e.g., 'Company blog and content management', 'E-commerce storefront for selling shoes', 'Internal admin dashboard for managing users')."})}).meta({title:"ExitToolInput"}),s9e=["running","stopped","starting","failed","unset"],o9e=["not-installed","installing","installed","install-failed","install-aborted"],a9e=["ok-2xx","error-4xx","error-5xx","error-fetch","stopped","connecting"],A9e=["unset","running","stopped","success","failure"],c9e=w.z.object({question:w.z.string(),context:w.z.string(),whatYouTried:w.z.string().optional(),header:w.z.string().optional().meta({description:"Short label (e.g., 'API Key', 'Database URL')"}),type:w.z.enum(["select","multi-select","text"]).optional().meta({description:'Question type: "select" for single-choice, "multi-select" for multiple choices, "text" for free-form input'}),placeholder:w.z.string().optional().meta({description:"Placeholder text for text-type questions"}),options:w.z.array(vL).optional()}),lie=w.z.object({setupCommand:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on setupState === 'installed'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),setupDependencies:w.z.object({value:w.z.array(Aie).optional(),verified:w.z.boolean().meta({description:"Based on setupState === 'installed'"})}),devCommand:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on devState === 'running'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),devServer:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds waiting for the server to respond"})}),validateCommand:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on validateState === 'success'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),appOrigin:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"})}),defaultOrigin:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Always true if set (used with wildcard appOrigin)"})}),environmentVariables:w.z.object({value:w.z.array(Bf).optional(),verified:w.z.boolean().meta({description:"Based on devState === 'running'"})}),autoDetectDevServer:w.z.object({value:w.z.boolean().optional(),verified:w.z.boolean().meta({description:"Always true if set"})}),autoDetectDevServerPatterns:w.z.object({value:w.z.array(w.z.string()).optional(),verified:w.z.boolean().meta({description:"Always true if set"})}),hasHotModuleReload:w.z.object({value:w.z.boolean().optional(),reason:w.z.string().optional().meta({description:"Detection-only, not auto-applied"})})}),gie=w.z.object({setupState:w.z.enum(o9e),devState:w.z.enum(s9e),httpServerState:w.z.enum(a9e),validateState:w.z.enum(A9e)}),h4t=w.z.object({id:w.z.string().meta({description:"Auto-generated document ID"}),projectId:w.z.string(),branchName:w.z.string(),createdAt:w.z.number(),updatedAt:w.z.number(),ownerId:w.z.string(),state:e0.meta({description:"Configuration state from Exit tool"}),running:w.z.boolean().default(!1),previousStates:w.z.array(e0).optional(),summary:w.z.string().meta({description:"Summary from Exit tool"}),questions:w.z.array(c9e).optional(),configuration:lie,sessionId:w.z.string(),orchestratorStates:gie,peakDiskUsage:w.z.number().optional().meta({description:"Peak disk usage in bytes"}),peakMemoryUsage:w.z.number().optional().meta({description:"Peak memory usage in bytes"}),screenshotUrl:w.z.string().optional().meta({description:"Screenshot URL from verification (e.g., error page screenshot)"}),isMonorepo:w.z.boolean().optional(),isMicrofrontend:w.z.boolean().optional(),setupNeedsCredentials:w.z.boolean().optional(),devServerNeedsCredentials:w.z.boolean().optional(),projectDescription:w.z.string().optional(),cost:w.z.number().optional(),durationMs:w.z.number().optional(),needsVPN:w.z.boolean().optional(),autoReload:w.z.boolean().optional(),usesBuilderCms:w.z.boolean().optional(),stack:w.z.array(w.z.string()).optional()}).meta({title:"ProposedConfig",description:"Configuration proposed by the configuration agent, stored in Firebase"}),m4t=w.z.object({projectId:w.z.string(),branchName:w.z.string(),state:e0,summary:w.z.string(),questions:w.z.array(w.z.object({question:w.z.string(),context:w.z.string(),whatYouTried:w.z.string().optional(),header:w.z.string().optional(),options:w.z.array(vL).optional(),multiSelect:w.z.boolean().optional()})).optional(),configuration:lie,sessionId:w.z.string(),orchestratorStates:gie,peakDiskUsage:w.z.number().optional(),peakMemoryUsage:w.z.number().optional(),screenshotUrl:w.z.string().optional(),isMonorepo:w.z.boolean().optional(),isMicrofrontend:w.z.boolean().optional(),setupNeedsCredentials:w.z.boolean().optional(),devServerNeedsCredentials:w.z.boolean().optional(),needsVPN:w.z.boolean().optional(),projectDescription:w.z.string().optional(),autoReload:w.z.boolean().optional(),usesBuilderCms:w.z.boolean().optional(),stack:w.z.array(w.z.string()).optional()}).meta({title:"ProposeConfigParams"}),u9e=w.z.object({command:w.z.string().meta({description:"The install command to run (e.g., 'npm install', 'yarn', 'pnpm install'). It can be a multi-line command too, just like a shell script."}),dependencies:w.z.array(w.z.object({tool:w.z.string().meta({description:"The tool/binary to verify (e.g., 'node', 'npm', 'git')"}),version:w.z.string().optional().meta({description:"Optional version requirement (e.g., '>=18.0.0', '20.x')"})})).optional()}).meta({title:"VerifySetupCommandToolInput"}),l9e=w.z.object({command:w.z.string().meta({description:"The dev server command to run (e.g., 'npm run dev', 'cd packages/frontend && yarn dev')"})}).meta({title:"VerifyDevCommandToolInput"}),g9e=w.z.object({autoDetect:w.z.boolean().meta({description:"Whether to automatically detect the dev server URL from terminal output"}),autoDetectPattern:w.z.string().optional().meta({description:"Pattern to match and extract URL from terminal output when multiple URLs are present (e.g., 'Local:.*http://localhost:\\\\d+')"}),hardcodedUrl:w.z.string().optional().meta({description:"The hardcoded dev server URL to use when autoDetect is false (e.g., 'http://localhost:3000')"}),appOrigin:w.z.string().meta({description:"The origin where the app should be accessed (e.g., 'https://acme.com', 'https://*.acme.com'). Can be a pattern with wildcard."}),defaultOrigin:w.z.string().optional().meta({description:"Default origin to use when appOrigin is a pattern (e.g., 'https://dev.acme.com'). Required if appOrigin contains a wildcard."})}).meta({title:"VerifyDevServerToolInput"}),p9e=w.z.object({command:w.z.string(),timeout:w.z.number().optional().meta({description:"Default: 300000 (5 minutes)"})}).meta({title:"VerifyValidateCommandToolInput"}),d9e=w.z.object({key:w.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:w.z.string().meta({description:"The environment variable value. Must be a concrete value, not a placeholder."}),secret:w.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"})}).meta({title:"ProposeEnvVariableToolInput"}),f9e=w.z.object({key:w.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:w.z.string().meta({description:"The environment variable value. Use clear placeholder like 'PLACEHOLDER_DATABASE_URL' if actual value is unknown."}),secret:w.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"}),placeholder:w.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:w.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"SetEnvVariableToolInput"}),h9e=w.z.object({path:w.z.string().meta({description:'Path where the file should be written. Supports absolute paths ("/app/.npmrc"), tilde ("~/.npmrc") and paths relative to the project working directory ("./.npmrc"). Use this tool ONLY for configuration-only files that should NOT be committed to the repo (e.g. `.npmrc` with auth tokens, machine-local env files) \u2014 never to patch source code or fix software issues.'}),content:w.z.string().optional().meta({description:"Plain text content to write to the file. Mutually exclusive with `base64`."}),base64:w.z.string().optional().meta({description:"Base64-encoded binary content to write to the file. Mutually exclusive with `content`. Use only when the file is genuinely binary."})}).meta({title:"SetFileOverrideToolInput"}),m9e=w.z.object({channel_id:w.z.string().meta({description:"The channel identifier in URI format (see supported formats in the tool description)"}),markdown:w.z.string().meta({description:"The message content to send in markdown format"}),status:w.z.enum(["starting","question","will-follow-up","done:success","done:error"]),loading_message:w.z.string().optional().meta({description:"Loading message displayed in the Slack thread while the agent is working (only used when status is 'starting')."}),voice_response:w.z.boolean().optional().meta({description:"When true, send the response as a voice message using text-to-speech. Only supported for Telegram channels. Only set to true when the user's original message was a voice/audio message (look for '[Voice message transcription]' or '[Audio' markers), the channel is Telegram, and the response is short and conversational with no URLs, code, lists, or other content that doesn't translate to audio. Default to false (text) for all text-originated messages."}),from_user_id:w.z.string().optional().meta({description:"Builder.io user ID this message is from / should be attributed to. Only allowed when channel_id is 'builder/branch/{project_id}/{branch_name}'. When set, the message is delivered to the target branch as coming from this user (role 'user') instead of from the agent. Use whenever the message represents user feedback/intent that should be assigned to someone \u2014 even if it was composed, summarized, or merged from multiple people."})}).meta({title:"SendMessageToolInput"}),C9e=w.z.object({project_id:w.z.string().meta({description:"The project ID to create the branch in"}),message:w.z.string().meta({description:"The initial message or task description for the branch. Do NOT include instructions to open or create a PR unless the user's original request explicitly asked for a PR."}),builder_user_id:w.z.string().optional().meta({description:"Builder.io user ID to act as. When provided, the branch will be created as if this user created it."}),hidden:w.z.boolean().optional().meta({description:"Whether to hide the branch from the user. Useful for exploratory branches not intended to ever get merged back to main. Default: false."}),origin_channel_id:w.z.string().optional().meta({description:"The channel identifier that originally triggered this work. Used for tracking purposes and coming back to the original slack thread with updates."}),session_mode:w.z.enum(["normal","planning","deep-research"]).optional(),model:w.z.enum(["auto","opus","sonnet","haiku"]).optional(),attachment_urls:w.z.array(w.z.string()).optional(),git_base_branch:w.z.string().optional(),auto_archive_on_idle:w.z.boolean().optional()}).meta({title:"SpawnBranchToolInput"}),I9e=w.z.object({repo_url:w.z.string().meta({description:"Repository URL (regular Git URL or template:// URL)"}),name:w.z.string().optional().meta({description:"Human-readable name for the project. If not provided, a name will be generated from the repo name."}),builder_user_id:w.z.string().meta({description:"Builder.io user ID to act as. The project and branch will be created as if this user created them, and their git credentials will be validated before creation."}),origin_channel_id:w.z.string().optional().meta({description:"The channel_id identifier that originally triggered this work. Used for routing status updates back to the user."}),initial_message:w.z.string().optional().meta({description:"Only valid for template:// URLs \u2014 creates a branch with this message"})}).meta({title:"CreateProjectToolInput"}),E9e=w.z.object({}).meta({title:"GetAvailableReposToolInput"}),B9e=w.z.object({project_id:w.z.string().meta({description:"The project ID containing the branch"}),branch_name:w.z.string().meta({description:"The name of the branch to read"})}).meta({title:"ReadBranchToolInput"}),y9e=w.z.object({project_id:w.z.string().meta({description:"The project ID containing the branch"}),branch_name:w.z.string().meta({description:"The name of the branch to archive"}),builder_user_id:w.z.string().meta({description:"The Builder.io user ID of the person requesting the archive. This is used to attribute the archive action to a specific user."}),reason:w.z.string().optional().meta({description:"The reason for archiving this branch (max 500 chars). Examples: 'Work completed and merged', 'No longer needed', 'Superseded by branch X'."})}).meta({title:"ArchiveBranchToolInput"}),SL=w.z.enum(["high","medium","low"]).meta({title:"ReviewSeverity"}),Q9e=w.z.object({file_path:w.z.string().meta({description:"Relative file path - MUST be a file that appears in the PR diff"}),line:w.z.number().meta({description:"Line number in the file (end line for multi-line). MUST be a line within the PR diff"}),start_line:w.z.number().optional().meta({description:"For multi-line comments (optional)"}),side:w.z.enum(["LEFT","RIGHT"]).optional().meta({description:"Diff side. RIGHT (default) = NEW file (added/context). LEFT = OLD file (removed/context). Use LEFT only when commenting on deleted code with no semantically related new-side anchor."}),title:w.z.string().meta({description:"Brief plain-text issue title. MUST NOT start with severity emojis"}),body:w.z.string().meta({description:"Review comment (1-2 sentences)"}),severity:SL.meta({description:"Issue severity: high (blocking), medium (should fix), or low (minor observation)"}),debugInfo:w.z.string().optional(),gif_id:w.z.string().optional().meta({description:"Per-comment GIF (optional)"})}).meta({title:"PRReviewComment"}),D9e=w.z.enum(["looks_good","has_findings","blocking"]).meta({title:"ReviewVerdict"}),w9e=w.z.object({summary:w.z.string().meta({description:"Your detailed analysis of the changes (displayed in a collapsible 'Review Details' section)"}),comments:w.z.array(Q9e).optional(),risk_level:SL.optional(),verdict:D9e.optional()}).meta({title:"SubmitPRReviewToolInput"}),b9e=w.z.object({thread_node_ids:w.z.array(w.z.string()).meta({description:"GraphQL thread node_ids (PRRT_...) from previous review response"})}).meta({title:"ResolveQACommentsToolInput"}),v9e=w.z.object({title:w.z.string().meta({description:"Brief summary of the issue (e.g., 'Button click has no effect')"}),description:w.z.string().meta({description:"Detailed description of what went wrong, what was expected, and what actually happened"}),debugInfo:w.z.string().optional().meta({description:"Optional console errors, stack traces, or other diagnostic information"})}).meta({title:"ReportUIIssueToolInput"}),S9e=w.z.object({file_path:w.z.string().meta({description:"File path where the issue occurs (e.g., 'packages/api/src/auth.ts')"}),line:w.z.number().meta({description:"End line number of the issue range (or single line if no start_line)"}),start_line:w.z.number().optional().meta({description:"Optional start line for multi-line issues. When provided, the comment spans from start_line to line"}),title:w.z.string().meta({description:"Short, descriptive title (one line, no markdown)"}),severity:SL.meta({description:"Issue severity: high for critical bugs, medium for should-fix, low for minor observations"}),body:w.z.string().meta({description:"Detailed explanation in markdown format. Should include: What the issue is, Why it's problematic, Impact, How to fix it, Evidence"})}).meta({title:"ReportIssueToolInput"}),x9e=w.z.object({issue:w.z.string().meta({description:"What's blocking execution"}),steps_attempted:w.z.string().meta({description:"What was tried before escalating"}),current_url:w.z.string().meta({description:"Current browser URL"}),test_case_id:w.z.string().meta({description:"Which test case is blocked"})}).meta({title:"EscalateToPlanner"}),F9e=w.z.object({}).meta({title:"GetLastBrowserTestToolInput"}),k9e=w.z.object({file_path:w.z.string().optional().meta({description:"Optional relative or absolute path to filter diagnostics to a single file. Omit to retrieve diagnostics for the entire workspace."})}).meta({title:"IDEDiagnosticsToolInput"}),R9e=w.z.object({event_id:w.z.string().meta({description:"The codegen event ID to load (e.g. cgen-<eventId>)."})}).meta({title:"GetCodegenEventToolInput"}),T9e=w.z.object({session_or_event_id:w.z.string().meta({description:"A session ID or codegen event ID. When an event ID is given, its session is resolved first."}),limit:w.z.number().optional().meta({description:"Maximum number of events to return."})}).meta({title:"ListCodegenSessionEventsToolInput"}),N9e=w.z.object({url:w.z.string().meta({description:"The prototype URL (e.g., https://builder.io/app/projects/<projectId>/<branchName>)"}),project_id:w.z.string().optional().meta({description:"The project ID (optional, parsed from URL if not provided)"}),branch_name:w.z.string().optional().meta({description:"The branch name (optional, parsed from URL if not provided)"})}).meta({title:"PullPrototypeToolInput"}),M9e=w.z.object({project_id:w.z.string().meta({description:"The Builder.io project ID containing the branch"}),branch_name:w.z.string().meta({description:"The Fusion branch name to push and open a PR for"}),builder_user_id:w.z.string().optional().meta({description:"Builder.io user ID to attribute the PR to. When provided, the PR body will credit this user and the user must be a member of the organization. Highly recommended when the PR is being opened on behalf of a specific user."}),draft:w.z.boolean().optional().meta({description:`Whether to create the PR as a draft. When omitted, defaults to the branch's configured commitMode: true for "draft-prs" branches, false for "prs" branches.`})}).meta({title:"EnsurePRToolInput"}),P9e=w.z.object({name:w.z.string().meta({description:'Human-readable name of the service to connect, e.g. "Jira", "Linear", "Sentry"'}),url:w.z.string().optional().meta({description:"Remote MCP endpoint URL (e.g. https://mcp.linear.app/mcp). When omitted, the tool discovers known URLs for the named service instead."})}).meta({title:"ConnectMCPToolInput"}),L9e=w.z.object({Read:cYe,Write:yYe,Edit:QYe,ReadRule:pYe,Skill:gYe,GetStyleInspiration:dYe,GetScreenshot:KYe,NavigatePreview:HYe,MultiEdit:DYe,FindMedia:wYe,Media:bYe,AddMemory:vYe,SearchMemories:SYe,ScoreMemories:xYe,Bash:IYe,PowerShell:EYe,WebSearch:BYe,AskUserQuestion:RYe,Agent:TYe,Grep:lYe,Glob:uYe,DevServerControl:fYe,DevServerLogs:hYe,DevServerRestart:CYe,Revert:NYe,TodoRead:MYe,TodoWrite:LYe,TaskCreate:_Ye,TaskUpdate:UYe,TaskList:GYe,BuilderEdit:OYe,WebFetch:JYe,ExplorationMetadata:jYe,EnterPlanMode:YYe,ExitPlanMode:qYe,ReadMcpResource:$Ye,RecordFrame:XYe,SubmitPRReview:w9e,ProposeConfig:t9e,UpdateSetupValue:n9e,Exit:i9e,ResolveQAComments:b9e,GetLastBrowserTest:F9e,ReportUIIssue:v9e,ReportIssue:S9e,ReportTestOutcome:ZYe,VerifySetupCommand:u9e,VerifyDevCommand:l9e,VerifyDevServer:g9e,VerifyValidateCommand:p9e,ProposeEnvVariable:d9e,SetEnvVariable:f9e,SetFileOverride:h9e,SendMessage:m9e,SpawnBranch:C9e,CreateProject:I9e,GetAvailableRepos:E9e,ReadBranch:B9e,ArchiveBranch:y9e,RunningAgents:PYe,IDEDiagnostics:k9e,EscalateToPlanner:x9e,PullPrototype:N9e,ConnectMCP:P9e,EnsurePR:M9e,GenerateDesignSystemAgentMd:mYe,GetCodegenEvent:R9e,ListCodegenSessionEvents:T9e}),_9e=L9e.keyof().meta({title:"CodeGenTools"}),pie=w.z.enum(["planning","normal","auto-planning","deep-research"]).meta({title:"SessionMode"}),U9e=w.z.enum(["quality","quality-v4","quality-v4-agent"]).meta({title:"CodeGenMode"}),G9e={schedule:"next-turn",coalesce:"merge"};O9e=["fusion","editor-ai","repo-indexing","cli","create-app-firebase","create-app-lovable","builder-code-panel","setup-project","code-review-orchestrator","project-configuration","org-agent","org-worker","browser-testing","projects-scheduler-memory-extraction","builder-code","unknown","dsi-mcp","design-system-indexer","builder-publish-integration"],cie=w.z.enum(O9e).meta({title:"BaseCodeGenPosition"}),K9e=w.z.union([cie,w.z.templateLiteral([cie,"-agent"])]).meta({title:"CodeGenPosition"}),H9e=w.z.object({designSystems:w.z.array(w.z.string())}).meta({title:"RepoIndexingConfig"}),J9e=w.z.object({name:w.z.string(),description:w.z.string().optional(),inputSchema:w.z.any().optional(),serverName:w.z.string(),deferLoading:w.z.boolean().optional()}).meta({title:"LocalMCPTools"}),fie=w.z.union([w.z.templateLiteral(["repair-",w.z.string()]),w.z.literal("user-normal"),w.z.literal("user-figma"),w.z.literal("user-pdf"),w.z.literal("user-image"),w.z.literal("setup-agent"),w.z.templateLiteral(["background-",w.z.string()]),w.z.templateLiteral(["indexing-",w.z.string()])]).meta({title:"CodeGenCategory"}),j9e=w.z.enum(["editCode","modifyMcpServers","modifyProjectSettings","createBranches","sendPullRequests","view"]).meta({title:"UserSourcePermission"}),r0={role:w.z.enum(["user","agent"]),principals:w.z.array(w.z.string()).optional().meta({description:"teams/roles like ['developer', 'admin']"}),jobs:w.z.array(w.z.string()).optional().meta({description:"job titles like ['designer', 'developer'] - used for role-aware communication instead of principals when available"}),permissions:w.z.array(j9e).optional(),channelId:w.z.string().optional()},C4t=w.z.object(r0).meta({title:"UserSourceBase"}),Y9e=w.z.object({...r0,source:w.z.enum(["slack","telegram","whatsapp","teams","jira","linear","github","gitlab","azure","bitbucket"]),userId:w.z.string().optional().meta({description:"User ID from the external platform (Slack user ID, GitHub user id, etc.)"}),userName:w.z.string().optional(),userEmail:w.z.string().optional(),photoURL:w.z.string().optional(),builderUserId:w.z.string().optional().meta({description:"Resolved Builder user ID for attribution/credits"}),link:w.z.string().optional().meta({description:"Optional link (e.g. comment/PR URL) for git provider sources"})}).meta({title:"UserSourceOther"}),q9e=w.z.object({...r0,source:w.z.literal("builder.io"),userId:w.z.string().optional(),userName:w.z.string().optional(),userEmail:w.z.string().optional(),photoURL:w.z.string().optional()}).meta({title:"UserSourceBuilder"}),$9e=w.z.object({...r0,source:w.z.literal("agent"),userId:w.z.string().optional(),userName:w.z.string().optional(),userEmail:w.z.string().optional()}).meta({title:"UserSourceAgent"}),hie=w.z.discriminatedUnion("source",[Y9e,q9e,$9e]).meta({title:"UserSource"}),V9e=w.z.enum(["read","write","list"]).meta({title:"Permission"}),W9e=w.z.object({action:w.z.enum(["allow","deny"]).meta({description:"whether this rule allows or denies access"}),resource:w.z.string().meta({description:"what \u2014 supports glob patterns like /files/*.txt"}),permissions:w.z.array(V9e).meta({description:"actions this rule applies to"}),description:w.z.string().optional().meta({description:"custom message, in deny case, this is the error message. This will override denyDescription on AclPolicy if defined."}),principals:w.z.array(w.z.string()).optional().meta({description:"array of teams/roles this rule applies to (e.g., ['developer', 'admin'])"})}).meta({title:"AclEntry"}),z9e=w.z.object({secrets:w.z.array(w.z.string()).optional(),entries:w.z.array(W9e).optional(),denyDescription:w.z.string().optional().meta({description:"Default message to use when a resource is denied access"})}).meta({title:"AclPolicy"}),mie=w.z.object({text:w.z.string(),tag:w.z.string().optional(),ephemeral:w.z.boolean().optional()}).meta({title:"SystemReminderObj"}),X9e=w.z.union([w.z.string(),mie]).meta({title:"SystemReminder"}),I4t=w.z.looseObject({position:K9e,eventName:w.z.string().optional(),sessionId:w.z.string(),codeGenMode:U9e.optional(),sessionMode:pie.optional(),url:w.z.string().optional(),diffActions:w.z.boolean().optional(),planningPrompt:w.z.boolean().optional(),customInstructions:w.z.array(iYe).optional(),customAgents:w.z.array(sYe).optional(),systemPromptOverride:w.z.union([w.z.string(),w.z.array(w.z.string())]).optional(),userPrompt:w.z.string().optional(),systemReminders:w.z.array(X9e).optional(),ephemeralUserPrompt:w.z.string().optional(),uiContextPrompt:w.z.string().optional(),displayUserPrompt:w.z.string().optional(),files:w.z.array(nYe).optional(),rerankFiles:w.z.number().optional(),toolResults:w.z.array(sie).optional(),attachments:w.z.array(DL).optional(),beforeCommit:rYe.optional(),workingDirectory:w.z.string().optional(),includeRelevantMemories:w.z.boolean().optional(),encryptKey:w.z.string().optional(),modelOverride:w.z.string().optional(),errorIfHadCompaction:w.z.boolean().optional(),softContextWindow:w.z.number().optional(),promptVersion:w.z.enum(["v1","v2","v3"]).optional(),reasoning:uie.optional(),redactUserMessages:w.z.boolean().optional(),redactLLMMessages:w.z.boolean().optional(),environmentVariables:w.z.array(Bf).optional(),skipCommandSecurity:w.z.boolean().optional(),builderContent:w.z.custom().optional(),framework:aYe.optional(),styleLibrary:AYe.optional(),typescript:w.z.boolean().optional(),userContext:aie.optional(),aclPolicy:z9e.optional(),repoIndexingConfig:H9e.optional(),recommendedRoot:w.z.string().optional(),enabledTools:w.z.array(_9e).optional(),enabledMCPs:w.z.array(w.z.string()).optional(),skippedMCPs:w.z.array(w.z.string()).optional().meta({description:"Per-message denylist of MCP server ids to skip. Skipped servers are not mounted or connected for this message and will not trigger an `mcp-auth-required` event. Tokens and org-level enabled state are untouched; this is purely message-scoped."}),skipFileDiff:w.z.boolean().optional(),interruptActiveTask:w.z.boolean().optional().meta({description:"When true, the agent should interrupt its current task to handle this message immediately, rather than finishing the current task first."}),localMCPTools:w.z.array(J9e).optional().meta({description:"Local MCP tool definitions from stdio servers (CLI-side only). These tools will be executed on the client side and passed through from the server."}),isLocal:w.z.boolean().optional().meta({description:"Indicates whether the codegen is running in local mode (local filesystem) vs cloud/container mode. Used to determine git auto-commit behavior."}),maxAgentLoops:w.z.number().optional(),maxAgentTiming:w.z.number().optional(),maxTokens:w.z.number().optional().meta({description:"Maximum output tokens allowed in the LLM response. This will set the maximum token output for the LLM."}),maxPages:w.z.number().optional(),autoContinue:w.z.number().optional(),isManualContinue:w.z.boolean().optional(),llmSuggestions:w.z.boolean().optional(),conclusionText:w.z.boolean().optional(),mcpServers:w.z.boolean().optional(),pingEvents:w.z.boolean().optional(),forceCompact:w.z.boolean().optional(),hadPagination:w.z.boolean().optional(),category:fie.optional(),metadata:w.z.record(w.z.string(),w.z.any()).optional(),searchResponse:w.z.any().nullish(),prettierConfig:w.z.custom().optional(),role:w.z.enum(["user","agent"]).optional(),user:hie.optional(),projectId:w.z.string().optional(),branchName:w.z.string().optional(),repoHash:w.z.string().optional(),repoBranch:w.z.string().optional(),parentSessionId:w.z.string().optional().meta({description:"Immediate parent session id when this completion runs inside a sub-agent."}),mainSessionId:w.z.string().optional().meta({description:"Root session of the agent tree. Sub-agents inherit this from their parent so cost rolls up to the root in one hop, regardless of nesting depth."}),prevId:w.z.string().optional(),vcpId:w.z.string().optional(),repair:w.z.boolean().optional(),systemReminderPrompt:w.z.string().optional()}).meta({title:"CodeGenInputOptions"}),Z9e=w.z.enum(["force-push","merge-push","ff-push","safe-push","none"]).meta({title:"AutoPushMode"}),e6e=w.z.object({remoteBranches:w.z.enum(["both","main","ai"]).optional(),fastForward:w.z.enum(["never","required","auto"]).optional(),canPush:w.z.boolean().optional(),uncommittedChanges:w.z.enum(["stash","commit","fail"]).optional(),requestRefresh:w.z.boolean().optional(),allowUnrelatedHistory:w.z.boolean().optional(),resetToBase:w.z.boolean().optional().meta({description:"When true, reset the AI branch hard to the remote feature/base branch instead of merging. This gives a clean slate that exactly matches the checked-out feature branch on remote, avoiding any merge-style conflicts or divergence. Fails clearly if the feature/base branch cannot be determined or is absent from the remote."}),updateLastCommits:w.z.boolean().optional().meta({description:"Whether to update the internal 'last AI commits' baseline after the sync completes. Defaults to `true` for backwards compatibility. Set to `false` when the caller wants `getChangesReport()` to keep diffing from the pre-sync baseline (e.g. so a downstream prompt can see exactly what changed since the last reset/sync)"})}).meta({title:"SyncChangesFromRemote"}),E4t=w.z.object({idempotencyKey:w.z.string().optional(),user:hie.optional(),userPrompt:w.z.string(),uiContextPrompt:w.z.string().optional(),ephemeralUserPrompt:w.z.string().optional(),displayPrompt:w.z.string().optional(),files:w.z.array(w.z.string()).optional(),systemReminders:w.z.array(mie).optional(),includeBaseFiles:w.z.boolean().optional(),attachments:w.z.array(DL).optional(),logsCheckpoint:w.z.boolean().optional(),dropAbortedPrompt:w.z.boolean().optional(),runValidateCommand:w.z.boolean().optional(),modelOverride:w.z.string().optional(),agentModelOverrides:oYe.optional(),softContextWindow:w.z.number().optional(),maxCompletions:w.z.number().optional(),isManualContinue:w.z.boolean().optional(),includeRelevantMemories:w.z.boolean().optional(),category:fie.optional(),metadata:w.z.record(w.z.string(),w.z.any()).optional(),autoPush:Z9e.optional(),syncChanges:e6e.optional(),enabledMCPs:w.z.array(w.z.string()).optional(),skippedMCPs:w.z.array(w.z.string()).optional().meta({description:"Per-message denylist of MCP server names to skip. Skipped servers are not mounted or connected for this message and will not trigger an `mcp-auth-required` event. Tokens and org-level enabled state are untouched; this is purely message-scoped."}),sessionMode:pie.optional(),queue:w.z.boolean().optional(),agentType:w.z.string().optional().meta({description:"Custom agent type to use for this message"}),enableQAReviewTool:w.z.boolean().optional().meta({description:"Enable AddQAReview tool for QA PR review branches"}),reasoning:uie.optional().meta({description:"Per-message reasoning effort override"}),repair:w.z.boolean().optional(),forceCompact:w.z.boolean().optional().meta({description:"Force compaction of the conversation before generating the next completion"})}).meta({title:"GenerateUserMessage"}),B4t=w.z.object({diff:w.z.string().meta({description:"Git diff from previous commit"}),userMessages:w.z.array(w.z.string()).meta({description:"User messages sent during AI work"}),recentCommits:w.z.array(w.z.string()).meta({description:"Last 10 commits from main branch for style reference"}),longCommit:w.z.boolean().optional().meta({description:"Whether to generate a long commit message"}),projectId:w.z.string().optional().meta({description:"Project ID for fetching project-specific commit instructions"})}).meta({title:"CommitMessageRequest"}),y4t=w.z.object({message:w.z.string().meta({description:"Full commit message"}),title:w.z.string().meta({description:"First line (50-72 chars) - the commit title"}),body:w.z.string().optional().meta({description:"Optional extended description"})}).meta({title:"CommitMessageResponse"}),Q4t=w.z.object({sessionId:w.z.string(),toolId:w.z.string(),approved:w.z.boolean(),reason:w.z.string().optional()}).meta({title:"ModelPermissionResponseRequest"})});var Iie=L(()=>{"use strict";h()});var Eie=L(()=>{"use strict";h()});function FL(t){try{let e=t.toLowerCase();return e.includes("github.com")?"github":e.includes("gitlab.com")?"gitlab":e.includes("bitbucket.org")?"bitbucket":e.includes("dev.azure.com")?"azure":e.includes("github")?"selfHostedGithub":"unknown"}catch{return"unknown"}}function Bie(t){if(t.type!=="ai")return null;let e=t.event;if(e.type==="tool_result"){let r=e.result;if(r.tool_name==="ExitPlanMode"){let n,i;if(typeof r.tool_input=="string")try{let s=JSON.parse(r.tool_input);s&&typeof s.plan=="string"&&!n&&(n=s.plan),s&&typeof s.sessionMode=="string"&&!i&&(i=s.sessionMode)}catch{}if(typeof r.content=="string")try{let s=JSON.parse(r.content);s&&typeof s.plan=="string"&&!n&&(n=s.plan),s&&typeof s.sessionMode=="string"&&!i&&(i=s.sessionMode)}catch{}if(r.structured_result&&typeof r.structured_result.plan=="string"&&!n&&(n=r.structured_result.plan),r.structured_result&&typeof r.structured_result.sessionMode=="string"&&!i&&(i=r.structured_result.sessionMode),n)return{plan:n,sessionMode:i}}}return null}var Ze,kL,yf,t6e,gI,k4t,R4t,yie,r6e,T4t,n6e,N4t,M4t,P4t,L4t,Qie=L(()=>{"use strict";h();Ze=require("zod");Zw();kL=["steve8708/mui-vite","steve8708/carbon-vite","steve8708/vite-react-shopify-polaris","steve8708/cloudscape-demos","BuilderIO/fusion-angular-tailwind-starter","BuilderIO/fusion-svelte-tailwind-starter","BuilderIO/fusion-vue-tailwind-starter","BuilderIO/org-agent-starter"],yf="BuilderIO/fusion-starter",t6e="BuilderIO/dsi-starter",gI=[...kL,yf,t6e],k4t=gI.map(t=>`https://github.com/${t}`),R4t=720*60*60*1e3;yie=Ze.z.enum(["queued","building","uploading","deploying","live","failed","canceled"]),r6e=Ze.z.object({buildCommand:Ze.z.string().optional(),nodeVersion:Ze.z.string().optional()}),T4t=Ze.z.object({enabled:Ze.z.boolean().optional().meta({description:"Whether hosting is enabled for this project or not."}),slug:Ze.z.string().optional().meta({description:'e.g. "my-cool-app" \u2014 set once on first publish, immutable'}),netlifySiteId:Ze.z.string().optional().meta({description:"Netlify site ID for management API calls; cleared on unpublish, set again on re-publish"}),netlifySiteName:Ze.z.string().optional().meta({description:"<name> in <name>.netlify.app \u2014 the upstream the HTTPRoute filter rewrites Host to; cleared on unpublish"}),url:Ze.z.string().optional().meta({description:'"https://my-cool-app.builder.cloud" \u2014 derived from slug'}),buildConfig:r6e.optional(),environment:Ze.z.object({build:Ze.z.array(Bf).optional().meta({description:"Env vars available to the build itself"}),prod:Ze.z.array(Bf).optional().meta({description:"Env vars for the production deploy served via Netlify"})}).optional(),lastDeployId:Ze.z.string().optional(),lastDeployAt:Ze.z.number().optional(),lastDeployStatus:yie.optional(),customDomain:Ze.z.string().optional(),customDomainVerified:Ze.z.boolean().optional(),autoDeploy:Ze.z.boolean().optional().meta({description:"auto-deploy on push/merge"})}),n6e=Ze.z.object({id:Ze.z.string(),projectId:Ze.z.string(),ownerId:Ze.z.string(),checkoutBranch:Ze.z.string().optional().meta({description:'The git ref that was deployed (always "main" in v0/v1; the feature branch for row 2 in v2). This is the value passed as `checkoutBranch` when the deploy pod was created.'}),deployBranchId:Ze.z.string().optional().meta({description:'Fusion branch id of the ephemeral hidden deploy branch (`type: "deploy"`) that ran the build.'}),devBranchId:Ze.z.string().optional().meta({description:"Fusion dev branch's id (unset if we are deploying project default branch)"}),status:yie,netlifyDeployId:Ze.z.string().optional(),url:Ze.z.string().optional(),error:Ze.z.string().optional().meta({description:"Single human-readable line on failure; raw build logs not surfaced in v0"}),createdAt:Ze.z.number(),completedAt:Ze.z.number().optional(),triggeredBy:Ze.z.string().meta({description:'user ID for manual publish, or "auto-deploy" (v1)'})}),N4t=Ze.z.object({projectId:Ze.z.string(),ownerId:Ze.z.string(),createdAt:Ze.z.number(),createdBy:Ze.z.string().meta({description:"user ID of the user who first clicked Publish on the project"})}),M4t=Ze.z.object({ownerId:Ze.z.string(),holderId:Ze.z.string().meta({description:"unique per acquisition (the fencing token); == deployId for a deploy holder"}),holderKind:Ze.z.enum(["deploy","unpublish"]),deployId:Ze.z.string().optional().meta({description:'set when holderKind === "deploy"'}),acquiredAt:Ze.z.number().meta({description:"unix time (ms)"}),expiresAt:Ze.z.number().meta({description:"acquiredAt + 15min (same ceiling as the deploy lazy-timeout)"})}),P4t=n6e.pick({id:!0,status:!0,url:!0,createdAt:!0,completedAt:!0,error:!0}).meta({title:"DeployListItem"}),L4t=Ze.z.object({files:Ze.z.record(Ze.z.string(),Ze.z.string()).meta({description:"static file path \u2192 sha1 hash"}),functions:Ze.z.record(Ze.z.string(),Ze.z.string()).meta({description:"serverless function name \u2192 sha256 hash"})})});var RL,Qf,Ku,Ug,n0,Die=L(()=>{"use strict";h();RL=t=>t.type==="agent",Qf=t=>t.type==="icon",Ku=t=>t.type==="token",Ug=t=>t.type==="component",n0=t=>t.type==="installation"});var wie=L(()=>{"use strict";h()});var bie=L(()=>{"use strict";h()});var vie=L(()=>{"use strict";h()});function i6e(t){let e=t.split("/");if(e.length<2)throw new Error(`Invalid channelId format: ${t}`);let[r,n,...i]=e;return{platform:r,type:n,ids:i}}function Sie(t){let e;try{e=i6e(t)}catch{return null}let{platform:r,type:n,ids:i}=e;return r==="slack"?s6e(n,i):null}function s6e(t,e){if(t==="thread"){let[r,n,i]=e;return!r||!n||!i?null:`https://slack.com/app_redirect?team=${r}&channel=${n}&message_ts=${i}`}if(t==="channel"){let[r,n]=e;return!r||!n?null:`https://slack.com/app_redirect?team=${r}&channel=${n}`}if(t==="dm"){let[r,n]=e;return!r||!n?null:`https://slack.com/app_redirect?team=${r}&channel=${n}`}return null}function TL(t){let e=`<worker_report>
|
|
1500
|
+
${t}`)}let s=BL(n);try{return zw.default.writeFileSync(s,i,{mode:493}),s}catch(o){throw new Error(`Failed to create temporary script: ${o}`)}},BL=t=>{let e=Mje(),r=Date.now(),n=Math.random().toString(36).substring(2,8);return EL.default.join(e,`builder_temp_${r}_${n}${t}`)},yL=(t,e,r=!0)=>{if(Pje(t)){let n=Lje(t,e);return e.includes("cmd")||e.includes("CMD")?["/c",n]:e.includes("powershell")||e.includes("PowerShell")||e.includes("pwsh")?["-ExecutionPolicy","Bypass","-File",n]:e.includes("bash")||e.includes("zsh")?r?["-l",n]:[n]:[n]}return e.includes("cmd")||e.includes("CMD")?["/c",t.replace(/2>\/dev\/null \|\| true/g,"2>nul || cd .")]:e.includes("powershell")||e.includes("PowerShell")||e.includes("pwsh")?["-Command",t.replace(/2>\/dev\/null \|\| true/g,"2>$null; if ($?) {}")]:e.includes("zsh")?r?["-l","-c",`source ~/.zshrc 2>/dev/null || true; ${t}`]:["-c",t]:e.includes("bash")?r?["-l","-c",t]:["-c",t]:["-c",t]};uI=t=>"type"in t});var Ef,_je,W4t,zne=L(()=>{"use strict";h();Ef=require("zod"),_je=Ef.z.object({kind:Ef.z.literal("postgres"),migrations:Ef.z.literal("drizzle"),schemaDir:Ef.z.string().default("drizzle")}),W4t=Ef.z.object({database:_je.optional()})});var Xne=L(()=>{"use strict";h()});var Zne,eie,tie,rie,nie,iie=L(()=>{"use strict";h();Zne={eventName:"client.devtools.session.started",version:"1"},eie={eventName:"client.devtools.session.idle",version:"1"},tie={eventName:"client.devtools.tool.call-request",version:"1"},rie={eventName:"client.devtools.tool.call",version:"1"},nie={eventName:"client.devtools.tool.result",version:"1"}});function QL(t){return typeof t=="string"?t:t.map(e=>e.type==="text"?e.text:"").join("")}var ye,Uje,Gje,Oje,Kje,Hje,DL,Jje,jje,Yje,qje,$je,Vje,Wje,zje,Xje,Zje,sie,wL=L(()=>{"use strict";h();ye=require("zod");Uje=ye.z.object({type:ye.z.literal("url"),value:ye.z.string()}).meta({title:"URL"}),Gje=ye.z.object({type:ye.z.literal("upload"),contentType:ye.z.enum(["image/webp","image/png","image/jpeg","image/gif","application/pdf","application/json","text/plain"]),name:ye.z.string(),dataUrl:ye.z.string(),text:ye.z.string().optional(),size:ye.z.number(),id:ye.z.string(),originalUrl:ye.z.string().optional(),ephemeral:ye.z.boolean().optional()}).meta({title:"FileUpload"}),Oje=ye.z.object({type:ye.z.literal("template"),name:ye.z.string(),id:ye.z.number()}).meta({title:"Template"}),Kje=ye.z.object({type:ye.z.literal("builder"),html:ye.z.string()}).meta({title:"BuilderContentAttachment"}),Hje=ye.z.object({type:ye.z.literal("figma"),html:ye.z.string()}).meta({title:"FigmaContentAttachment"}),DL=ye.z.discriminatedUnion("type",[Gje,Oje,Uje,Kje,Hje]).meta({title:"Attachment"}),Jje=ye.z.object({cited_text:ye.z.string(),document_index:ye.z.number(),document_title:ye.z.string().nullable(),end_char_index:ye.z.number(),start_char_index:ye.z.number(),type:ye.z.literal("char_location")}).meta({title:"CitationCharLocationParam"}),jje=ye.z.object({cited_text:ye.z.string(),document_index:ye.z.number(),document_title:ye.z.string().nullable(),end_block_index:ye.z.number(),start_block_index:ye.z.number(),type:ye.z.literal("content_block_location")}).meta({title:"CitationContentBlockLocationParam"}),Yje=ye.z.object({cited_text:ye.z.string(),document_index:ye.z.number(),document_title:ye.z.string().nullable(),end_page_number:ye.z.number(),start_page_number:ye.z.number(),type:ye.z.literal("page_location")}).meta({title:"CitationPageLocationParam"}),qje=ye.z.object({cited_text:ye.z.string(),encrypted_index:ye.z.string(),title:ye.z.string().nullable(),type:ye.z.literal("web_search_result_location"),url:ye.z.string()}).meta({title:"CitationWebSearchResultLocationParam"}),$je=ye.z.discriminatedUnion("type",[Jje,Yje,jje,qje]).meta({title:"TextCitationParam"}),Vje=ye.z.object({type:ye.z.literal("base64"),media_type:ye.z.enum(["image/webp","image/png","image/jpeg","image/gif"]),data:ye.z.string(),original_url:ye.z.string().optional()}).meta({title:"ImageBase64Source"}),Wje=ye.z.object({type:ye.z.literal("url"),url:ye.z.string()}).meta({title:"ImageUrlSource"}),zje=ye.z.object({type:ye.z.literal("text"),text:ye.z.string(),cache:ye.z.boolean().optional(),citations:ye.z.array($je).nullish(),ephemeral:ye.z.boolean().optional(),thoughtSignature:ye.z.string().optional(),tag:ye.z.string().optional()}).meta({title:"ContentMessageItemText"}),Xje=ye.z.object({type:ye.z.literal("image"),source:ye.z.discriminatedUnion("type",[Vje,Wje]),cache:ye.z.boolean().optional(),ephemeral:ye.z.boolean().optional()}).meta({title:"ContentMessageItemImage"}),Zje=ye.z.object({type:ye.z.literal("resource"),resource:ye.z.object({uri:ye.z.string(),mimeType:ye.z.string().optional(),text:ye.z.string().optional(),blob:ye.z.string().optional()})}).meta({title:"ContentMessageItemResource"}),sie=ye.z.object({type:ye.z.literal("tool_result"),tool_use_id:ye.z.string(),tool_name:ye.z.string().optional(),tool_input:ye.z.string().optional(),title:ye.z.string().optional(),content:ye.z.union([ye.z.string(),ye.z.array(ye.z.discriminatedUnion("type",[zje,Xje,Zje]))]),is_error:ye.z.boolean().optional(),cache:ye.z.boolean().optional(),ephemeral:ye.z.boolean().optional(),structured_result:ye.z.record(ye.z.string(),ye.z.any()).optional()}).meta({title:"ContentMessageItemToolResult"})});var oie=L(()=>{"use strict";h()});var Yn,aie,bL=L(()=>{"use strict";h();Yn=require("zod"),aie=Yn.z.object({client:Yn.z.string(),clientVersion:Yn.z.string(),nodeVersion:Yn.z.string(),systemPlatform:Yn.z.string(),frameworks:Yn.z.array(Yn.z.string()),systemEOL:Yn.z.string(),systemArch:Yn.z.string(),systemShell:Yn.z.string().optional(),inGitRepo:Yn.z.boolean().optional()}).catchall(Yn.z.union([Yn.z.string(),Yn.z.array(Yn.z.string()),Yn.z.boolean(),Yn.z.undefined()])).meta({title:"UserContext"})});var qn,Bf,eYe,tYe,Aie,Zw=L(()=>{"use strict";h();qn=require("zod"),Bf=qn.z.object({key:qn.z.string(),value:qn.z.string(),isSecret:qn.z.boolean(),placeholder:qn.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:qn.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"EnvironmentVariable"}),eYe=qn.z.object({key:qn.z.string(),type:qn.z.literal("mise"),tool:qn.z.string(),version:qn.z.string().optional()}).meta({title:"SetupMiseDependency"}),tYe=qn.z.object({key:qn.z.string(),type:qn.z.literal("script"),name:qn.z.string(),script:qn.z.string()}).meta({title:"SetupScriptDependency"}),Aie=qn.z.discriminatedUnion("type",[eYe,tYe]).meta({title:"SetupDependency"})});function die(t){return t==="interrupt"||t==="interrupt-clear"||t==="interrupt-replace"}function xL(t){return t===void 0?{...G9e}:t==="next-turn"?{schedule:"next-turn",coalesce:"merge"}:t==="until-idle"?{schedule:"until-idle",coalesce:"preserve-order"}:{schedule:t.schedule,coalesce:t.coalesce}}var w,rYe,pHt,nYe,iYe,uie,sYe,oYe,aYe,AYe,dHt,t0,cYe,uYe,lYe,gYe,pYe,dYe,fHt,fYe,hYe,mYe,CYe,IYe,EYe,BYe,yYe,QYe,DYe,wYe,bYe,vYe,SYe,xYe,vL,FYe,kYe,RYe,TYe,NYe,MYe,PYe,LYe,_Ye,UYe,GYe,OYe,KYe,HYe,JYe,jYe,YYe,qYe,$Ye,VYe,WYe,zYe,XYe,ZYe,e9e,t9e,r9e,n9e,e0,i9e,s9e,o9e,a9e,A9e,c9e,lie,gie,hHt,mHt,u9e,l9e,g9e,p9e,d9e,f9e,h9e,m9e,C9e,I9e,E9e,B9e,y9e,SL,Q9e,D9e,w9e,b9e,v9e,S9e,x9e,F9e,k9e,R9e,T9e,N9e,M9e,P9e,L9e,_9e,pie,U9e,G9e,O9e,cie,K9e,H9e,J9e,fie,j9e,r0,CHt,Y9e,q9e,$9e,hie,V9e,W9e,z9e,mie,X9e,IHt,Z9e,e6e,EHt,BHt,yHt,QHt,Cie=L(()=>{"use strict";h();w=require("zod");wL();bL();Zw();rYe=w.z.string().meta({title:"GitSnapshot",description:"Multi-repo git snapshot. Format: 'folder:hash,folder:hash' with URL-encoded folder names. Legacy single-hash form ('abc123') is also accepted. Empty string means no commits."}),pHt=w.z.enum(["named","default"]).meta({title:"ImportType"}),nYe=w.z.object({filePath:w.z.string(),content:w.z.string().optional(),importance:w.z.number().optional(),dropReason:w.z.string().optional(),wasIncluded:w.z.boolean().optional(),virtual:w.z.boolean().optional()}).meta({title:"ProjectFile"}),iYe=w.z.object({id:w.z.string(),name:w.z.string(),content:w.z.string(),type:w.z.enum(["always","agent-mode"]).optional(),filePath:w.z.string().optional(),glob:w.z.string().optional(),description:w.z.string().optional(),allowedTools:w.z.array(w.z.string()).optional(),hideUI:w.z.boolean().optional(),isSkill:w.z.boolean().optional(),disableModelInvocation:w.z.boolean().optional(),userInvocable:w.z.boolean().optional(),scope:w.z.enum(["project","user","plugin"]).optional(),pluginName:w.z.string().optional()}).meta({title:"CustomInstruction"}),uie=w.z.enum(["auto","none","minimal","low","medium","high","xhigh","max"]).meta({title:"ReasoningEffort"}),sYe=w.z.object({name:w.z.string(),description:w.z.string().optional()}).meta({title:"CustomAgentInfo"}),oYe=w.z.record(w.z.string(),w.z.union([w.z.string(),w.z.array(w.z.string())])).meta({title:"AgentModelOverrides"}),aYe=w.z.enum(["react","html","mitosis","react-native","angular","vue","svelte","qwik","solid","marko","swiftui","jetpack-compose","flutter"]).meta({title:"CodeGenFramework"}),AYe=w.z.enum(["tailwind","tailwind-precise","emotion","styled-components","styled-jsx","react-native"]).meta({title:"CodeGenStyleLibrary"}),dHt=w.z.enum(["max_tokens","stop_sequence","tool_use","end_turn","content_filter","error","aborted","pause_turn","refusal","compaction","model_context_window_exceeded"]).nullable().meta({title:"CompletionStopReason"}),t0="The path of the file. Accepts a path relative to the project working directory, an absolute path (`/Users/.../skill.md`), or a tilde path (`~/.builder/skills/.../SKILL.md`). User-level Builder state under `~/.builder/**` is allowed by default for plugin operations; other absolute paths require an explicit ACL policy.",cYe=w.z.object({file_path:w.z.string().meta({description:t0}),offset:w.z.number().nullish().meta({description:"The line number to start reading from."}),limit:w.z.number().nullish().meta({description:"The number of lines to read."})}).meta({title:"ReadToolInput"}),uYe=w.z.object({pattern:w.z.string().meta({description:"The pattern to search for"})}).meta({title:"GlobSearchToolInput"}),lYe=w.z.object({query:w.z.string().meta({description:'A string literal or a JavaScript-flavored regex to search for in all project files. Only escape special characters such as {} and () in string literals to avoid confusion with regex patterns (e.g. "import \\{ foo \\}"). Avoid over-escaping as that will cause errors. Do NOT use inline regex flags like (?i) or (?s) \u2014 they are not supported. The search is case-insensitive by default; use the case_sensitive parameter to control this.'}),include_glob:w.z.string().nullish().meta({description:"An optional single glob pattern to include only specific files (e.g. '**/*.(ts|tsx)' for all TypeScript files)"}),exclude_glob:w.z.string().nullish().meta({description:"Optional glob pattern to exclude specific files or directories"}),case_sensitive:w.z.boolean().nullish().meta({description:"Whether the search should be case-sensitive. Defaults to false (case-insensitive). Set to true for case-sensitive search."})}).meta({title:"GrepSearchToolInput"}),gYe=w.z.object({skill:w.z.string().meta({description:"The name of a skill from the available-skills list. Do not guess names."}),args:w.z.string().nullish().meta({description:"Optional invocation arguments; forwarded with the skill body in the tool result."})}).meta({title:"SkillToolInput"}),pYe=w.z.object({name:w.z.string().meta({description:"The name of the rule to get"})}).meta({title:"GetRuleToolInput"}),dYe=w.z.object({url:w.z.string().meta({description:"The URL of the website to analyze and mimic the style of, for example 'https://airbnb.com' or 'https://instagram.com'"})}).meta({title:"GetStyleInspirationToolInput"}),fHt=w.z.object({}).meta({title:"GetBuildOutputToolInput"}),fYe=w.z.object({restart:w.z.boolean().nullish().meta({description:"Whether to restart the dev server, it will also return the initial logs coming from the dev server. This tool can be very slow, only use as last resort, most of the times file changes do not require a restart."}),set_dev_command:w.z.string().nullish().meta({description:"Use to set the command of the dev server, for example 'npm run dev' or 'cd packages/frontend && yarn dev'. When updating the command, the dev server will be automatically restarted. After changing a command, the proxy port might change, so you need to use the 'set_proxy_port' tool to update the proxy port. Only use if there are explicit issues"}),set_proxy_port:w.z.number().nullish().meta({description:"Used to configure the proxy port of the dev server. For example, if `npm run dev` open a port in 8392, but current proxy server listens 3000, you can use this tool to update the proxy port. Only use if there are explicit issues."}),get_logs:w.z.boolean().nullish().meta({description:"When used standalone, the tool will return logs of the dev server and other status. But don't change or restart anything. It's a read-only operation."}),set_env_variable:w.z.tuple([w.z.string(),w.z.string()]).nullish().meta({description:"Tuple of two strings, the first string is the name of the environment variable, the second string is the value of the environment variable. For example, ['DB_API_KEY', '___PRIVATE_KEY___']"}),set_and_run_setup_command:w.z.string().nullish().meta({description:"Use to set the command of the setup command, for example 'npm install' or 'yarn'. Only use if there are explicit issues."})}).meta({title:"DevServerControlInput"}),hYe=w.z.object({}).meta({title:"DevServerLogsInput"}),mYe=w.z.object({}).meta({title:"GenerateDesignSystemAgentMdInput",description:"Generates and writes `.builder/output/AGENTS.md` from the token and component CSS files produced during DSI approximation indexing. Reads `.builder/sources/figma/manifest.json` for the design system name, `.builder/output/_index/tokens-report.json` for token categories, and globs `.builder/output/tokens/components/*.css` for component slugs. Call this as the final step after all CSS files have been written."}),CYe=w.z.object({}).meta({title:"DevServerRestartInput",description:"Restarts the dev server with current configuration."}),IYe=w.z.object({description:w.z.string().meta({description:"A human readable description of the command to run, for example 'install dependencies' or 'run tests'. This description will be used to explain the command to the user."}),command:w.z.string().meta({description:"The shell command to run, for example 'npm install --save uuid', 'yarn test' or 'npm run build'..."}),timeout:w.z.number().nullish().meta({description:"Optional timeout in milliseconds (max/default 600000)"})}).meta({title:"BashToolInput"}),EYe=w.z.object({command:w.z.string().nullish().meta({description:"The PowerShell command to run, for example 'npm install' or 'yarn test'"}),timeout:w.z.number().nullish().meta({description:"The timeout in milliseconds for the command to run. Choose an appropriate timeout based on the command"}),description:w.z.string().nullish().meta({description:"A human readable description of the command to run, for example 'install dependencies' or 'run tests'. This description will be used to explain the command to the user."})}).meta({title:"PowerShellToolInput"}),BYe=w.z.object({query:w.z.string().meta({description:"The question to search on the internet, be specific and concise."})}).meta({title:"WebSearchToolInput"}),yYe=w.z.object({title:w.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:w.z.string().meta({description:t0}),content:w.z.string().meta({description:"Actual content to write into the file, use an empty string to remove the file"})}).meta({title:"WriteFileInput"}),QYe=w.z.object({title:w.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:w.z.string().meta({description:`${t0} The content of this path must be previously known.`}),old_str:w.z.string().meta({description:"The text to replace"}),new_str:w.z.string().meta({description:"The text to replace it with (must be different from old_str)"}),replace_all:w.z.boolean().optional().meta({description:"Replace all occurences of old_str (default false)"}),apply_with_error:w.z.boolean().optional()}).meta({title:"SearchReplaceInput"}),DYe=w.z.object({title:w.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:w.z.string().meta({description:`${t0} The content of this path must be previously known.`}),edits:w.z.array(w.z.object({old_str:w.z.string().meta({description:"The text to replace (must match the file contents exactly, including all whitespace and indentation)"}),new_str:w.z.string().meta({description:"The edited text to replace the old_str"}),replace_all:w.z.boolean().optional().meta({description:"Replace all occurrences of old_str. This parameter is optional and defaults to false."})})).meta({description:"An array of edit operations to perform, where each edit contains: old_str, new_str, replace_all"}),apply_with_error:w.z.boolean().nullish()}).meta({title:"MultiSearchReplaceInput"}),wYe=w.z.object({query:w.z.string(),type:w.z.enum(["image","video"]),orientation:w.z.enum(["landscape","portrait","square"]).nullish(),hex_color:w.z.string().nullish()}).meta({title:"FindMediaToolInput"}),bYe=w.z.object({query:w.z.string().meta({description:"The text prompt describing the media to find or generate"}),type:w.z.enum(["image","video","gen-image"]).meta({description:"The type of media: 'image' to search images, 'video' to search videos, or 'gen-image' to generate an AI image"}),orientation:w.z.enum(["landscape","portrait","square"]).nullish().meta({description:"The orientation/aspect ratio of the media (landscape=wide, portrait=tall, square=1:1)"}),hex_color:w.z.string().nullish().meta({description:"Optionally use to find images with the predominant specified hex color, for example '#000000' or '#FFFFFF'"}),input_image_urls:w.z.array(w.z.string()).nullish().meta({description:'Reference image URLs for AI image generation (only used with type: "gen-image")'})}).meta({title:"MediaToolInput"}),vYe=w.z.object({content:w.z.string().meta({description:"Markdown content of the memory, keep it factual and to the point. Avoid using line numbers, code snippets as they are likely to change."}),when:w.z.string().meta({description:"The semantic search query that will be used to retrieve this memory later. Describe the situation, task, or context when this memory should be surfaced."}),category:w.z.union([w.z.literal("architecture").meta({description:"System structure, layers, and responsibilities"}),w.z.literal("data-and-sync").meta({description:"Data storage, persistence, synchronization, IPC, and state flow"}),w.z.literal("patterns-and-standards").meta({description:"Canonical ways of doing things in this codebase"}),w.z.literal("coupling-and-duplication").meta({description:"Cross-file, cross-surface, or duplicated logic that must stay aligned"}),w.z.literal("ui-and-ux-contracts").meta({description:"User-visible behavior, UX guarantees, and UI rules"}),w.z.literal("concurrency-and-lifecycle").meta({description:"Async behavior, ordering, lifecycle, and race prevention"}),w.z.literal("invariants").meta({description:"Hard rules that must always remain true"}),w.z.literal("security-and-trust").meta({description:"Security, permissions, and trust boundaries"}),w.z.literal("gotchas").meta({description:"Known sharp edges that will break things if ignored"}),w.z.literal("constraints-and-limits").meta({description:"System limits, assumptions, and non-obvious constraints"}),w.z.literal("rationale-and-history").meta({description:"Why something is the way it is (tradeoffs, history, intent)"})]).meta({description:"The general category that this memory fits into"}),glob:w.z.string().optional().meta({description:"Glob pattern for file-based memory retrieval. Use specific paths (e.g., 'src/components/Button.tsx', 'lib/api/**/*.ts') rather than broad patterns (e.g., '*.tsx'). When files matching this glob are read, this memory will be suggested."}),importance:w.z.number().optional(),glob_auto_include:w.z.boolean().optional().meta({description:"Whenever the memory should be included whenever the glob is matched."})}).meta({title:"MemoryToolInput"}),SYe=w.z.object({query:w.z.string(),limit:w.z.number().optional(),minSimilarity:w.z.number().optional()}).meta({title:"SearchMemoriesToolInput"}),xYe=w.z.object({outcome:w.z.enum(["worked","failed","partial","unknown"]).meta({description:"Overall exchange outcome based on user reaction"}),memory_scores:w.z.object({}).catchall(w.z.enum(["worked","failed","partial","unknown"])).meta({description:"Score for each memory used: { memory_id: outcome }"})}).meta({title:"ScoreMemoriesToolInput"}),vL=w.z.object({label:w.z.string(),description:w.z.string()}).meta({title:"LabelOption"}),FYe=w.z.strictObject({label:w.z.string().meta({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:w.z.string().meta({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}),preview:w.z.string().nullish().meta({description:"Optional preview content rendered when this option is focused. Use for mockups, code snippets, or visual comparisons that help users compare options. See the tool description for the expected content format."})}).meta({title:"AskUserQuestionOption"}),kYe=w.z.strictObject({question:w.z.string().meta({description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:w.z.string().meta({description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:w.z.array(FYe).min(2).max(4).meta({description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically."}),multiSelect:w.z.boolean().optional().meta({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}).meta({title:"AskUserQuestion"}),RYe=w.z.strictObject({questions:w.z.array(kYe).min(1,"Must have at least 1 question").max(4).meta({description:"Questions to ask the user (1-4 questions)"})}).meta({title:"AskUserQuestionToolInput"}),TYe=w.z.object({description:w.z.string().meta({description:"A short (3-5 word) description of the task"}),prompt:w.z.string().meta({description:"The task for the agent to perform"}),subagent_type:w.z.string().optional().meta({description:"The type of specialized agent to use for this task"}),resume:w.z.string().optional().meta({description:"Optional agent ID to resume from"}),origin_channel_id:w.z.string().optional().meta({description:"The original user's channel_id that triggered this work. When provided, it will be included in the worker report so you can route the response back to the correct channel. Always pass this when spawning agents on behalf of a user request."}),attachmentUrls:w.z.array(w.z.string()).optional().meta({description:"URLs of images or files to attach to the agent's context. Useful for providing visual context like screenshots, designs, or reference images."})}).meta({title:"AgentToolInput"}),NYe=w.z.object({checkpoint_id:w.z.string().meta({description:"The checkpoint ID to revert back to. All changes from this checkpoint to HEAD will be reverted."})}).meta({title:"RevertToolInput"}),MYe=w.z.object({}).meta({title:"TodoReadToolInput"}),PYe=w.z.object({}).meta({title:"RunningAgentsToolInput"}),LYe=w.z.object({mode:w.z.enum(["replace","patch"]).meta({description:"Determine how the new todos update the current list: 'patch' means existing items will remain and only the provided items will be updated. The same 'id' must be provided for items you want to update. 'replace' means all existing items will be replaced with the new array of todos."}),todos:w.z.array(w.z.object({content:w.z.string().meta({description:"The imperative form describing what needs to be done"}),status:w.z.enum(["pending","in_progress","completed"]),id:w.z.string()}))}).meta({title:"TodoWriteToolInput"}),_Ye=w.z.object({subject:w.z.string().meta({description:"A brief title for the task"}),description:w.z.string().meta({description:"What needs to be done"}),metadata:w.z.looseObject({}).optional()}).meta({title:"TaskCreateToolInput"}),UYe=w.z.object({taskId:w.z.string().meta({description:"The ID of the task to update"}),subject:w.z.string().optional().meta({description:"New subject for the task"}),description:w.z.string().optional().meta({description:"New description for the task"}),status:w.z.enum(["pending","in_progress","completed","deleted"]).optional().meta({description:"New status for the task"}),owner:w.z.string().optional().meta({description:"New owner for the task"}),addBlocks:w.z.array(w.z.string()).optional().meta({description:"Task IDs that this task blocks"}),addBlockedBy:w.z.array(w.z.string()).optional().meta({description:"Task IDs that block this task"}),metadata:w.z.looseObject({}).optional()}).meta({title:"TaskUpdateToolInput"}),GYe=w.z.object({}).meta({title:"TaskListToolInput"}),OYe=w.z.object({filePath:w.z.string().meta({description:"The path of the Mitosis file to edit (e.g., index.lite.tsx)"}),old_str:w.z.string().meta({description:"Content to be replaced, this substring should appear verbatim in the selected file_path"}),new_str:w.z.string().meta({description:"New content to replace the old content with"})}).meta({title:"BuilderEditToolInput"}),KYe=w.z.object({href:w.z.string().optional(),selector:w.z.string().optional(),width:w.z.number().optional(),height:w.z.number().optional()}).meta({title:"GetScreenshotToolInput"}),HYe=w.z.object({href:w.z.string().meta({description:"The URL or relative path to navigate the preview to (e.g., '/about' or 'https://example.com')"})}).meta({title:"NavigatePreviewToolInput"}),JYe=w.z.object({url:w.z.string().meta({description:"The URL to fetch content from"}),prompt:w.z.string().optional().meta({description:"Optional prompt to describe the content you want to extract from the URL. Leave it blank to fetch images."}),include_styles:w.z.boolean().optional().meta({description:"If true, the computed styles of the page will be extracted, as well as a screenshot. Prompt must be provided"})}).meta({title:"WebFetchToolInput"}),jYe=w.z.object({category:w.z.enum(["reusable_knowledge","one_off","bad_quality"]).optional(),gif_id:w.z.string().optional(),timeline_id:w.z.string().optional(),recording_id:w.z.string().optional(),important_files:w.z.array(w.z.object({file_path:w.z.string().meta({description:"The relative path of the file to read"}),relevance:w.z.enum(["high","medium","low"]).optional().meta({description:"The relevance of the file based on the initial user_prompt"}),offset:w.z.number().optional().meta({description:"The offset of the file to read, in lines"}),limit:w.z.number().optional().meta({description:"The limit of the file to read, in lines"})}))}).meta({title:"ExplorationMetadataToolInput"}),YYe=w.z.object({}).meta({title:"EnterPlanModeToolInput"}),qYe=w.z.object({plan:w.z.string().meta({description:"The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise. Do not include follow up questions in the plan."}),handled:w.z.boolean().optional()}).meta({title:"ExitPlanModeToolInput"}),$Ye=w.z.object({uri:w.z.string().meta({description:"The URI of the resource to read, matching a resource template pattern (e.g., 'file:///path/to/file')"}),serverName:w.z.string().optional().meta({description:"Optional name of the MCP server to use. If not provided, will auto-detect based on URI."})}).meta({title:"ReadMcpResourceToolInput"}),VYe=w.z.enum(["navigation","interaction","assertion","error","milestone","code-change","observation","verified"]).meta({title:"TimelineEventCategory"}),WYe=w.z.enum(["succeeded","couldnt_verify","failed","other"]).meta({title:"TestOutcome"}),zYe=w.z.enum(["env_issue","creds_missing","needs_user_input","server_not_ready","feature_not_reachable","timeout","assertion_failed","unexpected_error","not_applicable","escalated"]).meta({title:"TestCaseFailureCategory"}),XYe=w.z.object({title:w.z.string().meta({description:"A descriptive title for this frame (e.g., 'Login page loaded', 'Form submitted successfully')"}),frame:w.z.literal("last-image").meta({description:"The frame source. Use 'last-image' to record the most recent screenshot."}),category:VYe.optional().meta({description:"Category of this frame for timeline organization. Default: 'milestone'"}),description:w.z.string().optional().meta({description:"Optional longer description providing context about what this frame shows."}),pr_highlight:w.z.boolean().optional().meta({description:"Set true to mark this as a 'verified screenshot' worth showing in the PR description \u2014 i.e. visual proof of how the fix/feature behaves. Use sparingly (1\u20133 per session) for the key moments that demonstrate the feature working. The title is used as the caption."})}).meta({title:"RecordFrameToolInput"}),ZYe=w.z.object({outcome:WYe.meta({description:"The structured test outcome"}),summary:w.z.string().meta({description:"A concise 1\u20132 sentence summary explaining the test outcome"}),details:w.z.string().optional().meta({description:"Optional additional context: error messages, steps attempted, etc."}),test_case_id:w.z.string().optional().meta({description:"Links to a test case ID (e.g., 'TC-01'). If present, this is a per-case report. If absent, this is the session-level summary."}),evidence_frame_count:w.z.number().optional().meta({description:"Number of RecordFrame calls made for this test case. Should be >= 1 for per-case reports."}),failure_category:zYe.optional().meta({description:"Structured failure reason. Required when outcome is failed or couldnt_verify."}),failure_detail:w.z.string().optional().meta({description:"Human-readable failure explanation. E.g., 'Login page returned 403 \u2014 test account may have been disabled'"}),console_errors:w.z.string().optional(),network_failures:w.z.string().optional(),steps_attempted:w.z.string().optional(),urls_tested:w.z.array(w.z.string()).optional()}).meta({title:"ReportTestOutcomeToolInput"}),e9e=w.z.object({projectOverview:w.z.object({framework:w.z.string().nullable(),packageManager:w.z.enum(["npm","yarn","pnpm","bun"]).nullable(),isMonorepo:w.z.boolean(),detectedLanguage:w.z.enum(["typescript","javascript"]).nullable()}),rootDirectory:w.z.object({path:w.z.string(),reason:w.z.string()}).nullable(),installCommand:w.z.object({command:w.z.string(),reason:w.z.string()}).nullable(),runtimeDependencies:w.z.array(w.z.object({tool:w.z.string(),version:w.z.string(),source:w.z.string()})),devServer:w.z.object({command:w.z.string(),url:w.z.string(),port:w.z.number(),reason:w.z.string()}).nullable(),environmentVariables:w.z.array(w.z.object({key:w.z.string(),description:w.z.string(),isRequired:w.z.boolean(),isSecret:w.z.boolean(),defaultValue:w.z.string().nullable(),source:w.z.string()})),validationScript:w.z.object({command:w.z.string(),reason:w.z.string()}).nullable(),npmrcContents:w.z.string().nullable(),hasHotModuleReload:w.z.object({value:w.z.boolean(),reason:w.z.string()}).nullable()}).meta({title:"SetupAnalysisValues"}),t9e=w.z.object({config:e9e,message:w.z.string().optional()}).meta({title:"ProposeConfigToolInput"}),r9e=w.z.enum(["installCommand","devServer","validationScript","environmentVariables"]).meta({title:"SetupValueField"}),n9e=w.z.object({field:r9e.meta({description:"Which field to update"}),value:w.z.object({command:w.z.string().optional().meta({description:"The command to run (for installCommand, devServer, validationScript)"}),url:w.z.string().optional().meta({description:"Dev server URL (only for devServer)"}),port:w.z.number().optional().meta({description:"Dev server port (only for devServer)"}),environmentVariables:w.z.array(w.z.object({key:w.z.string().meta({description:"Variable name"}),description:w.z.string().optional().meta({description:"What this variable is for"}),isRequired:w.z.boolean().optional().meta({description:"Whether this variable is required"}),isSecret:w.z.boolean().optional().meta({description:"Whether this is a secret/credential"}),defaultValue:w.z.string().nullish()})).optional()}),reason:w.z.string()}).meta({title:"UpdateSetupValueToolInput"}),e0=w.z.enum(["verified","no-frontend","empty-project","mobile-project","user-question","code-change-required","other","started","failed"]).meta({title:"ExitState",description:"Current state: verified (all done), no-frontend (project has no dev server), empty-project (project has almost no code), mobile-project (mobile app e.g. Expo/React Native \u2014 recommend desktop local mode), user-question (need input), code-change-required (repo has code issues user must fix), other (other problem), started (Session started but Exit tool was never called (orphaned session)), failed (Session failed before reaching the agent (e.g. branch/container creation failed))"}),i9e=w.z.object({state:e0.meta({description:"Current state: verified (all done), no-frontend (project has no dev server), empty-project (project has almost no code), mobile-project (mobile app e.g. Expo/React Native), user-question (need input), code-change-required (repo has code issues user must fix), other (other problem)"}),summary:w.z.string().meta({description:"Brief summary of configuration outcome (what succeeded or what's needed)"}),questions:w.z.array(w.z.object({question:w.z.string().meta({description:"Full question text"}),context:w.z.string().meta({description:"Why this information is needed"}),header:w.z.string().optional().meta({description:'Short label (e.g., "API Key", "Database URL")'}),type:w.z.enum(["select","multi-select","text"]).optional().meta({description:'Question type: "select" for single-choice, "multi-select" for multiple choices, "text" for free-form input. Defaults to "select" if options are present, "text" if not.'}),placeholder:w.z.string().optional().meta({description:"Placeholder/hint text for 'text' type questions (e.g., 'Enter your API key', 'https://localhost:3000')"}),options:w.z.array(vL).optional().meta({description:"Suggested answer choices (for 'select' and 'multi-select' types). User can always choose 'Other'."})})).optional().meta({description:"Questions for user (only when state is 'user-question'). Include suggested options when possible."}),isMonorepo:w.z.boolean().optional().meta({description:"Repository contains multiple packages/apps"}),isMicrofrontend:w.z.boolean().optional().meta({description:"Frontend code served over multiple ports/servers"}),setupNeedsCredentials:w.z.boolean().optional().meta({description:"Setup requires credentials (e.g., NPM_TOKEN for private packages)"}),devServerNeedsCredentials:w.z.boolean().optional().meta({description:"Dev server needs special environment variables to run"}),needsVPN:w.z.boolean().optional().meta({description:"Setup requires a VPN connection"}),autoReload:w.z.boolean().optional().meta({description:"The dev server is able to reload the page automatically when the code changes, either through HMR or full page reload. Usually vite, webpack etc support this."}),usesBuilderCms:w.z.boolean().optional().meta({description:"The connected app uses Builder CMS (detected via @builder.io/react or @builder.io/sdk-* dependencies, a builder-registry file, or Builder CMS API keys such as BUILDER_PUBLIC_KEY)"}),stack:w.z.array(w.z.string()).optional().meta({description:'Technologies used by the connected application (not monorepo-wide). Include specific, high-confidence signals only, e.g. ["React", "Next.js", "Postgres", "Drizzle", "Tailwind CSS", "Clerk"]. Omit vague or uncertain entries.'}),projectDescription:w.z.string().optional().meta({description:"A human-readable description of what this project is about \u2014 focus on purpose and domain, not technical stack. This helps route user requests to the right project (e.g., 'Company blog and content management', 'E-commerce storefront for selling shoes', 'Internal admin dashboard for managing users')."})}).meta({title:"ExitToolInput"}),s9e=["running","stopped","starting","failed","unset"],o9e=["not-installed","installing","installed","install-failed","install-aborted"],a9e=["ok-2xx","error-4xx","error-5xx","error-fetch","stopped","connecting"],A9e=["unset","running","stopped","success","failure"],c9e=w.z.object({question:w.z.string(),context:w.z.string(),whatYouTried:w.z.string().optional(),header:w.z.string().optional().meta({description:"Short label (e.g., 'API Key', 'Database URL')"}),type:w.z.enum(["select","multi-select","text"]).optional().meta({description:'Question type: "select" for single-choice, "multi-select" for multiple choices, "text" for free-form input'}),placeholder:w.z.string().optional().meta({description:"Placeholder text for text-type questions"}),options:w.z.array(vL).optional()}),lie=w.z.object({setupCommand:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on setupState === 'installed'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),setupDependencies:w.z.object({value:w.z.array(Aie).optional(),verified:w.z.boolean().meta({description:"Based on setupState === 'installed'"})}),devCommand:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on devState === 'running'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),devServer:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds waiting for the server to respond"})}),validateCommand:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on validateState === 'success'"}),elapsed:w.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),appOrigin:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"})}),defaultOrigin:w.z.object({value:w.z.string().optional(),verified:w.z.boolean().meta({description:"Always true if set (used with wildcard appOrigin)"})}),environmentVariables:w.z.object({value:w.z.array(Bf).optional(),verified:w.z.boolean().meta({description:"Based on devState === 'running'"})}),autoDetectDevServer:w.z.object({value:w.z.boolean().optional(),verified:w.z.boolean().meta({description:"Always true if set"})}),autoDetectDevServerPatterns:w.z.object({value:w.z.array(w.z.string()).optional(),verified:w.z.boolean().meta({description:"Always true if set"})}),hasHotModuleReload:w.z.object({value:w.z.boolean().optional(),reason:w.z.string().optional().meta({description:"Detection-only, not auto-applied"})})}),gie=w.z.object({setupState:w.z.enum(o9e),devState:w.z.enum(s9e),httpServerState:w.z.enum(a9e),validateState:w.z.enum(A9e)}),hHt=w.z.object({id:w.z.string().meta({description:"Auto-generated document ID"}),projectId:w.z.string(),branchName:w.z.string(),createdAt:w.z.number(),updatedAt:w.z.number(),ownerId:w.z.string(),state:e0.meta({description:"Configuration state from Exit tool"}),running:w.z.boolean().default(!1),previousStates:w.z.array(e0).optional(),summary:w.z.string().meta({description:"Summary from Exit tool"}),questions:w.z.array(c9e).optional(),configuration:lie,sessionId:w.z.string(),orchestratorStates:gie,peakDiskUsage:w.z.number().optional().meta({description:"Peak disk usage in bytes"}),peakMemoryUsage:w.z.number().optional().meta({description:"Peak memory usage in bytes"}),screenshotUrl:w.z.string().optional().meta({description:"Screenshot URL from verification (e.g., error page screenshot)"}),isMonorepo:w.z.boolean().optional(),isMicrofrontend:w.z.boolean().optional(),setupNeedsCredentials:w.z.boolean().optional(),devServerNeedsCredentials:w.z.boolean().optional(),projectDescription:w.z.string().optional(),cost:w.z.number().optional(),durationMs:w.z.number().optional(),needsVPN:w.z.boolean().optional(),autoReload:w.z.boolean().optional(),usesBuilderCms:w.z.boolean().optional(),stack:w.z.array(w.z.string()).optional()}).meta({title:"ProposedConfig",description:"Configuration proposed by the configuration agent, stored in Firebase"}),mHt=w.z.object({projectId:w.z.string(),branchName:w.z.string(),state:e0,summary:w.z.string(),questions:w.z.array(w.z.object({question:w.z.string(),context:w.z.string(),whatYouTried:w.z.string().optional(),header:w.z.string().optional(),options:w.z.array(vL).optional(),multiSelect:w.z.boolean().optional()})).optional(),configuration:lie,sessionId:w.z.string(),orchestratorStates:gie,peakDiskUsage:w.z.number().optional(),peakMemoryUsage:w.z.number().optional(),screenshotUrl:w.z.string().optional(),isMonorepo:w.z.boolean().optional(),isMicrofrontend:w.z.boolean().optional(),setupNeedsCredentials:w.z.boolean().optional(),devServerNeedsCredentials:w.z.boolean().optional(),needsVPN:w.z.boolean().optional(),projectDescription:w.z.string().optional(),autoReload:w.z.boolean().optional(),usesBuilderCms:w.z.boolean().optional(),stack:w.z.array(w.z.string()).optional()}).meta({title:"ProposeConfigParams"}),u9e=w.z.object({command:w.z.string().meta({description:"The install command to run (e.g., 'npm install', 'yarn', 'pnpm install'). It can be a multi-line command too, just like a shell script."}),dependencies:w.z.array(w.z.object({tool:w.z.string().meta({description:"The tool/binary to verify (e.g., 'node', 'npm', 'git')"}),version:w.z.string().optional().meta({description:"Optional version requirement (e.g., '>=18.0.0', '20.x')"})})).optional()}).meta({title:"VerifySetupCommandToolInput"}),l9e=w.z.object({command:w.z.string().meta({description:"The dev server command to run (e.g., 'npm run dev', 'cd packages/frontend && yarn dev')"})}).meta({title:"VerifyDevCommandToolInput"}),g9e=w.z.object({autoDetect:w.z.boolean().meta({description:"Whether to automatically detect the dev server URL from terminal output"}),autoDetectPattern:w.z.string().optional().meta({description:"Pattern to match and extract URL from terminal output when multiple URLs are present (e.g., 'Local:.*http://localhost:\\\\d+')"}),hardcodedUrl:w.z.string().optional().meta({description:"The hardcoded dev server URL to use when autoDetect is false (e.g., 'http://localhost:3000')"}),appOrigin:w.z.string().meta({description:"The origin where the app should be accessed (e.g., 'https://acme.com', 'https://*.acme.com'). Can be a pattern with wildcard."}),defaultOrigin:w.z.string().optional().meta({description:"Default origin to use when appOrigin is a pattern (e.g., 'https://dev.acme.com'). Required if appOrigin contains a wildcard."})}).meta({title:"VerifyDevServerToolInput"}),p9e=w.z.object({command:w.z.string(),timeout:w.z.number().optional().meta({description:"Default: 300000 (5 minutes)"})}).meta({title:"VerifyValidateCommandToolInput"}),d9e=w.z.object({key:w.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:w.z.string().meta({description:"The environment variable value. Must be a concrete value, not a placeholder."}),secret:w.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"})}).meta({title:"ProposeEnvVariableToolInput"}),f9e=w.z.object({key:w.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:w.z.string().meta({description:"The environment variable value. Use clear placeholder like 'PLACEHOLDER_DATABASE_URL' if actual value is unknown."}),secret:w.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"}),placeholder:w.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:w.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"SetEnvVariableToolInput"}),h9e=w.z.object({path:w.z.string().meta({description:'Path where the file should be written. Supports absolute paths ("/app/.npmrc"), tilde ("~/.npmrc") and paths relative to the project working directory ("./.npmrc"). Use this tool ONLY for configuration-only files that should NOT be committed to the repo (e.g. `.npmrc` with auth tokens, machine-local env files) \u2014 never to patch source code or fix software issues.'}),content:w.z.string().optional().meta({description:"Plain text content to write to the file. Mutually exclusive with `base64`."}),base64:w.z.string().optional().meta({description:"Base64-encoded binary content to write to the file. Mutually exclusive with `content`. Use only when the file is genuinely binary."})}).meta({title:"SetFileOverrideToolInput"}),m9e=w.z.object({channel_id:w.z.string().meta({description:"The channel identifier in URI format (see supported formats in the tool description)"}),markdown:w.z.string().meta({description:"The message content to send in markdown format"}),status:w.z.enum(["starting","question","will-follow-up","done:success","done:error"]),loading_message:w.z.string().optional().meta({description:"Loading message displayed in the Slack thread while the agent is working (only used when status is 'starting')."}),voice_response:w.z.boolean().optional().meta({description:"When true, send the response as a voice message using text-to-speech. Only supported for Telegram channels. Only set to true when the user's original message was a voice/audio message (look for '[Voice message transcription]' or '[Audio' markers), the channel is Telegram, and the response is short and conversational with no URLs, code, lists, or other content that doesn't translate to audio. Default to false (text) for all text-originated messages."}),from_user_id:w.z.string().optional().meta({description:"Builder.io user ID this message is from / should be attributed to. Only allowed when channel_id is 'builder/branch/{project_id}/{branch_name}'. When set, the message is delivered to the target branch as coming from this user (role 'user') instead of from the agent. Use whenever the message represents user feedback/intent that should be assigned to someone \u2014 even if it was composed, summarized, or merged from multiple people."})}).meta({title:"SendMessageToolInput"}),C9e=w.z.object({project_id:w.z.string().meta({description:"The project ID to create the branch in"}),message:w.z.string().meta({description:"The initial message or task description for the branch. Do NOT include instructions to open or create a PR unless the user's original request explicitly asked for a PR."}),builder_user_id:w.z.string().optional().meta({description:"Builder.io user ID to act as. When provided, the branch will be created as if this user created it."}),hidden:w.z.boolean().optional().meta({description:"Whether to hide the branch from the user. Useful for exploratory branches not intended to ever get merged back to main. Default: false."}),origin_channel_id:w.z.string().optional().meta({description:"The channel identifier that originally triggered this work. Used for tracking purposes and coming back to the original slack thread with updates."}),session_mode:w.z.enum(["normal","planning","deep-research"]).optional(),model:w.z.enum(["auto","opus","sonnet","haiku"]).optional(),attachment_urls:w.z.array(w.z.string()).optional(),git_base_branch:w.z.string().optional(),auto_archive_on_idle:w.z.boolean().optional()}).meta({title:"SpawnBranchToolInput"}),I9e=w.z.object({repo_url:w.z.string().meta({description:"Repository URL (regular Git URL or template:// URL)"}),name:w.z.string().optional().meta({description:"Human-readable name for the project. If not provided, a name will be generated from the repo name."}),builder_user_id:w.z.string().meta({description:"Builder.io user ID to act as. The project and branch will be created as if this user created them, and their git credentials will be validated before creation."}),origin_channel_id:w.z.string().optional().meta({description:"The channel_id identifier that originally triggered this work. Used for routing status updates back to the user."}),initial_message:w.z.string().optional().meta({description:"Only valid for template:// URLs \u2014 creates a branch with this message"})}).meta({title:"CreateProjectToolInput"}),E9e=w.z.object({}).meta({title:"GetAvailableReposToolInput"}),B9e=w.z.object({project_id:w.z.string().meta({description:"The project ID containing the branch"}),branch_name:w.z.string().meta({description:"The name of the branch to read"})}).meta({title:"ReadBranchToolInput"}),y9e=w.z.object({project_id:w.z.string().meta({description:"The project ID containing the branch"}),branch_name:w.z.string().meta({description:"The name of the branch to archive"}),builder_user_id:w.z.string().meta({description:"The Builder.io user ID of the person requesting the archive. This is used to attribute the archive action to a specific user."}),reason:w.z.string().optional().meta({description:"The reason for archiving this branch (max 500 chars). Examples: 'Work completed and merged', 'No longer needed', 'Superseded by branch X'."})}).meta({title:"ArchiveBranchToolInput"}),SL=w.z.enum(["high","medium","low"]).meta({title:"ReviewSeverity"}),Q9e=w.z.object({file_path:w.z.string().meta({description:"Relative file path - MUST be a file that appears in the PR diff"}),line:w.z.number().meta({description:"Line number in the file (end line for multi-line). MUST be a line within the PR diff"}),start_line:w.z.number().optional().meta({description:"For multi-line comments (optional)"}),side:w.z.enum(["LEFT","RIGHT"]).optional().meta({description:"Diff side. RIGHT (default) = NEW file (added/context). LEFT = OLD file (removed/context). Use LEFT only when commenting on deleted code with no semantically related new-side anchor."}),title:w.z.string().meta({description:"Brief plain-text issue title. MUST NOT start with severity emojis"}),body:w.z.string().meta({description:"Review comment (1-2 sentences)"}),severity:SL.meta({description:"Issue severity: high (blocking), medium (should fix), or low (minor observation)"}),debugInfo:w.z.string().optional(),gif_id:w.z.string().optional().meta({description:"Per-comment GIF (optional)"})}).meta({title:"PRReviewComment"}),D9e=w.z.enum(["looks_good","has_findings","blocking"]).meta({title:"ReviewVerdict"}),w9e=w.z.object({summary:w.z.string().meta({description:"Your detailed analysis of the changes (displayed in a collapsible 'Review Details' section)"}),comments:w.z.array(Q9e).optional(),risk_level:SL.optional(),verdict:D9e.optional()}).meta({title:"SubmitPRReviewToolInput"}),b9e=w.z.object({thread_node_ids:w.z.array(w.z.string()).meta({description:"GraphQL thread node_ids (PRRT_...) from previous review response"})}).meta({title:"ResolveQACommentsToolInput"}),v9e=w.z.object({title:w.z.string().meta({description:"Brief summary of the issue (e.g., 'Button click has no effect')"}),description:w.z.string().meta({description:"Detailed description of what went wrong, what was expected, and what actually happened"}),debugInfo:w.z.string().optional().meta({description:"Optional console errors, stack traces, or other diagnostic information"})}).meta({title:"ReportUIIssueToolInput"}),S9e=w.z.object({file_path:w.z.string().meta({description:"File path where the issue occurs (e.g., 'packages/api/src/auth.ts')"}),line:w.z.number().meta({description:"End line number of the issue range (or single line if no start_line)"}),start_line:w.z.number().optional().meta({description:"Optional start line for multi-line issues. When provided, the comment spans from start_line to line"}),title:w.z.string().meta({description:"Short, descriptive title (one line, no markdown)"}),severity:SL.meta({description:"Issue severity: high for critical bugs, medium for should-fix, low for minor observations"}),body:w.z.string().meta({description:"Detailed explanation in markdown format. Should include: What the issue is, Why it's problematic, Impact, How to fix it, Evidence"})}).meta({title:"ReportIssueToolInput"}),x9e=w.z.object({issue:w.z.string().meta({description:"What's blocking execution"}),steps_attempted:w.z.string().meta({description:"What was tried before escalating"}),current_url:w.z.string().meta({description:"Current browser URL"}),test_case_id:w.z.string().meta({description:"Which test case is blocked"})}).meta({title:"EscalateToPlanner"}),F9e=w.z.object({}).meta({title:"GetLastBrowserTestToolInput"}),k9e=w.z.object({file_path:w.z.string().optional().meta({description:"Optional relative or absolute path to filter diagnostics to a single file. Omit to retrieve diagnostics for the entire workspace."})}).meta({title:"IDEDiagnosticsToolInput"}),R9e=w.z.object({event_id:w.z.string().meta({description:"The codegen event ID to load (e.g. cgen-<eventId>)."})}).meta({title:"GetCodegenEventToolInput"}),T9e=w.z.object({session_or_event_id:w.z.string().meta({description:"A session ID or codegen event ID. When an event ID is given, its session is resolved first."}),limit:w.z.number().optional().meta({description:"Maximum number of events to return."})}).meta({title:"ListCodegenSessionEventsToolInput"}),N9e=w.z.object({url:w.z.string().meta({description:"The prototype URL (e.g., https://builder.io/app/projects/<projectId>/<branchName>)"}),project_id:w.z.string().optional().meta({description:"The project ID (optional, parsed from URL if not provided)"}),branch_name:w.z.string().optional().meta({description:"The branch name (optional, parsed from URL if not provided)"})}).meta({title:"PullPrototypeToolInput"}),M9e=w.z.object({project_id:w.z.string().meta({description:"The Builder.io project ID containing the branch"}),branch_name:w.z.string().meta({description:"The Fusion branch name to push and open a PR for"}),builder_user_id:w.z.string().optional().meta({description:"Builder.io user ID to attribute the PR to. When provided, the PR body will credit this user and the user must be a member of the organization. Highly recommended when the PR is being opened on behalf of a specific user."}),draft:w.z.boolean().optional().meta({description:`Whether to create the PR as a draft. When omitted, defaults to the branch's configured commitMode: true for "draft-prs" branches, false for "prs" branches.`})}).meta({title:"EnsurePRToolInput"}),P9e=w.z.object({name:w.z.string().meta({description:'Human-readable name of the service to connect, e.g. "Jira", "Linear", "Sentry"'}),url:w.z.string().optional().meta({description:"Remote MCP endpoint URL (e.g. https://mcp.linear.app/mcp). When omitted, the tool discovers known URLs for the named service instead."})}).meta({title:"ConnectMCPToolInput"}),L9e=w.z.object({Read:cYe,Write:yYe,Edit:QYe,ReadRule:pYe,Skill:gYe,GetStyleInspiration:dYe,GetScreenshot:KYe,NavigatePreview:HYe,MultiEdit:DYe,FindMedia:wYe,Media:bYe,AddMemory:vYe,SearchMemories:SYe,ScoreMemories:xYe,Bash:IYe,PowerShell:EYe,WebSearch:BYe,AskUserQuestion:RYe,Agent:TYe,Grep:lYe,Glob:uYe,DevServerControl:fYe,DevServerLogs:hYe,DevServerRestart:CYe,Revert:NYe,TodoRead:MYe,TodoWrite:LYe,TaskCreate:_Ye,TaskUpdate:UYe,TaskList:GYe,BuilderEdit:OYe,WebFetch:JYe,ExplorationMetadata:jYe,EnterPlanMode:YYe,ExitPlanMode:qYe,ReadMcpResource:$Ye,RecordFrame:XYe,SubmitPRReview:w9e,ProposeConfig:t9e,UpdateSetupValue:n9e,Exit:i9e,ResolveQAComments:b9e,GetLastBrowserTest:F9e,ReportUIIssue:v9e,ReportIssue:S9e,ReportTestOutcome:ZYe,VerifySetupCommand:u9e,VerifyDevCommand:l9e,VerifyDevServer:g9e,VerifyValidateCommand:p9e,ProposeEnvVariable:d9e,SetEnvVariable:f9e,SetFileOverride:h9e,SendMessage:m9e,SpawnBranch:C9e,CreateProject:I9e,GetAvailableRepos:E9e,ReadBranch:B9e,ArchiveBranch:y9e,RunningAgents:PYe,IDEDiagnostics:k9e,EscalateToPlanner:x9e,PullPrototype:N9e,ConnectMCP:P9e,EnsurePR:M9e,GenerateDesignSystemAgentMd:mYe,GetCodegenEvent:R9e,ListCodegenSessionEvents:T9e}),_9e=L9e.keyof().meta({title:"CodeGenTools"}),pie=w.z.enum(["planning","normal","auto-planning","deep-research"]).meta({title:"SessionMode"}),U9e=w.z.enum(["quality","quality-v4","quality-v4-agent"]).meta({title:"CodeGenMode"}),G9e={schedule:"next-turn",coalesce:"merge"};O9e=["fusion","editor-ai","repo-indexing","cli","create-app-firebase","create-app-lovable","builder-code-panel","setup-project","code-review-orchestrator","project-configuration","org-agent","org-worker","browser-testing","projects-scheduler-memory-extraction","builder-code","unknown","dsi-mcp","design-system-indexer","builder-publish-integration"],cie=w.z.enum(O9e).meta({title:"BaseCodeGenPosition"}),K9e=w.z.union([cie,w.z.templateLiteral([cie,"-agent"])]).meta({title:"CodeGenPosition"}),H9e=w.z.object({designSystems:w.z.array(w.z.string())}).meta({title:"RepoIndexingConfig"}),J9e=w.z.object({name:w.z.string(),description:w.z.string().optional(),inputSchema:w.z.any().optional(),serverName:w.z.string(),deferLoading:w.z.boolean().optional()}).meta({title:"LocalMCPTools"}),fie=w.z.union([w.z.templateLiteral(["repair-",w.z.string()]),w.z.literal("user-normal"),w.z.literal("user-figma"),w.z.literal("user-pdf"),w.z.literal("user-image"),w.z.literal("setup-agent"),w.z.templateLiteral(["background-",w.z.string()]),w.z.templateLiteral(["indexing-",w.z.string()])]).meta({title:"CodeGenCategory"}),j9e=w.z.enum(["editCode","modifyMcpServers","modifyProjectSettings","createBranches","sendPullRequests","view"]).meta({title:"UserSourcePermission"}),r0={role:w.z.enum(["user","agent"]),principals:w.z.array(w.z.string()).optional().meta({description:"teams/roles like ['developer', 'admin']"}),jobs:w.z.array(w.z.string()).optional().meta({description:"job titles like ['designer', 'developer'] - used for role-aware communication instead of principals when available"}),permissions:w.z.array(j9e).optional(),channelId:w.z.string().optional()},CHt=w.z.object(r0).meta({title:"UserSourceBase"}),Y9e=w.z.object({...r0,source:w.z.enum(["slack","telegram","whatsapp","teams","jira","linear","github","gitlab","azure","bitbucket"]),userId:w.z.string().optional().meta({description:"User ID from the external platform (Slack user ID, GitHub user id, etc.)"}),userName:w.z.string().optional(),userEmail:w.z.string().optional(),photoURL:w.z.string().optional(),builderUserId:w.z.string().optional().meta({description:"Resolved Builder user ID for attribution/credits"}),link:w.z.string().optional().meta({description:"Optional link (e.g. comment/PR URL) for git provider sources"})}).meta({title:"UserSourceOther"}),q9e=w.z.object({...r0,source:w.z.literal("builder.io"),userId:w.z.string().optional(),userName:w.z.string().optional(),userEmail:w.z.string().optional(),photoURL:w.z.string().optional()}).meta({title:"UserSourceBuilder"}),$9e=w.z.object({...r0,source:w.z.literal("agent"),userId:w.z.string().optional(),userName:w.z.string().optional(),userEmail:w.z.string().optional()}).meta({title:"UserSourceAgent"}),hie=w.z.discriminatedUnion("source",[Y9e,q9e,$9e]).meta({title:"UserSource"}),V9e=w.z.enum(["read","write","list"]).meta({title:"Permission"}),W9e=w.z.object({action:w.z.enum(["allow","deny"]).meta({description:"whether this rule allows or denies access"}),resource:w.z.string().meta({description:"what \u2014 supports glob patterns like /files/*.txt"}),permissions:w.z.array(V9e).meta({description:"actions this rule applies to"}),description:w.z.string().optional().meta({description:"custom message, in deny case, this is the error message. This will override denyDescription on AclPolicy if defined."}),principals:w.z.array(w.z.string()).optional().meta({description:"array of teams/roles this rule applies to (e.g., ['developer', 'admin'])"})}).meta({title:"AclEntry"}),z9e=w.z.object({secrets:w.z.array(w.z.string()).optional(),entries:w.z.array(W9e).optional(),denyDescription:w.z.string().optional().meta({description:"Default message to use when a resource is denied access"})}).meta({title:"AclPolicy"}),mie=w.z.object({text:w.z.string(),tag:w.z.string().optional(),ephemeral:w.z.boolean().optional()}).meta({title:"SystemReminderObj"}),X9e=w.z.union([w.z.string(),mie]).meta({title:"SystemReminder"}),IHt=w.z.looseObject({position:K9e,eventName:w.z.string().optional(),sessionId:w.z.string(),codeGenMode:U9e.optional(),sessionMode:pie.optional(),url:w.z.string().optional(),diffActions:w.z.boolean().optional(),planningPrompt:w.z.boolean().optional(),customInstructions:w.z.array(iYe).optional(),customAgents:w.z.array(sYe).optional(),systemPromptOverride:w.z.union([w.z.string(),w.z.array(w.z.string())]).optional(),userPrompt:w.z.string().optional(),systemReminders:w.z.array(X9e).optional(),ephemeralUserPrompt:w.z.string().optional(),uiContextPrompt:w.z.string().optional(),displayUserPrompt:w.z.string().optional(),files:w.z.array(nYe).optional(),rerankFiles:w.z.number().optional(),toolResults:w.z.array(sie).optional(),attachments:w.z.array(DL).optional(),beforeCommit:rYe.optional(),workingDirectory:w.z.string().optional(),includeRelevantMemories:w.z.boolean().optional(),encryptKey:w.z.string().optional(),modelOverride:w.z.string().optional(),errorIfHadCompaction:w.z.boolean().optional(),softContextWindow:w.z.number().optional(),promptVersion:w.z.enum(["v1","v2","v3"]).optional(),reasoning:uie.optional(),redactUserMessages:w.z.boolean().optional(),redactLLMMessages:w.z.boolean().optional(),environmentVariables:w.z.array(Bf).optional(),skipCommandSecurity:w.z.boolean().optional(),builderContent:w.z.custom().optional(),framework:aYe.optional(),styleLibrary:AYe.optional(),typescript:w.z.boolean().optional(),userContext:aie.optional(),aclPolicy:z9e.optional(),repoIndexingConfig:H9e.optional(),recommendedRoot:w.z.string().optional(),enabledTools:w.z.array(_9e).optional(),enabledMCPs:w.z.array(w.z.string()).optional(),skippedMCPs:w.z.array(w.z.string()).optional().meta({description:"Per-message denylist of MCP server ids to skip. Skipped servers are not mounted or connected for this message and will not trigger an `mcp-auth-required` event. Tokens and org-level enabled state are untouched; this is purely message-scoped."}),skipFileDiff:w.z.boolean().optional(),interruptActiveTask:w.z.boolean().optional().meta({description:"When true, the agent should interrupt its current task to handle this message immediately, rather than finishing the current task first."}),localMCPTools:w.z.array(J9e).optional().meta({description:"Local MCP tool definitions from stdio servers (CLI-side only). These tools will be executed on the client side and passed through from the server."}),isLocal:w.z.boolean().optional().meta({description:"Indicates whether the codegen is running in local mode (local filesystem) vs cloud/container mode. Used to determine git auto-commit behavior."}),maxAgentLoops:w.z.number().optional(),maxAgentTiming:w.z.number().optional(),maxTokens:w.z.number().optional().meta({description:"Maximum output tokens allowed in the LLM response. This will set the maximum token output for the LLM."}),maxPages:w.z.number().optional(),autoContinue:w.z.number().optional(),isManualContinue:w.z.boolean().optional(),llmSuggestions:w.z.boolean().optional(),conclusionText:w.z.boolean().optional(),mcpServers:w.z.boolean().optional(),pingEvents:w.z.boolean().optional(),forceCompact:w.z.boolean().optional(),hadPagination:w.z.boolean().optional(),category:fie.optional(),metadata:w.z.record(w.z.string(),w.z.any()).optional(),searchResponse:w.z.any().nullish(),prettierConfig:w.z.custom().optional(),role:w.z.enum(["user","agent"]).optional(),user:hie.optional(),projectId:w.z.string().optional(),branchName:w.z.string().optional(),repoHash:w.z.string().optional(),repoBranch:w.z.string().optional(),parentSessionId:w.z.string().optional().meta({description:"Immediate parent session id when this completion runs inside a sub-agent."}),mainSessionId:w.z.string().optional().meta({description:"Root session of the agent tree. Sub-agents inherit this from their parent so cost rolls up to the root in one hop, regardless of nesting depth."}),prevId:w.z.string().optional(),vcpId:w.z.string().optional(),repair:w.z.boolean().optional(),systemReminderPrompt:w.z.string().optional()}).meta({title:"CodeGenInputOptions"}),Z9e=w.z.enum(["force-push","merge-push","ff-push","safe-push","none"]).meta({title:"AutoPushMode"}),e6e=w.z.object({remoteBranches:w.z.enum(["both","main","ai"]).optional(),fastForward:w.z.enum(["never","required","auto"]).optional(),canPush:w.z.boolean().optional(),uncommittedChanges:w.z.enum(["stash","commit","fail"]).optional(),requestRefresh:w.z.boolean().optional(),allowUnrelatedHistory:w.z.boolean().optional(),resetToBase:w.z.boolean().optional().meta({description:"When true, reset the AI branch hard to the remote feature/base branch instead of merging. This gives a clean slate that exactly matches the checked-out feature branch on remote, avoiding any merge-style conflicts or divergence. Fails clearly if the feature/base branch cannot be determined or is absent from the remote."}),updateLastCommits:w.z.boolean().optional().meta({description:"Whether to update the internal 'last AI commits' baseline after the sync completes. Defaults to `true` for backwards compatibility. Set to `false` when the caller wants `getChangesReport()` to keep diffing from the pre-sync baseline (e.g. so a downstream prompt can see exactly what changed since the last reset/sync)"})}).meta({title:"SyncChangesFromRemote"}),EHt=w.z.object({idempotencyKey:w.z.string().optional(),user:hie.optional(),userPrompt:w.z.string(),uiContextPrompt:w.z.string().optional(),ephemeralUserPrompt:w.z.string().optional(),displayPrompt:w.z.string().optional(),files:w.z.array(w.z.string()).optional(),systemReminders:w.z.array(mie).optional(),includeBaseFiles:w.z.boolean().optional(),attachments:w.z.array(DL).optional(),logsCheckpoint:w.z.boolean().optional(),dropAbortedPrompt:w.z.boolean().optional(),runValidateCommand:w.z.boolean().optional(),modelOverride:w.z.string().optional(),agentModelOverrides:oYe.optional(),softContextWindow:w.z.number().optional(),maxCompletions:w.z.number().optional(),isManualContinue:w.z.boolean().optional(),includeRelevantMemories:w.z.boolean().optional(),category:fie.optional(),metadata:w.z.record(w.z.string(),w.z.any()).optional(),autoPush:Z9e.optional(),syncChanges:e6e.optional(),enabledMCPs:w.z.array(w.z.string()).optional(),skippedMCPs:w.z.array(w.z.string()).optional().meta({description:"Per-message denylist of MCP server names to skip. Skipped servers are not mounted or connected for this message and will not trigger an `mcp-auth-required` event. Tokens and org-level enabled state are untouched; this is purely message-scoped."}),sessionMode:pie.optional(),queue:w.z.boolean().optional(),agentType:w.z.string().optional().meta({description:"Custom agent type to use for this message"}),enableQAReviewTool:w.z.boolean().optional().meta({description:"Enable AddQAReview tool for QA PR review branches"}),reasoning:uie.optional().meta({description:"Per-message reasoning effort override"}),repair:w.z.boolean().optional(),forceCompact:w.z.boolean().optional().meta({description:"Force compaction of the conversation before generating the next completion"})}).meta({title:"GenerateUserMessage"}),BHt=w.z.object({diff:w.z.string().meta({description:"Git diff from previous commit"}),userMessages:w.z.array(w.z.string()).meta({description:"User messages sent during AI work"}),recentCommits:w.z.array(w.z.string()).meta({description:"Last 10 commits from main branch for style reference"}),longCommit:w.z.boolean().optional().meta({description:"Whether to generate a long commit message"}),projectId:w.z.string().optional().meta({description:"Project ID for fetching project-specific commit instructions"})}).meta({title:"CommitMessageRequest"}),yHt=w.z.object({message:w.z.string().meta({description:"Full commit message"}),title:w.z.string().meta({description:"First line (50-72 chars) - the commit title"}),body:w.z.string().optional().meta({description:"Optional extended description"})}).meta({title:"CommitMessageResponse"}),QHt=w.z.object({sessionId:w.z.string(),toolId:w.z.string(),approved:w.z.boolean(),reason:w.z.string().optional()}).meta({title:"ModelPermissionResponseRequest"})});var Iie=L(()=>{"use strict";h()});var Eie=L(()=>{"use strict";h()});function FL(t){try{let e=t.toLowerCase();return e.includes("github.com")?"github":e.includes("gitlab.com")?"gitlab":e.includes("bitbucket.org")?"bitbucket":e.includes("dev.azure.com")?"azure":e.includes("github")?"selfHostedGithub":"unknown"}catch{return"unknown"}}function Bie(t){if(t.type!=="ai")return null;let e=t.event;if(e.type==="tool_result"){let r=e.result;if(r.tool_name==="ExitPlanMode"){let n,i;if(typeof r.tool_input=="string")try{let s=JSON.parse(r.tool_input);s&&typeof s.plan=="string"&&!n&&(n=s.plan),s&&typeof s.sessionMode=="string"&&!i&&(i=s.sessionMode)}catch{}if(typeof r.content=="string")try{let s=JSON.parse(r.content);s&&typeof s.plan=="string"&&!n&&(n=s.plan),s&&typeof s.sessionMode=="string"&&!i&&(i=s.sessionMode)}catch{}if(r.structured_result&&typeof r.structured_result.plan=="string"&&!n&&(n=r.structured_result.plan),r.structured_result&&typeof r.structured_result.sessionMode=="string"&&!i&&(i=r.structured_result.sessionMode),n)return{plan:n,sessionMode:i}}}return null}var Ze,kL,yf,t6e,gI,kHt,RHt,yie,r6e,THt,n6e,NHt,MHt,PHt,LHt,Qie=L(()=>{"use strict";h();Ze=require("zod");Zw();kL=["steve8708/mui-vite","steve8708/carbon-vite","steve8708/vite-react-shopify-polaris","steve8708/cloudscape-demos","BuilderIO/fusion-angular-tailwind-starter","BuilderIO/fusion-svelte-tailwind-starter","BuilderIO/fusion-vue-tailwind-starter","BuilderIO/org-agent-starter"],yf="BuilderIO/fusion-starter",t6e="BuilderIO/dsi-starter",gI=[...kL,yf,t6e],kHt=gI.map(t=>`https://github.com/${t}`),RHt=720*60*60*1e3;yie=Ze.z.enum(["queued","building","uploading","deploying","live","failed","canceled"]),r6e=Ze.z.object({buildCommand:Ze.z.string().optional(),nodeVersion:Ze.z.string().optional()}),THt=Ze.z.object({enabled:Ze.z.boolean().optional().meta({description:"Whether hosting is enabled for this project or not."}),slug:Ze.z.string().optional().meta({description:'e.g. "my-cool-app" \u2014 set once on first publish, immutable'}),netlifySiteId:Ze.z.string().optional().meta({description:"Netlify site ID for management API calls; cleared on unpublish, set again on re-publish"}),netlifySiteName:Ze.z.string().optional().meta({description:"<name> in <name>.netlify.app \u2014 the upstream the HTTPRoute filter rewrites Host to; cleared on unpublish"}),url:Ze.z.string().optional().meta({description:'"https://my-cool-app.builder.cloud" \u2014 derived from slug'}),buildConfig:r6e.optional(),environment:Ze.z.object({build:Ze.z.array(Bf).optional().meta({description:"Env vars available to the build itself"}),prod:Ze.z.array(Bf).optional().meta({description:"Env vars for the production deploy served via Netlify"})}).optional(),lastDeployId:Ze.z.string().optional(),lastDeployAt:Ze.z.number().optional(),lastDeployStatus:yie.optional(),customDomain:Ze.z.string().optional(),customDomainVerified:Ze.z.boolean().optional(),autoDeploy:Ze.z.boolean().optional().meta({description:"auto-deploy on push/merge"})}),n6e=Ze.z.object({id:Ze.z.string(),projectId:Ze.z.string(),ownerId:Ze.z.string(),checkoutBranch:Ze.z.string().optional().meta({description:'The git ref that was deployed (always "main" in v0/v1; the feature branch for row 2 in v2). This is the value passed as `checkoutBranch` when the deploy pod was created.'}),deployBranchId:Ze.z.string().optional().meta({description:'Fusion branch id of the ephemeral hidden deploy branch (`type: "deploy"`) that ran the build.'}),devBranchId:Ze.z.string().optional().meta({description:"Fusion dev branch's id (unset if we are deploying project default branch)"}),status:yie,netlifyDeployId:Ze.z.string().optional(),url:Ze.z.string().optional(),error:Ze.z.string().optional().meta({description:"Single human-readable line on failure; raw build logs not surfaced in v0"}),createdAt:Ze.z.number(),completedAt:Ze.z.number().optional(),triggeredBy:Ze.z.string().meta({description:'user ID for manual publish, or "auto-deploy" (v1)'})}),NHt=Ze.z.object({projectId:Ze.z.string(),ownerId:Ze.z.string(),createdAt:Ze.z.number(),createdBy:Ze.z.string().meta({description:"user ID of the user who first clicked Publish on the project"})}),MHt=Ze.z.object({ownerId:Ze.z.string(),holderId:Ze.z.string().meta({description:"unique per acquisition (the fencing token); == deployId for a deploy holder"}),holderKind:Ze.z.enum(["deploy","unpublish"]),deployId:Ze.z.string().optional().meta({description:'set when holderKind === "deploy"'}),acquiredAt:Ze.z.number().meta({description:"unix time (ms)"}),expiresAt:Ze.z.number().meta({description:"acquiredAt + 15min (same ceiling as the deploy lazy-timeout)"})}),PHt=n6e.pick({id:!0,status:!0,url:!0,createdAt:!0,completedAt:!0,error:!0}).meta({title:"DeployListItem"}),LHt=Ze.z.object({files:Ze.z.record(Ze.z.string(),Ze.z.string()).meta({description:"static file path \u2192 sha1 hash"}),functions:Ze.z.record(Ze.z.string(),Ze.z.string()).meta({description:"serverless function name \u2192 sha256 hash"})})});var RL,Qf,Ku,Ug,n0,Die=L(()=>{"use strict";h();RL=t=>t.type==="agent",Qf=t=>t.type==="icon",Ku=t=>t.type==="token",Ug=t=>t.type==="component",n0=t=>t.type==="installation"});var wie=L(()=>{"use strict";h()});var bie=L(()=>{"use strict";h()});var vie=L(()=>{"use strict";h()});function i6e(t){let e=t.split("/");if(e.length<2)throw new Error(`Invalid channelId format: ${t}`);let[r,n,...i]=e;return{platform:r,type:n,ids:i}}function Sie(t){let e;try{e=i6e(t)}catch{return null}let{platform:r,type:n,ids:i}=e;return r==="slack"?s6e(n,i):null}function s6e(t,e){if(t==="thread"){let[r,n,i]=e;return!r||!n||!i?null:`https://slack.com/app_redirect?team=${r}&channel=${n}&message_ts=${i}`}if(t==="channel"){let[r,n]=e;return!r||!n?null:`https://slack.com/app_redirect?team=${r}&channel=${n}`}if(t==="dm"){let[r,n]=e;return!r||!n?null:`https://slack.com/app_redirect?team=${r}&channel=${n}`}return null}function TL(t){let e=`<worker_report>
|
|
1501
1501
|
`;if(t.originChannelId){e+=`<origin_channel_id>${t.originChannelId}</origin_channel_id>
|
|
1502
1502
|
`;let r=t.channelUrl??Sie(t.originChannelId);r&&(e+=`<origin_channel_url>${r}</origin_channel_url>
|
|
1503
1503
|
`),t.channelName&&(e+=`<origin_channel_name>${t.channelName}</origin_channel_name>
|
|
@@ -1516,7 +1516,7 @@ ${t.content.trim()}
|
|
|
1516
1516
|
${t.content.trim()}
|
|
1517
1517
|
</content>
|
|
1518
1518
|
`,e+=`</worker_message>
|
|
1519
|
-
`,e}var o6e,Fie=L(()=>{"use strict";h();o6e="This is a report from a background worker, NOT a user message. Review the results and take appropriate action (e.g., send findings to the user, update memory)."});var kie=L(()=>{"use strict";h()});var Rie=L(()=>{"use strict";h()});var Tie=L(()=>{"use strict";h()});var fa,NL,
|
|
1519
|
+
`,e}var o6e,Fie=L(()=>{"use strict";h();o6e="This is a report from a background worker, NOT a user message. Review the results and take appropriate action (e.g., send findings to the user, update memory)."});var kie=L(()=>{"use strict";h()});var Rie=L(()=>{"use strict";h()});var Tie=L(()=>{"use strict";h()});var fa,NL,XHt,ZHt,Nie=L(()=>{"use strict";h();fa=require("zod"),NL=/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\.git)?\/?$/,XHt=2*1024*1024*1024,ZHt=fa.z.object({projectName:fa.z.string().trim().min(1).max(200).optional(),devToolsVersion:fa.z.string().trim().min(1).max(64).optional(),selection:fa.z.preprocess(t=>{if(typeof t!="string")return t;let e=t.trim();if(e)try{return JSON.parse(e)}catch{return t}},fa.z.record(fa.z.string(),fa.z.array(fa.z.string().min(1)).max(1e4))).optional(),githubRepoUrl:fa.z.string().trim().regex(NL,"must be a public github.com repo URL").optional(),connectedProjectId:fa.z.string().trim().min(1).max(128).optional()})});function Ks(t){let e=t.code;return e?Jie.has(e)?"dns_resolution_failed":e==="ECONNREFUSED"?"tcp_connection_refused":e==="ECONNRESET"||e==="EPIPE"?"tcp_connection_reset":Kie.has(e)?"tcp_connection_timeout":e==="ENETUNREACH"||e==="ENETDOWN"?"tcp_network_unreachable":e==="EHOSTUNREACH"?"tcp_host_unreachable":Mie.has(e)?"tls_self_signed_cert":Pie.has(e)?"tls_cert_expired":Lie.has(e)?"tls_cert_not_yet_valid":Uie.has(e)?"tls_cert_hostname_mismatch":_ie.has(e)?"tls_cert_invalid":Oie.has(e)?"tls_handshake_failed":Gie.has(e)?"tls_protocol_error":Hie.has(e)?"proxy_tunnel_failed":"unknown_error":"unknown_error"}function ML(t){if(t.cause&&"code"in t.cause)return Ks(t.cause);let e=t.message.toLowerCase();return e.includes("failed to fetch")||e.includes("network")?"tcp_connection_refused":e.includes("timeout")||e.includes("timed out")?"tcp_connection_timeout":e.includes("dns")||e.includes("not found")?"dns_resolution_failed":e.includes("certificate")||e.includes("ssl")?e.includes("expired")?"tls_cert_expired":e.includes("self-signed")||e.includes("self signed")?"tls_self_signed_cert":"tls_cert_invalid":"unknown_error"}function i0(t){if(!t)return;if(["tcp_connection_timeout","tcp_host_unreachable","tcp_network_unreachable"].includes(t))return"ip_whitelisting_required";if(["dns_resolution_failed","dns_timeout","dns_wrong_ip"].includes(t))return"dns_misconfiguration";if(["tls_self_signed_cert","tls_cert_expired","tls_cert_not_yet_valid","tls_cert_invalid","tls_cert_hostname_mismatch","tls_handshake_failed","tls_protocol_error"].includes(t))return"self_signed_certificate";if(["tcp_connection_refused","tcp_connection_reset"].includes(t))return"firewall_blocking";if(["proxy_auth_required","proxy_connection_failed","proxy_tunnel_failed"].includes(t))return"corporate_proxy_required";if(t==="http_service_unavailable"||t==="http_server_error")return"server_unavailable"}function s0(t){let e=t.toLowerCase();return e.includes("dns resolution failed")||e.includes("dns resolution")||e.includes("no addresses found")?{connectivityErrorCode:"dns_resolution_failed",checkType:"dns"}:e.includes("connection attempt failed")||e.includes("connection timed out")||e.includes("connection timeout")||e.includes("etimedout")||e.includes("timed out")?{connectivityErrorCode:"tcp_connection_timeout",checkType:"tcp"}:e.includes("econnrefused")||e.includes("connection refused")?{connectivityErrorCode:"tcp_connection_refused",checkType:"tcp"}:e.includes("enotfound")||e.includes("getaddrinfo")||e.includes("eai_again")||e.includes("enodata")?{connectivityErrorCode:"dns_resolution_failed",checkType:"dns"}:e.includes("network unreachable")?{connectivityErrorCode:"tcp_network_unreachable",checkType:"tcp"}:null}var Mie,Pie,Lie,_ie,Uie,Gie,Oie,Kie,Hie,Jie,Hu=L(()=>{"use strict";h();Mie=new Set(["DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN"]),Pie=new Set(["CERT_HAS_EXPIRED","ERROR_IN_CERT_NOT_AFTER_FIELD"]),Lie=new Set(["CERT_NOT_YET_VALID","ERROR_IN_CERT_NOT_BEFORE_FIELD"]),_ie=new Set(["UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","INVALID_CA","CERT_SIGNATURE_FAILURE","CERT_REVOKED","CERT_REJECTED","CERT_UNTRUSTED","CERT_CHAIN_TOO_LONG","PATH_LENGTH_EXCEEDED","INVALID_PURPOSE","UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY","UNABLE_TO_DECRYPT_CERT_SIGNATURE"]),Uie=new Set(["HOSTNAME_MISMATCH","ERR_TLS_CERT_ALTNAME_INVALID"]),Gie=new Set(["ERR_TLS_INVALID_PROTOCOL_VERSION","ERR_TLS_INVALID_PROTOCOL_METHOD","ERR_TLS_PROTOCOL_VERSION_CONFLICT","ERR_TLS_INVALID_STATE","ERR_TLS_INVALID_CONTEXT","ERR_TLS_RENEGOTIATION_DISABLED","ERR_TLS_REQUIRED_SERVER_NAME","ERR_TLS_SESSION_ATTACK","ERR_TLS_SNI_FROM_SERVER","ERR_TLS_DH_PARAM_SIZE","ERR_SSL_WRONG_VERSION_NUMBER","EPROTO"]),Oie=new Set(["ERR_TLS_HANDSHAKE_TIMEOUT","ERR_SSL_HANDSHAKE_FAILURE"]),Kie=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_SOCKET_CONNECTION_TIMEOUT","ERR_HTTP_REQUEST_TIMEOUT"]),Hie=new Set(["ERR_PROXY_INVALID_CONFIG","ERR_PROXY_TUNNEL","ERR_TUNNEL_CONNECTION_FAILED"]),Jie=new Set(["ENOTFOUND","EAI_AGAIN","ENODATA"])});var Hs=L(()=>{"use strict";h();zne();Xne();iie();wL();oie();bL();Zw();Cie();Iie();Eie();Qie();Die();wie();bie();vie();Fie();kie();Rie();Tie();Nie();Hu()});function jie({devServerUrl:t,proxyOrigin:e,proxyDefaultOrigin:r,proxyDestination:n}){let i;if(t)try{i=new URL(t)}catch{}return!e&&i&&(CA(i.hostname)?(e=`${i.protocol}//${i.hostname}:*`,r=i.origin):(e=i.origin,r=i.origin)),!r&&e&&(e.includes("*")||!e.startsWith("https://")&&!e.startsWith("http://")||(r=e)),{proxyOrigin:e,proxyDefaultOrigin:r,proxyDestination:n}}function CA(t){let e=typeof t=="string"?t:t.hostname;return e=e.replace(/^\[|\]$/g,""),e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}var pI=L(()=>{"use strict";h()});function Yie(){let t=process.env.FUSION_IDE_PORT;if(!t)return null;let e=Number(t);return Number.isFinite(e)&&e>0?e:null}async function qie(){let t=Yie();if(!t)return null;try{let e=await fetch(`http://127.0.0.1:${t}/context`,{signal:AbortSignal.timeout(300)});return e.ok?await e.json():null}catch{return null}}async function $ie(t){let e=Yie();if(!e)return null;try{let r=new URL(`http://127.0.0.1:${e}/diagnostics`);t&&r.searchParams.set("file",t);let n=await fetch(r.toString(),{signal:AbortSignal.timeout(500)});return n.ok?await n.json():null}catch{return null}}function Vie(t){let e=[];if(t.file){let r=t.line!=null?`:${t.line+1}`:"";e.push(`Active file: ${t.file}${r}`)}return t.selection&&e.push(`Selected text:
|
|
1520
1520
|
${t.selection}`),e.join(`
|
|
1521
1521
|
`)}function Wie(t){let{diagnostics:e}=t;if(e.length===0)return"No diagnostics found.";let r=[`IDE diagnostics (${e.length}):`];for(let n of e.slice(0,50)){let i=n.source?` (${n.source})`:"";r.push(` [${n.severity}] ${n.file}:${n.line+1}: ${n.message}${i}`)}return e.length>50&&r.push(` \u2026 and ${e.length-50} more`),r.join(`
|
|
1522
1522
|
`)}var PL=L(()=>{"use strict";h()});function dI(t){let r="^"+t.replace(/([.+^=!:${}()|[\]\\\/^])/g,"\\$1").replace(/\*/g,".*").replace(/\?/g,".")+"$";return new RegExp(r)}function LL(t){let e=t.match(/^timeout\s+(\d+[smhd]?)\s+(.+)$/i);return e?e[2]:t}function fI(t){let e=[],r="",n=!1,i="";for(let s=0;s<t.length;s++){let o=t[s],a=t[s+1];if(!n&&(o==='"'||o==="'")){let A=0;for(let c=s-1;c>=0&&t[c]==="\\";c--)A++;A%2===0&&(n=!0,i=o),r+=o}else if(n&&o===i){let A=0;for(let c=s-1;c>=0&&t[c]==="\\";c--)A++;A%2===0&&(n=!1,i=""),r+=o}else n?r+=o:o==="&"&&a==="&"||o==="|"&&a==="|"?(e.push(r.trim()),r="",s++):o===";"||o==="|"?(e.push(r.trim()),r=""):r+=o}return r.trim()&&e.push(r.trim()),e.filter(Boolean)}function Xie(t){let e=LL(t);return fI(e).some(n=>{let i=n.trim();for(;/^\w+=\S*\s/.test(i);)i=i.replace(/^\w+=\S*\s+/,"");let s=i.split(/\s/)[0],o=s.includes("/")?s.split("/").pop():s;return!a6e.has(o)})}function hI(t,e={policies:zie}){let r=LL(t);if(/`|\$\(/.test(r))return{policy:"injection_prevention",message:"Command substitution and backticks are prohibited to prevent injection attacks.",command:r};let n=[...e.policies].sort((a,A)=>A.priority-a.priority),i=(a,A)=>{for(let c of n){let u=c.patterns.map(l=>typeof l=="string"?dI(l):l);for(let l of u)if(l.test(a)){if(e.allowOverrides&&e.allowOverrides.map(p=>typeof p=="string"?dI(p):p).some(p=>p.test(a)))continue;return{policy:c.name,message:c.errorMessage,command:a,matchedPattern:l.source}}}return null},s=i(r,!0);if(s)return s;let o=fI(r);for(let a of o){let A=i(a,!1);if(A)return A}return null}function o0(t,e=[],r=[],n){let i=LL(t);if(n&&hI(i,n)||/`|\$\(/.test(i))return!1;let s=Array.isArray(e)&&e.length>0?typeof e[0]=="string"?e.map(dI):e:[],o=Array.isArray(r)&&r.length>0?typeof r[0]=="string"?r.map(dI):r:[];return fI(i).every(A=>o.some(u=>u.test(A))?s.some(u=>u.test(A)):s.length>0?s.some(u=>u.test(A)):!0)}function a0(t={}){return{policies:zie,...t}}function A0(t){return t.map(dI)}var zie,a6e,mI=L(()=>{"use strict";h();zie=[{name:"git_project_creation",description:"Prevents git operations that could cause permanent data loss",patterns:[/\bgit\s+clone\b/,/\bgit\s+checkout\s+-b\s+\S+/,/\bgit\s+switch\s+\S+/,/\bgit\s+branch\s+(?!-[dlDrav])(?!--(?:all|list|remote|verbose)\b)\S/,/\bgit\s+init\b/,/\bgit\s+remote\b/,/\bgit\s+clean\s+-[fF]/,/\bgit\s+commit\s+--amend/,/\bgit\s+rm\b/,/\bgit\s+mv\b/,/\bgit\s+tag\b/,/\bgit\s+restore\s+(?!--staged\b)(?!--source\b)(?!--\s)\S+\s*$/,/\bgit\s+reset\s+--hard/,/\bgit\s+reset\s+--mixed/,/\bgit\s+stash\s+drop/,/\bgit\s+stash\s+clear/],errorMessage:"Git operations that could cause permanent data loss are not supported. This includes branch switching, creating new branches, cloning repositories, or destructive operations. File-specific operations like 'git checkout -- file.json' or 'git checkout --ours file.json' are allowed for merge conflict resolution.",priority:95},{name:"git_operations",description:"Prevents direct .git directory manipulation",patterns:[/\.git\b/,/\/\.git\//,/\\\.git\\/,/\.git\//,/\.git$/],errorMessage:"Direct .git operations are prohibited for security reasons. Use proper git commands instead of manipulating .git directly.",priority:100},{name:"system_files",description:"Prevents access to critical system files",patterns:[/\/etc\/passwd/,/\/etc\/shadow/,/\/etc\/sudoers/,/\/proc\/self/,/\/sys\//,/\bsudo\s/,/\bsu\s+(root|admin)/],errorMessage:"Access to system files is prohibited for security reasons.",priority:90},{name:"network_commands",description:"Prevents potentially dangerous network operations",patterns:[/\bnc\s.*-e/,/\btelnet\b/,/\bftp\b.*<<</,/\bcurl\s+.*\|\s*(sh|bash)/,/\bwget\s+.*\|\s*(sh|bash)/],errorMessage:"Potentially dangerous network operations are restricted.",priority:80},{name:"file_permissions",description:"Prevents dangerous file permission changes",patterns:[/\bchmod\s+(777|755).*\/$/,/\bchown\s+root/,/\bchgrp\s+root/,/\bchmod\s+.*[+]s/,/\bchmod\s+777\s+\/etc/,/\bchmod\s+777\s+\/$/],errorMessage:"Dangerous file permission operations are prohibited.",priority:70},{name:"environment_manipulation",description:"Prevents dangerous environment variable manipulation",patterns:[/export\s+PATH=.*:/,/export\s+LD_LIBRARY_PATH/,/export\s+LD_PRELOAD/,/\$\{IFS\}/],errorMessage:"Environment variable manipulation that could compromise security is not allowed.",priority:60},{name:"code_execution",description:"Prevents various code execution patterns",patterns:[/\beval\s+/,/\bexec\s+\/bin\/(sh|bash)/,/\bsource\s+\/dev/,/\.\s+\/dev/,/\.\s+\/proc/,/\bdd\s+.*of=.*\|/],errorMessage:"Arbitrary code execution patterns are prohibited.",priority:50},{name:"data_exfiltration",description:"Prevents potential data exfiltration",patterns:[/\btar\s+.*\|.*nc\b/,/\bcat\s+.*\|.*curl\b/,/\bfind\s+.*-exec.*\|/,/\bbase64\s+.*\|.*curl/,/\btar\s+czf\s+-.*\|\s*nc/,/\bfind\s+\/.*-name.*\+.*\|\s*base64/,/\bcat\s+\/etc\/passwd\s*\|/],errorMessage:"Commands that could be used for data exfiltration are blocked.",priority:40},{name:"virtual_files_access",description:"Prevents Bash commands from referencing virtual file paths that only exist in the LLM context",patterns:[/\bdesign-system-docs\b/],errorMessage:"The 'design-system-docs/' directory is a virtual path that does not exist on the filesystem. These files are only accessible through the Read, Glob, and Grep tools. Do not use Bash commands (like cat, ls, cd, find, etc.) to access them.",priority:35}];a6e=new Set(["echo","cd","find","ls","rm","cp","mv","git","gh","rg","pwd","head","lsof","kill","ps","tr","awk","cat","grep","sed","tail","touch","mkdir","env","printenv","sleep","export","wc","curl","which","whoami","uname","date","dirname","basename","realpath","readlink","stat","file","diff","sort","uniq","tee","xargs","chmod","chown","test","true","false","builderio"])});async function A6e(t){return(await _L).getRandomValues(new Uint8Array(t))}async function c6e(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let i=await A6e(t-n.length);for(let s of i)s<r&&(n+=e[s%e.length])}return n}async function u6e(t){return await c6e(t)}async function l6e(t){let e=await(await _L).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function UL(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await u6e(t),r=await l6e(e);return{code_verifier:e,code_challenge:r}}var _L,Zie=L(()=>{h();_L=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto)});var T,Ju,u0,ju,l0,Ai,ese,tse,MJt,g6e,p6e,OL,Js,CI,rse,ci,fo,ho,ui,g0,nse,II,ise,sse,KL,Gg,Xe,HL,ose,Yu,PJt,Ec,d6e,p0,f6e,EI,Df,ase,h6e,m6e,C6e,I6e,E6e,B6e,JL,y6e,jL,d0,Ase,f0,Q6e,D6e,h0,w6e,BI,yI,b6e,QI,Bc,v6e,DI,m0,C0,I0,LJt,E0,B0,y0,cse,use,lse,YL,gse,wI,wf,pse,S6e,qL,$L,VL,WL,zL,x6e,XL,ZL,e_,F6e,k6e,R6e,T6e,N6e,M6e,P6e,L6e,_6e,t_,U6e,G6e,r_,n_,i_,O6e,K6e,H6e,s_,J6e,o_,a_,j6e,Y6e,dse,A_,c_,qu,_Jt,q6e,bI,u_,fse,vI,$6e,l_,V6e,W6e,z6e,X6e,Z6e,eqe,tqe,c0,rqe,nqe,g_,Og,SI,iqe,sqe,oqe,aqe,Aqe,cqe,uqe,lqe,gqe,pqe,dqe,fqe,hqe,mqe,Cqe,p_,Iqe,Eqe,$u,Bqe,yqe,Qqe,Dqe,d_,wqe,bqe,f_,vqe,UJt,GJt,OJt,KJt,HJt,JJt,He,GL,ha=L(()=>{h();T=z(require("zod/v4"),1),Ju="2025-11-25",u0=[Ju,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ju="io.modelcontextprotocol/related-task",l0="2.0",Ai=T.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ese=T.union([T.string(),T.number().int()]),tse=T.string(),MJt=T.looseObject({ttl:T.union([T.number(),T.null()]).optional(),pollInterval:T.number().optional()}),g6e=T.object({ttl:T.number().optional()}),p6e=T.object({taskId:T.string()}),OL=T.looseObject({progressToken:ese.optional(),[ju]:p6e.optional()}),Js=T.object({_meta:OL.optional()}),CI=Js.extend({task:g6e.optional()}),rse=t=>CI.safeParse(t).success,ci=T.object({method:T.string(),params:Js.loose().optional()}),fo=T.object({_meta:OL.optional()}),ho=T.object({method:T.string(),params:fo.loose().optional()}),ui=T.looseObject({_meta:OL.optional()}),g0=T.union([T.string(),T.number().int()]),nse=T.object({jsonrpc:T.literal(l0),id:g0,...ci.shape}).strict(),II=t=>nse.safeParse(t).success,ise=T.object({jsonrpc:T.literal(l0),...ho.shape}).strict(),sse=t=>ise.safeParse(t).success,KL=T.object({jsonrpc:T.literal(l0),id:g0,result:ui}).strict(),Gg=t=>KL.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Xe||(Xe={}));HL=T.object({jsonrpc:T.literal(l0),id:g0.optional(),error:T.object({code:T.number().int(),message:T.string(),data:T.unknown().optional()})}).strict(),ose=t=>HL.safeParse(t).success,Yu=T.union([nse,ise,KL,HL]),PJt=T.union([KL,HL]),Ec=ui.strict(),d6e=fo.extend({requestId:g0.optional(),reason:T.string().optional()}),p0=ho.extend({method:T.literal("notifications/cancelled"),params:d6e}),f6e=T.object({src:T.string(),mimeType:T.string().optional(),sizes:T.array(T.string()).optional(),theme:T.enum(["light","dark"]).optional()}),EI=T.object({icons:T.array(f6e).optional()}),Df=T.object({name:T.string(),title:T.string().optional()}),ase=Df.extend({...Df.shape,...EI.shape,version:T.string(),websiteUrl:T.string().optional(),description:T.string().optional()}),h6e=T.intersection(T.object({applyDefaults:T.boolean().optional()}),T.record(T.string(),T.unknown())),m6e=T.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,T.intersection(T.object({form:h6e.optional(),url:Ai.optional()}),T.record(T.string(),T.unknown()).optional())),C6e=T.looseObject({list:Ai.optional(),cancel:Ai.optional(),requests:T.looseObject({sampling:T.looseObject({createMessage:Ai.optional()}).optional(),elicitation:T.looseObject({create:Ai.optional()}).optional()}).optional()}),I6e=T.looseObject({list:Ai.optional(),cancel:Ai.optional(),requests:T.looseObject({tools:T.looseObject({call:Ai.optional()}).optional()}).optional()}),E6e=T.object({experimental:T.record(T.string(),Ai).optional(),sampling:T.object({context:Ai.optional(),tools:Ai.optional()}).optional(),elicitation:m6e.optional(),roots:T.object({listChanged:T.boolean().optional()}).optional(),tasks:C6e.optional()}),B6e=Js.extend({protocolVersion:T.string(),capabilities:E6e,clientInfo:ase}),JL=ci.extend({method:T.literal("initialize"),params:B6e}),y6e=T.object({experimental:T.record(T.string(),Ai).optional(),logging:Ai.optional(),completions:Ai.optional(),prompts:T.object({listChanged:T.boolean().optional()}).optional(),resources:T.object({subscribe:T.boolean().optional(),listChanged:T.boolean().optional()}).optional(),tools:T.object({listChanged:T.boolean().optional()}).optional(),tasks:I6e.optional()}),jL=ui.extend({protocolVersion:T.string(),capabilities:y6e,serverInfo:ase,instructions:T.string().optional()}),d0=ho.extend({method:T.literal("notifications/initialized"),params:fo.optional()}),Ase=t=>d0.safeParse(t).success,f0=ci.extend({method:T.literal("ping"),params:Js.optional()}),Q6e=T.object({progress:T.number(),total:T.optional(T.number()),message:T.optional(T.string())}),D6e=T.object({...fo.shape,...Q6e.shape,progressToken:ese}),h0=ho.extend({method:T.literal("notifications/progress"),params:D6e}),w6e=Js.extend({cursor:tse.optional()}),BI=ci.extend({params:w6e.optional()}),yI=ui.extend({nextCursor:tse.optional()}),b6e=T.enum(["working","input_required","completed","failed","cancelled"]),QI=T.object({taskId:T.string(),status:b6e,ttl:T.union([T.number(),T.null()]),createdAt:T.string(),lastUpdatedAt:T.string(),pollInterval:T.optional(T.number()),statusMessage:T.optional(T.string())}),Bc=ui.extend({task:QI}),v6e=fo.merge(QI),DI=ho.extend({method:T.literal("notifications/tasks/status"),params:v6e}),m0=ci.extend({method:T.literal("tasks/get"),params:Js.extend({taskId:T.string()})}),C0=ui.merge(QI),I0=ci.extend({method:T.literal("tasks/result"),params:Js.extend({taskId:T.string()})}),LJt=ui.loose(),E0=BI.extend({method:T.literal("tasks/list")}),B0=yI.extend({tasks:T.array(QI)}),y0=ci.extend({method:T.literal("tasks/cancel"),params:Js.extend({taskId:T.string()})}),cse=ui.merge(QI),use=T.object({uri:T.string(),mimeType:T.optional(T.string()),_meta:T.record(T.string(),T.unknown()).optional()}),lse=use.extend({text:T.string()}),YL=T.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),gse=use.extend({blob:YL}),wI=T.enum(["user","assistant"]),wf=T.object({audience:T.array(wI).optional(),priority:T.number().min(0).max(1).optional(),lastModified:T.iso.datetime({offset:!0}).optional()}),pse=T.object({...Df.shape,...EI.shape,uri:T.string(),description:T.optional(T.string()),mimeType:T.optional(T.string()),annotations:wf.optional(),_meta:T.optional(T.looseObject({}))}),S6e=T.object({...Df.shape,...EI.shape,uriTemplate:T.string(),description:T.optional(T.string()),mimeType:T.optional(T.string()),annotations:wf.optional(),_meta:T.optional(T.looseObject({}))}),qL=BI.extend({method:T.literal("resources/list")}),$L=yI.extend({resources:T.array(pse)}),VL=BI.extend({method:T.literal("resources/templates/list")}),WL=yI.extend({resourceTemplates:T.array(S6e)}),zL=Js.extend({uri:T.string()}),x6e=zL,XL=ci.extend({method:T.literal("resources/read"),params:x6e}),ZL=ui.extend({contents:T.array(T.union([lse,gse]))}),e_=ho.extend({method:T.literal("notifications/resources/list_changed"),params:fo.optional()}),F6e=zL,k6e=ci.extend({method:T.literal("resources/subscribe"),params:F6e}),R6e=zL,T6e=ci.extend({method:T.literal("resources/unsubscribe"),params:R6e}),N6e=fo.extend({uri:T.string()}),M6e=ho.extend({method:T.literal("notifications/resources/updated"),params:N6e}),P6e=T.object({name:T.string(),description:T.optional(T.string()),required:T.optional(T.boolean())}),L6e=T.object({...Df.shape,...EI.shape,description:T.optional(T.string()),arguments:T.optional(T.array(P6e)),_meta:T.optional(T.looseObject({}))}),_6e=BI.extend({method:T.literal("prompts/list")}),t_=yI.extend({prompts:T.array(L6e)}),U6e=Js.extend({name:T.string(),arguments:T.record(T.string(),T.string()).optional()}),G6e=ci.extend({method:T.literal("prompts/get"),params:U6e}),r_=T.object({type:T.literal("text"),text:T.string(),annotations:wf.optional(),_meta:T.record(T.string(),T.unknown()).optional()}),n_=T.object({type:T.literal("image"),data:YL,mimeType:T.string(),annotations:wf.optional(),_meta:T.record(T.string(),T.unknown()).optional()}),i_=T.object({type:T.literal("audio"),data:YL,mimeType:T.string(),annotations:wf.optional(),_meta:T.record(T.string(),T.unknown()).optional()}),O6e=T.object({type:T.literal("tool_use"),name:T.string(),id:T.string(),input:T.record(T.string(),T.unknown()),_meta:T.record(T.string(),T.unknown()).optional()}),K6e=T.object({type:T.literal("resource"),resource:T.union([lse,gse]),annotations:wf.optional(),_meta:T.record(T.string(),T.unknown()).optional()}),H6e=pse.extend({type:T.literal("resource_link")}),s_=T.union([r_,n_,i_,H6e,K6e]),J6e=T.object({role:wI,content:s_}),o_=ui.extend({description:T.string().optional(),messages:T.array(J6e)}),a_=ho.extend({method:T.literal("notifications/prompts/list_changed"),params:fo.optional()}),j6e=T.object({title:T.string().optional(),readOnlyHint:T.boolean().optional(),destructiveHint:T.boolean().optional(),idempotentHint:T.boolean().optional(),openWorldHint:T.boolean().optional()}),Y6e=T.object({taskSupport:T.enum(["required","optional","forbidden"]).optional()}),dse=T.object({...Df.shape,...EI.shape,description:T.string().optional(),inputSchema:T.object({type:T.literal("object"),properties:T.record(T.string(),Ai).optional(),required:T.array(T.string()).optional()}).catchall(T.unknown()),outputSchema:T.object({type:T.literal("object"),properties:T.record(T.string(),Ai).optional(),required:T.array(T.string()).optional()}).catchall(T.unknown()).optional(),annotations:j6e.optional(),execution:Y6e.optional(),_meta:T.record(T.string(),T.unknown()).optional()}),A_=BI.extend({method:T.literal("tools/list")}),c_=yI.extend({tools:T.array(dse)}),qu=ui.extend({content:T.array(s_).default([]),structuredContent:T.record(T.string(),T.unknown()).optional(),isError:T.boolean().optional()}),_Jt=qu.or(ui.extend({toolResult:T.unknown()})),q6e=CI.extend({name:T.string(),arguments:T.record(T.string(),T.unknown()).optional()}),bI=ci.extend({method:T.literal("tools/call"),params:q6e}),u_=ho.extend({method:T.literal("notifications/tools/list_changed"),params:fo.optional()}),fse=T.object({autoRefresh:T.boolean().default(!0),debounceMs:T.number().int().nonnegative().default(300)}),vI=T.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),$6e=Js.extend({level:vI}),l_=ci.extend({method:T.literal("logging/setLevel"),params:$6e}),V6e=fo.extend({level:vI,logger:T.string().optional(),data:T.unknown()}),W6e=ho.extend({method:T.literal("notifications/message"),params:V6e}),z6e=T.object({name:T.string().optional()}),X6e=T.object({hints:T.array(z6e).optional(),costPriority:T.number().min(0).max(1).optional(),speedPriority:T.number().min(0).max(1).optional(),intelligencePriority:T.number().min(0).max(1).optional()}),Z6e=T.object({mode:T.enum(["auto","required","none"]).optional()}),eqe=T.object({type:T.literal("tool_result"),toolUseId:T.string().describe("The unique identifier for the corresponding tool call."),content:T.array(s_).default([]),structuredContent:T.object({}).loose().optional(),isError:T.boolean().optional(),_meta:T.record(T.string(),T.unknown()).optional()}),tqe=T.discriminatedUnion("type",[r_,n_,i_]),c0=T.discriminatedUnion("type",[r_,n_,i_,O6e,eqe]),rqe=T.object({role:wI,content:T.union([c0,T.array(c0)]),_meta:T.record(T.string(),T.unknown()).optional()}),nqe=CI.extend({messages:T.array(rqe),modelPreferences:X6e.optional(),systemPrompt:T.string().optional(),includeContext:T.enum(["none","thisServer","allServers"]).optional(),temperature:T.number().optional(),maxTokens:T.number().int(),stopSequences:T.array(T.string()).optional(),metadata:Ai.optional(),tools:T.array(dse).optional(),toolChoice:Z6e.optional()}),g_=ci.extend({method:T.literal("sampling/createMessage"),params:nqe}),Og=ui.extend({model:T.string(),stopReason:T.optional(T.enum(["endTurn","stopSequence","maxTokens"]).or(T.string())),role:wI,content:tqe}),SI=ui.extend({model:T.string(),stopReason:T.optional(T.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(T.string())),role:wI,content:T.union([c0,T.array(c0)])}),iqe=T.object({type:T.literal("boolean"),title:T.string().optional(),description:T.string().optional(),default:T.boolean().optional()}),sqe=T.object({type:T.literal("string"),title:T.string().optional(),description:T.string().optional(),minLength:T.number().optional(),maxLength:T.number().optional(),format:T.enum(["email","uri","date","date-time"]).optional(),default:T.string().optional()}),oqe=T.object({type:T.enum(["number","integer"]),title:T.string().optional(),description:T.string().optional(),minimum:T.number().optional(),maximum:T.number().optional(),default:T.number().optional()}),aqe=T.object({type:T.literal("string"),title:T.string().optional(),description:T.string().optional(),enum:T.array(T.string()),default:T.string().optional()}),Aqe=T.object({type:T.literal("string"),title:T.string().optional(),description:T.string().optional(),oneOf:T.array(T.object({const:T.string(),title:T.string()})),default:T.string().optional()}),cqe=T.object({type:T.literal("string"),title:T.string().optional(),description:T.string().optional(),enum:T.array(T.string()),enumNames:T.array(T.string()).optional(),default:T.string().optional()}),uqe=T.union([aqe,Aqe]),lqe=T.object({type:T.literal("array"),title:T.string().optional(),description:T.string().optional(),minItems:T.number().optional(),maxItems:T.number().optional(),items:T.object({type:T.literal("string"),enum:T.array(T.string())}),default:T.array(T.string()).optional()}),gqe=T.object({type:T.literal("array"),title:T.string().optional(),description:T.string().optional(),minItems:T.number().optional(),maxItems:T.number().optional(),items:T.object({anyOf:T.array(T.object({const:T.string(),title:T.string()}))}),default:T.array(T.string()).optional()}),pqe=T.union([lqe,gqe]),dqe=T.union([cqe,uqe,pqe]),fqe=T.union([dqe,iqe,sqe,oqe]),hqe=CI.extend({mode:T.literal("form").optional(),message:T.string(),requestedSchema:T.object({type:T.literal("object"),properties:T.record(T.string(),fqe),required:T.array(T.string()).optional()})}),mqe=CI.extend({mode:T.literal("url"),message:T.string(),elicitationId:T.string(),url:T.string().url()}),Cqe=T.union([hqe,mqe]),p_=ci.extend({method:T.literal("elicitation/create"),params:Cqe}),Iqe=fo.extend({elicitationId:T.string()}),Eqe=ho.extend({method:T.literal("notifications/elicitation/complete"),params:Iqe}),$u=ui.extend({action:T.enum(["accept","decline","cancel"]),content:T.preprocess(t=>t===null?void 0:t,T.record(T.string(),T.union([T.string(),T.number(),T.boolean(),T.array(T.string())])).optional())}),Bqe=T.object({type:T.literal("ref/resource"),uri:T.string()}),yqe=T.object({type:T.literal("ref/prompt"),name:T.string()}),Qqe=Js.extend({ref:T.union([yqe,Bqe]),argument:T.object({name:T.string(),value:T.string()}),context:T.object({arguments:T.record(T.string(),T.string()).optional()}).optional()}),Dqe=ci.extend({method:T.literal("completion/complete"),params:Qqe}),d_=ui.extend({completion:T.looseObject({values:T.array(T.string()).max(100),total:T.optional(T.number().int()),hasMore:T.optional(T.boolean())})}),wqe=T.object({uri:T.string().startsWith("file://"),name:T.string().optional(),_meta:T.record(T.string(),T.unknown()).optional()}),bqe=ci.extend({method:T.literal("roots/list"),params:Js.optional()}),f_=ui.extend({roots:T.array(wqe)}),vqe=ho.extend({method:T.literal("notifications/roots/list_changed"),params:fo.optional()}),UJt=T.union([f0,JL,Dqe,l_,G6e,_6e,qL,VL,XL,k6e,T6e,bI,A_,m0,I0,E0,y0]),GJt=T.union([p0,h0,d0,vqe,DI]),OJt=T.union([Ec,Og,SI,$u,f_,C0,B0,Bc]),KJt=T.union([f0,g_,p_,bqe,m0,I0,E0,y0]),HJt=T.union([p0,h0,W6e,M6e,e_,u_,a_,DI,Eqe]),JJt=T.union([Ec,jL,d_,o_,t_,$L,WL,ZL,qu,c_,C0,B0,Bc]),He=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Xe.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new GL(i.elicitations,r)}return new t(e,r,n)}},GL=class extends He{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Xe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});var Ae,li,mse,h_,Sqe,Cse,Ise,Ese,hse,xqe,Fqe,Bse,qJt,$Jt,m_=L(()=>{h();Ae=z(require("zod/v4"),1),li=Ae.url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Ae.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),Ae.NEVER}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),mse=Ae.looseObject({resource:Ae.string().url(),authorization_servers:Ae.array(li).optional(),jwks_uri:Ae.string().url().optional(),scopes_supported:Ae.array(Ae.string()).optional(),bearer_methods_supported:Ae.array(Ae.string()).optional(),resource_signing_alg_values_supported:Ae.array(Ae.string()).optional(),resource_name:Ae.string().optional(),resource_documentation:Ae.string().optional(),resource_policy_uri:Ae.string().url().optional(),resource_tos_uri:Ae.string().url().optional(),tls_client_certificate_bound_access_tokens:Ae.boolean().optional(),authorization_details_types_supported:Ae.array(Ae.string()).optional(),dpop_signing_alg_values_supported:Ae.array(Ae.string()).optional(),dpop_bound_access_tokens_required:Ae.boolean().optional()}),h_=Ae.looseObject({issuer:Ae.string(),authorization_endpoint:li,token_endpoint:li,registration_endpoint:li.optional(),scopes_supported:Ae.array(Ae.string()).optional(),response_types_supported:Ae.array(Ae.string()),response_modes_supported:Ae.array(Ae.string()).optional(),grant_types_supported:Ae.array(Ae.string()).optional(),token_endpoint_auth_methods_supported:Ae.array(Ae.string()).optional(),token_endpoint_auth_signing_alg_values_supported:Ae.array(Ae.string()).optional(),service_documentation:li.optional(),revocation_endpoint:li.optional(),revocation_endpoint_auth_methods_supported:Ae.array(Ae.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Ae.array(Ae.string()).optional(),introspection_endpoint:Ae.string().optional(),introspection_endpoint_auth_methods_supported:Ae.array(Ae.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Ae.array(Ae.string()).optional(),code_challenge_methods_supported:Ae.array(Ae.string()).optional(),client_id_metadata_document_supported:Ae.boolean().optional()}),Sqe=Ae.looseObject({issuer:Ae.string(),authorization_endpoint:li,token_endpoint:li,userinfo_endpoint:li.optional(),jwks_uri:li,registration_endpoint:li.optional(),scopes_supported:Ae.array(Ae.string()).optional(),response_types_supported:Ae.array(Ae.string()),response_modes_supported:Ae.array(Ae.string()).optional(),grant_types_supported:Ae.array(Ae.string()).optional(),acr_values_supported:Ae.array(Ae.string()).optional(),subject_types_supported:Ae.array(Ae.string()),id_token_signing_alg_values_supported:Ae.array(Ae.string()),id_token_encryption_alg_values_supported:Ae.array(Ae.string()).optional(),id_token_encryption_enc_values_supported:Ae.array(Ae.string()).optional(),userinfo_signing_alg_values_supported:Ae.array(Ae.string()).optional(),userinfo_encryption_alg_values_supported:Ae.array(Ae.string()).optional(),userinfo_encryption_enc_values_supported:Ae.array(Ae.string()).optional(),request_object_signing_alg_values_supported:Ae.array(Ae.string()).optional(),request_object_encryption_alg_values_supported:Ae.array(Ae.string()).optional(),request_object_encryption_enc_values_supported:Ae.array(Ae.string()).optional(),token_endpoint_auth_methods_supported:Ae.array(Ae.string()).optional(),token_endpoint_auth_signing_alg_values_supported:Ae.array(Ae.string()).optional(),display_values_supported:Ae.array(Ae.string()).optional(),claim_types_supported:Ae.array(Ae.string()).optional(),claims_supported:Ae.array(Ae.string()).optional(),service_documentation:Ae.string().optional(),claims_locales_supported:Ae.array(Ae.string()).optional(),ui_locales_supported:Ae.array(Ae.string()).optional(),claims_parameter_supported:Ae.boolean().optional(),request_parameter_supported:Ae.boolean().optional(),request_uri_parameter_supported:Ae.boolean().optional(),require_request_uri_registration:Ae.boolean().optional(),op_policy_uri:li.optional(),op_tos_uri:li.optional(),client_id_metadata_document_supported:Ae.boolean().optional()}),Cse=Ae.object({...Sqe.shape,...h_.pick({code_challenge_methods_supported:!0}).shape}),Ise=Ae.object({access_token:Ae.string(),id_token:Ae.string().optional(),token_type:Ae.string(),expires_in:Ae.coerce.number().optional(),scope:Ae.string().optional(),refresh_token:Ae.string().optional()}).strip(),Ese=Ae.object({error:Ae.string(),error_description:Ae.string().optional(),error_uri:Ae.string().optional()}),hse=li.optional().or(Ae.literal("").transform(()=>{})),xqe=Ae.object({redirect_uris:Ae.array(li),token_endpoint_auth_method:Ae.string().optional(),grant_types:Ae.array(Ae.string()).optional(),response_types:Ae.array(Ae.string()).optional(),client_name:Ae.string().optional(),client_uri:li.optional(),logo_uri:hse,scope:Ae.string().optional(),contacts:Ae.array(Ae.string()).optional(),tos_uri:hse,policy_uri:Ae.string().optional(),jwks_uri:li.optional(),jwks:Ae.any().optional(),software_id:Ae.string().optional(),software_version:Ae.string().optional(),software_statement:Ae.string().optional()}).strip(),Fqe=Ae.object({client_id:Ae.string(),client_secret:Ae.string().optional(),client_id_issued_at:Ae.number().optional(),client_secret_expires_at:Ae.number().optional()}).strip(),Bse=xqe.merge(Fqe),qJt=Ae.object({error:Ae.string(),error_description:Ae.string().optional()}).strip(),$Jt=Ae.object({token:Ae.string(),token_type_hint:Ae.string().optional()}).strip()});function yse(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Qse({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(s)}var Dse=L(()=>{h()});var un,xI,IA,yc,EA,FI,kI,Kg,Qc,RI,TI,NI,Hg,MI,PI,Jg,LI,_I,wse,C_=L(()=>{h();un=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},xI=class extends un{};xI.errorCode="invalid_request";IA=class extends un{};IA.errorCode="invalid_client";yc=class extends un{};yc.errorCode="invalid_grant";EA=class extends un{};EA.errorCode="unauthorized_client";FI=class extends un{};FI.errorCode="unsupported_grant_type";kI=class extends un{};kI.errorCode="invalid_scope";Kg=class extends un{};Kg.errorCode="access_denied";Qc=class extends un{};Qc.errorCode="server_error";RI=class extends un{};RI.errorCode="temporarily_unavailable";TI=class extends un{};TI.errorCode="unsupported_response_type";NI=class extends un{};NI.errorCode="unsupported_token_type";Hg=class extends un{};Hg.errorCode="invalid_token";MI=class extends un{};MI.errorCode="method_not_allowed";PI=class extends un{};PI.errorCode="too_many_requests";Jg=class extends un{};Jg.errorCode="invalid_client_metadata";LI=class extends un{};LI.errorCode="insufficient_scope";_I=class extends un{};_I.errorCode="invalid_target";wse={[xI.errorCode]:xI,[IA.errorCode]:IA,[yc.errorCode]:yc,[EA.errorCode]:EA,[FI.errorCode]:FI,[kI.errorCode]:kI,[Kg.errorCode]:Kg,[Qc.errorCode]:Qc,[RI.errorCode]:RI,[TI.errorCode]:TI,[NI.errorCode]:NI,[Hg.errorCode]:Hg,[MI.errorCode]:MI,[PI.errorCode]:PI,[Jg.errorCode]:Jg,[LI.errorCode]:LI,[_I.errorCode]:_I}});function kqe(t){return["client_secret_basic","client_secret_post","none"].includes(t)}function Rqe(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&kqe(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Tqe(t,e,r,n){let{client_id:i,client_secret:s}=e;switch(t){case"client_secret_basic":Nqe(i,s,r);return;case"client_secret_post":Mqe(i,s,n);return;case"none":Pqe(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Nqe(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Mqe(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Pqe(t,e){e.set("client_id",t)}async function vse(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Ese.parse(JSON.parse(r)),{error:i,error_description:s,error_uri:o}=n,a=wse[i]||Qc;return new a(s||"",o)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Qc(i)}}async function ma(t,e){try{return await B_(t,e)}catch(r){if(r instanceof IA||r instanceof EA)return await t.invalidateCredentials?.("all"),await B_(t,e);if(r instanceof yc)return await t.invalidateCredentials?.("tokens"),await B_(t,e);throw r}}async function B_(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:s}){let o=await t.discoveryState?.(),a,A,c,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(A=o.authorizationServerUrl,a=o.resourceMetadata,c=o.authorizationServerMetadata??await GI(A,{fetchFn:s}),!a)try{a=await UI(e,{resourceMetadataUrl:u},s)}catch{}(c!==o.authorizationServerMetadata||a!==o.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(A),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:c})}else{let I=await Hqe(e,{resourceMetadataUrl:u,fetchFn:s});A=I.authorizationServerUrl,c=I.authorizationServerMetadata,a=I.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(A),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:c})}let l=await _qe(e,t,a),d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let I=c?.client_id_metadata_document_supported===!0,y=t.clientMetadataUrl;if(y&&!Lqe(y))throw new Jg(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${y}`);if(I&&y)d={client_id:y},await t.saveClientInformation?.(d);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let E=await Yqe(A,{metadata:c,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(E),d=E}}let g=!t.redirectUrl;if(r!==void 0||g){let I=await jqe(t,A,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(I),"AUTHORIZED"}let p=await t.tokens();if(p?.refresh_token)try{let I=await w_(A,{metadata:c,clientInformation:d,refreshToken:p.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(I),"AUTHORIZED"}catch(I){if(!(!(I instanceof un)||I instanceof Qc))throw I}let f=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:C}=await Jqe(A,{metadata:c,clientInformation:d,state:f,redirectUrl:t.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(C),await t.redirectToAuthorization(m),"REDIRECT"}function Lqe(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function _qe(t,e,r){let n=yse(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Qse({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Vu(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let i=y_(t,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let o=y_(t,"scope")||void 0,a=y_(t,"error")||void 0;return{resourceMetadataUrl:s,scope:o,error:a}}function y_(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(n);return i?i[1]||i[2]:null}async function UI(t,e,r=fetch){let n=await Oqe(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return mse.parse(await n.json())}async function Q_(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Q_(t,void 0,r):void 0;throw n}}function Uqe(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function bse(t,e,r=fetch){return await Q_(t,{"MCP-Protocol-Version":e},r)}function Gqe(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Oqe(t,e,r,n){let i=new URL(t),s=n?.protocolVersion??Ju,o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{let A=Uqe(e,i.pathname);o=new URL(A,n?.metadataServerUrl??i),o.search=i.search}let a=await bse(o,s,r);if(!n?.metadataUrl&&Gqe(a,i.pathname)){let A=new URL(`/.well-known/${e}`,i);a=await bse(A,s,r)}return a}function Kqe(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function GI(t,{fetchFn:e=fetch,protocolVersion:r=Ju}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=Kqe(t);for(let{url:s,type:o}of i){let a=await Q_(s,n,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${o==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return o==="oauth"?h_.parse(await a.json()):Cse.parse(await a.json())}}}async function Hqe(t,e){let r,n;try{r=await UI(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));let i=await GI(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:i,resourceMetadata:r}}async function Jqe(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:s,resource:o}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(I_))throw new Error(`Incompatible auth server: does not support response type ${I_}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(E_))throw new Error(`Incompatible auth server: does not support code challenge method ${E_}`)}else a=new URL("/authorize",t);let A=await UL(),c=A.code_verifier,u=A.code_challenge;return a.searchParams.set("response_type",I_),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",E_),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),o&&a.searchParams.set("resource",o.href),{authorizationUrl:a,codeVerifier:c}}function Sse(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function D_(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:i,resource:s,fetchFn:o}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),A=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),i)await i(A,r,a,e);else if(n){let u=e?.token_endpoint_auth_methods_supported??[],l=Rqe(n,u);Tqe(l,n,A,r)}let c=await(o??fetch)(a,{method:"POST",headers:A,body:r});if(!c.ok)throw await vse(c);return Ise.parse(await c.json())}async function xse(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:s,resource:o,addClientAuthentication:a,fetchFn:A}){let c=Sse(n,i,s);return D_(t,{metadata:e,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:o,fetchFn:A})}async function w_(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:s,fetchFn:o}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),A=await D_(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:o});return{refresh_token:n,...A}}async function jqe(t,e,{metadata:r,resource:n,authorizationCode:i,fetchFn:s}={}){let o=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(o)),!a){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let c=await t.codeVerifier();a=Sse(i,c,t.redirectUrl)}let A=await t.clientInformation();return D_(e,{metadata:r,tokenRequestParams:a,clientInformation:A??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function Yqe(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let s=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await vse(s);return Bse.parse(await s.json())}var Rn,I_,E_,bf=L(()=>{h();Zie();ha();m_();m_();Dse();C_();Rn=class extends Error{constructor(e){super(e??"Unauthorized")}};I_="code",E_="S256"});function qqe(){return Fse.default.randomBytes(32).toString("base64url")}function b_(t,e=5){let r=e*60*1e3;return Date.now()>=t-r}function $qe(t){return t instanceof yc||t instanceof IA||t instanceof Hg||t instanceof Kg||t instanceof EA}function Vqe(t){return t instanceof IA||t instanceof EA}var Fse,Q0,v_=L(()=>{"use strict";h();Fse=z(require("node:crypto"),1);C_();bf();Q0=class{serverUrl;serverName;_clientMetadata;identity;store;redirect;onWarning;currentState=null;currentCodeVerifier=null;saveCodeVerifierCalled=!1;constructor(e){this.serverUrl=e.serverUrl,this.serverName=e.serverName,this._clientMetadata=e.clientMetadata,this.identity=e.identity,this.store=e.store,this.redirect=e.redirect,this.onWarning=e.onWarning}get redirectUrl(){return this.redirect.redirectUrl}get clientMetadata(){return this._clientMetadata}async discoverOAuthMetadata(e){let r=await this.store.getMetadata(),n=await this.store.isDiscoveryFailed(),i=!!(r?.clientId&&r.authorizationEndpoint&&r.tokenEndpoint);if(!e&&i)return!0;if(!e&&n)return!1;e&&n&&await this.store.invalidateCredentials("discovery");try{let s,o;try{let l=await UI(this.serverUrl);s=l.authorization_servers?.[0],o=l.resource}catch{}if(!s){let l=await this.probeWwwAuthenticate();if(l)try{let d=await UI(this.serverUrl,{resourceMetadataUrl:l});s=d.authorization_servers?.[0],o=d.resource}catch{}}let a=s||this.serverUrl,A=await GI(a);if(!A)try{let l=new URL(a);l.pathname&&l.pathname!=="/"&&l.origin!==a&&(A=await GI(l.origin))}catch{}if(!A)return await this.store.markDiscoveryFailed("No authorization server metadata found"),!1;let c=r?.clientId??"",u=r?.clientSecret;if(!c&&A.registration_endpoint)try{let l=await fetch(A.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(this._clientMetadata)});if(l.ok){let d=await l.json();c=d.client_id,u=d.client_secret}else this.warn("Dynamic client registration failed",void 0,{status:l.status})}catch(l){this.warn("Dynamic client registration threw",l)}return await this.store.saveMetadata({clientId:c,clientSecret:u,scope:[],authorizationEndpoint:A.authorization_endpoint,tokenEndpoint:A.token_endpoint,registrationEndpoint:A.registration_endpoint,resource:o,discoveredAt:Date.now()}),!0}catch(s){let o=s instanceof Error?s.message:"Discovery failed";return await this.store.markDiscoveryFailed(o),this.warn("OAuth discovery failed",s),!1}}async probeWwwAuthenticate(){let e=async i=>{try{let s=await fetch(this.serverUrl,i);return await s.body?.cancel().catch(()=>{}),s.status!==401?{reached:!0}:{reached:!0,url:Vu(s).resourceMetadataUrl}}catch{return{reached:!1}}},r=await e({method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-oauth-probe",version:"0.0.0"}}})});if(r.reached)return r.url;let n=await e({method:"GET"});return n.reached?n.url:void 0}async clientInformation(){let e=await this.store.getMetadata();if(e?.clientId)return{client_id:e.clientId,...e.clientSecret&&{client_secret:e.clientSecret}}}async saveClientInformation(e){let r=await this.store.getMetadata();if(!r){await this.store.saveMetadata({clientId:e.client_id,clientSecret:e.client_secret,scope:[],authorizationEndpoint:"",tokenEndpoint:"",discoveredAt:Date.now()});return}await this.store.saveMetadata({...r,clientId:e.client_id,clientSecret:e.client_secret})}async tokens(){let e=await this.store.getTokens();if(e?.accessToken){if(b_(e.expiresAt)){if(e.refreshToken)try{let r=await this.refreshTokens(e.refreshToken);if(r)return r}catch(r){this.warn("OAuth token refresh failed",r)}return}return{access_token:e.accessToken,token_type:e.tokenType||"Bearer",expires_in:Math.floor((e.expiresAt-Date.now())/1e3),...e.refreshToken&&{refresh_token:e.refreshToken}}}}async refreshTokens(e){let r=await this.clientInformation();if(!r)return;let n=await this.store.getMetadata(),i=n?.resource,s=n?.tokenEndpoint?n.tokenEndpoint.replace(/\/token$/,""):this.serverUrl,o;try{o=await w_(s,{...n?.tokenEndpoint&&{metadata:{authorization_endpoint:n.authorizationEndpoint,token_endpoint:n.tokenEndpoint}},clientInformation:r,refreshToken:e,...i&&{resource:new URL(i)}})}catch(a){if($qe(a)){let A=Vqe(a)?"all":"tokens";try{await this.invalidateCredentials(A)}catch(c){this.warn("Failed to invalidate credentials after permanent OAuth failure",c,{invalidationScope:A})}}throw a}return await this.saveTokens(o),o}async saveTokens(e){await this.persistTokens(e)}async persistTokens(e,r){let n=e.expires_in?Date.now()+e.expires_in*1e3:Date.now()+36e5;await this.store.saveTokens({accessToken:e.access_token,refreshToken:e.refresh_token||void 0,expiresAt:n,tokenType:e.token_type||"Bearer",...r?.clientId&&{clientId:r.clientId},...r?.clientSecret&&{clientSecret:r.clientSecret}})}async redirectToAuthorization(e){await this.redirect.onAuthorizationRequired(e)}async saveCodeVerifier(e){if(this.saveCodeVerifierCalled)return;if(this.saveCodeVerifierCalled=!0,this.currentCodeVerifier=e,!this.currentState){this.warn("No state available when saving code verifier",new Error("No state available when saving code verifier"));return}let r=await this.store.getMetadata();if(!r){this.warn("No metadata found when saving code verifier",new Error("No metadata found for server"));return}let n=Date.now(),i=n+1800*1e3;await this.store.saveOAuthState({state:this.currentState,codeVerifier:e,serverId:this.identity.serverId,ownerId:this.identity.ownerId,userId:this.identity.userId??null,sessionId:this.identity.sessionId,serverUrl:this.serverUrl,serverName:this.serverName,authorizationEndpoint:r.authorizationEndpoint,tokenEndpoint:r.tokenEndpoint,clientId:r.clientId,clientSecret:r.clientSecret,scope:r.scope||[],resource:r.resource,createdAt:n,expiresAt:i})}async codeVerifier(){if(!this.currentCodeVerifier)throw new Error("Code verifier not found");return this.currentCodeVerifier}async state(){return this.currentState||(this.currentState=qqe()),this.currentState}async invalidateCredentials(e="tokens"){await this.store.invalidateCredentials(e),(e==="verifier"||e==="all")&&(this.currentState=null,this.currentCodeVerifier=null,this.saveCodeVerifierCalled=!1)}async handleCallback(e,r){if(!r)throw new Error("Missing OAuth state parameter");let n=await this.store.consumeOAuthState(r);if(!n)throw new Error("Invalid or expired OAuth state");let i=n.tokenEndpoint.replace(/\/token$/,""),s=await xse(i,{metadata:{authorization_endpoint:n.authorizationEndpoint,token_endpoint:n.tokenEndpoint},clientInformation:{client_id:n.clientId,...n.clientSecret&&{client_secret:n.clientSecret}},authorizationCode:e,codeVerifier:n.codeVerifier,redirectUri:this.redirect.redirectUrl,...n.resource&&{resource:new URL(n.resource)}});return await this.persistTokens(s,{clientId:n.clientId,clientSecret:n.clientSecret}),s}warn(e,r,n){this.onWarning?.(e,r,{serverUrl:this.serverUrl,serverName:this.serverName,...n})}}});function Wqe(t){let e=process.env.BUILDER_DEV_TOOLS_CREDS_DIR;return e||t||(0,D0.join)((0,kse.homedir)(),".builder","config","mcp")}function Wu(t){if((0,Ca.existsSync)(t))try{let e=(0,Ca.readFileSync)(t,"utf8");return e.trim()?JSON.parse(e):void 0}catch{return}}function OI(t,e){let r=JSON.stringify(e,null,2);(0,Ca.writeFileSync)(t,r,{mode:384,encoding:"utf8"});try{(0,Ca.chmodSync)(t,384)}catch{}}function zqe(t){return!!t.oauthMetadata||!!t.discoveryFailed||!!t.discoveryError}var kse,D0,Ca,Dc,w0=L(()=>{"use strict";h();kse=require("node:os"),D0=require("node:path"),Ca=require("node:fs");Dc=class{serverUrl;dir;serversPath;tokensPath;pkceStates=new Map;constructor(e){this.serverUrl=e.serverUrl,this.dir=Wqe(e.baseDir),this.serversPath=(0,D0.join)(this.dir,"servers.json"),this.tokensPath=(0,D0.join)(this.dir,"tokens.json")}async getMetadata(){return Wu(this.serversPath)?.[this.serverUrl]?.oauthMetadata}async saveMetadata(e){this.ensureDir();let r=Wu(this.serversPath)??{},n=r[this.serverUrl]??{};r[this.serverUrl]={...n,oauthMetadata:e,discoveryFailed:!1,discoveryError:void 0},OI(this.serversPath,r)}async markDiscoveryFailed(e){this.ensureDir();let r=Wu(this.serversPath)??{},n=r[this.serverUrl]??{};r[this.serverUrl]={...n,discoveryFailed:!0,discoveryError:e},OI(this.serversPath,r)}async isDiscoveryFailed(){return!!Wu(this.serversPath)?.[this.serverUrl]?.discoveryFailed}async getTokens(){let r=Wu(this.tokensPath)?.[this.serverUrl];if(r)return{accessToken:r.accessToken,refreshToken:r.refreshToken||void 0,expiresAt:r.expiresAt,tokenType:r.tokenType||"Bearer"}}async saveTokens(e){this.ensureDir();let r=Wu(this.tokensPath)??{};r[this.serverUrl]={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,tokenType:e.tokenType||"Bearer",obtainedAt:Date.now(),obtainedFrom:"local"},OI(this.tokensPath,r)}async invalidateCredentials(e){(e==="tokens"||e==="all")&&this.removeTokenEntry(),(e==="client"||e==="all")&&this.updateServerEntry(r=>{let{oauthMetadata:n,...i}=r;return{...i,discoveryFailed:!1,discoveryError:void 0}}),(e==="discovery"||e==="all")&&this.updateServerEntry(r=>({...r,discoveryFailed:!1,discoveryError:void 0})),(e==="verifier"||e==="all")&&this.pkceStates.clear()}async saveOAuthState(e){this.pkceStates.set(e.state,e)}async consumeOAuthState(e){let r=this.pkceStates.get(e);if(r&&(this.pkceStates.delete(e),!(r.expiresAt<Date.now())))return r}ensureDir(){(0,Ca.existsSync)(this.dir)||(0,Ca.mkdirSync)(this.dir,{recursive:!0,mode:448})}removeTokenEntry(){let e=Wu(this.tokensPath);!e||!(this.serverUrl in e)||(delete e[this.serverUrl],this.ensureDir(),OI(this.tokensPath,e))}updateServerEntry(e){let r=Wu(this.serversPath)??{},n=r[this.serverUrl]??{},i=e(n);zqe(i)?r[this.serverUrl]=i:delete r[this.serverUrl],this.ensureDir(),OI(this.serversPath,r)}}});function Xqe(){try{return x_.default.statSync("/.dockerenv"),!0}catch{return!1}}function Zqe(){try{return x_.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function F_(){return S_===void 0&&(S_=Xqe()||Zqe()),S_}var x_,S_,Rse=L(()=>{h();x_=z(require("node:fs"),1)});function jg(){return k_===void 0&&(k_=e$e()||F_()),k_}var Tse,k_,e$e,R_=L(()=>{h();Tse=z(require("node:fs"),1);Rse();e$e=()=>{try{return Tse.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var T_,Mse,b0,Nse,zu,N_=L(()=>{h();T_=z(require("node:process"),1),Mse=z(require("node:os"),1),b0=z(require("node:fs"),1);R_();Nse=()=>{if(T_.default.platform!=="linux")return!1;if(Mse.default.release().toLowerCase().includes("microsoft"))return!jg();try{if(b0.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!jg()}catch{}return b0.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||b0.default.existsSync("/run/WSL")?!jg():!1},zu=T_.default.env.__IS_WSL_TEST__?Nse:Nse()});var M_,KI,t$e,r$e,P_,Pse=L(()=>{h();M_=z(require("node:process"),1),KI=z(require("node:fs/promises"),1);N_();N_();t$e=(()=>{let t="/mnt/",e;return async function(){if(e)return e;let r="/etc/wsl.conf",n=!1;try{await KI.default.access(r,KI.constants.F_OK),n=!0}catch{}if(!n)return t;let i=await KI.default.readFile(r,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):t}})(),r$e=async()=>`${await t$e()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,P_=async()=>zu?r$e():`${M_.default.env.SYSTEMROOT||M_.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Xu(t,e,r){let n=i=>Object.defineProperty(t,e,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){let i=r();return n(i),i},set(i){n(i)}}),t}var Lse=L(()=>{h()});async function L_(){if(Use.default.platform!=="darwin")throw new Error("macOS only");let{stdout:t}=await n$e("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(t)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}var _se,Use,Gse,n$e,Ose=L(()=>{h();_se=require("node:util"),Use=z(require("node:process"),1),Gse=require("node:child_process"),n$e=(0,_se.promisify)(Gse.execFile)});async function Jse(t,{humanReadableOutput:e=!0,signal:r}={}){if(Kse.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],i={};r&&(i.signal=r);let{stdout:s}=await i$e("osascript",["-e",t,n],i);return s.trim()}var Kse,Hse,__,i$e,jse=L(()=>{h();Kse=z(require("node:process"),1),Hse=require("node:util"),__=require("node:child_process"),i$e=(0,Hse.promisify)(__.execFile)});async function U_(t){return Jse(`tell application "Finder" to set app_path to application file id "${t}" as string
|
|
@@ -1748,24 +1748,24 @@ ${r}
|
|
|
1748
1748
|
`;break;case"id":a=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new KS(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:C}));break;default:r(new KS(`Unknown field "${f.length>20?`${f.slice(0,20)}\u2026`:f}"`,{type:"unknown-field",field:f,value:m,line:C}));break}}function g(){A.length>0&&e({id:a,event:c||void 0,data:A.endsWith(`
|
|
1749
1749
|
`)?A.slice(0,-1):A}),a=void 0,A="",c=""}function p(f={}){s&&f.consume&&l(s),o=!0,a=void 0,A="",c="",s=""}return{feed:u,reset:p}}function Bpt(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),s=t.indexOf(`
|
|
1750
1750
|
`,n),o=-1;if(i!==-1&&s!==-1?o=Math.min(i,s):i!==-1?i===t.length-1?o=-1:o=i:s!==-1&&(o=s),o===-1){r=t.slice(n);break}else{let a=t.slice(n,o);e.push(a),n=o+1,t[n-1]==="\r"&&t[n]===`
|
|
1751
|
-
`&&n++}}return[e,r]}var KS,qK=L(()=>{h();KS=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function ypt(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function $K(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map($K).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${$K(t.cause)}`:t.message:`${t}`}function zEe(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function Qpt(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var jS,ZEe,rH,_t,Mn,Or,$c,Es,xp,Hh,JS,YS,BB,Yh,yB,Ql,Jh,qh,jh,IB,xa,VK,WK,zK,XEe,XK,ZK,EB,eH,tH,Fp,eBe=L(()=>{h();qK();jS=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(zEe(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(zEe(this),r)}};ZEe=t=>{throw TypeError(t)},rH=(t,e,r)=>e.has(t)||ZEe("Cannot "+r),_t=(t,e,r)=>(rH(t,e,"read from private field"),r?r.call(t):e.get(t)),Mn=(t,e,r)=>e.has(t)?ZEe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Or=(t,e,r,n)=>(rH(t,e,"write to private field"),e.set(t,r),r),$c=(t,e,r)=>(rH(t,e,"access private method"),r),Fp=class extends EventTarget{constructor(e,r){var n,i;super(),Mn(this,xa),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Mn(this,Es),Mn(this,xp),Mn(this,Hh),Mn(this,JS),Mn(this,YS),Mn(this,BB),Mn(this,Yh),Mn(this,yB,null),Mn(this,Ql),Mn(this,Jh),Mn(this,qh,null),Mn(this,jh,null),Mn(this,IB,null),Mn(this,WK,async s=>{var o;_t(this,Jh).reset();let{body:a,redirected:A,status:c,headers:u}=s;if(c===204){$c(this,xa,EB).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(A?Or(this,Hh,new URL(s.url)):Or(this,Hh,void 0),c!==200){$c(this,xa,EB).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){$c(this,xa,EB).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(_t(this,Es)===this.CLOSED)return;Or(this,Es,this.OPEN);let l=new Event("open");if((o=_t(this,IB))==null||o.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){$c(this,xa,EB).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let d=new TextDecoder,g=a.getReader(),p=!0;do{let{done:f,value:m}=await g.read();m&&_t(this,Jh).feed(d.decode(m,{stream:!f})),f&&(p=!1,_t(this,Jh).reset(),$c(this,xa,eH).call(this))}while(p)}),Mn(this,zK,s=>{Or(this,Ql,void 0),!(s.name==="AbortError"||s.type==="aborted")&&$c(this,xa,eH).call(this,$K(s))}),Mn(this,XK,s=>{typeof s.id=="string"&&Or(this,yB,s.id);let o=new MessageEvent(s.event||"message",{data:s.data,origin:_t(this,Hh)?_t(this,Hh).origin:_t(this,xp).origin,lastEventId:s.id||""});_t(this,jh)&&(!s.event||s.event==="message")&&_t(this,jh).call(this,o),this.dispatchEvent(o)}),Mn(this,ZK,s=>{Or(this,BB,s)}),Mn(this,tH,()=>{Or(this,Yh,void 0),_t(this,Es)===this.CONNECTING&&$c(this,xa,VK).call(this)});try{if(e instanceof URL)Or(this,xp,e);else if(typeof e=="string")Or(this,xp,new URL(e,Qpt()));else throw new Error("Invalid URL")}catch{throw ypt("An invalid or illegal string was specified")}Or(this,Jh,HS({onEvent:_t(this,XK),onRetry:_t(this,ZK)})),Or(this,Es,this.CONNECTING),Or(this,BB,3e3),Or(this,YS,(n=r?.fetch)!=null?n:globalThis.fetch),Or(this,JS,(i=r?.withCredentials)!=null?i:!1),$c(this,xa,VK).call(this)}get readyState(){return _t(this,Es)}get url(){return _t(this,xp).href}get withCredentials(){return _t(this,JS)}get onerror(){return _t(this,qh)}set onerror(e){Or(this,qh,e)}get onmessage(){return _t(this,jh)}set onmessage(e){Or(this,jh,e)}get onopen(){return _t(this,IB)}set onopen(e){Or(this,IB,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){_t(this,Yh)&&clearTimeout(_t(this,Yh)),_t(this,Es)!==this.CLOSED&&(_t(this,Ql)&&_t(this,Ql).abort(),Or(this,Es,this.CLOSED),Or(this,Ql,void 0))}};Es=new WeakMap,xp=new WeakMap,Hh=new WeakMap,JS=new WeakMap,YS=new WeakMap,BB=new WeakMap,Yh=new WeakMap,yB=new WeakMap,Ql=new WeakMap,Jh=new WeakMap,qh=new WeakMap,jh=new WeakMap,IB=new WeakMap,xa=new WeakSet,VK=function(){Or(this,Es,this.CONNECTING),Or(this,Ql,new AbortController),_t(this,YS)(_t(this,xp),$c(this,xa,XEe).call(this)).then(_t(this,WK)).catch(_t(this,zK))},WK=new WeakMap,zK=new WeakMap,XEe=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",..._t(this,yB)?{"Last-Event-ID":_t(this,yB)}:void 0},cache:"no-store",signal:(t=_t(this,Ql))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},XK=new WeakMap,ZK=new WeakMap,EB=function(t,e){var r;_t(this,Es)!==this.CLOSED&&Or(this,Es,this.CLOSED);let n=new jS("error",{code:e,message:t});(r=_t(this,qh))==null||r.call(this,n),this.dispatchEvent(n)},eH=function(t,e){var r;if(_t(this,Es)===this.CLOSED)return;Or(this,Es,this.CONNECTING);let n=new jS("error",{code:e,message:t});(r=_t(this,qh))==null||r.call(this,n),this.dispatchEvent(n),Or(this,Yh,setTimeout(_t(this,tH),_t(this,BB)))},tH=new WeakMap,Fp.CONNECTING=0,Fp.OPEN=1,Fp.CLOSED=2});function $h(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function qS(t=fetch,e){return e?async(r,n)=>{let i={...e,...n,headers:n?.headers?{...$h(e.headers),...$h(n.headers)}:e.headers};return t(r,i)}:t}var nH=L(()=>{h()});var iH,$S,tBe=L(()=>{h();eBe();nH();ha();bf();iH=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},$S=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=qS(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Rn("No auth provider");let e;try{e=await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Rn;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=$h(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Fp(this._url.href,{...this._eventSourceInit,fetch:async(i,s)=>{let o=await this._commonHeaders();o.set("Accept","text/event-stream");let a=await e(i,{...s,headers:o});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:A,scope:c}=Vu(a);this._resourceMetadataUrl=A,this._scope=c}return a}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{if(i.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let s=new iH(i.code,i.message,i);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{let s=i;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){n(o),this.onerror?.(o),this.close();return}r()}),this._eventSource.onmessage=i=>{let s=i,o;try{o=Yu.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(o)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Rn("No auth provider");if(await ma(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._endpoint,n);if(!i.ok){let s=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){let{resourceMetadataUrl:o,scope:a}=Vu(i);if(this._resourceMetadataUrl=o,this._scope=a,await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${s}`)}await i.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}}});var VS,rBe=L(()=>{h();qK();VS=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(s){i=HS({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:n})},transform(s){i.feed(s)}})}}});var Dpt,Dl,WS,nBe=L(()=>{h();nH();ha();bf();rBe();Dpt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Dl=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},WS=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=qS(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Dpt}async _authThenStart(){if(!this._authProvider)throw new Rn("No auth provider");let e;try{e=await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Rn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=$h(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Dl(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:s}=r,o,a=!1,A=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new VS({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:p}=await u.read();if(p)break;if(g.id&&(o=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let f=Yu.parse(JSON.parse(g.data));Gg(f)&&(A=!0,s!==void 0&&(f.id=s)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(n||a)&&!A&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!A&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:s},0)}catch(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Rn("No auth provider");if(await ma(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:II(e)?e.id:void 0}).catch(d=>this.onerror?.(d));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,o),A=a.headers.get("mcp-session-id");if(A&&(this._sessionId=A),!a.ok){let d=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Dl(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:p}=Vu(a);if(this._resourceMetadataUrl=g,this._scope=p,await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:p,error:f}=Vu(a);if(f==="insufficient_scope"){let m=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===m)throw new Dl(403,"Server returned 403 after trying upscoping");if(p&&(this._scope=p),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=m??void 0,await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rn;return this.send(e)}}throw new Dl(a.status,`Error POSTing to endpoint: ${d}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Ase(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(d=>this.onerror?.(d));return}let u=(Array.isArray(e)?e:[e]).filter(d=>"method"in d&&"id"in d&&d.id!==void 0).length>0,l=a.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(l?.includes("application/json")){let d=await a.json(),g=Array.isArray(d)?d.map(p=>Yu.parse(p)):[Yu.parse(d)];for(let p of g)this.onmessage?.(p)}else throw await a.body?.cancel(),new Dl(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Dl(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}});var iBe=N((esr,wpt)=>{wpt.exports={name:"dotenv",version:"16.3.2",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard","lint-readme":"standard-markdown",pretest:"npm run lint && npm run dts-check",test:"tap tests/*.js --100 -Rspec",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://github.com/motdotla/dotenv?sponsor=1",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@definitelytyped/dtslint":"^0.0.133","@types/node":"^18.11.3",decache:"^4.6.1",sinon:"^14.0.1",standard:"^17.0.0","standard-markdown":"^7.1.0","standard-version":"^9.5.0",tap:"^16.3.0",tar:"^6.1.11",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var aH=N((tsr,Vc)=>{h();var sBe=require("fs"),sH=require("path"),bpt=require("os"),vpt=require("crypto"),Spt=iBe(),oH=Spt.version,xpt=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Fpt(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
1751
|
+
`&&n++}}return[e,r]}var KS,qK=L(()=>{h();KS=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function ypt(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function $K(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map($K).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${$K(t.cause)}`:t.message:`${t}`}function zEe(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}function Qpt(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var jS,ZEe,r4,_t,Mn,Or,$c,Es,xp,Hh,JS,YS,BB,Yh,yB,Ql,Jh,qh,jh,IB,xa,VK,WK,zK,XEe,XK,ZK,EB,e4,t4,Fp,eBe=L(()=>{h();qK();jS=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(zEe(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(zEe(this),r)}};ZEe=t=>{throw TypeError(t)},r4=(t,e,r)=>e.has(t)||ZEe("Cannot "+r),_t=(t,e,r)=>(r4(t,e,"read from private field"),r?r.call(t):e.get(t)),Mn=(t,e,r)=>e.has(t)?ZEe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Or=(t,e,r,n)=>(r4(t,e,"write to private field"),e.set(t,r),r),$c=(t,e,r)=>(r4(t,e,"access private method"),r),Fp=class extends EventTarget{constructor(e,r){var n,i;super(),Mn(this,xa),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Mn(this,Es),Mn(this,xp),Mn(this,Hh),Mn(this,JS),Mn(this,YS),Mn(this,BB),Mn(this,Yh),Mn(this,yB,null),Mn(this,Ql),Mn(this,Jh),Mn(this,qh,null),Mn(this,jh,null),Mn(this,IB,null),Mn(this,WK,async s=>{var o;_t(this,Jh).reset();let{body:a,redirected:A,status:c,headers:u}=s;if(c===204){$c(this,xa,EB).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(A?Or(this,Hh,new URL(s.url)):Or(this,Hh,void 0),c!==200){$c(this,xa,EB).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){$c(this,xa,EB).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(_t(this,Es)===this.CLOSED)return;Or(this,Es,this.OPEN);let l=new Event("open");if((o=_t(this,IB))==null||o.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){$c(this,xa,EB).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let d=new TextDecoder,g=a.getReader(),p=!0;do{let{done:f,value:m}=await g.read();m&&_t(this,Jh).feed(d.decode(m,{stream:!f})),f&&(p=!1,_t(this,Jh).reset(),$c(this,xa,e4).call(this))}while(p)}),Mn(this,zK,s=>{Or(this,Ql,void 0),!(s.name==="AbortError"||s.type==="aborted")&&$c(this,xa,e4).call(this,$K(s))}),Mn(this,XK,s=>{typeof s.id=="string"&&Or(this,yB,s.id);let o=new MessageEvent(s.event||"message",{data:s.data,origin:_t(this,Hh)?_t(this,Hh).origin:_t(this,xp).origin,lastEventId:s.id||""});_t(this,jh)&&(!s.event||s.event==="message")&&_t(this,jh).call(this,o),this.dispatchEvent(o)}),Mn(this,ZK,s=>{Or(this,BB,s)}),Mn(this,t4,()=>{Or(this,Yh,void 0),_t(this,Es)===this.CONNECTING&&$c(this,xa,VK).call(this)});try{if(e instanceof URL)Or(this,xp,e);else if(typeof e=="string")Or(this,xp,new URL(e,Qpt()));else throw new Error("Invalid URL")}catch{throw ypt("An invalid or illegal string was specified")}Or(this,Jh,HS({onEvent:_t(this,XK),onRetry:_t(this,ZK)})),Or(this,Es,this.CONNECTING),Or(this,BB,3e3),Or(this,YS,(n=r?.fetch)!=null?n:globalThis.fetch),Or(this,JS,(i=r?.withCredentials)!=null?i:!1),$c(this,xa,VK).call(this)}get readyState(){return _t(this,Es)}get url(){return _t(this,xp).href}get withCredentials(){return _t(this,JS)}get onerror(){return _t(this,qh)}set onerror(e){Or(this,qh,e)}get onmessage(){return _t(this,jh)}set onmessage(e){Or(this,jh,e)}get onopen(){return _t(this,IB)}set onopen(e){Or(this,IB,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){_t(this,Yh)&&clearTimeout(_t(this,Yh)),_t(this,Es)!==this.CLOSED&&(_t(this,Ql)&&_t(this,Ql).abort(),Or(this,Es,this.CLOSED),Or(this,Ql,void 0))}};Es=new WeakMap,xp=new WeakMap,Hh=new WeakMap,JS=new WeakMap,YS=new WeakMap,BB=new WeakMap,Yh=new WeakMap,yB=new WeakMap,Ql=new WeakMap,Jh=new WeakMap,qh=new WeakMap,jh=new WeakMap,IB=new WeakMap,xa=new WeakSet,VK=function(){Or(this,Es,this.CONNECTING),Or(this,Ql,new AbortController),_t(this,YS)(_t(this,xp),$c(this,xa,XEe).call(this)).then(_t(this,WK)).catch(_t(this,zK))},WK=new WeakMap,zK=new WeakMap,XEe=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",..._t(this,yB)?{"Last-Event-ID":_t(this,yB)}:void 0},cache:"no-store",signal:(t=_t(this,Ql))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},XK=new WeakMap,ZK=new WeakMap,EB=function(t,e){var r;_t(this,Es)!==this.CLOSED&&Or(this,Es,this.CLOSED);let n=new jS("error",{code:e,message:t});(r=_t(this,qh))==null||r.call(this,n),this.dispatchEvent(n)},e4=function(t,e){var r;if(_t(this,Es)===this.CLOSED)return;Or(this,Es,this.CONNECTING);let n=new jS("error",{code:e,message:t});(r=_t(this,qh))==null||r.call(this,n),this.dispatchEvent(n),Or(this,Yh,setTimeout(_t(this,t4),_t(this,BB)))},t4=new WeakMap,Fp.CONNECTING=0,Fp.OPEN=1,Fp.CLOSED=2});function $h(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function qS(t=fetch,e){return e?async(r,n)=>{let i={...e,...n,headers:n?.headers?{...$h(e.headers),...$h(n.headers)}:e.headers};return t(r,i)}:t}var n4=L(()=>{h()});var i4,$S,tBe=L(()=>{h();eBe();n4();ha();bf();i4=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},$S=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=qS(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Rn("No auth provider");let e;try{e=await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Rn;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=$h(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new Fp(this._url.href,{...this._eventSourceInit,fetch:async(i,s)=>{let o=await this._commonHeaders();o.set("Accept","text/event-stream");let a=await e(i,{...s,headers:o});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:A,scope:c}=Vu(a);this._resourceMetadataUrl=A,this._scope=c}return a}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{if(i.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let s=new i4(i.code,i.message,i);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{let s=i;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){n(o),this.onerror?.(o),this.close();return}r()}),this._eventSource.onmessage=i=>{let s=i,o;try{o=Yu.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(o)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Rn("No auth provider");if(await ma(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._endpoint,n);if(!i.ok){let s=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){let{resourceMetadataUrl:o,scope:a}=Vu(i);if(this._resourceMetadataUrl=o,this._scope=a,await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${s}`)}await i.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}}});var VS,rBe=L(()=>{h();qK();VS=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(s){i=HS({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:n})},transform(s){i.feed(s)}})}}});var Dpt,Dl,WS,nBe=L(()=>{h();n4();ha();bf();rBe();Dpt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Dl=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},WS=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=qS(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Dpt}async _authThenStart(){if(!this._authProvider)throw new Rn("No auth provider");let e;try{e=await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Rn;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=$h(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Dl(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:s}=r,o,a=!1,A=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new VS({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:p}=await u.read();if(p)break;if(g.id&&(o=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let f=Yu.parse(JSON.parse(g.data));Gg(f)&&(A=!0,s!==void 0&&(f.id=s)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(n||a)&&!A&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!A&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:s},0)}catch(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Rn("No auth provider");if(await ma(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:II(e)?e.id:void 0}).catch(d=>this.onerror?.(d));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,o),A=a.headers.get("mcp-session-id");if(A&&(this._sessionId=A),!a.ok){let d=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Dl(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:p}=Vu(a);if(this._resourceMetadataUrl=g,this._scope=p,await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rn;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:p,error:f}=Vu(a);if(f==="insufficient_scope"){let m=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===m)throw new Dl(403,"Server returned 403 after trying upscoping");if(p&&(this._scope=p),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=m??void 0,await ma(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rn;return this.send(e)}}throw new Dl(a.status,`Error POSTing to endpoint: ${d}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Ase(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(d=>this.onerror?.(d));return}let u=(Array.isArray(e)?e:[e]).filter(d=>"method"in d&&"id"in d&&d.id!==void 0).length>0,l=a.headers.get("content-type");if(u)if(l?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(l?.includes("application/json")){let d=await a.json(),g=Array.isArray(d)?d.map(p=>Yu.parse(p)):[Yu.parse(d)];for(let p of g)this.onmessage?.(p)}else throw await a.body?.cancel(),new Dl(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Dl(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}});var iBe=N((esr,wpt)=>{wpt.exports={name:"dotenv",version:"16.3.2",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard","lint-readme":"standard-markdown",pretest:"npm run lint && npm run dts-check",test:"tap tests/*.js --100 -Rspec",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://github.com/motdotla/dotenv?sponsor=1",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@definitelytyped/dtslint":"^0.0.133","@types/node":"^18.11.3",decache:"^4.6.1",sinon:"^14.0.1",standard:"^17.0.0","standard-markdown":"^7.1.0","standard-version":"^9.5.0",tap:"^16.3.0",tar:"^6.1.11",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var a4=N((tsr,Vc)=>{h();var sBe=require("fs"),s4=require("path"),bpt=require("os"),vpt=require("crypto"),Spt=iBe(),o4=Spt.version,xpt=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Fpt(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
1752
1752
|
`);let n;for(;(n=xpt.exec(r))!=null;){let i=n[1],s=n[2]||"";s=s.trim();let o=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(s=s.replace(/\\n/g,`
|
|
1753
|
-
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}function kpt(t){let e=aBe(t),r=Zn.configDotenv({path:e});if(!r.parsed)throw new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);let n=oBe(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),A=Npt(r,a);s=Zn.decrypt(A.ciphertext,A.key);break}catch(a){if(o+1>=i)throw a}return Zn.parse(s)}function Rpt(t){console.log(`[dotenv@${
|
|
1754
|
-
\u{1F50C} Connecting to ${E.type.toUpperCase()} MCP server: ${E.name}`),It.debug(` URL: ${E.url}`),E.sessionId?It.debug(" Session ID configured: yes",JSON.stringify(Kpt(E.sessionId))):It.debug(" Session ID: not configured"),E.headers&&Object.keys(E.headers).length>0&&It.debug(` Headers: ${Object.keys(E.headers).join(", ")}`);let v=E.retries??0,D,S=!1;for(let b=0;b<=v;b++){b>0&&(It.debug(` Retry ${b}/${v} for ${E.name}...`),await new Promise(x=>setTimeout(x,3e3)));try{let{client:x,transport:P,protocol:O}=await ABe(E,n);It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${b>0?` (attempt ${b+1})`:""}`),s.push({client:x,transport:P,status:{status:"ok",protocol:O,connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:E.type,url:E.url,oauth:E.oauth,serverDef:E}),S=!0;break}catch(x){if(D=x,x instanceof Rn||
|
|
1755
|
-
\u{1F50C} Connecting to STDIO MCP server: ${E.name}`),It.debug(` Command: ${E.command}`),E.args&&E.args.length>0&&It.debug(` Args: ${E.args.join(" ")}`),E.env&&Object.keys(E.env).length>0&&It.debug(` Environment variables: ${Object.keys(E.env).join(", ")}`);let v=E.retries??0;for(let D=0;D<=v;D++){D>0&&(It.debug(` Retry ${D}/${v} for ${E.name}...`),await new Promise(x=>setTimeout(x,3e3)));let S,b;try{S=new mB({name:"Builder",version:"1.0.0"}),b=new OS({command:E.command,args:E.args||[],cwd:r,env:{...process.env,...E.env}}),await S.connect(b),It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${D>0?` (attempt ${D+1})`:""}`),s.push({client:S,transport:b,status:{status:"ok",protocol:"stdio",connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:"stdio",command:E.command});break}catch(x){let P=x instanceof Error?x.message:"Unknown error",O=Math.round(performance.now()-Q);if(S?await
|
|
1753
|
+
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}function kpt(t){let e=aBe(t),r=Zn.configDotenv({path:e});if(!r.parsed)throw new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);let n=oBe(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),A=Npt(r,a);s=Zn.decrypt(A.ciphertext,A.key);break}catch(a){if(o+1>=i)throw a}return Zn.parse(s)}function Rpt(t){console.log(`[dotenv@${o4}][INFO] ${t}`)}function Tpt(t){console.log(`[dotenv@${o4}][WARN] ${t}`)}function zS(t){console.log(`[dotenv@${o4}][DEBUG] ${t}`)}function oBe(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function Npt(t,e){let r;try{r=new URL(e)}catch(a){throw a.code==="ERR_INVALID_URL"?new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development"):a}let n=r.password;if(!n)throw new Error("INVALID_DOTENV_KEY: Missing key part");let i=r.searchParams.get("environment");if(!i)throw new Error("INVALID_DOTENV_KEY: Missing environment part");let s=`DOTENV_VAULT_${i.toUpperCase()}`,o=t.parsed[s];if(!o)throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);return{ciphertext:o,key:n}}function aBe(t){let e=s4.resolve(process.cwd(),".env");return t&&t.path&&t.path.length>0&&(e=t.path),e.endsWith(".vault")?e:`${e}.vault`}function Mpt(t){return t[0]==="~"?s4.join(bpt.homedir(),t.slice(1)):t}function Ppt(t){Rpt("Loading env from encrypted .env.vault");let e=Zn._parseVault(t),r=process.env;return t&&t.processEnv!=null&&(r=t.processEnv),Zn.populate(r,e,t),{parsed:e}}function Lpt(t){let e=s4.resolve(process.cwd(),".env"),r="utf8",n=!!(t&&t.debug);t&&(t.path!=null&&(e=Mpt(t.path)),t.encoding!=null?r=t.encoding:n&&zS("No encoding is specified. UTF-8 is used by default"));try{let i=Zn.parse(sBe.readFileSync(e,{encoding:r})),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),Zn.populate(s,i,t),{parsed:i}}catch(i){return n&&zS(`Failed to load ${e} ${i.message}`),{error:i}}}function _pt(t){let e=aBe(t);return oBe(t).length===0?Zn.configDotenv(t):sBe.existsSync(e)?Zn._configVault(t):(Tpt(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),Zn.configDotenv(t))}function Upt(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),i=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{let o=vpt.createDecipheriv("aes-256-gcm",r,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let a=o instanceof RangeError,A=o.message==="Invalid key length",c=o.message==="Unsupported state or unable to authenticate data";if(a||A){let u="INVALID_DOTENV_KEY: It must be 64 characters long (or more)";throw new Error(u)}else if(c){let u="DECRYPTION_FAILED: Please check your DOTENV_KEY";throw new Error(u)}else throw console.error("Error: ",o.code),console.error("Error: ",o.message),o}}function Gpt(t,e,r={}){let n=!!(r&&r.debug),i=!!(r&&r.override);if(typeof e!="object")throw new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(t,s)?(i===!0&&(t[s]=e[s]),n&&zS(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):t[s]=e[s]}var Zn={configDotenv:Lpt,_configVault:Ppt,_parseVault:kpt,config:_pt,decrypt:Upt,parse:Fpt,populate:Gpt};Vc.exports.configDotenv=Zn.configDotenv;Vc.exports._configVault=Zn._configVault;Vc.exports._parseVault=Zn._parseVault;Vc.exports.config=Zn.config;Vc.exports.decrypt=Zn.decrypt;Vc.exports.parse=Zn.parse;Vc.exports.populate=Zn.populate;Vc.exports=Zn});function Kpt(t){return{length:t.length,looksLikeJWT:t.split(".").length===3,hasEnvPlaceholder:/\$\{[^}]+\}/.test(t)}}function A4(t){if(!(t instanceof Error))return!1;if(t.constructor?.name==="UnauthorizedError")return!0;let e=t;return e.status===401||e.code===401?!0:/\b401\b|\bUnauthorized\b/.test(t.message)}async function Hpt(t,e,r){let n=Vh.isAbsolute(e)?e:Vh.join(r,e);try{if(!t.existsSync(n))return{};let i=(0,cBe.config)({path:n});if(i.error)throw i.error;return i.parsed||{}}catch(i){return Bs.captureException(i,{level:"warning",tags:{operation:"load-mcp-config",envFilePath:n}}),{}}}function Jpt(){return new Set}function jpt(t){return t.scope?t.scope==="plugin"?"plugin":"local":"builtin"}function Ypt(t){switch(t.scope){case"plugin":return 0;case"user":return 1;case"project":return 2;default:return 3}}async function c4(t,e,r){try{await e.close()}catch(n){Bs.captureException(n,{level:"warning",tags:{operation:"load-mcp-config"}})}if(r)try{await r.close()}catch(n){Bs.captureException(n,{level:"warning",tags:{operation:"load-mcp-config"}})}}async function qpt(t){try{let r=await new Dc({serverUrl:t}).getTokens();return!r||b_(r.expiresAt)?void 0:{Authorization:`Bearer ${r.accessToken}`}}catch{return}}async function ABe(t,e){let r,n;try{r=new mB({name:"Builder",version:"1.0.0"});let i=new URL(t.url),s=await qpt(t.url),o=t.headers?.Authorization||!s?t.headers:{...t.headers,...s},a=t.connectTimeoutMs??Opt;return t.type==="http"?(n=new WS(i,{requestInit:{headers:o},sessionId:t.sessionId}),await r.connect(n,{signal:e,maxTotalTimeout:a}),{client:r,transport:n,protocol:"streamable-http"}):(t.sessionId&&It.warn(` \u26A0\uFE0F sessionId is configured for SSE server "${t.name}" but SSEClientTransport does not accept a sessionId option. The value will be ignored. If your server requires a session, pass it via "headers" instead.`),n=new $S(i,{requestInit:{headers:o}}),await r.connect(n,{signal:e,maxTotalTimeout:a}),{client:r,transport:n,protocol:"sse"})}catch(i){if(r)try{await r.close()}catch{}if(n)try{await n.close()}catch{}throw i}}async function lBe(t,e,r,n){let i=Jpt(),s=[],o=new Map,a=new Map,A=[],c=[],u=new Set(i),l=E=>"type"in E&&"url"in E,d=t.map((E,Q)=>({source:"local-configured",name:E.name,url:l(E)?E.url:void 0,transport:l(E)?E.type==="http"?"streamable-http":"sse":"stdio",server:E,localPrecedence:Ypt(E),originalIndex:Q})).sort((E,Q)=>E.localPrecedence!==Q.localPrecedence?Q.localPrecedence-E.localPrecedence:E.originalIndex-Q.originalIndex),g=Doe(d);for(let E of g.warnings)Bs.captureMessage(E,{level:"info",tags:{operation:"local-mcp-dedup-warning"}});for(let E of g.shadowed)o.set(E.name,E.shadowedBy);let p=g.active.map(E=>E.server),f=E=>{let Q=l(E);return{source:jpt(E),scope:E.scope,pluginName:E.pluginName,configFilePath:E.configFilePath,url:Q?E.url:void 0,command:Q?void 0:E.command}};for(let E of p){if(E.disabled){s.push({client:void 0,transport:void 0,status:{status:"disabled",message:"Server disabled by user",connectionDurationMs:0,resolutionDurationMs:0,...f(E),toolCount:0},serverName:E.name,normalizedServerName:BA(E.name),serverType:l(E)?E.type:"stdio",command:l(E)?void 0:E.command,url:l(E)?E.url:void 0});continue}let Q=performance.now();if(l(E)){It.debug(`
|
|
1754
|
+
\u{1F50C} Connecting to ${E.type.toUpperCase()} MCP server: ${E.name}`),It.debug(` URL: ${E.url}`),E.sessionId?It.debug(" Session ID configured: yes",JSON.stringify(Kpt(E.sessionId))):It.debug(" Session ID: not configured"),E.headers&&Object.keys(E.headers).length>0&&It.debug(` Headers: ${Object.keys(E.headers).join(", ")}`);let v=E.retries??0,D,S=!1;for(let b=0;b<=v;b++){b>0&&(It.debug(` Retry ${b}/${v} for ${E.name}...`),await new Promise(x=>setTimeout(x,3e3)));try{let{client:x,transport:P,protocol:O}=await ABe(E,n);It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${b>0?` (attempt ${b+1})`:""}`),s.push({client:x,transport:P,status:{status:"ok",protocol:O,connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:E.type,url:E.url,oauth:E.oauth,serverDef:E}),S=!0;break}catch(x){if(D=x,x instanceof Rn||A4(x))break;if(b<v){let O=x instanceof Error?x.message:"Unknown error",J=Math.round(performance.now()-Q);It.debug(` \u2717 Attempt ${b+1} failed after ${J}ms: ${O}`);continue}}}if(!S){let b=D,x=b instanceof Error?b.message:"Unknown error",P=Math.round(performance.now()-Q),O=b instanceof Rn||A4(b);It.error(` \u2717 Connection FAILED after ${P}ms${v>0&&!O?` (${v+1} attempts)`:""}: ${x}`),O&&It.debug(" \u26A0\uFE0F Server returned 401/Unauthorized \u2014 surfacing as auth-required for the LLM-driven __authenticate flow (Phase 2b)."),s.push({client:void 0,transport:void 0,status:{status:O?"auth_required":"error",message:x,connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:E.type,url:E.url,authRequired:O,oauth:E.oauth,serverDef:O?E:void 0}),Bs.captureException(b,{level:"warning",tags:{operation:"load-mcp-config",serverName:E.name,serverType:E.type,url:E.url}})}}else{It.debug(`
|
|
1755
|
+
\u{1F50C} Connecting to STDIO MCP server: ${E.name}`),It.debug(` Command: ${E.command}`),E.args&&E.args.length>0&&It.debug(` Args: ${E.args.join(" ")}`),E.env&&Object.keys(E.env).length>0&&It.debug(` Environment variables: ${Object.keys(E.env).join(", ")}`);let v=E.retries??0;for(let D=0;D<=v;D++){D>0&&(It.debug(` Retry ${D}/${v} for ${E.name}...`),await new Promise(x=>setTimeout(x,3e3)));let S,b;try{S=new mB({name:"Builder",version:"1.0.0"}),b=new OS({command:E.command,args:E.args||[],cwd:r,env:{...process.env,...E.env}}),await S.connect(b),It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${D>0?` (attempt ${D+1})`:""}`),s.push({client:S,transport:b,status:{status:"ok",protocol:"stdio",connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:"stdio",command:E.command});break}catch(x){let P=x instanceof Error?x.message:"Unknown error",O=Math.round(performance.now()-Q);if(S?await c4(e,S,b):b&&await b.close(),D<v){It.debug(` \u2717 Attempt ${D+1} failed after ${O}ms: ${P}`);continue}It.error(` \u2717 Connection FAILED after ${O}ms (${v+1} attempts): ${P}`),s.push({client:void 0,transport:void 0,status:{status:"error",message:P,connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:"stdio",command:E.command}),Bs.captureException(x,{level:"warning",tags:{operation:"load-mcp-config",serverName:E.name,command:E.command}})}}}}let m=async(E,Q)=>{if(!E.client)return 0;let v=performance.now(),D=0,S=[];try{let b=E.client,x=await b.getServerCapabilities();if(E.status.capabilities={tools:!!x?.tools,resources:!!x?.resources,prompts:!!x?.prompts},It.debug(` Capabilities: tools=${!!x?.tools}, resources=${!!x?.resources}`),!x||x.tools){let P=await b.listTools(void 0,{signal:Q});if(P.tools&&P.tools.length>0?It.debug(` \u2713 Found ${P.tools.length} tool(s): ${P.tools.map(O=>O.name).join(", ")}`):It.debug(" No tools found"),P.tools)for(let O of P.tools){let J=O.name;Boe(J)||It.debug(` \u2717 Tool name is invalid: ${J}`);let _=yoe(E.normalizedServerName,J),K=Qoe(u,_,{serverName:E.serverName,originalToolName:J});a.set(K,{client:E,tool:{...O,name:K},originalName:J}),A.push({...O,name:K,serverName:E.serverName}),S.push({name:O.name,description:O.description}),D++}}if(x?.resources){let P=await b.listResources(void 0,{signal:Q});if(P.resources&&P.resources.length>0?It.debug(` \u2713 Found ${P.resources.length} resource(s): ${P.resources.map(O=>O.name||O.uri).join(", ")}`):It.debug(" No resources found"),P.resources){let J=(await Promise.all(P.resources.map(async _=>{if(_.mimeType!=="text/plain")return null;let K=await b.readResource(_,{signal:Q}),j=K.contents[0]&&"text"in K.contents[0]?K.contents[0].text:void 0;return j?{uri:_.uri,name:_.name,description:_.description,mimeType:_.mimeType,text:j,serverName:E.serverName}:null}))).filter(_=>_!==null);E.resources=J;for(let _ of J)c.push(_)}}}catch(b){It.error(`Local MCP ${E.serverName} error`,b),E.status.message=b instanceof Error?b.message:"Unknown error",E.status.status="error",Bs.captureException(b,{level:"warning",tags:{operation:"load-mcp-config",serverName:E.serverName}})}finally{E.status.resolutionDurationMs=performance.now()-v,E.status.toolCount=D,E.status.tools=S}return D};await Promise.all(s.map(E=>m(E,n))),A.sort((E,Q)=>E.name.localeCompare(Q.name)),c.sort((E,Q)=>{let v=`${E.serverName}__${E.name}`,D=`${Q.serverName}__${Q.name}`;return v.localeCompare(D)});let C=s.filter(E=>E.status.status==="ok"),I=s.filter(E=>E.status.status==="error");if(It.debug(`
|
|
1756
1756
|
\u{1F4CA} MCP Connection Summary: ${C.length}/${s.length} successful`),C.length>0){It.debug(" \u2713 Connected servers:");for(let E of C){let Q=A.filter(D=>D.serverName===E.serverName).length||0,v=c.filter(D=>D.serverName===E.serverName).length||0;It.debug(` - ${E.serverName}: ${Q} tools, ${v} resources`)}}if(I.length>0){It.debug(" \u2717 Failed servers:");for(let E of I)It.debug(` - ${E.serverName}: ${E.status.message}`)}It.debug(` Total available: ${A.length} tools, ${c.length} resources
|
|
1757
|
-
`);let y=()=>s.filter(E=>E.authRequired===!0&&E.url!==void 0).map(E=>({serverId:null,name:E.serverName,normalizedName:E.normalizedServerName,url:E.url,source:"local-failed"})),B=()=>{let E=y();if(E.length===0)return[];let Q=new Set(A.map(S=>S.name)),v=new Map(E.map(S=>[$g(S.normalizedName),S]));return woe(E,Q,S=>{Bs.captureMessage("Duplicate local MCP auth tool skipped",{level:"warning",extra:{toolName:S.name,candidateName:S.candidate.name,existingName:S.existingName}})}).map(S=>{let b=v.get(S.name);return{name:S.name,description:S.description,inputSchema:S.input_schema,serverName:b?.name??S.name,deferLoading:S.defer_loading}})};return{clients:s,listTools:()=>[...A,...B()],callTool:async(E,Q,v)=>{let D=a.get(E);if(!D||!D.client.client)throw new Error(`Tool "${E}" not found in any connected local MCP server`);try{let S=await D.client.client.callTool({name:D.originalName,arguments:Q},void 0,{timeout:3e5,resetTimeoutOnProgress:!0});return{content:boe(S),isError:S.isError===!0}}catch(S){throw Bs.captureException(S,{level:"warning",tags:{operation:"load-mcp-config",toolName:E,originalToolName:D.originalName,serverName:D.client.serverName}}),S}},getResources:E=>E?c.filter(Q=>Q.serverName===E):c,getStatus:()=>{let E={};for(let Q of s)E[Q.serverName]=Q.status;for(let[Q,v]of o)E[Q]={status:"shadowed",message:`Shadowed by mcp.json entry '${v.name}'`,shadowedBy:v,connectionDurationMs:0,resolutionDurationMs:0,source:"local"};return E},getAuthRequiredServers:y,reconnectServer:async(E,Q)=>{let v=s.find(S=>S.serverName===E);if(!v)return{success:!1,toolsAdded:0,message:`No CLI-managed MCP server named '${E}'.`};if(!v.serverDef)return{success:!1,toolsAdded:0,message:`Server '${E}' has no stored remote definition (not auth-required or stdio).`};v.client?await
|
|
1758
|
-
\u{1F50D} Loading MCP configuration...`),It.debug(` Working directory: ${e}`),It.debug(` Auto-import from mcp.json: ${n}`),r&&typeof r=="object"&&Object.keys(r).length>0&&It.debug(` Built-in servers from fusion config: ${Object.keys(r).join(", ")}`);let o=Vh.join(e,"mcp.json"),a=s??(0,uBe.homedir)(),A=a?Vh.join(a,".builder","mcp.json"):null,c={...process.env},u=p=>"type"in p&&"url"in p,l=new Map,d=async(p,f,m)=>{try{if(!t.existsSync(p)){It.debug(` No ${f} file found at ${p}`);return}let C=await t.readFile(p);if(!C)return;let I=JSON.parse(C);if(!I.mcpServers||typeof I.mcpServers!="object")return;let y=Object.keys(I.mcpServers);y.length>0&&It.debug(` \u2713 Found ${f} with ${y.length} server(s): ${y.join(", ")}`);for(let[B,E]of Object.entries(I.mcpServers))u(E)||E.command?l.set(B,{...E,scope:m,configFilePath:p}):It.debug(`Skipping local MCP server "${B}".`,E)}catch(C){It.warn(`Failed to load ${f}:`,C),Bs.captureException(C,{level:"warning",tags:{operation:"load-mcp-config",configPath:p}})}};if(n&&(A&&(It.debug(` Checking for: ${A}`),await d(A,"user-level mcp.json","user")),It.debug(` Checking for: ${o}`),await d(o,"mcp.json","project")),r)for(let[p,f]of Object.entries(r))u(f)||f.command?l.set(p,f):It.debug(`Skipping local MCP server "${p}".`,f);if(i?.aborted)throw rn(i.reason);let g=[];for(let[p,f]of l.entries()){if(i?.aborted)throw rn(i.reason);try{let m={};if(f.envFile){let C=Qa(f.envFile,c);m=await Hpt(t,C,e)}if(u(f)){let C=Vpt(f,p,c,m);g.push(C)}else{let C=$pt(f,p,c,m);g.push(C)}}catch(m){Bs.captureException(m,{level:"warning",tags:{operation:"load-mcp-config",serverName:p,workingDirectory:e}})}}return g}var Bs,cBe,Vh,uBe,It,Opt,pBe=L(()=>{"use strict";h();oEe();WEe();tBe();nBe();bf();Bs=z(require("@sentry/node"),1);O0();cBe=z(
|
|
1757
|
+
`);let y=()=>s.filter(E=>E.authRequired===!0&&E.url!==void 0).map(E=>({serverId:null,name:E.serverName,normalizedName:E.normalizedServerName,url:E.url,source:"local-failed"})),B=()=>{let E=y();if(E.length===0)return[];let Q=new Set(A.map(S=>S.name)),v=new Map(E.map(S=>[$g(S.normalizedName),S]));return woe(E,Q,S=>{Bs.captureMessage("Duplicate local MCP auth tool skipped",{level:"warning",extra:{toolName:S.name,candidateName:S.candidate.name,existingName:S.existingName}})}).map(S=>{let b=v.get(S.name);return{name:S.name,description:S.description,inputSchema:S.input_schema,serverName:b?.name??S.name,deferLoading:S.defer_loading}})};return{clients:s,listTools:()=>[...A,...B()],callTool:async(E,Q,v)=>{let D=a.get(E);if(!D||!D.client.client)throw new Error(`Tool "${E}" not found in any connected local MCP server`);try{let S=await D.client.client.callTool({name:D.originalName,arguments:Q},void 0,{timeout:3e5,resetTimeoutOnProgress:!0});return{content:boe(S),isError:S.isError===!0}}catch(S){throw Bs.captureException(S,{level:"warning",tags:{operation:"load-mcp-config",toolName:E,originalToolName:D.originalName,serverName:D.client.serverName}}),S}},getResources:E=>E?c.filter(Q=>Q.serverName===E):c,getStatus:()=>{let E={};for(let Q of s)E[Q.serverName]=Q.status;for(let[Q,v]of o)E[Q]={status:"shadowed",message:`Shadowed by mcp.json entry '${v.name}'`,shadowedBy:v,connectionDurationMs:0,resolutionDurationMs:0,source:"local"};return E},getAuthRequiredServers:y,reconnectServer:async(E,Q)=>{let v=s.find(S=>S.serverName===E);if(!v)return{success:!1,toolsAdded:0,message:`No CLI-managed MCP server named '${E}'.`};if(!v.serverDef)return{success:!1,toolsAdded:0,message:`Server '${E}' has no stored remote definition (not auth-required or stdio).`};v.client?await c4(e,v.client,v.transport):v.transport&&await v.transport.close(),v.client=void 0,v.transport=void 0;for(let[S,b]of Array.from(a.entries()))b.client===v&&(a.delete(S),u.delete(S));for(let S=A.length-1;S>=0;S--)A[S].serverName===v.serverName&&A.splice(S,1);for(let S=c.length-1;S>=0;S--)c[S].serverName===v.serverName&&c.splice(S,1);v.resources=void 0;let D=performance.now();try{let{client:S,transport:b,protocol:x}=await ABe(v.serverDef,Q);v.client=S,v.transport=b,v.status={status:"ok",protocol:x,connectionDurationMs:performance.now()-D,resolutionDurationMs:0,...f(v.serverDef)},v.authRequired=!1;let P=await m(v,Q);return A.sort((O,J)=>O.name.localeCompare(J.name)),{success:!0,toolsAdded:P}}catch(S){let b=S instanceof Error?S.message:"Unknown error",x=S instanceof Rn||A4(S);return v.status={status:x?"auth_required":"error",message:b,connectionDurationMs:performance.now()-D,resolutionDurationMs:0,...f(v.serverDef)},v.authRequired=x,Bs.captureException(S,{level:"warning",tags:{operation:"local-mcp-reconnect",serverName:v.serverName,url:v.url}}),{success:!1,toolsAdded:0,message:b}}},cleanup:async()=>{await Promise.all(s.map(async E=>{E.client?await c4(e,E.client,E.transport):E.transport&&await E.transport.close()}))}}}function $pt(t,e,r,n){let i={...r,...n},s=Qa(t.command,i),o=(t.args||[]).map(u=>Qa(u,i)),a={};for(let[u,l]of Object.entries(t.env||{}))l!==void 0&&(a[u]=Qa(l,i));let A={...n,...a},c=t.envFile?Qa(t.envFile,r):void 0;return{name:e,command:s,args:o,env:A,envFile:c,retries:t.retries,disabled:t.disabled,scope:t.scope,pluginName:t.pluginName,configFilePath:t.configFilePath}}function Vpt(t,e,r,n){let i={...r,...n},s=Qa(t.url,i),o={};for(let[A,c]of Object.entries(t.headers||{}))o[A]=Qa(c,i);let a=t.sessionId?Qa(t.sessionId,i):void 0;return{name:e,type:t.type,url:s,headers:Object.keys(o).length>0?o:void 0,sessionId:a,envFile:t.envFile,connectTimeoutMs:t.connectTimeoutMs,retries:t.retries,oauth:t.oauth,disabled:t.disabled,scope:t.scope,pluginName:t.pluginName,configFilePath:t.configFilePath}}async function gBe(t,e,r,n,i,s){It.debug(`
|
|
1758
|
+
\u{1F50D} Loading MCP configuration...`),It.debug(` Working directory: ${e}`),It.debug(` Auto-import from mcp.json: ${n}`),r&&typeof r=="object"&&Object.keys(r).length>0&&It.debug(` Built-in servers from fusion config: ${Object.keys(r).join(", ")}`);let o=Vh.join(e,"mcp.json"),a=s??(0,uBe.homedir)(),A=a?Vh.join(a,".builder","mcp.json"):null,c={...process.env},u=p=>"type"in p&&"url"in p,l=new Map,d=async(p,f,m)=>{try{if(!t.existsSync(p)){It.debug(` No ${f} file found at ${p}`);return}let C=await t.readFile(p);if(!C)return;let I=JSON.parse(C);if(!I.mcpServers||typeof I.mcpServers!="object")return;let y=Object.keys(I.mcpServers);y.length>0&&It.debug(` \u2713 Found ${f} with ${y.length} server(s): ${y.join(", ")}`);for(let[B,E]of Object.entries(I.mcpServers))u(E)||E.command?l.set(B,{...E,scope:m,configFilePath:p}):It.debug(`Skipping local MCP server "${B}".`,E)}catch(C){It.warn(`Failed to load ${f}:`,C),Bs.captureException(C,{level:"warning",tags:{operation:"load-mcp-config",configPath:p}})}};if(n&&(A&&(It.debug(` Checking for: ${A}`),await d(A,"user-level mcp.json","user")),It.debug(` Checking for: ${o}`),await d(o,"mcp.json","project")),r)for(let[p,f]of Object.entries(r))u(f)||f.command?l.set(p,f):It.debug(`Skipping local MCP server "${p}".`,f);if(i?.aborted)throw rn(i.reason);let g=[];for(let[p,f]of l.entries()){if(i?.aborted)throw rn(i.reason);try{let m={};if(f.envFile){let C=Qa(f.envFile,c);m=await Hpt(t,C,e)}if(u(f)){let C=Vpt(f,p,c,m);g.push(C)}else{let C=$pt(f,p,c,m);g.push(C)}}catch(m){Bs.captureException(m,{level:"warning",tags:{operation:"load-mcp-config",serverName:p,workingDirectory:e}})}}return g}var Bs,cBe,Vh,uBe,It,Opt,pBe=L(()=>{"use strict";h();oEe();WEe();tBe();nBe();bf();Bs=z(require("@sentry/node"),1);O0();cBe=z(a4(),1);RO();Vh=z(require("node:path"),1),uBe=require("node:os");Ic();Bt();w0();v_();It=ve("MCP",{debug:()=>!!(process.env.DEBUG||process.env.FUSION_DEBUG==="true")}),Opt=1e4});function Wpt(t){return t==="project"?(0,QB.join)(process.cwd(),"mcp.json"):(0,QB.join)((0,dBe.homedir)(),".builder","mcp.json")}function zpt(t){return t==="project"?"project":"user"}function Xpt(t){if(!(0,OA.existsSync)(t))return{};let e=(0,OA.readFileSync)(t,"utf8");return e.trim()?JSON.parse(e):{}}function Zpt(t,e){let r=!1;if((0,OA.existsSync)(t))try{r=(0,OA.readFileSync)(t,"utf8").includes(`\r
|
|
1759
1759
|
`)}catch{}else(0,OA.mkdirSync)((0,QB.dirname)(t),{recursive:!0});let n=JSON.stringify(e,null,2)+`
|
|
1760
1760
|
`;r&&(n=n.replace(/\n/g,`\r
|
|
1761
1761
|
`)),(0,OA.writeFileSync)(t,n,"utf8")}function edt(t){if(!t||typeof t!="string")throw new Error("MCP server name is required.");if(t.toLowerCase()==="workspace")throw new Error("`workspace` is a reserved MCP server name; pick a different name.");return BA(t)||t}function fBe(t,e,r){let n=edt(t),i=Wpt(e),s=Xpt(i),o=s.mcpServers??{},a=o[n];if(!a)throw new Error(`No MCP server "${n}" in ${zpt(e)} config (${i}).`);return r?a.disabled=!0:delete a.disabled,o[n]=a,s.mcpServers=o,Zpt(i,s),{scope:e,path:i,name:n,disabled:r}}var OA,dBe,QB,hBe=L(()=>{"use strict";h();OA=require("node:fs"),dBe=require("node:os"),QB=require("node:path");O0()});function tdt(t){return t.replace(/^[ab]\//,"")}function rdt(t){let e=new Map,r=t.split(`
|
|
1762
|
-
`);for(let i of r){let s=i.trim();if(s!=="")if(s.startsWith(":")){let o=s.split(" ");if(o.length>=2){let a=o[0],A=o.slice(1).join(" "),c=a.match(/[AMDRTC]$/);if(c){let u=c[0],l;switch(u){case"A":l="create";break;case"D":l="delete";break;default:l="update";break}let d=e.get(A)||{addedLines:0,removedLines:0};d.action=l,e.set(A,d)}}}else{let o=s.split(" ");if(o.length>=3){let a=o[0],A=o[1],c=o.slice(2).join(" "),u=a==="-"?0:parseInt(a,10)||0,l=A==="-"?0:parseInt(A,10)||0,d=e.get(c)||{addedLines:0,removedLines:0};d.addedLines=u,d.removedLines=l,e.set(c,d)}}}let n=[];for(let[i,{addedLines:s,removedLines:o,action:a}]of e.entries())n.push({filePath:i,addedLines:s,removedLines:o,action:a||"update",content:void 0,oldContent:void 0});return n}function
|
|
1762
|
+
`);for(let i of r){let s=i.trim();if(s!=="")if(s.startsWith(":")){let o=s.split(" ");if(o.length>=2){let a=o[0],A=o.slice(1).join(" "),c=a.match(/[AMDRTC]$/);if(c){let u=c[0],l;switch(u){case"A":l="create";break;case"D":l="delete";break;default:l="update";break}let d=e.get(A)||{addedLines:0,removedLines:0};d.action=l,e.set(A,d)}}}else{let o=s.split(" ");if(o.length>=3){let a=o[0],A=o[1],c=o.slice(2).join(" "),u=a==="-"?0:parseInt(a,10)||0,l=A==="-"?0:parseInt(A,10)||0,d=e.get(c)||{addedLines:0,removedLines:0};d.addedLines=u,d.removedLines=l,e.set(c,d)}}}let n=[];for(let[i,{addedLines:s,removedLines:o,action:a}]of e.entries())n.push({filePath:i,addedLines:s,removedLines:o,action:a||"update",content:void 0,oldContent:void 0});return n}function u4(t,e=!1){let r=[],n=t.split(`
|
|
1763
1763
|
`),i=null,s=null,o=null,a=0,A=0,c=[],u=[],l=!1,d=!1;if(e)return rdt(t);for(let g=0;g<n.length;g++){let p=n[g];if(p.startsWith("--- ")||p.startsWith("+++ ")){if(i&&o){let C;l?C="create":d?C="delete":C="update";let I=C==="delete"&&s?s:i;r.push({filePath:I,addedLines:a,removedLines:A,action:C,content:c.length>0?c.join(`
|
|
1764
1764
|
`):void 0,oldContent:u.length>0?u.join(`
|
|
1765
1765
|
`):void 0})}let f=p.substring(4).split(" ")[0],m=tdt(f);p.startsWith("--- ")?(s=m,i=m,a=0,A=0,c=[],u=[],o=null,l=f==="/dev/null",d=!1):p.startsWith("+++ ")&&(d=f==="/dev/null",f==="/dev/null"?i=s:i=m);continue}else{if(p.startsWith("@@"))continue;p.startsWith("+")?(a++,c.push(p.substring(1)),o===null&&(o="update")):p.startsWith("-")?(A++,u.push(p.substring(1)),o===null&&(o="update")):(p.startsWith(" ")||p==="")&&(c.push(p.substring(1)),u.push(p.substring(1)))}}if(i&&o){let g;l?g="create":d?g="delete":g="update";let p=g==="delete"&&s?s:i;r.push({filePath:p,addedLines:a,removedLines:A,action:g,content:c.length>0?c.join(`
|
|
1766
1766
|
`):void 0,oldContent:u.length>0?u.join(`
|
|
1767
|
-
`):void 0})}return r}var mBe=L(()=>{"use strict";h()});var wl,CBe=L(()=>{"use strict";h();wl=(...t)=>{typeof process<"u"&&process.env.DEBUG==="true"&&console.debug("[DEBUG] ",...t)}});var ndt,Wh,IBe,idt,sdt,odt,XS,lH=L(()=>{"use strict";h();CBe();ndt=()=>{if(typeof globalThis<"u"&&globalThis.crypto)return globalThis.crypto;if(typeof require<"u")try{let t=require("crypto");if(t.webcrypto)return t.webcrypto}catch{}throw new Error("Web Crypto API is not available. Requires Node.js 15+ or a browser environment.")},Wh=ndt(),IBe=async()=>{let t=await Wh.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),e=await Wh.subtle.exportKey("jwk",t);return JSON.stringify(e)},idt=async()=>Wh.getRandomValues(new Uint8Array(16)),sdt=async(t,e,r)=>{let n=await Wh.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:128},t,typeof r=="string"?new TextEncoder().encode(r):r);return Buffer.from(n)},odt=async(t,e,r)=>{let n=await Wh.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:128},t,r);return new TextDecoder().decode(n)},XS=async t=>{try{wl("validateEncryptionKey: Validating encryption key");let e=JSON.parse(t);wl("validateEncryptionKey: Parsed JWK");let r=await Wh.subtle.importKey("jwk",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);wl("validateEncryptionKey: Imported crypto key");let n="test",i=await idt();wl("validateEncryptionKey: Generated test IV",i);let s=await sdt(r,i,n);wl("validateEncryptionKey: Encrypted test data",s);let o=new Uint8Array(s);wl("validateEncryptionKey: Encrypted test data array",o);let a=await odt(r,i,o);return wl("validateEncryptionKey: Decrypted test data",a),a===n}catch(e){return console.error("Could not validate encryption key:",e),!1}}});function EBe(t){return t.length<=gH?t:t.slice(0,gH)+`... [+${t.length-gH} chars]`}var adt,gH,ZS,BBe=L(()=>{"use strict";h();kr();yr();hr();adt=5e3,gH=8e3,ZS=class{#n;#c;#s;#t=[];#o;#i=!1;#e=Promise.resolve();constructor(e){this.#n=e.credentials,this.#c=e.replayId,this.#s=e.debug??!1;let r=setInterval(()=>{this.#B()},adt);r.unref?.(),this.#o=r}recordText(e,r=Date.now()){this.#i||this.#a({ts:r,type:"text",content:EBe(e)})}recordReasoning(e,r=Date.now()){this.#i||this.#a({ts:r,type:"thinking",content:EBe(e)})}recordCheckpoint(e=Date.now(),r="",n){this.#i||this.#a({ts:e,type:"checkpoint",label:r,imageUrl:n})}#a(e){e.type!=="checkpoint"&&!e.content||this.#t.push(e)}async#B(){if(this.#t.length===0)return;let e=this.#t;return this.#t=[],this.#e=this.#e.catch(()=>{}).then(()=>this.#m(e)),this.#e}async#m(e){try{let r=new URL(`${Ne}/codegen/replay/${encodeURIComponent(this.#c)}/actions`);this.#n.builderPublicKey&&r.searchParams.set("apiKey",this.#n.builderPublicKey),this.#n.userId&&r.searchParams.set("userId",this.#n.userId);let n={"content-type":"application/json"};this.#n.builderPrivateKey&&(n.authorization=`Bearer ${this.#n.builderPrivateKey}`),await Fe(r,{method:"POST",body:JSON.stringify({actions:e}),headers:n,keepalive:!0},this.#s)}catch{}}async flush(){await this.#B(),await this.#e.catch(()=>{})}async close(){this.#i||(this.#i=!0,this.#o&&clearInterval(this.#o),await this.flush())}}});var pH,yBe,Adt,QBe=L(()=>{h();pH=(t,e,r)=>{let n=t instanceof RegExp?yBe(t,r):t,i=e instanceof RegExp?yBe(e,r):e,s=n!==null&&i!=null&&Adt(n,i,r);return s&&{start:s[0],end:s[1],pre:r.slice(0,s[0]),body:r.slice(s[0]+n.length,s[1]),post:r.slice(s[1]+i.length)}},yBe=(t,e)=>{let r=e.match(t);return r?r[0]:null},Adt=(t,e,r)=>{let n,i,s,o,a,A=r.indexOf(t),c=r.indexOf(e,A+1),u=A;if(A>=0&&c>0){if(t===e)return[A,c];for(n=[],s=r.length;u>=0&&!a;){if(u===A)n.push(u),A=r.indexOf(t,u+1);else if(n.length===1){let l=n.pop();l!==void 0&&(a=[l,c])}else i=n.pop(),i!==void 0&&i<s&&(s=i,o=c),c=r.indexOf(e,u+1);u=A<c&&A>=0?A:c}n.length&&o!==void 0&&(a=[s,o])}return a}});function dH(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function Edt(t){return t.replace(ddt,DBe).replace(fdt,wBe).replace(hdt,fH).replace(mdt,bBe).replace(Cdt,vBe)}function Bdt(t){return t.replace(cdt,"\\").replace(udt,"{").replace(ldt,"}").replace(gdt,",").replace(pdt,".")}function SBe(t){if(!t)return[""];let e=[],r=pH("{","}",t);if(!r)return t.split(",");let{pre:n,body:i,post:s}=r,o=n.split(",");o[o.length-1]+="{"+i+"}";let a=SBe(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function xBe(t,e={}){if(!t)return[];let{max:r=Idt}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),DB(Edt(t),r,!0).map(Bdt)}function ydt(t){return"{"+t+"}"}function Qdt(t){return/^-?0\d/.test(t)}function Ddt(t,e){return t<=e}function wdt(t,e){return t>=e}function DB(t,e,r){let n=[],i=pH("{","}",t);if(!i)return[t];let s=i.pre,o=i.post.length?DB(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let A=s+"{"+i.body+"}"+o[a];n.push(A)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),A=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||A,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+fH+i.post,DB(t,e,!0)):[t];let l;if(c)l=i.body.split(/\.\./);else if(l=SBe(i.body),l.length===1&&l[0]!==void 0&&(l=DB(l[0],e,!1).map(ydt),l.length===1))return o.map(g=>i.pre+l[0]+g);let d;if(c&&l[0]!==void 0&&l[1]!==void 0){let g=dH(l[0]),p=dH(l[1]),f=Math.max(l[0].length,l[1].length),m=l.length===3&&l[2]!==void 0?Math.abs(dH(l[2])):1,C=Ddt;p<g&&(m*=-1,C=wdt);let y=l.some(Qdt);d=[];for(let B=g;C(B,p);B+=m){let E;if(A)E=String.fromCharCode(B),E==="\\"&&(E="");else if(E=String(B),y){let Q=f-E.length;if(Q>0){let v=new Array(Q+1).join("0");B<0?E="-"+v+E.slice(1):E=v+E}}d.push(E)}}else{d=[];for(let g=0;g<l.length;g++)d.push.apply(d,DB(l[g],e,!1))}for(let g=0;g<d.length;g++)for(let p=0;p<o.length&&n.length<e;p++){let f=s+d[g]+o[p];(!r||c||f)&&n.push(f)}}return n}var DBe,wBe,fH,bBe,vBe,cdt,udt,ldt,gdt,pdt,ddt,fdt,hdt,mdt,Cdt,Idt,FBe=L(()=>{h();QBe();DBe="\0SLASH"+Math.random()+"\0",wBe="\0OPEN"+Math.random()+"\0",fH="\0CLOSE"+Math.random()+"\0",bBe="\0COMMA"+Math.random()+"\0",vBe="\0PERIOD"+Math.random()+"\0",cdt=new RegExp(DBe,"g"),udt=new RegExp(wBe,"g"),ldt=new RegExp(fH,"g"),gdt=new RegExp(bBe,"g"),pdt=new RegExp(vBe,"g"),ddt=/\\\\/g,fdt=/\\{/g,hdt=/\\}/g,mdt=/\\,/g,Cdt=/\\\./g,Idt=1e5});var wB,kBe=L(()=>{h();wB=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")}});var bdt,bB,vdt,RBe,TBe,NBe=L(()=>{h();bdt={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},bB=t=>t.replace(/[[\]\\-]/g,"\\$&"),vdt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),RBe=t=>t.join(""),TBe=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],s=r+1,o=!1,a=!1,A=!1,c=!1,u=r,l="";e:for(;s<t.length;){let f=t.charAt(s);if((f==="!"||f==="^")&&s===r+1){c=!0,s++;continue}if(f==="]"&&o&&!A){u=s+1;break}if(o=!0,f==="\\"&&!A){A=!0,s++;continue}if(f==="["&&!A){for(let[m,[C,I,y]]of Object.entries(bdt))if(t.startsWith(m,s)){if(l)return["$.",!1,t.length-r,!0];s+=m.length,y?i.push(C):n.push(C),a=a||I;continue e}}if(A=!1,l){f>l?n.push(bB(l)+"-"+bB(f)):f===l&&n.push(bB(f)),l="",s++;continue}if(t.startsWith("-]",s+1)){n.push(bB(f+"-")),s+=2;continue}if(t.startsWith("-",s+1)){l=f,s+=2;continue}n.push(bB(f)),s++}if(u<s)return["",!1,0,!1];if(!n.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let f=n[0].length===2?n[0].slice(-1):n[0];return[vdt(f),!1,u-r,!1]}let d="["+(c?"^":"")+RBe(n)+"]",g="["+(c?"":"^")+RBe(i)+"]";return[n.length&&i.length?"("+d+"|"+g+")":n.length?d:g,a,u-r,!0]}});var bl,ex=L(()=>{h();bl=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1")});var ys,Sdt,hH,MBe,xdt,Fdt,kdt,PBe,Rdt,tx,Tdt,Ndt,Mdt,Pdt,mH,LBe,_Be,Ldt,kp,CH=L(()=>{h();NBe();ex();Sdt=new Set(["!","?","+","*","@"]),hH=t=>Sdt.has(t),MBe=t=>hH(t.type),xdt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Fdt=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),kdt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),PBe=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Rdt="(?!(?:^|/)\\.\\.?(?:$|/))",tx="(?!\\.)",Tdt=new Set(["[","."]),Ndt=new Set(["..","."]),Mdt=new Set("().*{}+?[]^$\\!"),Pdt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),mH="[^/]",LBe=mH+"*?",_Be=mH+"+?",Ldt=0,kp=class{type;#n;#c;#s=!1;#t=[];#o;#i;#e;#a=!1;#B;#m;#L=!1;id=++Ldt;get depth(){return(this.#o?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#n.id,parent:this.#o?.id,depth:this.depth,partsLength:this.#t.length,parts:this.#t}}constructor(e,r,n={}){this.type=e,e&&(this.#c=!0),this.#o=r,this.#n=this.#o?this.#o.#n:this,this.#B=this.#n===this?n:this.#n.#B,this.#e=this.#n===this?[]:this.#n.#e,e==="!"&&!this.#n.#a&&this.#e.push(this),this.#i=this.#o?this.#o.#t.length:0}get hasMagic(){if(this.#c!==void 0)return this.#c;for(let e of this.#t)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#c=!0;return this.#c}toString(){return this.#m!==void 0?this.#m:this.type?this.#m=this.type+"("+this.#t.map(e=>String(e)).join("|")+")":this.#m=this.#t.map(e=>String(e)).join("")}#k(){if(this!==this.#n)throw new Error("should only call on root");if(this.#a)return this;this.toString(),this.#a=!0;let e;for(;e=this.#e.pop();){if(e.type!=="!")continue;let r=e,n=r.#o;for(;n;){for(let i=r.#i+1;!n.type&&i<n.#t.length;i++)for(let s of e.#t){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(n.#t[i])}r=n,n=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof ys&&r.#o===this))throw new Error("invalid part: "+r);this.#t.push(r)}}toJSON(){let e=this.type===null?this.#t.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#t.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#n||this.#n.#a&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#n===this)return!0;if(!this.#o?.isStart())return!1;if(this.#i===0)return!0;let e=this.#o;for(let r=0;r<this.#i;r++){let n=e.#t[r];if(!(n instanceof ys&&n.type==="!"))return!1}return!0}isEnd(){if(this.#n===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#t.length:0;return this.#i===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new ys(this.type,e);for(let n of this.#t)r.copyIn(n);return r}static#b(e,r,n,i,s){let o=i.maxExtglobRecursion??2,a=!1,A=!1,c=-1,u=!1;if(r.type===null){let f=n,m="";for(;f<e.length;){let C=e.charAt(f++);if(a||C==="\\"){a=!a,m+=C;continue}if(A){f===c+1?(C==="^"||C==="!")&&(u=!0):C==="]"&&!(f===c+2&&u)&&(A=!1),m+=C;continue}else if(C==="["){A=!0,c=f,u=!1,m+=C;continue}if(!i.noext&&hH(C)&&e.charAt(f)==="("&&s<=o){r.push(m),m="";let y=new ys(C,r);f=ys.#b(e,y,f,i,s+1),r.push(y);continue}m+=C}return r.push(m),f}let l=n+1,d=new ys(null,r),g=[],p="";for(;l<e.length;){let f=e.charAt(l++);if(a||f==="\\"){a=!a,p+=f;continue}if(A){l===c+1?(f==="^"||f==="!")&&(u=!0):f==="]"&&!(l===c+2&&u)&&(A=!1),p+=f;continue}else if(f==="["){A=!0,c=l,u=!1,p+=f;continue}if(!i.noext&&hH(f)&&e.charAt(l)==="("&&(s<=o||r&&r.#p(f))){let C=r&&r.#p(f)?0:1;d.push(p),p="";let I=new ys(f,d);d.push(I),l=ys.#b(e,I,l,i,s+C);continue}if(f==="|"){d.push(p),p="",g.push(d),d=new ys(null,r);continue}if(f===")")return p===""&&r.#t.length===0&&(r.#L=!0),d.push(p),p="",r.push(...g,d),l;p+=f}return r.type=null,r.#c=void 0,r.#t=[e.substring(n-1)],l}#S(e){return this.#A(e,Fdt)}#A(e,r=xdt){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null)return!1;let n=e.#t[0];return!n||typeof n!="object"||n.type===null?!1:this.#p(n.type,r)}#p(e,r=kdt){return!!r.get(this.type)?.includes(e)}#r(e,r){let n=e.#t[0],i=new ys(null,n,this.options);i.#t.push(""),n.push(i),this.#g(e,r)}#g(e,r){let n=e.#t[0];this.#t.splice(r,1,...n.#t);for(let i of n.#t)typeof i=="object"&&(i.#o=this);this.#m=void 0}#J(e){return!!PBe.get(this.type)?.has(e)}#z(e){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null||this.#t.length!==1)return!1;let r=e.#t[0];return!r||typeof r!="object"||r.type===null?!1:this.#J(r.type)}#N(e){let r=PBe.get(this.type),n=e.#t[0],i=r?.get(n.type);if(!i)return!1;this.#t=n.#t;for(let s of this.#t)typeof s=="object"&&(s.#o=this);this.type=i,this.#m=void 0,this.#L=!1}static fromGlob(e,r={}){let n=new ys(null,void 0,r);return ys.#b(e,n,0,r,0),n}toMMPattern(){if(this!==this.#n)return this.#n.toMMPattern();let e=this.toString(),[r,n,i,s]=this.toRegExpSource();if(!(i||this.#c||this.#B.nocase&&!this.#B.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#B.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:e})}get options(){return this.#B}toRegExpSource(e){let r=e??!!this.#B.dot;if(this.#n===this&&(this.#R(),this.#k()),!MBe(this)){let A=this.isStart()&&this.isEnd()&&!this.#t.some(g=>typeof g!="string"),c=this.#t.map(g=>{let[p,f,m,C]=typeof g=="string"?ys.#j(g,this.#c,A):g.toRegExpSource(e);return this.#c=this.#c||m,this.#s=this.#s||C,p}).join(""),u="";if(this.isStart()&&typeof this.#t[0]=="string"&&!(this.#t.length===1&&Ndt.has(this.#t[0]))){let p=Tdt,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?Rdt:m?tx:""}let l="";return this.isEnd()&&this.#n.#a&&this.#o?.type==="!"&&(l="(?:$|\\/)"),[u+c+l,bl(c),this.#c=!!this.#c,this.#s]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#T(r);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let A=this.toString(),c=this;return c.#t=[A],c.type=null,c.#c=void 0,[A,bl(this.toString()),!1,!1]}let o=!n||e||r||!tx?"":this.#T(!0);o===s&&(o=""),o&&(s=`(?:${s})(?:${o})*?`);let a="";if(this.type==="!"&&this.#L)a=(this.isStart()&&!r?tx:"")+_Be;else{let A=this.type==="!"?"))"+(this.isStart()&&!r&&!e?tx:"")+LBe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+s+A}return[a,bl(s),this.#c=!!this.#c,this.#s]}#R(){if(MBe(this)){let e=0,r=!1;do{r=!0;for(let n=0;n<this.#t.length;n++){let i=this.#t[n];typeof i=="object"&&(i.#R(),this.#A(i)?(r=!1,this.#g(i,n)):this.#S(i)?(r=!1,this.#r(i,n)):this.#z(i)&&(r=!1,this.#N(i)))}}while(!r&&++e<10)}else for(let e of this.#t)typeof e=="object"&&e.#R();this.#m=void 0}#T(e){return this.#t.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,s,o]=r.toRegExpSource(e);return this.#s=this.#s||o,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#j(e,r,n=!1){let i=!1,s="",o=!1,a=!1;for(let A=0;A<e.length;A++){let c=e.charAt(A);if(i){i=!1,s+=(Mdt.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,s+=n&&/^[*]+$/.test(e)?_Be:LBe,r=!0;continue}else a=!1;if(c==="\\"){A===e.length-1?s+="\\\\":i=!0;continue}if(c==="["){let[u,l,d,g]=TBe(e,A);if(d){s+=u,o=o||l,A+=d-1,r=r||g;continue}}if(c==="?"){s+=mH,r=!0;continue}s+=Pdt(c)}return[s,bl(e),!!r,o]}};ys=kp});var IH,EH=L(()=>{h();IH=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&")});var Ii,_dt,Udt,Gdt,Odt,Kdt,Hdt,Jdt,jdt,Ydt,qdt,$dt,Vdt,Wdt,zdt,Xdt,Zdt,eft,tft,OBe,KBe,HBe,UBe,rft,Ui,nft,ift,sft,oft,aft,Lo,Aft,JBe,cft,uft,GBe,lft,zh,jBe=L(()=>{h();FBe();kBe();CH();EH();ex();CH();EH();ex();Ii=(t,e,r={})=>(wB(e),!r.nocomment&&e.charAt(0)==="#"?!1:new zh(e,r).match(t)),_dt=/^\*+([^+@!?\*\[\(]*)$/,Udt=t=>e=>!e.startsWith(".")&&e.endsWith(t),Gdt=t=>e=>e.endsWith(t),Odt=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),Kdt=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),Hdt=/^\*+\.\*+$/,Jdt=t=>!t.startsWith(".")&&t.includes("."),jdt=t=>t!=="."&&t!==".."&&t.includes("."),Ydt=/^\.\*+$/,qdt=t=>t!=="."&&t!==".."&&t.startsWith("."),$dt=/^\*+$/,Vdt=t=>t.length!==0&&!t.startsWith("."),Wdt=t=>t.length!==0&&t!=="."&&t!=="..",zdt=/^\?+([^+@!?\*\[\(]*)?$/,Xdt=([t,e=""])=>{let r=OBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},Zdt=([t,e=""])=>{let r=KBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},eft=([t,e=""])=>{let r=KBe([t]);return e?n=>r(n)&&n.endsWith(e):r},tft=([t,e=""])=>{let r=OBe([t]);return e?n=>r(n)&&n.endsWith(e):r},OBe=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},KBe=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},HBe=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",UBe={win32:{sep:"\\"},posix:{sep:"/"}},rft=HBe==="win32"?UBe.win32.sep:UBe.posix.sep;Ii.sep=rft;Ui=Symbol("globstar **");Ii.GLOBSTAR=Ui;nft="[^/]",ift=nft+"*?",sft="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",oft="(?:(?!(?:\\/|^)\\.).)*?",aft=(t,e={})=>r=>Ii(r,t,e);Ii.filter=aft;Lo=(t,e={})=>Object.assign({},t,e),Aft=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ii;let e=Ii;return Object.assign((n,i,s={})=>e(n,i,Lo(t,s)),{Minimatch:class extends e.Minimatch{constructor(i,s={}){super(i,Lo(t,s))}static defaults(i){return e.defaults(Lo(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,s,o={}){super(i,s,Lo(t,o))}static fromGlob(i,s={}){return e.AST.fromGlob(i,Lo(t,s))}},unescape:(n,i={})=>e.unescape(n,Lo(t,i)),escape:(n,i={})=>e.escape(n,Lo(t,i)),filter:(n,i={})=>e.filter(n,Lo(t,i)),defaults:n=>e.defaults(Lo(t,n)),makeRe:(n,i={})=>e.makeRe(n,Lo(t,i)),braceExpand:(n,i={})=>e.braceExpand(n,Lo(t,i)),match:(n,i,s={})=>e.match(n,i,Lo(t,s)),sep:e.sep,GLOBSTAR:Ui})};Ii.defaults=Aft;JBe=(t,e={})=>(wB(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:xBe(t,{max:e.braceExpandMax}));Ii.braceExpand=JBe;cft=(t,e={})=>new zh(t,e).makeRe();Ii.makeRe=cft;uft=(t,e,r={})=>{let n=new zh(e,r);return t=t.filter(i=>n.match(i)),n.options.nonull&&!t.length&&t.push(e),t};Ii.match=uft;GBe=/[?*]|[+@!]\(.*?\)|\[|\]/,lft=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zh=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,r={}){wB(e),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=e,this.platform=r.platform||HBe,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let r of e)if(typeof r!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,r=this.options;if(!r.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let A=s[0]===""&&s[1]===""&&(s[2]==="?"||!GBe.test(s[2]))&&!GBe.test(s[3]),c=/^[a-z]:/i.test(s[0]);if(A)return[...s.slice(0,4),...s.slice(4).map(u=>this.parse(u))];if(c)return[s[0],...s.slice(1).map(u=>this.parse(u))]}return s.map(A=>this.parse(A))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let o=this.set[s];o[0]===""&&o[1]===""&&this.globParts[s][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let i=0;i<e[n].length;i++)e[n][i]==="**"&&(e[n][i]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):r>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(e){return e.map(r=>(r=r.reduce((n,i)=>{let s=n[n.length-1];return i==="**"&&s==="**"?n:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;i<e.length-1;i++){let s=e[i];i===1&&s===""&&e[0]===""||(s==="."||s==="")&&(r=!0,e.splice(i,1),i--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(r=!0,e.pop())}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let i=e[n-1];i&&i!=="."&&i!==".."&&i!=="**"&&(r=!0,e.splice(n-1,2),n-=2)}}while(r);return e.length===0?[""]:e}firstPhasePreProcess(e){let r=!1;do{r=!1;for(let n of e){let i=-1;for(;(i=n.indexOf("**",i+1))!==-1;){let o=i;for(;n[o+1]==="**";)o++;o>i&&n.splice(i+1,o-i);let a=n[i+1],A=n[i+2],c=n[i+3];if(a!==".."||!A||A==="."||A===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(i,1);let u=n.slice(0);u[i]="**",e.push(u),i--}if(!this.preserveMultipleSlashes){for(let o=1;o<n.length-1;o++){let a=n[o];o===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(o,1),o--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let s=0;for(;(s=n.indexOf("..",s+1))!==-1;){let o=n[s-1];if(o&&o!=="."&&o!==".."&&o!=="**"){r=!0;let A=s===1&&n[s+1]==="**"?["."]:[];n.splice(s-1,2,...A),n.length===0&&n.push(""),s-=2}}}}while(r);return e}secondPhasePreProcess(e){for(let r=0;r<e.length-1;r++)for(let n=r+1;n<e.length;n++){let i=this.partsMatch(e[r],e[n],!this.preserveMultipleSlashes);if(i){e[r]=[],e[n]=i;break}}return e.filter(r=>r.length)}partsMatch(e,r,n=!1){let i=0,s=0,o=[],a="";for(;i<e.length&&s<r.length;)if(e[i]===r[s])o.push(a==="b"?r[s]:e[i]),i++,s++;else if(n&&e[i]==="**"&&r[s]===e[i+1])o.push(e[i]),i++;else if(n&&r[s]==="**"&&e[i]===r[s+1])o.push(r[s]),s++;else if(e[i]==="*"&&r[s]&&(this.options.dot||!r[s].startsWith("."))&&r[s]!=="**"){if(a==="b")return!1;a="a",o.push(e[i]),i++,s++}else if(r[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(a==="a")return!1;a="b",o.push(r[s]),i++,s++}else return!1;return e.length===r.length&&o}parseNegate(){if(this.nonegate)return;let e=this.pattern,r=!1,n=0;for(let i=0;i<e.length&&e.charAt(i)==="!";i++)r=!r,n++;n&&(this.pattern=e.slice(n)),this.negate=r}matchOne(e,r,n=!1){let i=0,s=0;if(this.isWindows){let a=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),A=!a&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),l=A?3:a?0:void 0,d=u?3:c?0:void 0;if(typeof l=="number"&&typeof d=="number"){let[g,p]=[e[l],r[d]];g.toLowerCase()===p.toLowerCase()&&(r[d]=g,s=d,i=l)}}let{optimizationLevel:o=1}=this.options;return o>=2&&(e=this.levelTwoFileOptimize(e)),r.includes(Ui)?this.#n(e,r,n,i,s):this.#s(e,r,n,i,s)}#n(e,r,n,i,s){let o=r.indexOf(Ui,s),a=r.lastIndexOf(Ui),[A,c,u]=n?[r.slice(s,o),r.slice(o+1),[]]:[r.slice(s,o),r.slice(o+1,a),r.slice(a+1)];if(A.length){let I=e.slice(i,i+A.length);if(!this.#s(I,A,n,0,0))return!1;i+=A.length,s+=A.length}let l=0;if(u.length){if(u.length+i>e.length)return!1;let I=e.length-u.length;if(this.#s(e,u,n,I,0))l=u.length;else{if(e[e.length-1]!==""||i+u.length===e.length||(I--,!this.#s(e,u,n,I,0)))return!1;l=u.length+1}}if(!c.length){let I=!!l;for(let y=i;y<e.length-l;y++){let B=String(e[y]);if(I=!0,B==="."||B===".."||!this.options.dot&&B.startsWith("."))return!1}return n||I}let d=[[[],0]],g=d[0],p=0,f=[0];for(let I of c)I===Ui?(f.push(p),g=[[],0],d.push(g)):(g[0].push(I),p++);let m=d.length-1,C=e.length-l;for(let I of d)I[1]=C-(f[m--]+I[0].length);return!!this.#c(e,d,i,0,n,0,!!l)}#c(e,r,n,i,s,o,a){let A=r[i];if(!A){for(let l=n;l<e.length;l++){a=!0;let d=e[l];if(d==="."||d===".."||!this.options.dot&&d.startsWith("."))return!1}return a}let[c,u]=A;for(;n<=u;){if(this.#s(e.slice(0,n+c.length),c,s,n,0)&&o<this.maxGlobstarRecursion){let g=this.#c(e,r,n+c.length,i+1,s,o+1,a);if(g!==!1)return g}let d=e[n];if(d==="."||d===".."||!this.options.dot&&d.startsWith("."))return!1;n++}return s||null}#s(e,r,n,i,s){let o,a,A,c;for(o=i,a=s,c=e.length,A=r.length;o<c&&a<A;o++,a++){this.debug("matchOne loop");let u=r[a],l=e[o];if(this.debug(r,u,l),u===!1||u===Ui)return!1;let d;if(typeof u=="string"?(d=l===u,this.debug("string match",u,l,d)):(d=u.test(l),this.debug("pattern match",u,l,d)),!d)return!1}if(o===c&&a===A)return!0;if(o===c)return n;if(a===A)return o===c-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return JBe(this.pattern,this.options)}parse(e){wB(e);let r=this.options;if(e==="**")return Ui;if(e==="")return"";let n,i=null;(n=e.match($dt))?i=r.dot?Wdt:Vdt:(n=e.match(_dt))?i=(r.nocase?r.dot?Kdt:Odt:r.dot?Gdt:Udt)(n[1]):(n=e.match(zdt))?i=(r.nocase?r.dot?Zdt:Xdt:r.dot?eft:tft)(n):(n=e.match(Hdt))?i=r.dot?jdt:Jdt:(n=e.match(Ydt))&&(i=qdt);let s=kp.fromGlob(e,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?ift:r.dot?sft:oft,i=new Set(r.nocase?["i"]:[]),s=e.map(A=>{let c=A.map(l=>{if(l instanceof RegExp)for(let d of l.flags.split(""))i.add(d);return typeof l=="string"?lft(l):l===Ui?Ui:l._src});c.forEach((l,d)=>{let g=c[d+1],p=c[d-1];l!==Ui||p===Ui||(p===void 0?g!==void 0&&g!==Ui?c[d+1]="(?:\\/|"+n+"\\/)?"+g:c[d]=n:g===void 0?c[d-1]=p+"(?:\\/|\\/"+n+")?":g!==Ui&&(c[d-1]=p+"(?:\\/|\\/"+n+"\\/)"+g,c[d+1]=Ui))});let u=c.filter(l=>l!==Ui);if(this.partial&&u.length>=1){let l=[];for(let d=1;d<=u.length;d++)l.push(u.slice(0,d).join("/"));return"(?:"+l.join("|")+")"}return u.join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];s="^"+o+s+a+"$",this.partial&&(s="^(?:\\/|"+o+s.slice(1,-1)+a+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,r=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let o=i[i.length-1];if(!o)for(let a=i.length-2;!o&&a>=0;a--)o=i[a];for(let a=0;a<s.length;a++){let A=s[a],c=i;if(n.matchBase&&A.length===1&&(c=[o]),this.matchOne(c,A,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return Ii.defaults(e).Minimatch}};Ii.AST=kp;Ii.Minimatch=zh;Ii.escape=IH;Ii.unescape=bl});async function gft(t,e,r){let n=t.builderPublicKey;if(!n)return[];let i=new URL(`${Ne}/projects/memories`);i.searchParams.set("apiKey",n),i.searchParams.set("projectId",e),t.userId&&i.searchParams.set("userId",t.userId);let s={"Content-Type":"application/json"};t.builderPrivateKey&&(s.Authorization=`Bearer ${t.builderPrivateKey}`);let a=await(await Fe(i,{method:"GET",headers:s,keepalive:!0,signal:r})).json();return Array.isArray(a?.memories)?a.memories:[]}function pft(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function YBe(t){return t.replace(/[*?{}[\]!]/g,"").replace(/\/+/g,"/").toLowerCase()}async function dft(t,e){let r=new Map;for(let i of t){let s=i.category||"general";r.has(s)||r.set(s,[]),r.get(s).push(i)}if(r.size===0)return;await rx.default.mkdir(e,{recursive:!0});let n=[];for(let[i,s]of r){let o=`${pft(i)}.md`,a=qBe.default.join(e,o),A=s.filter(g=>g.glob),c=s.filter(g=>!g.glob),u=new Map;for(let g of A){let p=g.glob;u.has(p)||u.set(p,[]),u.get(p).push(g)}let l=[...u.keys()].sort((g,p)=>YBe(g).localeCompare(YBe(p))),d=[];if(d.push(`# ${i}`),d.push(""),l.length>0){d.push("## File-specific"),d.push("");for(let g of l){let p=u.get(g);d.push(`### \`${g}\``),d.push("");for(let f of p)d.push(`- **When**: ${f.when}`),d.push(` ${f.memory}`),d.push("")}}if(c.length>0){d.push("## General"),d.push("");for(let g of c)d.push(`- **When**: ${g.when}`),d.push(` ${g.memory}`),d.push("")}n.push(rx.default.writeFile(a,d.join(`
|
|
1768
|
-
`),"utf-8"))}await Promise.all(n)}function fft(t){let e=[],r=0,n=0;for(let i=0;i<t.length;i++){let s=t[i];s==="{"?r++:s==="}"&&r>0?r--:s===","&&r===0&&(e.push(t.slice(n,i)),n=i+1)}return e.push(t.slice(n)),e.map(i=>i.trim()).filter(Boolean)}function $Be(t,e){if(!e)return[];let r=e.replace(/\\/g,"/");return t.filter(n=>n.glob?fft(n.glob).some(s=>{try{return Ii(r,s.replace(/\\/g,"/"),{matchBase:!0})}catch{return!1}}):!1)}async function VBe(t,e,r,n){try{return await gft(e,r,n)}catch(i){return t.Sentry?.captureException(new Error("Failed to load memories",{cause:i})),[]}}async function nx(t,e,r){try{await rx.default.rm(r,{recursive:!0,force:!0}),e.length>0&&await dft(e,r)}catch(n){t.Sentry?.captureException(new Error("Failed to sync memories to disk",{cause:n}))}}var rx,qBe,
|
|
1767
|
+
`):void 0})}return r}var mBe=L(()=>{"use strict";h()});var wl,CBe=L(()=>{"use strict";h();wl=(...t)=>{typeof process<"u"&&process.env.DEBUG==="true"&&console.debug("[DEBUG] ",...t)}});var ndt,Wh,IBe,idt,sdt,odt,XS,l4=L(()=>{"use strict";h();CBe();ndt=()=>{if(typeof globalThis<"u"&&globalThis.crypto)return globalThis.crypto;if(typeof require<"u")try{let t=require("crypto");if(t.webcrypto)return t.webcrypto}catch{}throw new Error("Web Crypto API is not available. Requires Node.js 15+ or a browser environment.")},Wh=ndt(),IBe=async()=>{let t=await Wh.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),e=await Wh.subtle.exportKey("jwk",t);return JSON.stringify(e)},idt=async()=>Wh.getRandomValues(new Uint8Array(16)),sdt=async(t,e,r)=>{let n=await Wh.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:128},t,typeof r=="string"?new TextEncoder().encode(r):r);return Buffer.from(n)},odt=async(t,e,r)=>{let n=await Wh.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:128},t,r);return new TextDecoder().decode(n)},XS=async t=>{try{wl("validateEncryptionKey: Validating encryption key");let e=JSON.parse(t);wl("validateEncryptionKey: Parsed JWK");let r=await Wh.subtle.importKey("jwk",e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);wl("validateEncryptionKey: Imported crypto key");let n="test",i=await idt();wl("validateEncryptionKey: Generated test IV",i);let s=await sdt(r,i,n);wl("validateEncryptionKey: Encrypted test data",s);let o=new Uint8Array(s);wl("validateEncryptionKey: Encrypted test data array",o);let a=await odt(r,i,o);return wl("validateEncryptionKey: Decrypted test data",a),a===n}catch(e){return console.error("Could not validate encryption key:",e),!1}}});function EBe(t){return t.length<=g4?t:t.slice(0,g4)+`... [+${t.length-g4} chars]`}var adt,g4,ZS,BBe=L(()=>{"use strict";h();kr();yr();hr();adt=5e3,g4=8e3,ZS=class{#n;#c;#s;#t=[];#o;#i=!1;#e=Promise.resolve();constructor(e){this.#n=e.credentials,this.#c=e.replayId,this.#s=e.debug??!1;let r=setInterval(()=>{this.#B()},adt);r.unref?.(),this.#o=r}recordText(e,r=Date.now()){this.#i||this.#a({ts:r,type:"text",content:EBe(e)})}recordReasoning(e,r=Date.now()){this.#i||this.#a({ts:r,type:"thinking",content:EBe(e)})}recordCheckpoint(e=Date.now(),r="",n){this.#i||this.#a({ts:e,type:"checkpoint",label:r,imageUrl:n})}#a(e){e.type!=="checkpoint"&&!e.content||this.#t.push(e)}async#B(){if(this.#t.length===0)return;let e=this.#t;return this.#t=[],this.#e=this.#e.catch(()=>{}).then(()=>this.#m(e)),this.#e}async#m(e){try{let r=new URL(`${Ne}/codegen/replay/${encodeURIComponent(this.#c)}/actions`);this.#n.builderPublicKey&&r.searchParams.set("apiKey",this.#n.builderPublicKey),this.#n.userId&&r.searchParams.set("userId",this.#n.userId);let n={"content-type":"application/json"};this.#n.builderPrivateKey&&(n.authorization=`Bearer ${this.#n.builderPrivateKey}`),await Fe(r,{method:"POST",body:JSON.stringify({actions:e}),headers:n,keepalive:!0},this.#s)}catch{}}async flush(){await this.#B(),await this.#e.catch(()=>{})}async close(){this.#i||(this.#i=!0,this.#o&&clearInterval(this.#o),await this.flush())}}});var p4,yBe,Adt,QBe=L(()=>{h();p4=(t,e,r)=>{let n=t instanceof RegExp?yBe(t,r):t,i=e instanceof RegExp?yBe(e,r):e,s=n!==null&&i!=null&&Adt(n,i,r);return s&&{start:s[0],end:s[1],pre:r.slice(0,s[0]),body:r.slice(s[0]+n.length,s[1]),post:r.slice(s[1]+i.length)}},yBe=(t,e)=>{let r=e.match(t);return r?r[0]:null},Adt=(t,e,r)=>{let n,i,s,o,a,A=r.indexOf(t),c=r.indexOf(e,A+1),u=A;if(A>=0&&c>0){if(t===e)return[A,c];for(n=[],s=r.length;u>=0&&!a;){if(u===A)n.push(u),A=r.indexOf(t,u+1);else if(n.length===1){let l=n.pop();l!==void 0&&(a=[l,c])}else i=n.pop(),i!==void 0&&i<s&&(s=i,o=c),c=r.indexOf(e,u+1);u=A<c&&A>=0?A:c}n.length&&o!==void 0&&(a=[s,o])}return a}});function d4(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function Edt(t){return t.replace(ddt,DBe).replace(fdt,wBe).replace(hdt,f4).replace(mdt,bBe).replace(Cdt,vBe)}function Bdt(t){return t.replace(cdt,"\\").replace(udt,"{").replace(ldt,"}").replace(gdt,",").replace(pdt,".")}function SBe(t){if(!t)return[""];let e=[],r=p4("{","}",t);if(!r)return t.split(",");let{pre:n,body:i,post:s}=r,o=n.split(",");o[o.length-1]+="{"+i+"}";let a=SBe(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function xBe(t,e={}){if(!t)return[];let{max:r=Idt}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),DB(Edt(t),r,!0).map(Bdt)}function ydt(t){return"{"+t+"}"}function Qdt(t){return/^-?0\d/.test(t)}function Ddt(t,e){return t<=e}function wdt(t,e){return t>=e}function DB(t,e,r){let n=[],i=p4("{","}",t);if(!i)return[t];let s=i.pre,o=i.post.length?DB(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let A=s+"{"+i.body+"}"+o[a];n.push(A)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),A=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||A,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+f4+i.post,DB(t,e,!0)):[t];let l;if(c)l=i.body.split(/\.\./);else if(l=SBe(i.body),l.length===1&&l[0]!==void 0&&(l=DB(l[0],e,!1).map(ydt),l.length===1))return o.map(g=>i.pre+l[0]+g);let d;if(c&&l[0]!==void 0&&l[1]!==void 0){let g=d4(l[0]),p=d4(l[1]),f=Math.max(l[0].length,l[1].length),m=l.length===3&&l[2]!==void 0?Math.abs(d4(l[2])):1,C=Ddt;p<g&&(m*=-1,C=wdt);let y=l.some(Qdt);d=[];for(let B=g;C(B,p);B+=m){let E;if(A)E=String.fromCharCode(B),E==="\\"&&(E="");else if(E=String(B),y){let Q=f-E.length;if(Q>0){let v=new Array(Q+1).join("0");B<0?E="-"+v+E.slice(1):E=v+E}}d.push(E)}}else{d=[];for(let g=0;g<l.length;g++)d.push.apply(d,DB(l[g],e,!1))}for(let g=0;g<d.length;g++)for(let p=0;p<o.length&&n.length<e;p++){let f=s+d[g]+o[p];(!r||c||f)&&n.push(f)}}return n}var DBe,wBe,f4,bBe,vBe,cdt,udt,ldt,gdt,pdt,ddt,fdt,hdt,mdt,Cdt,Idt,FBe=L(()=>{h();QBe();DBe="\0SLASH"+Math.random()+"\0",wBe="\0OPEN"+Math.random()+"\0",f4="\0CLOSE"+Math.random()+"\0",bBe="\0COMMA"+Math.random()+"\0",vBe="\0PERIOD"+Math.random()+"\0",cdt=new RegExp(DBe,"g"),udt=new RegExp(wBe,"g"),ldt=new RegExp(f4,"g"),gdt=new RegExp(bBe,"g"),pdt=new RegExp(vBe,"g"),ddt=/\\\\/g,fdt=/\\{/g,hdt=/\\}/g,mdt=/\\,/g,Cdt=/\\\./g,Idt=1e5});var wB,kBe=L(()=>{h();wB=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")}});var bdt,bB,vdt,RBe,TBe,NBe=L(()=>{h();bdt={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},bB=t=>t.replace(/[[\]\\-]/g,"\\$&"),vdt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),RBe=t=>t.join(""),TBe=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],s=r+1,o=!1,a=!1,A=!1,c=!1,u=r,l="";e:for(;s<t.length;){let f=t.charAt(s);if((f==="!"||f==="^")&&s===r+1){c=!0,s++;continue}if(f==="]"&&o&&!A){u=s+1;break}if(o=!0,f==="\\"&&!A){A=!0,s++;continue}if(f==="["&&!A){for(let[m,[C,I,y]]of Object.entries(bdt))if(t.startsWith(m,s)){if(l)return["$.",!1,t.length-r,!0];s+=m.length,y?i.push(C):n.push(C),a=a||I;continue e}}if(A=!1,l){f>l?n.push(bB(l)+"-"+bB(f)):f===l&&n.push(bB(f)),l="",s++;continue}if(t.startsWith("-]",s+1)){n.push(bB(f+"-")),s+=2;continue}if(t.startsWith("-",s+1)){l=f,s+=2;continue}n.push(bB(f)),s++}if(u<s)return["",!1,0,!1];if(!n.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let f=n[0].length===2?n[0].slice(-1):n[0];return[vdt(f),!1,u-r,!1]}let d="["+(c?"^":"")+RBe(n)+"]",g="["+(c?"":"^")+RBe(i)+"]";return[n.length&&i.length?"("+d+"|"+g+")":n.length?d:g,a,u-r,!0]}});var bl,ex=L(()=>{h();bl=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1")});var ys,Sdt,h4,MBe,xdt,Fdt,kdt,PBe,Rdt,tx,Tdt,Ndt,Mdt,Pdt,m4,LBe,_Be,Ldt,kp,C4=L(()=>{h();NBe();ex();Sdt=new Set(["!","?","+","*","@"]),h4=t=>Sdt.has(t),MBe=t=>h4(t.type),xdt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Fdt=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),kdt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),PBe=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Rdt="(?!(?:^|/)\\.\\.?(?:$|/))",tx="(?!\\.)",Tdt=new Set(["[","."]),Ndt=new Set(["..","."]),Mdt=new Set("().*{}+?[]^$\\!"),Pdt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),m4="[^/]",LBe=m4+"*?",_Be=m4+"+?",Ldt=0,kp=class{type;#n;#c;#s=!1;#t=[];#o;#i;#e;#a=!1;#B;#m;#L=!1;id=++Ldt;get depth(){return(this.#o?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#n.id,parent:this.#o?.id,depth:this.depth,partsLength:this.#t.length,parts:this.#t}}constructor(e,r,n={}){this.type=e,e&&(this.#c=!0),this.#o=r,this.#n=this.#o?this.#o.#n:this,this.#B=this.#n===this?n:this.#n.#B,this.#e=this.#n===this?[]:this.#n.#e,e==="!"&&!this.#n.#a&&this.#e.push(this),this.#i=this.#o?this.#o.#t.length:0}get hasMagic(){if(this.#c!==void 0)return this.#c;for(let e of this.#t)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#c=!0;return this.#c}toString(){return this.#m!==void 0?this.#m:this.type?this.#m=this.type+"("+this.#t.map(e=>String(e)).join("|")+")":this.#m=this.#t.map(e=>String(e)).join("")}#k(){if(this!==this.#n)throw new Error("should only call on root");if(this.#a)return this;this.toString(),this.#a=!0;let e;for(;e=this.#e.pop();){if(e.type!=="!")continue;let r=e,n=r.#o;for(;n;){for(let i=r.#i+1;!n.type&&i<n.#t.length;i++)for(let s of e.#t){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(n.#t[i])}r=n,n=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof ys&&r.#o===this))throw new Error("invalid part: "+r);this.#t.push(r)}}toJSON(){let e=this.type===null?this.#t.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#t.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#n||this.#n.#a&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#n===this)return!0;if(!this.#o?.isStart())return!1;if(this.#i===0)return!0;let e=this.#o;for(let r=0;r<this.#i;r++){let n=e.#t[r];if(!(n instanceof ys&&n.type==="!"))return!1}return!0}isEnd(){if(this.#n===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#t.length:0;return this.#i===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new ys(this.type,e);for(let n of this.#t)r.copyIn(n);return r}static#b(e,r,n,i,s){let o=i.maxExtglobRecursion??2,a=!1,A=!1,c=-1,u=!1;if(r.type===null){let f=n,m="";for(;f<e.length;){let C=e.charAt(f++);if(a||C==="\\"){a=!a,m+=C;continue}if(A){f===c+1?(C==="^"||C==="!")&&(u=!0):C==="]"&&!(f===c+2&&u)&&(A=!1),m+=C;continue}else if(C==="["){A=!0,c=f,u=!1,m+=C;continue}if(!i.noext&&h4(C)&&e.charAt(f)==="("&&s<=o){r.push(m),m="";let y=new ys(C,r);f=ys.#b(e,y,f,i,s+1),r.push(y);continue}m+=C}return r.push(m),f}let l=n+1,d=new ys(null,r),g=[],p="";for(;l<e.length;){let f=e.charAt(l++);if(a||f==="\\"){a=!a,p+=f;continue}if(A){l===c+1?(f==="^"||f==="!")&&(u=!0):f==="]"&&!(l===c+2&&u)&&(A=!1),p+=f;continue}else if(f==="["){A=!0,c=l,u=!1,p+=f;continue}if(!i.noext&&h4(f)&&e.charAt(l)==="("&&(s<=o||r&&r.#p(f))){let C=r&&r.#p(f)?0:1;d.push(p),p="";let I=new ys(f,d);d.push(I),l=ys.#b(e,I,l,i,s+C);continue}if(f==="|"){d.push(p),p="",g.push(d),d=new ys(null,r);continue}if(f===")")return p===""&&r.#t.length===0&&(r.#L=!0),d.push(p),p="",r.push(...g,d),l;p+=f}return r.type=null,r.#c=void 0,r.#t=[e.substring(n-1)],l}#S(e){return this.#A(e,Fdt)}#A(e,r=xdt){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null)return!1;let n=e.#t[0];return!n||typeof n!="object"||n.type===null?!1:this.#p(n.type,r)}#p(e,r=kdt){return!!r.get(this.type)?.includes(e)}#r(e,r){let n=e.#t[0],i=new ys(null,n,this.options);i.#t.push(""),n.push(i),this.#g(e,r)}#g(e,r){let n=e.#t[0];this.#t.splice(r,1,...n.#t);for(let i of n.#t)typeof i=="object"&&(i.#o=this);this.#m=void 0}#J(e){return!!PBe.get(this.type)?.has(e)}#z(e){if(!e||typeof e!="object"||e.type!==null||e.#t.length!==1||this.type===null||this.#t.length!==1)return!1;let r=e.#t[0];return!r||typeof r!="object"||r.type===null?!1:this.#J(r.type)}#N(e){let r=PBe.get(this.type),n=e.#t[0],i=r?.get(n.type);if(!i)return!1;this.#t=n.#t;for(let s of this.#t)typeof s=="object"&&(s.#o=this);this.type=i,this.#m=void 0,this.#L=!1}static fromGlob(e,r={}){let n=new ys(null,void 0,r);return ys.#b(e,n,0,r,0),n}toMMPattern(){if(this!==this.#n)return this.#n.toMMPattern();let e=this.toString(),[r,n,i,s]=this.toRegExpSource();if(!(i||this.#c||this.#B.nocase&&!this.#B.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#B.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:e})}get options(){return this.#B}toRegExpSource(e){let r=e??!!this.#B.dot;if(this.#n===this&&(this.#R(),this.#k()),!MBe(this)){let A=this.isStart()&&this.isEnd()&&!this.#t.some(g=>typeof g!="string"),c=this.#t.map(g=>{let[p,f,m,C]=typeof g=="string"?ys.#j(g,this.#c,A):g.toRegExpSource(e);return this.#c=this.#c||m,this.#s=this.#s||C,p}).join(""),u="";if(this.isStart()&&typeof this.#t[0]=="string"&&!(this.#t.length===1&&Ndt.has(this.#t[0]))){let p=Tdt,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?Rdt:m?tx:""}let l="";return this.isEnd()&&this.#n.#a&&this.#o?.type==="!"&&(l="(?:$|\\/)"),[u+c+l,bl(c),this.#c=!!this.#c,this.#s]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#T(r);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let A=this.toString(),c=this;return c.#t=[A],c.type=null,c.#c=void 0,[A,bl(this.toString()),!1,!1]}let o=!n||e||r||!tx?"":this.#T(!0);o===s&&(o=""),o&&(s=`(?:${s})(?:${o})*?`);let a="";if(this.type==="!"&&this.#L)a=(this.isStart()&&!r?tx:"")+_Be;else{let A=this.type==="!"?"))"+(this.isStart()&&!r&&!e?tx:"")+LBe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+s+A}return[a,bl(s),this.#c=!!this.#c,this.#s]}#R(){if(MBe(this)){let e=0,r=!1;do{r=!0;for(let n=0;n<this.#t.length;n++){let i=this.#t[n];typeof i=="object"&&(i.#R(),this.#A(i)?(r=!1,this.#g(i,n)):this.#S(i)?(r=!1,this.#r(i,n)):this.#z(i)&&(r=!1,this.#N(i)))}}while(!r&&++e<10)}else for(let e of this.#t)typeof e=="object"&&e.#R();this.#m=void 0}#T(e){return this.#t.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,s,o]=r.toRegExpSource(e);return this.#s=this.#s||o,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#j(e,r,n=!1){let i=!1,s="",o=!1,a=!1;for(let A=0;A<e.length;A++){let c=e.charAt(A);if(i){i=!1,s+=(Mdt.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,s+=n&&/^[*]+$/.test(e)?_Be:LBe,r=!0;continue}else a=!1;if(c==="\\"){A===e.length-1?s+="\\\\":i=!0;continue}if(c==="["){let[u,l,d,g]=TBe(e,A);if(d){s+=u,o=o||l,A+=d-1,r=r||g;continue}}if(c==="?"){s+=m4,r=!0;continue}s+=Pdt(c)}return[s,bl(e),!!r,o]}};ys=kp});var I4,E4=L(()=>{h();I4=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&")});var Ii,_dt,Udt,Gdt,Odt,Kdt,Hdt,Jdt,jdt,Ydt,qdt,$dt,Vdt,Wdt,zdt,Xdt,Zdt,eft,tft,OBe,KBe,HBe,UBe,rft,Ui,nft,ift,sft,oft,aft,Lo,Aft,JBe,cft,uft,GBe,lft,zh,jBe=L(()=>{h();FBe();kBe();C4();E4();ex();C4();E4();ex();Ii=(t,e,r={})=>(wB(e),!r.nocomment&&e.charAt(0)==="#"?!1:new zh(e,r).match(t)),_dt=/^\*+([^+@!?\*\[\(]*)$/,Udt=t=>e=>!e.startsWith(".")&&e.endsWith(t),Gdt=t=>e=>e.endsWith(t),Odt=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),Kdt=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),Hdt=/^\*+\.\*+$/,Jdt=t=>!t.startsWith(".")&&t.includes("."),jdt=t=>t!=="."&&t!==".."&&t.includes("."),Ydt=/^\.\*+$/,qdt=t=>t!=="."&&t!==".."&&t.startsWith("."),$dt=/^\*+$/,Vdt=t=>t.length!==0&&!t.startsWith("."),Wdt=t=>t.length!==0&&t!=="."&&t!=="..",zdt=/^\?+([^+@!?\*\[\(]*)?$/,Xdt=([t,e=""])=>{let r=OBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},Zdt=([t,e=""])=>{let r=KBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},eft=([t,e=""])=>{let r=KBe([t]);return e?n=>r(n)&&n.endsWith(e):r},tft=([t,e=""])=>{let r=OBe([t]);return e?n=>r(n)&&n.endsWith(e):r},OBe=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},KBe=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},HBe=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",UBe={win32:{sep:"\\"},posix:{sep:"/"}},rft=HBe==="win32"?UBe.win32.sep:UBe.posix.sep;Ii.sep=rft;Ui=Symbol("globstar **");Ii.GLOBSTAR=Ui;nft="[^/]",ift=nft+"*?",sft="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",oft="(?:(?!(?:\\/|^)\\.).)*?",aft=(t,e={})=>r=>Ii(r,t,e);Ii.filter=aft;Lo=(t,e={})=>Object.assign({},t,e),Aft=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ii;let e=Ii;return Object.assign((n,i,s={})=>e(n,i,Lo(t,s)),{Minimatch:class extends e.Minimatch{constructor(i,s={}){super(i,Lo(t,s))}static defaults(i){return e.defaults(Lo(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,s,o={}){super(i,s,Lo(t,o))}static fromGlob(i,s={}){return e.AST.fromGlob(i,Lo(t,s))}},unescape:(n,i={})=>e.unescape(n,Lo(t,i)),escape:(n,i={})=>e.escape(n,Lo(t,i)),filter:(n,i={})=>e.filter(n,Lo(t,i)),defaults:n=>e.defaults(Lo(t,n)),makeRe:(n,i={})=>e.makeRe(n,Lo(t,i)),braceExpand:(n,i={})=>e.braceExpand(n,Lo(t,i)),match:(n,i,s={})=>e.match(n,i,Lo(t,s)),sep:e.sep,GLOBSTAR:Ui})};Ii.defaults=Aft;JBe=(t,e={})=>(wB(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:xBe(t,{max:e.braceExpandMax}));Ii.braceExpand=JBe;cft=(t,e={})=>new zh(t,e).makeRe();Ii.makeRe=cft;uft=(t,e,r={})=>{let n=new zh(e,r);return t=t.filter(i=>n.match(i)),n.options.nonull&&!t.length&&t.push(e),t};Ii.match=uft;GBe=/[?*]|[+@!]\(.*?\)|\[|\]/,lft=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zh=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,r={}){wB(e),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=e,this.platform=r.platform||HBe,this.isWindows=this.platform==="win32";let n="allowWindowsEscape";this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r[n]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let r of e)if(typeof r!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,r=this.options;if(!r.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let A=s[0]===""&&s[1]===""&&(s[2]==="?"||!GBe.test(s[2]))&&!GBe.test(s[3]),c=/^[a-z]:/i.test(s[0]);if(A)return[...s.slice(0,4),...s.slice(4).map(u=>this.parse(u))];if(c)return[s[0],...s.slice(1).map(u=>this.parse(u))]}return s.map(A=>this.parse(A))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let o=this.set[s];o[0]===""&&o[1]===""&&this.globParts[s][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let i=0;i<e[n].length;i++)e[n][i]==="**"&&(e[n][i]="*");let{optimizationLevel:r=1}=this.options;return r>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):r>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(e){return e.map(r=>(r=r.reduce((n,i)=>{let s=n[n.length-1];return i==="**"&&s==="**"?n:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;i<e.length-1;i++){let s=e[i];i===1&&s===""&&e[0]===""||(s==="."||s==="")&&(r=!0,e.splice(i,1),i--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(r=!0,e.pop())}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let i=e[n-1];i&&i!=="."&&i!==".."&&i!=="**"&&(r=!0,e.splice(n-1,2),n-=2)}}while(r);return e.length===0?[""]:e}firstPhasePreProcess(e){let r=!1;do{r=!1;for(let n of e){let i=-1;for(;(i=n.indexOf("**",i+1))!==-1;){let o=i;for(;n[o+1]==="**";)o++;o>i&&n.splice(i+1,o-i);let a=n[i+1],A=n[i+2],c=n[i+3];if(a!==".."||!A||A==="."||A===".."||!c||c==="."||c==="..")continue;r=!0,n.splice(i,1);let u=n.slice(0);u[i]="**",e.push(u),i--}if(!this.preserveMultipleSlashes){for(let o=1;o<n.length-1;o++){let a=n[o];o===1&&a===""&&n[0]===""||(a==="."||a==="")&&(r=!0,n.splice(o,1),o--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(r=!0,n.pop())}let s=0;for(;(s=n.indexOf("..",s+1))!==-1;){let o=n[s-1];if(o&&o!=="."&&o!==".."&&o!=="**"){r=!0;let A=s===1&&n[s+1]==="**"?["."]:[];n.splice(s-1,2,...A),n.length===0&&n.push(""),s-=2}}}}while(r);return e}secondPhasePreProcess(e){for(let r=0;r<e.length-1;r++)for(let n=r+1;n<e.length;n++){let i=this.partsMatch(e[r],e[n],!this.preserveMultipleSlashes);if(i){e[r]=[],e[n]=i;break}}return e.filter(r=>r.length)}partsMatch(e,r,n=!1){let i=0,s=0,o=[],a="";for(;i<e.length&&s<r.length;)if(e[i]===r[s])o.push(a==="b"?r[s]:e[i]),i++,s++;else if(n&&e[i]==="**"&&r[s]===e[i+1])o.push(e[i]),i++;else if(n&&r[s]==="**"&&e[i]===r[s+1])o.push(r[s]),s++;else if(e[i]==="*"&&r[s]&&(this.options.dot||!r[s].startsWith("."))&&r[s]!=="**"){if(a==="b")return!1;a="a",o.push(e[i]),i++,s++}else if(r[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(a==="a")return!1;a="b",o.push(r[s]),i++,s++}else return!1;return e.length===r.length&&o}parseNegate(){if(this.nonegate)return;let e=this.pattern,r=!1,n=0;for(let i=0;i<e.length&&e.charAt(i)==="!";i++)r=!r,n++;n&&(this.pattern=e.slice(n)),this.negate=r}matchOne(e,r,n=!1){let i=0,s=0;if(this.isWindows){let a=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),A=!a&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),c=typeof r[0]=="string"&&/^[a-z]:$/i.test(r[0]),u=!c&&r[0]===""&&r[1]===""&&r[2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3]),l=A?3:a?0:void 0,d=u?3:c?0:void 0;if(typeof l=="number"&&typeof d=="number"){let[g,p]=[e[l],r[d]];g.toLowerCase()===p.toLowerCase()&&(r[d]=g,s=d,i=l)}}let{optimizationLevel:o=1}=this.options;return o>=2&&(e=this.levelTwoFileOptimize(e)),r.includes(Ui)?this.#n(e,r,n,i,s):this.#s(e,r,n,i,s)}#n(e,r,n,i,s){let o=r.indexOf(Ui,s),a=r.lastIndexOf(Ui),[A,c,u]=n?[r.slice(s,o),r.slice(o+1),[]]:[r.slice(s,o),r.slice(o+1,a),r.slice(a+1)];if(A.length){let I=e.slice(i,i+A.length);if(!this.#s(I,A,n,0,0))return!1;i+=A.length,s+=A.length}let l=0;if(u.length){if(u.length+i>e.length)return!1;let I=e.length-u.length;if(this.#s(e,u,n,I,0))l=u.length;else{if(e[e.length-1]!==""||i+u.length===e.length||(I--,!this.#s(e,u,n,I,0)))return!1;l=u.length+1}}if(!c.length){let I=!!l;for(let y=i;y<e.length-l;y++){let B=String(e[y]);if(I=!0,B==="."||B===".."||!this.options.dot&&B.startsWith("."))return!1}return n||I}let d=[[[],0]],g=d[0],p=0,f=[0];for(let I of c)I===Ui?(f.push(p),g=[[],0],d.push(g)):(g[0].push(I),p++);let m=d.length-1,C=e.length-l;for(let I of d)I[1]=C-(f[m--]+I[0].length);return!!this.#c(e,d,i,0,n,0,!!l)}#c(e,r,n,i,s,o,a){let A=r[i];if(!A){for(let l=n;l<e.length;l++){a=!0;let d=e[l];if(d==="."||d===".."||!this.options.dot&&d.startsWith("."))return!1}return a}let[c,u]=A;for(;n<=u;){if(this.#s(e.slice(0,n+c.length),c,s,n,0)&&o<this.maxGlobstarRecursion){let g=this.#c(e,r,n+c.length,i+1,s,o+1,a);if(g!==!1)return g}let d=e[n];if(d==="."||d===".."||!this.options.dot&&d.startsWith("."))return!1;n++}return s||null}#s(e,r,n,i,s){let o,a,A,c;for(o=i,a=s,c=e.length,A=r.length;o<c&&a<A;o++,a++){this.debug("matchOne loop");let u=r[a],l=e[o];if(this.debug(r,u,l),u===!1||u===Ui)return!1;let d;if(typeof u=="string"?(d=l===u,this.debug("string match",u,l,d)):(d=u.test(l),this.debug("pattern match",u,l,d)),!d)return!1}if(o===c&&a===A)return!0;if(o===c)return n;if(a===A)return o===c-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return JBe(this.pattern,this.options)}parse(e){wB(e);let r=this.options;if(e==="**")return Ui;if(e==="")return"";let n,i=null;(n=e.match($dt))?i=r.dot?Wdt:Vdt:(n=e.match(_dt))?i=(r.nocase?r.dot?Kdt:Odt:r.dot?Gdt:Udt)(n[1]):(n=e.match(zdt))?i=(r.nocase?r.dot?Zdt:Xdt:r.dot?eft:tft)(n):(n=e.match(Hdt))?i=r.dot?jdt:Jdt:(n=e.match(Ydt))&&(i=qdt);let s=kp.fromGlob(e,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?ift:r.dot?sft:oft,i=new Set(r.nocase?["i"]:[]),s=e.map(A=>{let c=A.map(l=>{if(l instanceof RegExp)for(let d of l.flags.split(""))i.add(d);return typeof l=="string"?lft(l):l===Ui?Ui:l._src});c.forEach((l,d)=>{let g=c[d+1],p=c[d-1];l!==Ui||p===Ui||(p===void 0?g!==void 0&&g!==Ui?c[d+1]="(?:\\/|"+n+"\\/)?"+g:c[d]=n:g===void 0?c[d-1]=p+"(?:\\/|\\/"+n+")?":g!==Ui&&(c[d-1]=p+"(?:\\/|\\/"+n+"\\/)"+g,c[d+1]=Ui))});let u=c.filter(l=>l!==Ui);if(this.partial&&u.length>=1){let l=[];for(let d=1;d<=u.length;d++)l.push(u.slice(0,d).join("/"));return"(?:"+l.join("|")+")"}return u.join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];s="^"+o+s+a+"$",this.partial&&(s="^(?:\\/|"+o+s.slice(1,-1)+a+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,r=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let o=i[i.length-1];if(!o)for(let a=i.length-2;!o&&a>=0;a--)o=i[a];for(let a=0;a<s.length;a++){let A=s[a],c=i;if(n.matchBase&&A.length===1&&(c=[o]),this.matchOne(c,A,r))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return Ii.defaults(e).Minimatch}};Ii.AST=kp;Ii.Minimatch=zh;Ii.escape=I4;Ii.unescape=bl});async function gft(t,e,r){let n=t.builderPublicKey;if(!n)return[];let i=new URL(`${Ne}/projects/memories`);i.searchParams.set("apiKey",n),i.searchParams.set("projectId",e),t.userId&&i.searchParams.set("userId",t.userId);let s={"Content-Type":"application/json"};t.builderPrivateKey&&(s.Authorization=`Bearer ${t.builderPrivateKey}`);let a=await(await Fe(i,{method:"GET",headers:s,keepalive:!0,signal:r})).json();return Array.isArray(a?.memories)?a.memories:[]}function pft(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function YBe(t){return t.replace(/[*?{}[\]!]/g,"").replace(/\/+/g,"/").toLowerCase()}async function dft(t,e){let r=new Map;for(let i of t){let s=i.category||"general";r.has(s)||r.set(s,[]),r.get(s).push(i)}if(r.size===0)return;await rx.default.mkdir(e,{recursive:!0});let n=[];for(let[i,s]of r){let o=`${pft(i)}.md`,a=qBe.default.join(e,o),A=s.filter(g=>g.glob),c=s.filter(g=>!g.glob),u=new Map;for(let g of A){let p=g.glob;u.has(p)||u.set(p,[]),u.get(p).push(g)}let l=[...u.keys()].sort((g,p)=>YBe(g).localeCompare(YBe(p))),d=[];if(d.push(`# ${i}`),d.push(""),l.length>0){d.push("## File-specific"),d.push("");for(let g of l){let p=u.get(g);d.push(`### \`${g}\``),d.push("");for(let f of p)d.push(`- **When**: ${f.when}`),d.push(` ${f.memory}`),d.push("")}}if(c.length>0){d.push("## General"),d.push("");for(let g of c)d.push(`- **When**: ${g.when}`),d.push(` ${g.memory}`),d.push("")}n.push(rx.default.writeFile(a,d.join(`
|
|
1768
|
+
`),"utf-8"))}await Promise.all(n)}function fft(t){let e=[],r=0,n=0;for(let i=0;i<t.length;i++){let s=t[i];s==="{"?r++:s==="}"&&r>0?r--:s===","&&r===0&&(e.push(t.slice(n,i)),n=i+1)}return e.push(t.slice(n)),e.map(i=>i.trim()).filter(Boolean)}function $Be(t,e){if(!e)return[];let r=e.replace(/\\/g,"/");return t.filter(n=>n.glob?fft(n.glob).some(s=>{try{return Ii(r,s.replace(/\\/g,"/"),{matchBase:!0})}catch{return!1}}):!1)}async function VBe(t,e,r,n){try{return await gft(e,r,n)}catch(i){return t.Sentry?.captureException(new Error("Failed to load memories",{cause:i})),[]}}async function nx(t,e,r){try{await rx.default.rm(r,{recursive:!0,force:!0}),e.length>0&&await dft(e,r)}catch(n){t.Sentry?.captureException(new Error("Failed to sync memories to disk",{cause:n}))}}var rx,qBe,B4=L(()=>{"use strict";h();rx=z(require("node:fs/promises"),1),qBe=z(require("node:path"),1);jBe();yr();hr()});var zBe,WBe=L(()=>{zBe=`You are a file search specialist for Fusion, Builder.io's AI software development assistant. You excel at thoroughly navigating and exploring codebases.
|
|
1769
1769
|
|
|
1770
1770
|
=== CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
|
|
1771
1771
|
This is a READ-ONLY exploration task. You are STRICTLY PROHIBITED from:
|
|
@@ -1796,7 +1796,7 @@ Notes:
|
|
|
1796
1796
|
- In your final response always share relevant file names and code snippets.
|
|
1797
1797
|
- For clear communication with the user the assistant MUST avoid using emojis.
|
|
1798
1798
|
- Before the report is finished, call ExplorationMetadata tool to communicate back which files are the most relevant to the user's prompt.
|
|
1799
|
-
`});var mft,Cft,Ift,Xh,
|
|
1799
|
+
`});var mft,Cft,Ift,Xh,y4=L(()=>{"use strict";h();WBe();mft="explorer",Cft='Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',Ift=["Read","Glob","Skill","Grep","WebSearch","SearchMemories","ExplorationMetadata"],Xh={name:mft,description:Cft,systemPrompt:zBe,tools:Ift,model:"opa5-mini",includeMemories:!0}});var ZBe,XBe=L(()=>{ZBe=`You are an agent for Fusion, Builder.io coding CLI. Given the user's message, you should use the tools available to complete the task. Complete the task fully\u2014don't gold-plate, but don't leave it half-done. When you complete the task, respond with a concise report covering what was done and any key findings \u2014 the caller will relay this to the user, so it only needs the essentials.
|
|
1800
1800
|
|
|
1801
1801
|
Your strengths:
|
|
1802
1802
|
- Searching for code, configurations, and patterns across large codebases
|
|
@@ -1817,10 +1817,10 @@ Notes:
|
|
|
1817
1817
|
- For clear communication with the user the assistant MUST avoid using emojis.
|
|
1818
1818
|
- Do not use a colon before tool calls. Text like "Let me read the file:" followed by a read tool call should just be "Let me read the file." with a period.
|
|
1819
1819
|
- Do NOT Write report/summary/findings/analysis .md files. Return findings directly as your final assistant message \u2014 the parent agent reads your text output, not files you create.
|
|
1820
|
-
`});var Bft,yft,ix,
|
|
1820
|
+
`});var Bft,yft,ix,Q4=L(()=>{"use strict";h();XBe();Bft="general-purpose",yft="General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)",ix={name:Bft,description:yft,systemPrompt:ZBe}});function Qft(){if(vB!==void 0)return vB;try{return vB=require("prettier"),vB}catch{return vB=null,null}}function _o(t){try{return JSON.stringify(t)}catch{return String(t)}}var vl,w4,sx,tye,cx,ox,rye,vB,eye,Dft,wft,bft,vft,ka,D4,Zh=L(()=>{"use strict";h();Cp();ahe();kr();Ls();yr();hr();vl=z(require("node:fs"),1),w4=require("node:crypto");TO();NO();ghe();fhe();xv();PL();pI();Fhe();sx=z(require("node:os"),1);t8();xi();Bt();_he();Ov();zhe();eme();Hs();r8();tye=z(require("chokidar"),1);i8();F4();Ame();T4();rr();cx=z(require("node:events"),1);JI();ox=require("node:crypto");Ap();lme();tU();jI();mI();Tu();pBe();z_();hBe();w0();xo();mBe();rye=require("node:fs/promises");l4();HI();kB();Ic();BBe();B4();da();K0();uw();Jv();y4();Q4();eye=["ask-to-continue","credits-limit-daily","credits-limit-monthly","credits-limit-user","credits-limit-other","invalid-last-message"],Dft=["initial-with-url","initial-without-url","success"],wft=1800*1e3,bft=2147483647,vft=t=>{let e=Number(process.env.AGENT_TIMEOUT_OVERRIDE_MS),r=Number.isFinite(e)&&e>0?e:t&&Number.isFinite(t)&&t>0?t:wft;return Math.min(r,bft)},ka=class t{#n;#c;#s;#t=[];#o;#i;#e;#a;#B;#m;#L;#k;#b;#S;#A=!!(process.env.DEBUG||process.env.FUSION_DEBUG==="true");#p=!1;#r=ve("Agent",{debug:()=>this.#A});#g=new cx.default;#J=new Map;#z=new Set;#N;#R;#T;#j=[];#se=void 0;#vt="";#re;#St=Promise.resolve(void 0);#X=[];#_;#Y=[];#at=!1;#we;#Z=new Map;#oe=new Map;#Oe=new Map;#Ke=[];#ae;#zt=0;#Ae;#ee;#h;#I;#xt;#At;#ct;#He=!1;#be;#ve=void 0;#ut;#Se;#Je;#ce;#d;#f=[];#x;#Ft;#C;#lt;#U;#xe=0;#ue;#D;#kt=[];#Rt=new Set;#u;#E;#y;#je;#q;#le;#gt;#Ye=!1;#Tt=0;#ge=null;#pe=0;#ne=!1;#qe;#$e;#M;#Ve;#Nt;#Mt;#de=[];#We=[];#pt=!1;#fe=new Map;#Fe=new Map;#ke={};#v={};#Pt=!1;#ze;#Lt;#dt=!1;#Xt=new Set;#Re;#P={};#ft;#Xe=[];#Ze=0;#he=null;#me=void 0;#_t=void 0;#w=new Map;#Q={watcher:null,listeners:new Set,debounceMs:300,pendingEvents:[]};#Ut=!1;#l=null;#et=new Set;#tt=new Map;#Te=new Map;#Ne=new Map;#Me=new Map;static#rt=3e4;#Pe=null;#Ce=[];get primaryGitPath(){return this.#f[0]?.path||this.#d}#Le(e){if(!e)return this.primaryGitPath;let r=this.#f.find(n=>n.folderName===e);if(!r)throw new Error(`Folder "${e}" not found in git-enabled folders`);return r.path}#Gt(e,r){if(typeof e!="string")throw new TypeError(`#parsePathWithFolder: 'path' must be a string, received ${typeof e}: ${_o(e)}`);if(r)return{repoPath:this.#Le(r),relativePath:e};for(let n of this.#f){let i=`${n.folderName}/`;if(e.startsWith(i))return{repoPath:n.path,relativePath:e.slice(i.length)}}return{repoPath:this.primaryGitPath,relativePath:e}}constructor(e){if(this.#e=e.sys,this.#q=e.modelOverride,this.#le=e.agentModelOverrides,this.#a=e.credentials,"initialUrl"in e){let n=gye(e.initialUrl).id;n?this.#ee=n:this.#B=e.initialUrl}typeof e.autoImportLocalMCPs=="boolean"&&(this.#Ut=e.autoImportLocalMCPs),"sessionOrCompletionId"in e?this.#ee=e.sessionOrCompletionId:this.#ee=e.fusionConfig?.sessionId;let r=e.workingDirectory??e.fusionConfig?.workingDirectory;if(this.#d=r?e.sys.resolve(e.sys.cwd(),r):e.sys.getCwdDir(),this.#L=e.skipFileDiff??!0,this.#m=e.position,this.#_=e.privacyMode??e.fusionConfig?.privacyMode,this.#h=e.devServerOrchestrator,this.#I=e.git??!1,this.#b=e.softContextWindow,this.#I&&(process.env.GIT_CEILING_DIRECTORIES=this.#d),this.#xt=e.gitAutoInit??!1,this.#u=e.fusionConfig,this.#pt=e.asyncSubAgents??!1,this.#o=xL(e.queueMode),this.#N=e.fusionConfig?.autoPush,this.#E=e.fusionConfig?.projectId,this.#y=e.fusionConfig?.branchName,this.#R=e.fusionConfig?.featureBranch,this.#T=e.fusionConfig?.aiBranch,this.#qe=e.fusionConfig?.proxyOrigin,this.#$e=e.fusionConfig?.proxyDefaultOrigin,this.#At=e.fusionStatusMonitor,process.env.FUSION_ENV_ORIGIN&&(this.#Nt=process.env.FUSION_ENV_ORIGIN),this.#M=e.agentType,this.#Ve=e.defaultSyncChanges,this.#Pt=e.persistSessionLocally??!1,this.#ze=e.parentSessionId,this.#Lt=e.mainSessionId,e.enabledTools)this.#D=D4(this.#u,e.enabledTools);else{let n=["Write","Edit","Read","MultiEdit","Grep","Glob","Skill","TaskCreate","TaskUpdate","TaskList","Agent","Media","WebFetch","AskUserQuestion","ExitPlanMode","EnterPlanMode",process.platform==="win32"?"PowerShell":"Bash"],i=!!(this.#_?.enabled||this.#_?.redactUserMessages||this.#_?.redactLLMMessages);i||n.push("WebSearch"),this.#E&&!i&&this.getCommitMode()!=="commits"&&n.push("SearchMemories"),i||n.push("GetScreenshot"),n.push("NavigatePreview"),this.#h&&(n.push("DevServerLogs"),n.push("DevServerRestart"),n.push("ProposeEnvVariable")),process.env.FUSION_IDE_PORT&&n.push("IDEDiagnostics"),n.push("PullPrototype"),this.#D=D4(this.#u,n)}if(this.#Ft=e.maxTokens,this.#gt=e.reasoning,this.#ut=e.builtInCustomInstructions??[],e.builtInCustomAgents?this.#Se=e.builtInCustomAgents:this.#Se=[Xh,ix],this.#Je=e.builtInMCPServerConfig??{},this.#ce=e.systemPromptOverride,this.#C=e.fusionConfig?.workspace,this.#lt=e.mcpServers??!1,this.#x=this.#d,this.#f=[],this.#C?.folders.length){let n=this.#C.folders.filter(i=>i.enableGit);this.#f=n.map(i=>({folderName:i.name??i.path,path:this.#e.resolve(this.#d,i.path),branchName:i.branchName||"main",repoUrl:i.repoUrl,originalRepoUrl:i.originalRepoUrl,repoName:i.repoName}));for(let i of n){let s=i.backupMetadata?.check.backup,o=i.name??i.path,a=PE({version:s?.version,originalRepoUrl:s?.repoUrl,commitHash:s?.lastCommitHash});a&&(this.#ke[o]=a)}}this.#f.length===0&&(this.#f=[{folderName:this.#e.basename(this.#d),path:this.#d,branchName:"main"}]),this.#Re=yye(this.#C),this.#C?.folders[0]&&this.#K()&&(this.#x=this.#e.resolve(this.#d,this.#C.folders[0].path)),this.#g.on("idle",()=>{let n=this.#Ze;if(this.#Ze=0,this.#E==null&&this.#y==null||this.#ze)return;this.clearSessionCanHandleTools(),this.#r.debug("emitting ClientDevtoolsSessionIdleEventV1",{projectId:this.#E,branchName:this.#y});let i=this.#Ie;KA(this.#a,"/events/publish",{event:eie,extraData:{sessionId:this.getSessionId(),lastMessage:this.getLastMessage(),projectId:this.#E,branchName:this.#y,hasPlanToApply:i,sessionMode:this.getSessionMode(),gifId:this.#v.gif_id,planContent:this.#Zt,completionId:this.getLastCompletionId(),credits:n},extraAttributes:{projectId:this.#E,branchName:this.#y}},{debug:this.#A})})}get fusionConfig(){return this.#u}get gitEnabledFolder(){return this.#C?.folders.find(e=>e.enableGit)}get gitEnabledFolders(){return this.#C?.folders.filter(e=>e.enableGit)||[]}get gitRepoContexts(){return this.#f}get workingDirectory(){return this.#d}get bashWorkingDirectory(){return this.#x}getSessionMode(){return this.#n?.sessionMode??"normal"}get#Zt(){let e=this.getSessionContext();for(let r=e.turns.length-1;r>=0;r--){let n=e.turns[r];if(n.state==="done"){if(n.user.role==="user")return;for(let i of n.actions??[])if(i.type==="tool"&&i.filePath==="ExitPlanMode")try{let s=JSON.parse(i.content);if(typeof s.plan=="string")return s.plan}catch{}}}}get#Ie(){let e=this.getSessionContext();if(e.sessionMode!=="planning")return!1;for(let r=e.turns.length-1;r>=0;r--){let n=e.turns[r];if(n.state==="done"){if(n.user.role==="user")return!1;for(let i of n.actions??[])if(i.type==="tool"&&i.filePath==="ExitPlanMode")try{let s=JSON.parse(i.content);if(s.hasPlanToApply||s.sessionMode==="planning")return!0}catch{}}}return!1}async switchSessionMode(e){let r=this.getSessionContext();r.sessionMode!==e&&(r.sessionMode=e,await this.#De())}async switchModelOverride(e){this.#q=e||void 0,await this.#De()}#er(){if(!this.#M||!this.#le)return;let e=this.#le[this.#M];if(e){if(typeof e=="string")return ul(e);if(Array.isArray(e)&&e.length){let r=this.#fe.get(this.#M)??0;return this.#fe.set(this.#M,r+1),ul(e[r%e.length])}}}removeSystemReminder(e){let r=this.#Y.findIndex(n=>n.tag===e);r!==-1&&this.#Y.splice(r,1)}getMemoriesForFile(e){let r=$Be(this.#kt,e).filter(n=>!this.#Rt.has(n.id));for(let n of r)this.#Rt.add(n.id);return r}#ht(){return Cye(this.#u?.environmentVariables??[],this.#h?.environmentVariables??[])}#tr(){if(this.#at)return;let e=this.#ht();e.length!==0&&(this.#at=!0,this.queueSystemReminder({text:`The system has the following environment variables:
|
|
1821
1821
|
${cw(e,{skipCommandSecurity:this.#u?.skipCommandSecurity})}`,tag:"reminder:environment-variables"}))}queueSystemReminder(e){let r=e.tag?this.#Y.findIndex(n=>n.tag===e.tag):-1;return r!==-1?e.text?(this.#Y[r]=e,{operation:"update"}):(this.#Y.splice(r,1),{operation:"delete"}):e.text?(this.#Y.push(e),{operation:"add"}):{operation:"noop"}}setDefaultAutoPush(e){this.#N=e}async setPrivacyMode(e){if(e&&e.enabled){if(!e.encryptKey&&!this.#we)this.#we=await IBe();else if(e.encryptKey){if(!await XS(e.encryptKey))throw new Error("Invalid encryption key: key failed validation");this.#we=e.encryptKey}}else this.#we=void 0;this.#_=e}getLocalMcpStatus(){return this.#U?.getStatus()??{}}refreshMcpStatus(){return this.#Ee(),this.#se?.status??{}}#Ee(){let e=this.getLocalMcpStatus(),n={type:"mcp-status",status:{...this.#se?.status??{},...e}};this.#se=n,this.#g.emit("step",n)}async authenticateMcpServer(e){let r=this.#U;if(!r)return{started:!1,message:"Local MCP manager not initialized."};let n=r.clients.find(i=>i.serverName===e);if(!n)return{started:!1,message:`'${e}' is not a CLI-managed MCP; manage from Builder.io org settings.`};if(!n.url)return{started:!1,message:`'${e}' is a stdio server and has no OAuth flow.`};try{await new Dc({serverUrl:n.url}).invalidateCredentials("tokens")}catch{}return M0({serverUrl:n.url,serverName:n.serverName,normalizedServerName:n.normalizedServerName,pinnedClientId:n.oauth?.clientId,pinnedClientSecret:n.oauth?.clientSecret,pinnedRedirectPort:n.oauth?.redirectPort,localMCPManager:r,onReconnected:()=>this.#Ee(),emitter:this.#g}),{started:!0}}async clearMcpAuth(e){let r=this.#U;if(!r)return{cleared:!1,message:"Local MCP manager not initialized."};let n=r.clients.find(s=>s.serverName===e);return!n||!n.url?{cleared:!1,message:`'${e}' has no CLI-managed remote credentials to clear.`}:(await new Dc({serverUrl:n.url}).invalidateCredentials("all"),n.status={...n.status,status:"auth_required",message:"Credentials cleared. Re-authenticate to reconnect.",toolCount:0,tools:[]},n.authRequired=!0,this.#Ee(),{cleared:!0})}async reconnectMcpServer(e){let r=this.#U;if(!r)return{success:!1,toolsAdded:0,message:"Local MCP manager not initialized."};let n=await r.reconnectServer(e);return this.#Ee(),n}async setMcpServerDisabled(e,r,n){let s=this.#U?.clients.find(c=>c.serverName===e);if(s?.status.source&&s.status.source!=="local")throw new Error(`${s.status.source} MCP servers are read-only in /mcp. Update the source configuration to change '${e}'.`);let o=n?[n]:s?.status.scope==="user"||s?.status.scope==="project"?[s.status.scope,s.status.scope==="user"?"project":"user"]:["project","user"],a,A;for(let c of o)try{A=fBe(e,c,r);break}catch(u){a=u}if(!A)throw a instanceof Error?a:new Error(`Could not toggle disabled state for '${e}'.`);return s&&(r?s.status={...s.status,status:"disabled",message:"Server disabled by user",toolCount:0,tools:[]}:s.status={...s.status,status:"ok",message:"Re-enabled \u2014 reconnect to load tools.",toolCount:0,tools:[]}),this.#Ee(),{disabled:A.disabled,path:A.path,scope:A.scope}}async initializeSession(e={}){return this.#ct||(this.#ct=this.#ir(e)),await this.#ct}async loadHistory(){let e=this.getSessionContext(),r=await Ax(this.#e,this.#a,e.sessionId,!1,this.#A),n=new Map,i=new Map;for(let a of r.turns)for(let A of[a.beforeCommit,a.afterCommit,a.lastCommit]){if(!A)continue;let c=fh(A,this.gitRepoContexts[0]?.folderName);n.set(A,c);for(let[u,l]of Object.entries(c))i.has(u)||i.set(u,new Set),i.get(u).add(l)}let s=new Map;for(let[a,A]of i.entries()){let c=this.gitRepoContexts.find(l=>l.folderName===a);if(!c||A.size===0)continue;let u=new Set;try{let d=(await this.git(["cat-file","--batch-check","--buffer"],{sys:this.#e,cwd:c.path,stdin:Array.from(A).map(p=>`${p}^{commit}`).join(`
|
|
1822
1822
|
`)})).trim().split(`
|
|
1823
|
-
`),g=new Set;for(let p of d)if(p.includes("missing")){let f=p.split(/\s+/)[0].replace("^{commit}","");g.add(f)}for(let p of A)g.has(p)||u.add(p)}catch(l){this.#e.Sentry?.captureException(l)}s.set(a,u)}let o=r.turns.filter(a=>{for(let A of[a.beforeCommit,a.afterCommit,a.lastCommit]){if(!A)continue;let c=n.get(A);if(c)for(let[u,l]of Object.entries(c)){if(!this.gitRepoContexts.find(p=>p.folderName===u))continue;let g=s.get(u);if(!g||!g.has(l))return!1}}return!0});return{sessionId:e.sessionId,title:e.title,beforeCommit:e.beforeCommit,createdUnixTime:e.createdUnixTime,updatedUnixTime:e.updatedUnixTime,turns:o}}async loadWholeSession(e={}){let{getAll:r=!0}=e,n=this.getSessionContext(),i=0;for(;n.canLoadMore&&n.canLoadMore;){let s=await this.loadMoreTurns();i+=s.length}return{sessionId:n.sessionId,title:n.title,beforeCommit:n.beforeCommit,createdUnixTime:n.createdUnixTime,updatedUnixTime:n.updatedUnixTime,addedTurns:i,turns:r?n.turns:n.turns.slice(0,i)}}async loadMoreTurns(){return this.#be||(this.#be=this.#rr().then(e=>(this.#be=void 0,e))),this.#be}async#rr(){let e=this.getSessionContext();if(e.canLoadMore){let r=e.turns[0]?.completionId,n=await Ax(this.#e,this.#a,e.sessionId,!0,this.#A,r);return n.turns.length>0&&e.turns.unshift(...n.turns),e.canLoadMore=n.canLoadMore,n.turns}return[]}async#nr(){try{let e=Qft();if(!e)return null;let r=this.#e.join(this.primaryGitPath,"file.tsx");return await e.resolveConfig(r)}catch{return null}}async setCustomInstructions(e){this.#ut=e,this.#n&&(this.#n.customInstructions=await this.#_e())}async setCustomAgents(e){this.#Se=e,this.#n&&(this.#n.customAgents=await this.#nt())}async#_e(){let e=await
|
|
1823
|
+
`),g=new Set;for(let p of d)if(p.includes("missing")){let f=p.split(/\s+/)[0].replace("^{commit}","");g.add(f)}for(let p of A)g.has(p)||u.add(p)}catch(l){this.#e.Sentry?.captureException(l)}s.set(a,u)}let o=r.turns.filter(a=>{for(let A of[a.beforeCommit,a.afterCommit,a.lastCommit]){if(!A)continue;let c=n.get(A);if(c)for(let[u,l]of Object.entries(c)){if(!this.gitRepoContexts.find(p=>p.folderName===u))continue;let g=s.get(u);if(!g||!g.has(l))return!1}}return!0});return{sessionId:e.sessionId,title:e.title,beforeCommit:e.beforeCommit,createdUnixTime:e.createdUnixTime,updatedUnixTime:e.updatedUnixTime,turns:o}}async loadWholeSession(e={}){let{getAll:r=!0}=e,n=this.getSessionContext(),i=0;for(;n.canLoadMore&&n.canLoadMore;){let s=await this.loadMoreTurns();i+=s.length}return{sessionId:n.sessionId,title:n.title,beforeCommit:n.beforeCommit,createdUnixTime:n.createdUnixTime,updatedUnixTime:n.updatedUnixTime,addedTurns:i,turns:r?n.turns:n.turns.slice(0,i)}}async loadMoreTurns(){return this.#be||(this.#be=this.#rr().then(e=>(this.#be=void 0,e))),this.#be}async#rr(){let e=this.getSessionContext();if(e.canLoadMore){let r=e.turns[0]?.completionId,n=await Ax(this.#e,this.#a,e.sessionId,!0,this.#A,r);return n.turns.length>0&&e.turns.unshift(...n.turns),e.canLoadMore=n.canLoadMore,n.turns}return[]}async#nr(){try{let e=Qft();if(!e)return null;let r=this.#e.join(this.primaryGitPath,"file.tsx");return await e.resolveConfig(r)}catch{return null}}async setCustomInstructions(e){this.#ut=e,this.#n&&(this.#n.customInstructions=await this.#_e())}async setCustomAgents(e){this.#Se=e,this.#n&&(this.#n.customAgents=await this.#nt())}async#_e(){let e=await R4({sys:this.#e,projectDir:this.#d,currentDir:this.#f.map(n=>n.path),rootDir:"/",allowedCommands:A0(this.#u?.allowedCommands??[]),skipCommandSecurity:this.#u?.skipCommandSecurity===!0}),r=SB(this.#ut,this.#u?.customInstructions??[]);return SB(r,e)}async#nt(){if(!this.#D?.includes("Agent"))return[];let e=await ame({sys:this.#e,projectDir:this.#d,currentDir:this.#f.map(n=>n.path),rootDir:"/"}),r=SB(this.#Se,this.#u?.customAgents??[]);return SB(r,e)}async#ir(e){try{if(this.#Ye)throw new Error("Code session already closed");if(this.#n)throw new Error("Session context already initialized");this.#r.debug(`Current AI working directory: ${this.#d}`),await this.setPrivacyMode(this.#_);let r=await this.#or(),n=await this.#nr();r&&(this.#P=await this.#H());let i=this.#f[0]?.repoUrl;if(this.#je=await Lv(i),!this.#je)try{let u=await this.git(["remote","get-url","origin"],{cwd:this.#d});u&&(this.#je=await Lv(u))}catch{}let s,o;this.#ee||(this.#ee=r?.sessionId),this.#ee?e.skipSessionLoading?s=this.#ee:(o=await Ax(this.#e,this.#a,this.#ee,!0,this.#A,void 0,e.signal),s=o.sessionId,this.#r.debug(`Session recovered (sessionId=${s}, turnsCount=${o.turns.length})`)):s=(0,ox.randomUUID)(),this.#R||(this.#R=r?.featureBranch?.trim());let a={turns:o?.turns??[],sessionId:s,customInstructions:await this.#_e(),customAgents:await this.#nt(),title:o?.title,beforeCommit:o?.beforeCommit,createdUnixTime:o?.createdUnixTime??Date.now(),updatedUnixTime:o?.updatedUnixTime??Date.now(),userContext:await pye(this.#e,this.primaryGitPath),prettierConfig:n,canLoadMore:o?.canLoadMore??!1,state:o?.turns.length?"success":this.#B?"initial-with-url":"initial-without-url",sessionMode:o?.sessionMode??"normal"};this.#v=o?.metadata??{};let A=this.#v.pendingToolFulfilments;if(A)for(let[u,l]of Object.entries(A))this.#oe.set(u,{id:u,name:l.name,input:l.input,messageValid:l.messageValid});if(o){let u=Fa(o.turns);u?.completionId!==o.lastCompletionId&&this.#e.Sentry?.captureException(new Error("Last completion id mismatch"),{tags:{operation:"codegen-initialize-session"},extra:{lastTurn:u,sessionMetadata:o}})}if(this.#A&&this.#g.on("step",u=>{u.type!=="delta"&&this.#r.debug(`(${u.type}): ${Sf(JSON.stringify(u),400)}`)}),await this.#Ar(a),this.#n=a,this.#M){let u=await this.getNamedAgentConfig(this.#M,this.getSessionId(),e.signal);if(u.success){if(this.#k=u.options.includeMemories,this.#D=u.options.enabledTools,this.#q=u.options.modelOverride,this.#ce=u.options.systemPromptOverride,this.#m=u.options.position,this.#o=xL(u.options.queueMode),this.#pt=u.options.asyncSubAgents??!1,this.#b=u.options.softContextWindow,this.#Ve=u.options.defaultSyncChanges,this.#Je={...this.#Je,...u.options.builtInMCPServerConfig},u.options.builtInMCPServerConfig?.chrome&&!this.#it){let l=new NE(this.getSessionId(),{framesDir:this.#e.join(sx.default.homedir(),".builder","recordings"),debug:this.#A});this.setTimeline(l)}typeof u.options.mcpServers=="boolean"&&(this.#lt=u.options.mcpServers)}else this.#r.error(u.response)}try{let u=await gBe(this.#e,this.primaryGitPath,this.#Je,this.#Ut,e.signal);u.length>0?(this.#r.debug(`Initializing ${u.length} local MCP server(s)...`),this.#U=await lBe(u,this.#e,this.primaryGitPath,e.signal)):this.#r.debug(`No local MCP servers found in: ${this.primaryGitPath}`),this.#U&&this.#Ee()}catch(u){this.#r.error("Failed to initialize local MCP servers:",u,{loggerOptions:{debug:!0}})}if(this.#I&&this.#E&&this.#D?.includes("SearchMemories")){let u=await VBe(this.#e,this.#a,this.#E,e.signal);await nx(this.#e,u,this.#e.join(this.#x,".builder","memories")),this.#kt=u,this.#D&&u.length===0&&(this.#D=this.#D.filter(l=>l!=="SearchMemories"))}let c=this.#h;if(c){let u=()=>{this.#g.emit("step",S4(c,this.#u))},l=()=>{this.#g.emit("step",S4(c,this.#u)),this.#De(),this.#ye()},d=g=>{g==="ok-2xx"&&this.requestRefresh()};c.emitter.on("setupState",l),c.emitter.on("devState",l),c.emitter.on("httpServerData",l),c.emitter.on("httpServerState",d),c.emitter.on("validateState",u),this.#Ke.push(()=>{c.emitter.off("setupState",l),c.emitter.off("devState",l),c.emitter.off("httpServerData",l),c.emitter.off("httpServerState",d),c.emitter.off("validateState",u)})}}catch(r){throw this.#r.error(r),this.#e.Sentry?.captureException(r,{tags:{operation:"codegen-initialize-session"}}),r}}async#mt(e,r){let n="reminder:health";this.removeSystemReminder(n);let i=this.#h;if(!i||this.#M==="setup-project"||!(this.#D?.includes("DevServerLogs")||this.#D?.includes("DevServerRestart")||this.#D?.includes("DevServerControl")||this.#D?.includes("ProposeEnvVariable")))return;let o=this.getSessionContext();if(o.sessionMode!=="normal")return;e&&await i.waitUntilIdle(500,500);let a=i.setupState,A=await this.#It(),c=i.devCommand,u=i.devState,l=i.state,d=i.setupCommand,g=await i.getOpenPorts(),p=i.proxyTarget,f=i.httpServerState.state,m=i.lastServerStatus,C=f==="error-fetch",I=!1;this.#I&&(I=await this.getCurrentBranch()!==this.getAiBranch());let y=f==="error-5xx"||f==="error-4xx"&&m!==401&&m!==404,B="",E=!1,Q=!1;l==="install-failed"||l==="install-aborted"?B=i.getSetupOutput():(B=i.getCheckpoints(1,u!=="running"?"err":"all"),E=hye(B??""));let v="",D="",S="error",b="Try to fix",x="repair-unknown";if(l==="not-installed"||l==="install-failed"||l==="install-aborted"||l==="failed"||I||C||y||E||A.length>0){if(I&&(x="repair-bad-branch",D+=`- The current git branch is not the AI branch (${this.getAiBranch()}).
|
|
1824
1824
|
`,D+=`- Please switch to the AI branch using the 'git' tool.
|
|
1825
1825
|
`,v=`The current branch is not the AI branch (${this.getAiBranch()}).`),A.length>0){x="repair-merge-conflict",b="Resolve conflict",v="Merge conflict detected - changes from different sources need to be combined";let J=this.#ft,_=J?`
|
|
1826
1826
|
ours (:2:) = ${J.ourBranch} (AI branch), theirs (:3:) = ${J.theirBranch} (${J.theirIsMain?"main \u2014 prefer preserving these changes":"AI remote"})`:"";D+=`Merge conflict detected. Resolve ALL conflicted files:
|
|
@@ -1880,10 +1880,10 @@ ${E.join(`
|
|
|
1880
1880
|
- their branch (theirs): refs/remotes/origin/${O} ${_?" -- this is main/feature branch (work here needs to be preserved)":"-- same branch pushed by remote"}
|
|
1881
1881
|
`),J}}if(n){let O=await this.#Ot(!0,C);await this.git(O,{cwd:C.path})}if(v)try{await this.git(["stash","pop"],{cwd:I})}catch(O){this.#e.Sentry?.captureException(O,{tags:{operation:"codegen-git",endpoint:"syncChanges-stash-pop"}})}})).results.filter(C=>!C.success||C.error);if(f.length>0){let C=f.map(I=>I.error?.message||`${I.folderName} failed`).join("; ");throw new Error(`Sync failed: ${C}`)}let m=await this.#H();if(c&&(this.#P={...this.#P,...m}),n){let C=await this.#Ue(!1);if(!C.success)throw C.error}else await this.#F(),await this.#Qe({lastCommit:So(m)});return d.length>0&&this.queueSystemReminder({text:d.join(`
|
|
1882
1882
|
|
|
1883
|
-
`)}),o&&this.requestRefresh(),{success:!0,message:A?`Successfully reset to remote feature branch "${e.join(", ")}" in all repos`:`Successfully merged ${e.join(", ")} in all repos`}}catch(u){if(this.#r.error(`Error syncing changes from branches: ${u}`,{loggerOptions:{debug:!0}}),await this.#F(),c){let d=await this.#H();this.#P={...this.#P,...d}}this.#e.Sentry?.captureException(u,{tags:{operation:"codegen-git",endpoint:"syncChangesFromBranches"},extra:{branches:e,allowUnrelatedHistory:r}});let l=Rp(u);return{success:!1,message:l,error:u instanceof Error?u:new Error(l)}}}async getCurrentCommitHash(e="HEAD",r){if(this.#I)try{let n=["rev-parse",e];return(await this.git(n,{sys:this.#e,cwd:r})).trim()}catch{return}}async#H(e="HEAD"){let r={};for(let n of this.gitRepoContexts)try{let i=await this.getCurrentCommitHash(e,n.path);i&&(r[n.folderName]=i)}catch(i){this.#r.warn(`Failed to get commit for ${n.folderName}:`,i)}return r}async getCurrentBranch(e){return(await this.git(["branch","--show-current"],{cwd:e})).trim()}getFeatureBranch(){if(!this.#R)throw new Error("Feature branch is missing");return this.#R}getAiBranch(){if(!this.#T)throw new Error("AI branch is missing");return this.#T}async git(e,r){let n=e[0];(n==="push"||n==="fetch"||n==="pull")&&await this.#Ct();let s=typeof r=="object"?{sys:this.#e,...r}:r,o=await this.#Ht(()=>this.#mr(e,s));return this.#fr(n)&&(this.#Me.clear(),this.#Te.clear(),this.#Ne.clear()),o}static#dr=new Set(["commit","merge","rebase","checkout","switch","pull","fetch","reset","cherry-pick","revert","am","stash","push"]);#fr(e){return!!e&&t.#dr.has(e)}async#$(e){if(this.#f.length===0)return{success:!0,partialSuccess:!1,results:[]};let n=(await Promise.allSettled(this.#f.map(o=>e(o)))).map((o,a)=>({folderName:this.#f[a].folderName,success:o.status==="fulfilled",result:o.status==="fulfilled"?o.value:void 0,error:o.status==="rejected"?o.reason:void 0,message:o.status==="rejected"?o.reason?.message:void 0})),i=n.filter(o=>o.success),s=n.filter(o=>!o.success);return{success:s.length===0,partialSuccess:i.length>0&&s.length>0,results:n}}#Kt(e){let r=Dn(e),n=this.#f.find(a=>{let A=Dn(a.folderName);return r.startsWith(A+"/")||r===A});if(n)return n;let i=e.startsWith("/")||e.includes(":")?e:this.#e.resolve(this.#d,e),s=Dn(i);return this.#f.find(a=>{let A=Dn(a.path);return s.startsWith(A+"/")||s===A})}#hr(e){let r=new Map;for(let n of e){let i=this.#Kt(n);if(i){let s=r.get(i.folderName)||[];s.push(n),r.set(i.folderName,s)}}return r}#Ht(e){let r=this.#St.then(()=>e());return this.#St=r.catch(()=>{}),r}async#mr(e,r){let n=`git ${e.join(" ")}`;this.#ue&&this.#e.Sentry?.captureException(new Error(`currentGitCommand is not finished yet. Current command: ${this.#ue}, New command Received: ${n}`),{tags:{operation:"codegen-git"},extra:{oldCommand:this.#ue,newCommand:n}});try{this.#ue=n;let i=typeof r=="object"?r:void 0,s=typeof r=="string"?r:i?.cwd??this.primaryGitPath;return await Ws("git",e,{...i,cwd:s,sys:this.#e,timeout:60*1e3})}finally{this.#ue=void 0}}setDebug(e){this.#A=e,e&&!process.env.DEBUG?(process.env.DEBUG="1",this.#p=!0):!e&&this.#p&&(delete process.env.DEBUG,this.#p=!1)}async createTerminal(e){let r=this.#h,n=e?.terminalId||`pty_${Date.now()}_${(0,ox.randomUUID)()}`,i=this.#Bt().find(y=>y.terminalId===n),s=new Set,o=new Set;if(i&&e?.terminalId){if(!e?.force)return i;let y=this.#w.get(e.terminalId);if(!y)return i;y.onDataListeners.forEach(B=>{s.add(B)}),y.onExitListeners.forEach(B=>{o.add(B)}),this.disposeTerminal({terminalId:n,emitTerminals:!1})}let a=e?.shell||(process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/bash"),A=e?.cols??120,c=e?.rows??30,u={...process.env,...r?.envVars,...e?.env};e?.inheritCredentials&&(u.BUILDER_USER_ID=e.createdBy??this.#a.userId,u.BUILDER_PUBLIC_KEY=this.#a.builderPublicKey,u.BUILDER_PRIVATE_KEY=this.#a.builderPrivateKey);let l=[],d=y=>{for(let B of s)B(y)},g=({exitCode:y,error:B})=>{let E=this.#w.get(n);E&&(E.state=B?"error":"exited",E.exitCode=y);for(let Q of o)Q(y);this.#w.delete(n),l.forEach(Q=>Q())},p=e?.cwd||this.#x,f,m;if(e?.readonly){f="starting";let y=!r?.hasSetupEnvVars,B=mA(a,e?.initialCommand??"true",{cwd:p,env:u,stdio:["ignore","pipe","pipe"]},y);B.on("spawn",()=>{let E=this.#w.get(n);E&&(E.state="running")}),B.stdout.on("data",E=>{d(E.toString())}),B.stderr.on("data",E=>{d(E.toString())}),B.on("error",E=>{g({exitCode:1,error:E})}),B.on("exit",E=>{g({exitCode:E??0})}),l.push(()=>{try{B.removeAllListeners()}catch{}B.kill()}),m=B}else{f="running";let y=
|
|
1883
|
+
`)}),o&&this.requestRefresh(),{success:!0,message:A?`Successfully reset to remote feature branch "${e.join(", ")}" in all repos`:`Successfully merged ${e.join(", ")} in all repos`}}catch(u){if(this.#r.error(`Error syncing changes from branches: ${u}`,{loggerOptions:{debug:!0}}),await this.#F(),c){let d=await this.#H();this.#P={...this.#P,...d}}this.#e.Sentry?.captureException(u,{tags:{operation:"codegen-git",endpoint:"syncChangesFromBranches"},extra:{branches:e,allowUnrelatedHistory:r}});let l=Rp(u);return{success:!1,message:l,error:u instanceof Error?u:new Error(l)}}}async getCurrentCommitHash(e="HEAD",r){if(this.#I)try{let n=["rev-parse",e];return(await this.git(n,{sys:this.#e,cwd:r})).trim()}catch{return}}async#H(e="HEAD"){let r={};for(let n of this.gitRepoContexts)try{let i=await this.getCurrentCommitHash(e,n.path);i&&(r[n.folderName]=i)}catch(i){this.#r.warn(`Failed to get commit for ${n.folderName}:`,i)}return r}async getCurrentBranch(e){return(await this.git(["branch","--show-current"],{cwd:e})).trim()}getFeatureBranch(){if(!this.#R)throw new Error("Feature branch is missing");return this.#R}getAiBranch(){if(!this.#T)throw new Error("AI branch is missing");return this.#T}async git(e,r){let n=e[0];(n==="push"||n==="fetch"||n==="pull")&&await this.#Ct();let s=typeof r=="object"?{sys:this.#e,...r}:r,o=await this.#Ht(()=>this.#mr(e,s));return this.#fr(n)&&(this.#Me.clear(),this.#Te.clear(),this.#Ne.clear()),o}static#dr=new Set(["commit","merge","rebase","checkout","switch","pull","fetch","reset","cherry-pick","revert","am","stash","push"]);#fr(e){return!!e&&t.#dr.has(e)}async#$(e){if(this.#f.length===0)return{success:!0,partialSuccess:!1,results:[]};let n=(await Promise.allSettled(this.#f.map(o=>e(o)))).map((o,a)=>({folderName:this.#f[a].folderName,success:o.status==="fulfilled",result:o.status==="fulfilled"?o.value:void 0,error:o.status==="rejected"?o.reason:void 0,message:o.status==="rejected"?o.reason?.message:void 0})),i=n.filter(o=>o.success),s=n.filter(o=>!o.success);return{success:s.length===0,partialSuccess:i.length>0&&s.length>0,results:n}}#Kt(e){let r=Dn(e),n=this.#f.find(a=>{let A=Dn(a.folderName);return r.startsWith(A+"/")||r===A});if(n)return n;let i=e.startsWith("/")||e.includes(":")?e:this.#e.resolve(this.#d,e),s=Dn(i);return this.#f.find(a=>{let A=Dn(a.path);return s.startsWith(A+"/")||s===A})}#hr(e){let r=new Map;for(let n of e){let i=this.#Kt(n);if(i){let s=r.get(i.folderName)||[];s.push(n),r.set(i.folderName,s)}}return r}#Ht(e){let r=this.#St.then(()=>e());return this.#St=r.catch(()=>{}),r}async#mr(e,r){let n=`git ${e.join(" ")}`;this.#ue&&this.#e.Sentry?.captureException(new Error(`currentGitCommand is not finished yet. Current command: ${this.#ue}, New command Received: ${n}`),{tags:{operation:"codegen-git"},extra:{oldCommand:this.#ue,newCommand:n}});try{this.#ue=n;let i=typeof r=="object"?r:void 0,s=typeof r=="string"?r:i?.cwd??this.primaryGitPath;return await Ws("git",e,{...i,cwd:s,sys:this.#e,timeout:60*1e3})}finally{this.#ue=void 0}}setDebug(e){this.#A=e,e&&!process.env.DEBUG?(process.env.DEBUG="1",this.#p=!0):!e&&this.#p&&(delete process.env.DEBUG,this.#p=!1)}async createTerminal(e){let r=this.#h,n=e?.terminalId||`pty_${Date.now()}_${(0,ox.randomUUID)()}`,i=this.#Bt().find(y=>y.terminalId===n),s=new Set,o=new Set;if(i&&e?.terminalId){if(!e?.force)return i;let y=this.#w.get(e.terminalId);if(!y)return i;y.onDataListeners.forEach(B=>{s.add(B)}),y.onExitListeners.forEach(B=>{o.add(B)}),this.disposeTerminal({terminalId:n,emitTerminals:!1})}let a=e?.shell||(process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/bash"),A=e?.cols??120,c=e?.rows??30,u={...process.env,...r?.envVars,...e?.env};e?.inheritCredentials&&(u.BUILDER_USER_ID=e.createdBy??this.#a.userId,u.BUILDER_PUBLIC_KEY=this.#a.builderPublicKey,u.BUILDER_PRIVATE_KEY=this.#a.builderPrivateKey);let l=[],d=y=>{for(let B of s)B(y)},g=({exitCode:y,error:B})=>{let E=this.#w.get(n);E&&(E.state=B?"error":"exited",E.exitCode=y);for(let Q of o)Q(y);this.#w.delete(n),l.forEach(Q=>Q())},p=e?.cwd||this.#x,f,m;if(e?.readonly){f="starting";let y=!r?.hasSetupEnvVars,B=mA(a,e?.initialCommand??"true",{cwd:p,env:u,stdio:["ignore","pipe","pipe"]},y);B.on("spawn",()=>{let E=this.#w.get(n);E&&(E.state="running")}),B.stdout.on("data",E=>{d(E.toString())}),B.stderr.on("data",E=>{d(E.toString())}),B.on("error",E=>{g({exitCode:1,error:E})}),B.on("exit",E=>{g({exitCode:E??0})}),l.push(()=>{try{B.removeAllListeners()}catch{}B.kill()}),m=B}else{f="running";let y=x4(this.#e);if(!y)throw new Error("Could not import node-pty");let B=a.includes("bash")||a.includes("zsh"),E=a.includes("zsh")?"%~ $ ":"\\w $ ",Q=y.spawn(a,[],{name:"xterm-color",cwd:p,cols:A,rows:c,env:B?{...u,PS1:E}:u}),v=Q.onData(d);l.push(()=>{try{v?.dispose?.()}catch{}});let D=Q.onExit(g);l.push(()=>{try{D?.dispose?.()}catch{}});let S=e?.initialCommand;S&&(S.endsWith(`
|
|
1884
1884
|
`)||(S+=`
|
|
1885
|
-
`),Q.write(S)),m=Q}let C=Date.now(),I={terminalId:n,title:e?.title||`Terminal ${this.#w.size+1}`,cwd:p,createdAt:C,lastWrittenAt:C,createdBy:e?.createdBy||"unknown",readonly:e?.readonly??!1,initialCommand:e?.initialCommand,builtIn:!1,state:f,stale:!1,exitCode:void 0,command:void 0};return this.#w.set(n,{...I,pty:m,onDataListeners:s,onExitListeners:o,disposeFns:l,env:e?.env,shell:a,inheritCredentials:e?.inheritCredentials}),(e?.emitTerminals??!0)&&this.#ye(),I}#Bt(){let e=this.getSessionContext(),r=Array.from(this.#w.values()).map(s=>({terminalId:s.terminalId,title:s.title,cwd:s.cwd,createdAt:s.createdAt,lastWrittenAt:s.lastWrittenAt,createdBy:s.createdBy,readonly:s.readonly,builtIn:s.builtIn,exitCode:s.exitCode,state:s.state,stale:s.stale,command:s.command})),n=[];this.#D?.includes("Bash")&&n.push({terminalId:"bash-tools",title:"Bash",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:Date.now(),createdBy:"fusion",readonly:!0,builtIn:!0,exitCode:void 0,state:"running",command:void 0});let i=this.#h;if(i){let s=Date.now();if(i.devState!=="unset"&&n.push({terminalId:"dev-command",title:"Dev Command",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:s,createdBy:"fusion",readonly:!i.devCommandProcess?.write,builtIn:!0,state:i.devState==="running"?"running":"exited",exitCode:void 0,command:i.devCommand}),i.setupCommand&&n.push({terminalId:"setup-command",title:"Setup Command",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:s,createdBy:"fusion",readonly:!0,builtIn:!0,state:i.setupState==="installing"?"running":"exited",exitCode:void 0,command:i.setupCommand}),i.validateCommandState!=="unset"){let o;switch(i.validateCommandState){case"running":o="running";break;case"success":o="exited";break;case"failure":o="error";break;case"stopped":o="exited";break}n.unshift({terminalId:"validate-command",title:"Validate Command",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:s,createdBy:"fusion",readonly:!0,builtIn:!0,state:o,exitCode:void 0,command:i.validateCommand})}}return n.push(...r),n}#ye(){this.#g.emit("step",{type:"terminals",terminals:this.#Bt()})}updateTerminal({terminalId:e,cols:r,rows:n,title:i}){if(e==="dev-command"){if(r||n){let o=this.#h;if(o?.devCommandProcess?.resize)return o.devCommandProcess.resize(r,n),!0}return!1}let s=this.#w.get(e);return s?("resize"in s.pty&&(r||n)&&s.pty.resize(r??s.pty.cols,n??s.pty.rows),i&&(s.title=i,this.#ye()),!0):!1}writeTerminal({terminalId:e,data:r}){if(e==="dev-command"){let i=this.#h;return i?.devCommandProcess?.write?(i.devCommandProcess.write(r),!0):!1}let n=this.#w.get(e);return!n||n.readonly?!1:("write"in n.pty&&n.pty.write(r),n.lastWrittenAt=Date.now(),!0)}signalTerminal({terminalId:e,signal:r}){if(e==="dev-command"){let i=this.#h;return i?.devCommandProcess?.kill?(i.devCommandProcess.kill(r),!0):!1}let n=this.#w.get(e);if(!n||n.readonly)return!1;try{"write"in n.pty?process.platform==="win32"?n.pty.kill():(r==="SIGINT"&&n.pty.write(""),n.pty.kill(r)):n.pty.kill(r)}catch{}return!0}disposeTerminal({terminalId:e,emitTerminals:r=!0}){let n=this.#w.get(e);if(!n)return!1;try{n.pty.kill()}catch{}return n.disposeFns.forEach(i=>{try{i()}catch{}}),n.onDataListeners.clear(),n.onExitListeners.clear(),n.disposeFns=[],this.#w.delete(e),r&&this.#ye(),!0}async restartTerminal({terminalId:e}){if(e==="dev-command"){let i=this.#h;if(i)try{return await i.restart(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="setup-command"){let i=this.#h;if(i)try{return await i.runSetupCommand(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="validate-command"){if(this.#h)try{return await this.#Vt(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="bash-tools")return!1;let r=this.#w.get(e);return r?(await this.createTerminal({terminalId:e,title:r.title,cwd:r.cwd,env:r.env,shell:r.shell,cols:"cols"in r.pty?r.pty.cols:void 0,rows:"rows"in r.pty?r.pty.rows:void 0,createdBy:r.createdBy,emitTerminals:!1,initialCommand:r.initialCommand,readonly:r.readonly,inheritCredentials:r.inheritCredentials,force:!0}),this.#w.get(e)?(this.#ye(),!0):!1):!1}subscribeTerminal({terminalId:e,onData:r,onExit:n}){if(e==="dev-command"){let i=this.#h;if(i){let s=i.getDevWrite();return s&&r(s),i.emitter.on("stdout",r),i.emitter.on("stderr",r),()=>{i.emitter.off("stdout",r),i.emitter.off("stderr",r)}}}else if(e==="setup-command"){let i=this.#h;if(i){let s=i.getSetupOutput();return s&&r(s),i.emitter.on("installStdout",r),i.emitter.on("installStderr",r),()=>{i.emitter.off("installStdout",r),i.emitter.off("installStderr",r)}}}else if(e==="validate-command"){let i=this.#h;if(i){let s=i.getValidateOutput();return s&&r(s),i.emitter.on("validateStdout",r),i.emitter.on("validateStderr",r),()=>{i.emitter.off("validateStdout",r),i.emitter.off("validateStderr",r)}}}else if(e==="bash-tools"){let i=s=>{s.type==="stdio"&&s.source==="tool-command"&&r(s.content)};return this.#g.on("step",i),()=>{this.#g.off("step",i)}}else{let i=this.#w.get(e);if(!i)throw new Error("Terminal not found");return i.onDataListeners.add(r),n&&i.onExitListeners.add(n),()=>{i.onDataListeners.delete(r),n&&i.onExitListeners.delete(n)}}}async getAllFiles(e={}){let{getDotFiles:r=!1,globbyPattern:n="**/*",includePattern:i,gitignore:s,deep:o,truncate:a,maxFiles:A=5e4,onlyFiles:c=!0}=e,u=this.#u?.accessControl,l=u?.entries?.filter(f=>f.action==="allow"&&f.permissions.includes("list")).map(f=>(f.resource.startsWith("/")?f.resource.slice(1):f.resource)||".")??[];if(!this.#C?.folders?.length){let f=await cl({basePath:this.#d,globPattern:[i??n,...l],extraIgnorePatterns:L0(u).deny,dot:r,gitignore:s,sys:this.#e,deep:o,onlyFiles:c,maxFiles:A});return Z_(f,a)}let d=[],g=await this.#e.readdir(this.#d);for(let f of g)
|
|
1886
|
-
`),y=[],B=null;for(let Q of I)if(Q.trim())try{let v=JSON.parse(Q);if(v.type==="match"){let D=v.data.path.text,S=v.data.line_number,b=v.data.lines.text.trimEnd(),x=v.data.submatches||[],P,O;x.length>0&&(P=x[0].start,O=x[0].end),m.add(D);let J={filePath:D,lineNumber:S,lineContent:b,columnStart:P,columnEnd:O,contextBefore:y,contextAfter:[]};if(y=[],B=J,f.push(J),f.length>=o)break}else if(v.type==="context"){let D=v.data.line_number,S=v.data.lines.text.trimEnd();B&&D>B.lineNumber?B.contextAfter.push(S):y.push(S)}}catch{continue}let E=f.length>=o;l({matches:f,totalMatches:f.length,filesWithMatches:m.size,truncated:E})}})})}#Jt(e){let r=this.#Ce.indexOf(e);r!==-1&&this.#Ce.splice(r,1),this.#Ce.unshift(e),this.#Ce.length>50&&(this.#Ce.length=50)}async#Cr(){let e=this.#Pe;if(e&&Date.now()-e.timestamp<t.#rt)return e.promise;let r=this.#u?.accessControl,n=cl({basePath:this.#x,extraIgnorePatterns:L0(r).deny,gitignore:!0,dot:!0,sys:this.#e}).then(i=>Ff({files:i,policy:r,getDotFiles:!0}));return this.#Pe={promise:n,timestamp:Date.now(),fuse:null},n}async#Ir(){let e=this.#Pe;if(e?.fuse)return e.fuse;let r=await this.#Cr(),n=She(r);return this.#Pe&&(this.#Pe.fuse=n),n}async searchFileTree(e){let{query:r,maxResults:n=100}=e;if(!r){let A=this.#Ce.slice(0,n).map(c=>{let u=c.lastIndexOf("/");return{filePath:c,fileName:u>=0?c.slice(u+1):c,parentPath:u>=0?c.slice(0,u):"",matchIndices:[]}});return{matches:A,totalMatches:A.length,truncated:!1}}let s=(await this.#Ir()).search(r,{limit:n});return{matches:s.map(a=>{let{fullPath:A,basename:c,dirname:u}=a.item,l=xhe(a);return{filePath:A,fileName:c,parentPath:u,matchIndices:l}}),totalMatches:s.length,truncated:s.length>=n}}async collectRepoMetrics(e={}){let r=this.#Le(e.folderName);return e.rootPath&&(r=this.#e.join(r,e.rootPath)),Whe(this.#e,r)}getSessionId(){return this.getSessionContext().sessionId}getMainSessionId(){return this.#Lt??this.getSessionId()}updateMetadata(e){this.#yt(e,!1)}getMetadata(){return this.#v}#it=null;setTimeline(e){this.#it=e}getTimeline(){return this.#it}getSpaceId(){return this.#a.builderPublicKey}async revertToCommitSnapshot(e){await this.waitUntilBlockingPendingPromises(),await this.abortMerge(!1),await this.#ie(!1);let n=(await this.#$(async s=>{let o=al(e,s.folderName,this.gitRepoContexts[0]?.folderName);return o?(await this.git(["revert","--no-commit",`${o}..HEAD`],{cwd:s.path}),await this.git(["commit","--allow-empty","--quiet","--no-verify","--no-gpg-sign","-m","Revert changes"],{cwd:s.path}),{commitHash:await this.getCurrentCommitHash("HEAD",s.path)}):(this.#r.warn(`No commit found for ${s.folderName}, skipping revert`),{skipped:!0})})).results.filter(s=>!s.success);if(n.length>0)throw new Error(`Failed to revert ${n.length} repos`);let i=await this.#H();this.#P={...this.#P,...i},await this.#F(),this.requestRefresh(),await this.#Qe({lastCommit:So(i)})}async revertToCommitHash(e){let r=fh(e,this.gitRepoContexts[0]?.folderName),n=Object.keys(r).length===0?e:So(r);return this.revertToCommitSnapshot(n)}async resetToCommitSnapshot(e,r=!0){await this.waitUntilBlockingPendingPromises(),await this.abortMerge(!1),await this.#ie(!1);let n=20,i=`${Date.now()}`,s=[],a=(await this.#$(async c=>{let u=al(e,c.folderName,this.gitRepoContexts[0]?.folderName);if(!u)return this.#r.warn(`No commit found for ${c.folderName}, skipping reset`),{skipped:!0};let l=await this.getCurrentCommitHash("HEAD",c.path),d=0;if(l&&l!==u)try{let C=await this.git(["rev-list","--count",`${u}..HEAD`],{cwd:c.path});d=Number.parseInt(C.trim(),10)||0}catch{}let g=!1,p=l;try{g=!await this.#st(c.path),g&&(await this.git(["add","-A","."],{cwd:c.path,retry:2}),await this.git(["commit","--quiet","--no-verify","--no-gpg-sign","-m","buildercode: safety snapshot before restore"],{cwd:c.path}),p=await this.getCurrentCommitHash("HEAD",c.path))}catch(C){this.#e.Sentry?.captureException(new Error(`Failed to capture pre-restore safety snapshot for ${c.folderName}: ${C}`),{tags:{operation:"codegen-git",endpoint:"resetToCommitSnapshot"}})}let f;if(p&&(d>0||g)){f=`refs/fusion/pre-restore/${i}`;try{await this.git(["update-ref",f,p],{cwd:c.path})}catch{f=void 0}}s.push({folderName:c.folderName,fromCommit:l,toCommit:u,discardedCommits:d,hadUncommittedWork:g,recoveryRef:f}),await this.git(["reset","--quiet","--hard",u],{cwd:c.path}),await this.git(["clean","-fd"],{cwd:c.path});let m=await this.getCurrentCommitHash("HEAD",c.path);if(m!==u)throw new Error(`Failed to reset commit hash for ${c.folderName}: expected ${u}, got ${m}`);return{commitHash:m}})).results.filter(c=>!c.success);if(a.length>0)throw new Error(`Failed to reset ${a.length} repos`);for(let c of s){let u=`(resetToCommitSnapshot) ${c.folderName}: ${c.fromCommit??"?"} -> ${c.toCommit} discardedCommits=${c.discardedCommits} uncommittedWork=${c.hadUncommittedWork} recovery=${c.recoveryRef??"(reflog only)"}`;c.discardedCommits>=n||c.hadUncommittedWork?(this.#r.warn(u),this.#e.Sentry?.captureException(new Error("Restore discarded a large amount of work"),{level:"warning",tags:{operation:"codegen-git",endpoint:"resetToCommitSnapshot"},extra:{...c,sessionId:this.getSessionId()}})):this.#r.debug(u)}let A=fh(e,this.gitRepoContexts[0]?.folderName);this.#P={...this.#P,...A},await this.#F(),r&&this.requestRefresh()}async resetToCommitHash(e,r=!0){let n=fh(e,this.gitRepoContexts[0]?.folderName),i=Object.keys(n).length===0?e:So(n);return this.resetToCommitSnapshot(i,r)}async restore({location:e,predicate:r,revert:n=!1,dryRun:i=!1,forceReplay:s=!1,debug:o}){let a=this.getSessionContext(),A=a.turns.length,c=null;for(let p=A-1;p>=0;p--)if(r(a.turns[p],p)){c=p;break}if(c===null)return{undone:null,message:"Could not find the target to restore to, the completion id could be wrong"};n||await this.abort({cleanCurrentMessage:!0});let u=new Map,l=!!this.#I,d=a.turns,g=e==="before"?c:c+1;for(let p=d.length-1;p>=g;p--){let f=d[p];for(let m of f.applyResults)u.set(m.filePath,m.oldContent??"")}if(!i){let p;if(l){e==="after"?(p=d[c].afterCommit,!p&&c+1<d.length&&(p=d[c+1].beforeCommit)):p=d[c].beforeCommit;let I={commitSnapshot:p,sessionId:a.sessionId,sessionBeforeCommit:a.beforeCommit,turnsLength:d.length,targetIndex:c,currentTurn:d[d.length-1],targetTurn:d[c],targetTurnNext:d[c+1],location:e,forceReplay:s,dryRun:i,debug:o};if(!p)return this.#e.Sentry?.captureException(new Error("No commit snapshot found for restore"),{tags:{operation:"codegen-git",endpoint:"revertToCommitHash"},contexts:{restore:I}}),{undone:null,message:"Could not find the target to restore to, the git history is missing"};try{n?await this.revertToCommitSnapshot(p):await this.resetToCommitSnapshot(p)}catch(y){return this.#e.Sentry?.captureException(new Error("Error resetting git",{cause:y}),{tags:{operation:"codegen-git",endpoint:"resetToCommitHash"},contexts:{restore:I}}),{undone:null,message:"Failed to reset/restore, the file history is missing"}}}else for(let[I,y]of u.entries())try{y?await this.writeFile(I,y):await this.deleteFile(I)}catch{}if(n)return{undone:[],message:"The revert operation was successful"};let f=d.splice(g,d.length-g),m=Fa(d);m&&m?.afterCommit!==p&&(this.#e.Sentry?.captureException(new Error("Reset After commit snapshot mismatch"),{tags:{operation:"codegen-git",endpoint:"resetToCommitHash"},extra:{lastTurn:m,commitSnapshot:p}}),m.lastCommit=p,await this.#Qe({completionId:m.completionId,lastCommit:p}));let C=m?.completionId;if(f.length>0&&(await ax(this.#e,this.#a,{lastCompletionId:C,sessionId:a.sessionId},!!this.#A),a.updatedUnixTime=Date.now()),s){let I=a.state;this.#g.emit("step",{type:"batch",steps:[{type:"state",newState:"replay",abortable:!1,previousState:I},...this.#$t(),{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e},{type:"state",newState:I,abortable:!1,previousState:"replay"}]})}else f.length>0&&this.#g.emit("step",{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e})}return await this.#jt(),{undone:Array.from(u.keys()),message:"The restore operation was successful"}}async#jt(e){return await this.#h?.ensureDevCommand(e)}async restoreFromCompletionId({location:e,completionId:r,forceReplay:n}){let i=this.getSessionContext();if(!i.turns.find(o=>o.completionId===r)){await this.#be;let o=i.turns,a=i.canLoadMore,A=FB(i)?.completionId??Fa(o)?.completionId;return i.turns=[],i.canLoadMore=!0,await ax(this.#e,this.#a,{sessionId:i.sessionId,lastCompletionId:r},!!this.#A),await this.loadMoreTurns(),i.turns.some(u=>u.completionId===r)?this.restore({location:e,predicate:u=>u?.completionId===r,forceReplay:!0,debug:"restore after history"}):(this.#e.Sentry?.captureException(new Error("Restore target completion not found after reload"),{tags:{operation:"codegen-restore",endpoint:"restoreFromCompletionId"},extra:{completionId:r,location:e,turnsLoaded:i.turns.length}}),i.turns=o,i.canLoadMore=a,await ax(this.#e,this.#a,{sessionId:i.sessionId,lastCompletionId:A},!!this.#A),{undone:null,message:"Could not find the target completion to restore to"})}return this.restore({location:e,predicate:o=>o?.completionId===r,forceReplay:n,debug:`restore to: ${r}`})}async restoreBeforeCompletionId(e){return this.restoreFromCompletionId({location:"before",completionId:e,forceReplay:!1})}async undoLastUserMessage(e=!1){return this.restore({location:"before",predicate:r=>r?.user.role==="user",dryRun:e})}getLastUserCompletionId(){let e=this.getSessionContext();return NH(e)?.completionId}getLastCompletionId(){let e=this.getSessionContext();return FB(e)?.completionId}getCurrentState(){return this.getSessionContext().state}getLastApplyResultsTurn(){let e=this.getSessionContext();return Aye(e)}getLastTurn(){let e=this.getSessionContext();return FB(e)}getLastMessage(){return this.getLastTurn()?.actions.find(r=>r.type==="text")?.content}getNextUrl(){return this.getLastTurn()?.nextUrl}async sendFeedback(e){if(process.env.NODE_ENV==="test")return;if(e.feedbackSentiment){let n=e.feedbackSentiment==="positive"?`User provided positive feedback (thumbs up) on the previous completion.${e.feedbackText??""}`:`User provided negative feedback (thumbs down) on the previous completion.${e.feedbackText??""}`;this.queueSystemReminder({text:n,tag:"reminder:user-feedback"})}Pt("quality code feedback given",{spaceId:this.#a.builderPublicKey,sentiment:e.feedbackSentiment,mode:"cli"});let r=e.id??this.getLastCompletionId();r&&await this.#Br({...e,id:r})}#Qe(e){let r=e.completionId;if(!r){let i=this.getLastTurn();i&&e.lastCommit&&(i.lastCommit=e.lastCommit),r=i?.completionId}let n=xB(this.#e,this.#a,"/codegen/finalize",{completionId:r,projectId:this.#u?.projectId,branchName:this.#u?.branchName,userCompletionId:this.getLastUserCompletionId(),sessionId:this.getSessionId(),metadata:this.#v,hasPlanToApply:this.#Ie,...e},this.#A);return this.#Pt&&this.#Er(),this.#O(n,"completionFinalize")}#Er(){try{let e=this.#e.getCwdDir(),r=this.getSessionId();if(this.#dt){e8(this.#e,e,r).catch(()=>{});return}let n=Pv(this.#e,e).then(i=>{if(i.some(l=>l.sessionId===r)){this.#dt=!0,e8(this.#e,e,r).catch(()=>{});return}let s=this.getSessionContext().turns,o=s[s.length-1],a=o?.title,A=a&&a!=="Untitled"&&!a.startsWith("completionId:"),c=o?.userMessage?.displayPrompt??o?.userMessage?.userPrompt??"",u=A?a:Phe(c);return Mhe(this.#e,e,r,u).then(()=>{this.#dt=!0})}).catch(()=>{});this.#O(n,"saveLocalHistory")}catch{}}#Br(e){let r=xB(this.#e,this.#a,"/codegen/feedback",e,this.#A);return this.#O(r,"completionFeedback")}#G(e,r,n={}){this.#h?.emitter.emit("metrics",{durations:[{key:e,ms:r,attributes:n}]})}#O(e,r,n=!1){let i=Uo();this.#r.debug(`(addToPendingPromises-${i}): adding ${r} (blocking: ${n})`),this.#de.push(e),n&&this.#We.push(e);let s=new Error(`Deadlock detected in codegen (function: ${r})`),o=setTimeout(()=>{this.#e.Sentry?.captureException(s,{level:"fatal",tags:{operation:"codegen-stream",functionName:r,sessionId:this.getSessionId(),projectId:this.#E,branchName:this.#y}})},300*1e3);return e.finally(()=>{clearTimeout(o),this.#r.debug(`(addToPendingPromises-${i}): removing ${r} (blocking: ${n})`);let a=this.#We.indexOf(e);a!==-1&&this.#We.splice(a,1);let A=this.#de.indexOf(e);A!==-1&&this.#de.splice(A,1)})}async lastTurnHasChanges(){let e=await this.undoLastUserMessage(!0);return e.undone?e.undone.length>0:!1}#V(e){let r=this.getSessionContext(),n=r.state;return n!==e?(r.state=e,this.#g.emit("step",{type:"state",abortable:e==="generating",previousState:n,newState:e}),!0):!1}waitUntilState(e,r=1e4){return new Promise(n=>{if(this.getSessionContext().state===e){n();return}let s,o=a=>{a.type==="state"&&a.newState===e&&(clearTimeout(s),this.#g.removeListener("step",o),n())};s=setTimeout(()=>{this.#g.removeListener("step",o),n()},r),this.#g.on("step",o)})}getProxyConfig(){return jie({devServerUrl:this.#u?.serverUrl,proxyOrigin:this.#qe,proxyDefaultOrigin:this.#$e,proxyDestination:this.#Nt})}async clearSession(){this.#r.debug("(clearSession): clearing session"),await this.abort({cleanCurrentMessage:!0,flushMessageQueue:!1});let e=this.getSessionContext();e.turns=[],e.customInstructions=await this.#_e(),e.customAgents=await this.#nt(),this.#Y.length=0,this.#at=!1,this.#v={},this.#re=void 0,this.#He=!1,this.#Ze=0,this.#he=null,this.#me=void 0,this.#Xe=[],this.clearMessageQueue(!1),this.queueGitStatusReminder({trigger:"session-start"}),this.#g.emit("step",this.#qt())}async clearMessageQueue(e=!1){let r=[],n=this.getSessionMode();if(e)for(let i of this.#t)i.user&&r.push({type:"user",previousId:this.getLastCompletionId(),displayPrompt:i.displayPrompt,user:i.user,role:i.user.role,compacting:!1,idempotencyKey:i.idempotencyKey,sessionMode:i.sessionMode??n});this.#t.length=0,this.#Ge(),r.length>0&&this.#g.emit("step",{type:"batch",steps:r})}updateMessage(e){if(e.type==="delete"){let r=this.#t.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&this.#t.splice(r,1)}else if(e.type==="move"){let r=this.#t.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&Bye(this.#t,r,r+e.delta)}this.#Ge()}async flushMessageQueue(){this.#r.debug("(flushMessageQueue): flushing message queue"),await this.abort({cleanCurrentMessage:!1,flushMessageQueue:!0}),this.#s&&this.#s()}#Yt(e){let r=e.idempotencyKey;if(r){let n=this.#t.findIndex(i=>i.idempotencyKey===r);if(n>=0)return this.#t[n]=e,!1}else e.idempotencyKey=(0,ox.randomUUID)();if(e.queue==null&&(e.queue=!0),e.user?e.user={...this.#re,...e.user}:e.user=this.#re,e.userPrompt==="___BROWSER_AUTOMATION_PROMPT___"){let n=this.getProxyConfig();e.userPrompt=Lhe(n.proxyDefaultOrigin,this.#Re||void 0)}return this.#o.coalesce==="replace-latest"&&(this.#t.length=0),this.#t.push(e),!0}async sendMessage(e){this.#He=!1;let r=this.#o.schedule,n=die(r)&&(this.#c!==void 0||this.#i!==void 0);if(r==="interrupt-clear"&&(this.#r.debug("(sendMessage): interrupt-clear schedule \u2014 clearing session"),await this.clearSession()),n&&r==="interrupt-replace"){this.#r.debug("(sendMessage): interrupt-replace schedule \u2014 undoing last user message"),await this.undoLastUserMessage();let o=Array.isArray(e)?e:[e];for(let a of o)a.dropAbortedPrompt=!0}let i=0;if(Array.isArray(e))for(let o of e)this.#Yt(o)&&i++;else this.#Yt(e)&&i++;if(i===0)return null;this.#r.debug(`(sendMessage): added messages(${i}) to queue(${this.#t.length})`),this.#Ge();let s=this.#t[this.#t.length-1];return s?(this.cancelAllPendingToolFulfilments(s.userPrompt),n&&this.#c&&(this.#r.debug(`(sendMessage): ${r} \u2014 aborting current run`),this.#c.abort(),this.#c=void 0),s.queue?this.#s&&this.#s():await this.flushMessageQueue(),await Sl(),s.idempotencyKey):null}#yr(){if(this.#o.schedule==="until-idle")return;let e=this.#t;if(e.length===0)return;let r;switch(this.#o.coalesce){case"preserve-order":r=[e[0]];break;case"replace-latest":r=[e[e.length-1]];break;default:r=e.slice();break}for(let n of r)if(n.systemReminders)for(let i of n.systemReminders)this.queueSystemReminder(i);return this.#i=bH(r),this.#re=this.#i.user,this.#i.softContextWindow&&(this.#b=Math.min(this.#b??3e4,this.#i.softContextWindow)),this.#o.coalesce==="preserve-order"?(this.#t.shift(),this.#Ge()):this.clearMessageQueue(!0),this.#i}#Qr(){let e=this.#t.length===0||this.#He,r=new Promise(n=>{e?this.#s=n:n()}).then(()=>{let n=this.#t;if(n.length===0)return;if(this.#o.coalesce!=="merge"){let s=this.#o.coalesce==="replace-latest"?n.pop():n.shift();if(this.#o.coalesce==="replace-latest"&&(this.#t.length=0),s.user&&!s.forceCompact){this.#re=s.user;let o=this.getSessionMode();this.#g.emit("step",{type:"user",previousId:this.getLastCompletionId(),displayPrompt:s.displayPrompt,user:s.user,role:s.user.role,compacting:!1,idempotencyKey:s.idempotencyKey,sessionMode:s.sessionMode??o})}if(s.systemReminders)for(let o of s.systemReminders)this.queueSystemReminder(o);return this.#i=s,this.#re=s.user,this.#i.softContextWindow&&(this.#b=Math.min(this.#b??3e4,this.#i.softContextWindow)),this.#Ge(),s}for(let s of n)if(s.systemReminders)for(let o of s.systemReminders)this.queueSystemReminder(o);let i=bH(n);if(!i.dropAbortedPrompt&&this.#i){let s=i.idempotencyKey;i=PH(this.#i,i),i.idempotencyKey=s}return this.clearMessageQueue(!0),this.#i=i,this.#re=i.user,i});return{shouldWait:e,promise:r}}#Ge(){this.#g.emit("step",{type:"message-queue",queue:this.#t.map(e=>({idempotencyKey:e.idempotencyKey,displayPrompt:e.displayPrompt,user:e.user}))})}#yt(e,r=!1){r&&(this.#v={}),Object.assign(this.#v,e),this.#g.emit("step",{type:"metadata",...this.#v})}async waitForSetupCommand(e){let r=this.#h;if(!r)return{state:"installed",shouldProceed:!0};if(r.setupState==="installing")try{await Wc(r.setupCommandPromise,e)}catch{}let n=r.setupState;return n==="not-installed"||n==="install-failed"||n==="install-aborted"?{state:n,shouldProceed:!0}:{state:"installed",shouldProceed:!0}}async waitForDevServer(e,r,n){if(!this.#h&&this.#u?.serverUrl)return{shouldProceed:!0,message:"Dev server is ready.",serverUrl:this.#u.serverUrl};let i=await this.waitForSetupCommand(e);if(!i.shouldProceed)return{shouldProceed:!1,message:`Project setup command did not completed. State: ${i.state}`};let s=this.#h;if(s){await s.ensureDevCommand(e);let o=await s.waitUntilServer(e,r,n);return o.ok?{shouldProceed:!0,message:"Dev server is ready.",serverUrl:s.serverUrl?.toString()}:{shouldProceed:!1,message:o.message,serverUrl:void 0}}return{shouldProceed:!1,message:"Dev server is not ready.",serverUrl:void 0}}async getNamedAgentConfig(e,r,n){let i=this.getSessionContext(),s=i.customAgents,o=e?s.find(K=>K.name.toLowerCase()===e.toLowerCase()):void 0,a=o?.name??"explorer",{mcpServers:A=!1,model:c,systemPrompt:u,subagent_type:l,includeMemories:d,needDevServer:g,needValidation:p,queueMode:f,asyncSubAgents:m,resetAfterRun:C=!1,reasoning:I,softContextWindow:y,maxTimeoutMs:B}={mcpServers:o?.mcpServers,subagent_type:a,systemPrompt:o?.systemPrompt,softContextWindow:o?.softContextWindow,model:(()=>{let K=o?.name??a,j=K?this.#le?.[K]:void 0;if(typeof j=="string")return j;if(Array.isArray(j)&&j.length){let ee=K,U=this.#fe.get(ee)??0;return this.#fe.set(ee,U+1),j[U%j.length]}if(o?.roundRobinModels?.length){let ee=o.name,U=this.#fe.get(ee)??0;return this.#fe.set(ee,U+1),o.roundRobinModels[U%o.roundRobinModels.length]}return o?.model})(),includeMemories:o?.includeMemories,needDevServer:o?.needDevServer,needValidation:o?.needValidation,resetAfterRun:o?.resetAfterRun,queueMode:o?.queueBehavior??o?.queueMode,asyncSubAgents:o?.asyncSubAgents,reasoning:o?.reasoning??this.#gt,maxTimeoutMs:o?.maxTimeoutMs},E=(this.#D??[]).filter(K=>K!=="Agent");E.includes("ExplorationMetadata")||E.push("ExplorationMetadata");let Q=DH(this.#u,o?.tools??E),v=c,D=this.#h;if(g&&n){if(!D)return{success:!1,response:`The ${l} agent can not be used on this session. Do no try again.`};if(D.httpServerState.state==="stopped"||D.httpServerState.state==="connecting"||D.httpServerState.state==="error-fetch")try{if(D.state==="not-installed")throw new Error(`The ${l} agent can not be used until the setupCommand finish successfully. However, the dev server is not installed.`);if(D.state==="install-failed")throw new Error(`The ${l} agent can not be used until the setupCommand finish successfully. However, last time we try to run the install script, it failed.`);if(D.state==="install-aborted")throw new Error(`The ${l} agent can not be used until the setupCommand finish successfully. However, last time we try to run the install script, it was aborted.`);await this.waitForSetupCommand(n),await D.ensureDevCommand(n)}catch(j){return{success:!1,response:j instanceof Error?j.message:String(j)}}if(p&&D.validateCommand&&this.#ne){let j=await D.runValidateCommand(void 0,n);if(j.status==="failure")return{success:!1,response:`The Agent could not start yet, because the validate command failed:
|
|
1885
|
+
`),Q.write(S)),m=Q}let C=Date.now(),I={terminalId:n,title:e?.title||`Terminal ${this.#w.size+1}`,cwd:p,createdAt:C,lastWrittenAt:C,createdBy:e?.createdBy||"unknown",readonly:e?.readonly??!1,initialCommand:e?.initialCommand,builtIn:!1,state:f,stale:!1,exitCode:void 0,command:void 0};return this.#w.set(n,{...I,pty:m,onDataListeners:s,onExitListeners:o,disposeFns:l,env:e?.env,shell:a,inheritCredentials:e?.inheritCredentials}),(e?.emitTerminals??!0)&&this.#ye(),I}#Bt(){let e=this.getSessionContext(),r=Array.from(this.#w.values()).map(s=>({terminalId:s.terminalId,title:s.title,cwd:s.cwd,createdAt:s.createdAt,lastWrittenAt:s.lastWrittenAt,createdBy:s.createdBy,readonly:s.readonly,builtIn:s.builtIn,exitCode:s.exitCode,state:s.state,stale:s.stale,command:s.command})),n=[];this.#D?.includes("Bash")&&n.push({terminalId:"bash-tools",title:"Bash",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:Date.now(),createdBy:"fusion",readonly:!0,builtIn:!0,exitCode:void 0,state:"running",command:void 0});let i=this.#h;if(i){let s=Date.now();if(i.devState!=="unset"&&n.push({terminalId:"dev-command",title:"Dev Command",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:s,createdBy:"fusion",readonly:!i.devCommandProcess?.write,builtIn:!0,state:i.devState==="running"?"running":"exited",exitCode:void 0,command:i.devCommand}),i.setupCommand&&n.push({terminalId:"setup-command",title:"Setup Command",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:s,createdBy:"fusion",readonly:!0,builtIn:!0,state:i.setupState==="installing"?"running":"exited",exitCode:void 0,command:i.setupCommand}),i.validateCommandState!=="unset"){let o;switch(i.validateCommandState){case"running":o="running";break;case"success":o="exited";break;case"failure":o="error";break;case"stopped":o="exited";break}n.unshift({terminalId:"validate-command",title:"Validate Command",cwd:this.#x,createdAt:e.createdUnixTime,lastWrittenAt:s,createdBy:"fusion",readonly:!0,builtIn:!0,state:o,exitCode:void 0,command:i.validateCommand})}}return n.push(...r),n}#ye(){this.#g.emit("step",{type:"terminals",terminals:this.#Bt()})}updateTerminal({terminalId:e,cols:r,rows:n,title:i}){if(e==="dev-command"){if(r||n){let o=this.#h;if(o?.devCommandProcess?.resize)return o.devCommandProcess.resize(r,n),!0}return!1}let s=this.#w.get(e);return s?("resize"in s.pty&&(r||n)&&s.pty.resize(r??s.pty.cols,n??s.pty.rows),i&&(s.title=i,this.#ye()),!0):!1}writeTerminal({terminalId:e,data:r}){if(e==="dev-command"){let i=this.#h;return i?.devCommandProcess?.write?(i.devCommandProcess.write(r),!0):!1}let n=this.#w.get(e);return!n||n.readonly?!1:("write"in n.pty&&n.pty.write(r),n.lastWrittenAt=Date.now(),!0)}signalTerminal({terminalId:e,signal:r}){if(e==="dev-command"){let i=this.#h;return i?.devCommandProcess?.kill?(i.devCommandProcess.kill(r),!0):!1}let n=this.#w.get(e);if(!n||n.readonly)return!1;try{"write"in n.pty?process.platform==="win32"?n.pty.kill():(r==="SIGINT"&&n.pty.write(""),n.pty.kill(r)):n.pty.kill(r)}catch{}return!0}disposeTerminal({terminalId:e,emitTerminals:r=!0}){let n=this.#w.get(e);if(!n)return!1;try{n.pty.kill()}catch{}return n.disposeFns.forEach(i=>{try{i()}catch{}}),n.onDataListeners.clear(),n.onExitListeners.clear(),n.disposeFns=[],this.#w.delete(e),r&&this.#ye(),!0}async restartTerminal({terminalId:e}){if(e==="dev-command"){let i=this.#h;if(i)try{return await i.restart(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="setup-command"){let i=this.#h;if(i)try{return await i.runSetupCommand(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="validate-command"){if(this.#h)try{return await this.#Vt(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="bash-tools")return!1;let r=this.#w.get(e);return r?(await this.createTerminal({terminalId:e,title:r.title,cwd:r.cwd,env:r.env,shell:r.shell,cols:"cols"in r.pty?r.pty.cols:void 0,rows:"rows"in r.pty?r.pty.rows:void 0,createdBy:r.createdBy,emitTerminals:!1,initialCommand:r.initialCommand,readonly:r.readonly,inheritCredentials:r.inheritCredentials,force:!0}),this.#w.get(e)?(this.#ye(),!0):!1):!1}subscribeTerminal({terminalId:e,onData:r,onExit:n}){if(e==="dev-command"){let i=this.#h;if(i){let s=i.getDevWrite();return s&&r(s),i.emitter.on("stdout",r),i.emitter.on("stderr",r),()=>{i.emitter.off("stdout",r),i.emitter.off("stderr",r)}}}else if(e==="setup-command"){let i=this.#h;if(i){let s=i.getSetupOutput();return s&&r(s),i.emitter.on("installStdout",r),i.emitter.on("installStderr",r),()=>{i.emitter.off("installStdout",r),i.emitter.off("installStderr",r)}}}else if(e==="validate-command"){let i=this.#h;if(i){let s=i.getValidateOutput();return s&&r(s),i.emitter.on("validateStdout",r),i.emitter.on("validateStderr",r),()=>{i.emitter.off("validateStdout",r),i.emitter.off("validateStderr",r)}}}else if(e==="bash-tools"){let i=s=>{s.type==="stdio"&&s.source==="tool-command"&&r(s.content)};return this.#g.on("step",i),()=>{this.#g.off("step",i)}}else{let i=this.#w.get(e);if(!i)throw new Error("Terminal not found");return i.onDataListeners.add(r),n&&i.onExitListeners.add(n),()=>{i.onDataListeners.delete(r),n&&i.onExitListeners.delete(n)}}}async getAllFiles(e={}){let{getDotFiles:r=!1,globbyPattern:n="**/*",includePattern:i,gitignore:s,deep:o,truncate:a,maxFiles:A=5e4,onlyFiles:c=!0}=e,u=this.#u?.accessControl,l=u?.entries?.filter(f=>f.action==="allow"&&f.permissions.includes("list")).map(f=>(f.resource.startsWith("/")?f.resource.slice(1):f.resource)||".")??[];if(!this.#C?.folders?.length){let f=await cl({basePath:this.#d,globPattern:[i??n,...l],extraIgnorePatterns:L0(u).deny,dot:r,gitignore:s,sys:this.#e,deep:o,onlyFiles:c,maxFiles:A});return Z_(f,a)}let d=[],g=await this.#e.readdir(this.#d);for(let f of g)M4(f)&&d.push(f);!d.includes("AGENTS.md")&&this.#C.agentsMD&&d.push("AGENTS.md");for(let f of this.#C.folders){let m=this.#e.resolve(this.#d,f.path),C=await cl({basePath:m,globPattern:[n,...l],dot:r,gitignore:s,sys:this.#e,deep:o,onlyFiles:c,maxFiles:A}),I=this.#K()?".":f.name||this.#e.basename(m);for(let y of C)I!=="."?d.push(this.#e.join(I,y)):d.push(y)}let p=Ff({files:d,policy:u,filterPattern:i,getDotFiles:r});return Z_(p,a)}async searchFiles(e){let{query:r,caseInsensitive:n=!0,includeGlob:i,excludeGlob:s,maxResults:o=1e3,contextBefore:a=0,contextAfter:A=0}=e,c=await RB(this.#e),u=["--path-separator","/","--json","--line-number","--column","--hidden","--max-columns","500"];return n&&u.push("-i"),a>0&&u.push("-B",a.toString()),A>0&&u.push("-A",A.toString()),i&&u.push("--glob",i),s&&u.push("--glob",`!${s}`),u.push("--ignore-file",".builderignore"),u.push("--",r),new Promise(l=>{let d=Cc({command:c,args:u,options:{env:process.env,cwd:this.#x,stdio:["ignore","pipe","pipe"]}}),g=new Ni(5e4);d.stdout.on("data",p=>{g.write(p.toString())}),d.on("error",()=>{l({matches:[],totalMatches:0,filesWithMatches:0,truncated:!1})}),d.on("close",p=>{if(p!==0)l({matches:[],totalMatches:0,filesWithMatches:0,truncated:!1});else{let f=[],m=new Set,I=g.getContent().split(`
|
|
1886
|
+
`),y=[],B=null;for(let Q of I)if(Q.trim())try{let v=JSON.parse(Q);if(v.type==="match"){let D=v.data.path.text,S=v.data.line_number,b=v.data.lines.text.trimEnd(),x=v.data.submatches||[],P,O;x.length>0&&(P=x[0].start,O=x[0].end),m.add(D);let J={filePath:D,lineNumber:S,lineContent:b,columnStart:P,columnEnd:O,contextBefore:y,contextAfter:[]};if(y=[],B=J,f.push(J),f.length>=o)break}else if(v.type==="context"){let D=v.data.line_number,S=v.data.lines.text.trimEnd();B&&D>B.lineNumber?B.contextAfter.push(S):y.push(S)}}catch{continue}let E=f.length>=o;l({matches:f,totalMatches:f.length,filesWithMatches:m.size,truncated:E})}})})}#Jt(e){let r=this.#Ce.indexOf(e);r!==-1&&this.#Ce.splice(r,1),this.#Ce.unshift(e),this.#Ce.length>50&&(this.#Ce.length=50)}async#Cr(){let e=this.#Pe;if(e&&Date.now()-e.timestamp<t.#rt)return e.promise;let r=this.#u?.accessControl,n=cl({basePath:this.#x,extraIgnorePatterns:L0(r).deny,gitignore:!0,dot:!0,sys:this.#e}).then(i=>Ff({files:i,policy:r,getDotFiles:!0}));return this.#Pe={promise:n,timestamp:Date.now(),fuse:null},n}async#Ir(){let e=this.#Pe;if(e?.fuse)return e.fuse;let r=await this.#Cr(),n=She(r);return this.#Pe&&(this.#Pe.fuse=n),n}async searchFileTree(e){let{query:r,maxResults:n=100}=e;if(!r){let A=this.#Ce.slice(0,n).map(c=>{let u=c.lastIndexOf("/");return{filePath:c,fileName:u>=0?c.slice(u+1):c,parentPath:u>=0?c.slice(0,u):"",matchIndices:[]}});return{matches:A,totalMatches:A.length,truncated:!1}}let s=(await this.#Ir()).search(r,{limit:n});return{matches:s.map(a=>{let{fullPath:A,basename:c,dirname:u}=a.item,l=xhe(a);return{filePath:A,fileName:c,parentPath:u,matchIndices:l}}),totalMatches:s.length,truncated:s.length>=n}}async collectRepoMetrics(e={}){let r=this.#Le(e.folderName);return e.rootPath&&(r=this.#e.join(r,e.rootPath)),Whe(this.#e,r)}getSessionId(){return this.getSessionContext().sessionId}getMainSessionId(){return this.#Lt??this.getSessionId()}updateMetadata(e){this.#yt(e,!1)}getMetadata(){return this.#v}#it=null;setTimeline(e){this.#it=e}getTimeline(){return this.#it}getSpaceId(){return this.#a.builderPublicKey}async revertToCommitSnapshot(e){await this.waitUntilBlockingPendingPromises(),await this.abortMerge(!1),await this.#ie(!1);let n=(await this.#$(async s=>{let o=al(e,s.folderName,this.gitRepoContexts[0]?.folderName);return o?(await this.git(["revert","--no-commit",`${o}..HEAD`],{cwd:s.path}),await this.git(["commit","--allow-empty","--quiet","--no-verify","--no-gpg-sign","-m","Revert changes"],{cwd:s.path}),{commitHash:await this.getCurrentCommitHash("HEAD",s.path)}):(this.#r.warn(`No commit found for ${s.folderName}, skipping revert`),{skipped:!0})})).results.filter(s=>!s.success);if(n.length>0)throw new Error(`Failed to revert ${n.length} repos`);let i=await this.#H();this.#P={...this.#P,...i},await this.#F(),this.requestRefresh(),await this.#Qe({lastCommit:So(i)})}async revertToCommitHash(e){let r=fh(e,this.gitRepoContexts[0]?.folderName),n=Object.keys(r).length===0?e:So(r);return this.revertToCommitSnapshot(n)}async resetToCommitSnapshot(e,r=!0){await this.waitUntilBlockingPendingPromises(),await this.abortMerge(!1),await this.#ie(!1);let n=20,i=`${Date.now()}`,s=[],a=(await this.#$(async c=>{let u=al(e,c.folderName,this.gitRepoContexts[0]?.folderName);if(!u)return this.#r.warn(`No commit found for ${c.folderName}, skipping reset`),{skipped:!0};let l=await this.getCurrentCommitHash("HEAD",c.path),d=0;if(l&&l!==u)try{let C=await this.git(["rev-list","--count",`${u}..HEAD`],{cwd:c.path});d=Number.parseInt(C.trim(),10)||0}catch{}let g=!1,p=l;try{g=!await this.#st(c.path),g&&(await this.git(["add","-A","."],{cwd:c.path,retry:2}),await this.git(["commit","--quiet","--no-verify","--no-gpg-sign","-m","buildercode: safety snapshot before restore"],{cwd:c.path}),p=await this.getCurrentCommitHash("HEAD",c.path))}catch(C){this.#e.Sentry?.captureException(new Error(`Failed to capture pre-restore safety snapshot for ${c.folderName}: ${C}`),{tags:{operation:"codegen-git",endpoint:"resetToCommitSnapshot"}})}let f;if(p&&(d>0||g)){f=`refs/fusion/pre-restore/${i}`;try{await this.git(["update-ref",f,p],{cwd:c.path})}catch{f=void 0}}s.push({folderName:c.folderName,fromCommit:l,toCommit:u,discardedCommits:d,hadUncommittedWork:g,recoveryRef:f}),await this.git(["reset","--quiet","--hard",u],{cwd:c.path}),await this.git(["clean","-fd"],{cwd:c.path});let m=await this.getCurrentCommitHash("HEAD",c.path);if(m!==u)throw new Error(`Failed to reset commit hash for ${c.folderName}: expected ${u}, got ${m}`);return{commitHash:m}})).results.filter(c=>!c.success);if(a.length>0)throw new Error(`Failed to reset ${a.length} repos`);for(let c of s){let u=`(resetToCommitSnapshot) ${c.folderName}: ${c.fromCommit??"?"} -> ${c.toCommit} discardedCommits=${c.discardedCommits} uncommittedWork=${c.hadUncommittedWork} recovery=${c.recoveryRef??"(reflog only)"}`;c.discardedCommits>=n||c.hadUncommittedWork?(this.#r.warn(u),this.#e.Sentry?.captureException(new Error("Restore discarded a large amount of work"),{level:"warning",tags:{operation:"codegen-git",endpoint:"resetToCommitSnapshot"},extra:{...c,sessionId:this.getSessionId()}})):this.#r.debug(u)}let A=fh(e,this.gitRepoContexts[0]?.folderName);this.#P={...this.#P,...A},await this.#F(),r&&this.requestRefresh()}async resetToCommitHash(e,r=!0){let n=fh(e,this.gitRepoContexts[0]?.folderName),i=Object.keys(n).length===0?e:So(n);return this.resetToCommitSnapshot(i,r)}async restore({location:e,predicate:r,revert:n=!1,dryRun:i=!1,forceReplay:s=!1,debug:o}){let a=this.getSessionContext(),A=a.turns.length,c=null;for(let p=A-1;p>=0;p--)if(r(a.turns[p],p)){c=p;break}if(c===null)return{undone:null,message:"Could not find the target to restore to, the completion id could be wrong"};n||await this.abort({cleanCurrentMessage:!0});let u=new Map,l=!!this.#I,d=a.turns,g=e==="before"?c:c+1;for(let p=d.length-1;p>=g;p--){let f=d[p];for(let m of f.applyResults)u.set(m.filePath,m.oldContent??"")}if(!i){let p;if(l){e==="after"?(p=d[c].afterCommit,!p&&c+1<d.length&&(p=d[c+1].beforeCommit)):p=d[c].beforeCommit;let I={commitSnapshot:p,sessionId:a.sessionId,sessionBeforeCommit:a.beforeCommit,turnsLength:d.length,targetIndex:c,currentTurn:d[d.length-1],targetTurn:d[c],targetTurnNext:d[c+1],location:e,forceReplay:s,dryRun:i,debug:o};if(!p)return this.#e.Sentry?.captureException(new Error("No commit snapshot found for restore"),{tags:{operation:"codegen-git",endpoint:"revertToCommitHash"},contexts:{restore:I}}),{undone:null,message:"Could not find the target to restore to, the git history is missing"};try{n?await this.revertToCommitSnapshot(p):await this.resetToCommitSnapshot(p)}catch(y){return this.#e.Sentry?.captureException(new Error("Error resetting git",{cause:y}),{tags:{operation:"codegen-git",endpoint:"resetToCommitHash"},contexts:{restore:I}}),{undone:null,message:"Failed to reset/restore, the file history is missing"}}}else for(let[I,y]of u.entries())try{y?await this.writeFile(I,y):await this.deleteFile(I)}catch{}if(n)return{undone:[],message:"The revert operation was successful"};let f=d.splice(g,d.length-g),m=Fa(d);m&&m?.afterCommit!==p&&(this.#e.Sentry?.captureException(new Error("Reset After commit snapshot mismatch"),{tags:{operation:"codegen-git",endpoint:"resetToCommitHash"},extra:{lastTurn:m,commitSnapshot:p}}),m.lastCommit=p,await this.#Qe({completionId:m.completionId,lastCommit:p}));let C=m?.completionId;if(f.length>0&&(await ax(this.#e,this.#a,{lastCompletionId:C,sessionId:a.sessionId},!!this.#A),a.updatedUnixTime=Date.now()),s){let I=a.state;this.#g.emit("step",{type:"batch",steps:[{type:"state",newState:"replay",abortable:!1,previousState:I},...this.#$t(),{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e},{type:"state",newState:I,abortable:!1,previousState:"replay"}]})}else f.length>0&&this.#g.emit("step",{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e})}return await this.#jt(),{undone:Array.from(u.keys()),message:"The restore operation was successful"}}async#jt(e){return await this.#h?.ensureDevCommand(e)}async restoreFromCompletionId({location:e,completionId:r,forceReplay:n}){let i=this.getSessionContext();if(!i.turns.find(o=>o.completionId===r)){await this.#be;let o=i.turns,a=i.canLoadMore,A=FB(i)?.completionId??Fa(o)?.completionId;return i.turns=[],i.canLoadMore=!0,await ax(this.#e,this.#a,{sessionId:i.sessionId,lastCompletionId:r},!!this.#A),await this.loadMoreTurns(),i.turns.some(u=>u.completionId===r)?this.restore({location:e,predicate:u=>u?.completionId===r,forceReplay:!0,debug:"restore after history"}):(this.#e.Sentry?.captureException(new Error("Restore target completion not found after reload"),{tags:{operation:"codegen-restore",endpoint:"restoreFromCompletionId"},extra:{completionId:r,location:e,turnsLoaded:i.turns.length}}),i.turns=o,i.canLoadMore=a,await ax(this.#e,this.#a,{sessionId:i.sessionId,lastCompletionId:A},!!this.#A),{undone:null,message:"Could not find the target completion to restore to"})}return this.restore({location:e,predicate:o=>o?.completionId===r,forceReplay:n,debug:`restore to: ${r}`})}async restoreBeforeCompletionId(e){return this.restoreFromCompletionId({location:"before",completionId:e,forceReplay:!1})}async undoLastUserMessage(e=!1){return this.restore({location:"before",predicate:r=>r?.user.role==="user",dryRun:e})}getLastUserCompletionId(){let e=this.getSessionContext();return N4(e)?.completionId}getLastCompletionId(){let e=this.getSessionContext();return FB(e)?.completionId}getCurrentState(){return this.getSessionContext().state}getLastApplyResultsTurn(){let e=this.getSessionContext();return Aye(e)}getLastTurn(){let e=this.getSessionContext();return FB(e)}getLastMessage(){return this.getLastTurn()?.actions.find(r=>r.type==="text")?.content}getNextUrl(){return this.getLastTurn()?.nextUrl}async sendFeedback(e){if(process.env.NODE_ENV==="test")return;if(e.feedbackSentiment){let n=e.feedbackSentiment==="positive"?`User provided positive feedback (thumbs up) on the previous completion.${e.feedbackText??""}`:`User provided negative feedback (thumbs down) on the previous completion.${e.feedbackText??""}`;this.queueSystemReminder({text:n,tag:"reminder:user-feedback"})}Pt("quality code feedback given",{spaceId:this.#a.builderPublicKey,sentiment:e.feedbackSentiment,mode:"cli"});let r=e.id??this.getLastCompletionId();r&&await this.#Br({...e,id:r})}#Qe(e){let r=e.completionId;if(!r){let i=this.getLastTurn();i&&e.lastCommit&&(i.lastCommit=e.lastCommit),r=i?.completionId}let n=xB(this.#e,this.#a,"/codegen/finalize",{completionId:r,projectId:this.#u?.projectId,branchName:this.#u?.branchName,userCompletionId:this.getLastUserCompletionId(),sessionId:this.getSessionId(),metadata:this.#v,hasPlanToApply:this.#Ie,...e},this.#A);return this.#Pt&&this.#Er(),this.#O(n,"completionFinalize")}#Er(){try{let e=this.#e.getCwdDir(),r=this.getSessionId();if(this.#dt){e8(this.#e,e,r).catch(()=>{});return}let n=Pv(this.#e,e).then(i=>{if(i.some(l=>l.sessionId===r)){this.#dt=!0,e8(this.#e,e,r).catch(()=>{});return}let s=this.getSessionContext().turns,o=s[s.length-1],a=o?.title,A=a&&a!=="Untitled"&&!a.startsWith("completionId:"),c=o?.userMessage?.displayPrompt??o?.userMessage?.userPrompt??"",u=A?a:Phe(c);return Mhe(this.#e,e,r,u).then(()=>{this.#dt=!0})}).catch(()=>{});this.#O(n,"saveLocalHistory")}catch{}}#Br(e){let r=xB(this.#e,this.#a,"/codegen/feedback",e,this.#A);return this.#O(r,"completionFeedback")}#G(e,r,n={}){this.#h?.emitter.emit("metrics",{durations:[{key:e,ms:r,attributes:n}]})}#O(e,r,n=!1){let i=Uo();this.#r.debug(`(addToPendingPromises-${i}): adding ${r} (blocking: ${n})`),this.#de.push(e),n&&this.#We.push(e);let s=new Error(`Deadlock detected in codegen (function: ${r})`),o=setTimeout(()=>{this.#e.Sentry?.captureException(s,{level:"fatal",tags:{operation:"codegen-stream",functionName:r,sessionId:this.getSessionId(),projectId:this.#E,branchName:this.#y}})},300*1e3);return e.finally(()=>{clearTimeout(o),this.#r.debug(`(addToPendingPromises-${i}): removing ${r} (blocking: ${n})`);let a=this.#We.indexOf(e);a!==-1&&this.#We.splice(a,1);let A=this.#de.indexOf(e);A!==-1&&this.#de.splice(A,1)})}async lastTurnHasChanges(){let e=await this.undoLastUserMessage(!0);return e.undone?e.undone.length>0:!1}#V(e){let r=this.getSessionContext(),n=r.state;return n!==e?(r.state=e,this.#g.emit("step",{type:"state",abortable:e==="generating",previousState:n,newState:e}),!0):!1}waitUntilState(e,r=1e4){return new Promise(n=>{if(this.getSessionContext().state===e){n();return}let s,o=a=>{a.type==="state"&&a.newState===e&&(clearTimeout(s),this.#g.removeListener("step",o),n())};s=setTimeout(()=>{this.#g.removeListener("step",o),n()},r),this.#g.on("step",o)})}getProxyConfig(){return jie({devServerUrl:this.#u?.serverUrl,proxyOrigin:this.#qe,proxyDefaultOrigin:this.#$e,proxyDestination:this.#Nt})}async clearSession(){this.#r.debug("(clearSession): clearing session"),await this.abort({cleanCurrentMessage:!0,flushMessageQueue:!1});let e=this.getSessionContext();e.turns=[],e.customInstructions=await this.#_e(),e.customAgents=await this.#nt(),this.#Y.length=0,this.#at=!1,this.#v={},this.#re=void 0,this.#He=!1,this.#Ze=0,this.#he=null,this.#me=void 0,this.#Xe=[],this.clearMessageQueue(!1),this.queueGitStatusReminder({trigger:"session-start"}),this.#g.emit("step",this.#qt())}async clearMessageQueue(e=!1){let r=[],n=this.getSessionMode();if(e)for(let i of this.#t)i.user&&r.push({type:"user",previousId:this.getLastCompletionId(),displayPrompt:i.displayPrompt,user:i.user,role:i.user.role,compacting:!1,idempotencyKey:i.idempotencyKey,sessionMode:i.sessionMode??n});this.#t.length=0,this.#Ge(),r.length>0&&this.#g.emit("step",{type:"batch",steps:r})}updateMessage(e){if(e.type==="delete"){let r=this.#t.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&this.#t.splice(r,1)}else if(e.type==="move"){let r=this.#t.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&Bye(this.#t,r,r+e.delta)}this.#Ge()}async flushMessageQueue(){this.#r.debug("(flushMessageQueue): flushing message queue"),await this.abort({cleanCurrentMessage:!1,flushMessageQueue:!0}),this.#s&&this.#s()}#Yt(e){let r=e.idempotencyKey;if(r){let n=this.#t.findIndex(i=>i.idempotencyKey===r);if(n>=0)return this.#t[n]=e,!1}else e.idempotencyKey=(0,ox.randomUUID)();if(e.queue==null&&(e.queue=!0),e.user?e.user={...this.#re,...e.user}:e.user=this.#re,e.userPrompt==="___BROWSER_AUTOMATION_PROMPT___"){let n=this.getProxyConfig();e.userPrompt=Lhe(n.proxyDefaultOrigin,this.#Re||void 0)}return this.#o.coalesce==="replace-latest"&&(this.#t.length=0),this.#t.push(e),!0}async sendMessage(e){this.#He=!1;let r=this.#o.schedule,n=die(r)&&(this.#c!==void 0||this.#i!==void 0);if(r==="interrupt-clear"&&(this.#r.debug("(sendMessage): interrupt-clear schedule \u2014 clearing session"),await this.clearSession()),n&&r==="interrupt-replace"){this.#r.debug("(sendMessage): interrupt-replace schedule \u2014 undoing last user message"),await this.undoLastUserMessage();let o=Array.isArray(e)?e:[e];for(let a of o)a.dropAbortedPrompt=!0}let i=0;if(Array.isArray(e))for(let o of e)this.#Yt(o)&&i++;else this.#Yt(e)&&i++;if(i===0)return null;this.#r.debug(`(sendMessage): added messages(${i}) to queue(${this.#t.length})`),this.#Ge();let s=this.#t[this.#t.length-1];return s?(this.cancelAllPendingToolFulfilments(s.userPrompt),n&&this.#c&&(this.#r.debug(`(sendMessage): ${r} \u2014 aborting current run`),this.#c.abort(),this.#c=void 0),s.queue?this.#s&&this.#s():await this.flushMessageQueue(),await Sl(),s.idempotencyKey):null}#yr(){if(this.#o.schedule==="until-idle")return;let e=this.#t;if(e.length===0)return;let r;switch(this.#o.coalesce){case"preserve-order":r=[e[0]];break;case"replace-latest":r=[e[e.length-1]];break;default:r=e.slice();break}for(let n of r)if(n.systemReminders)for(let i of n.systemReminders)this.queueSystemReminder(i);return this.#i=b4(r),this.#re=this.#i.user,this.#i.softContextWindow&&(this.#b=Math.min(this.#b??3e4,this.#i.softContextWindow)),this.#o.coalesce==="preserve-order"?(this.#t.shift(),this.#Ge()):this.clearMessageQueue(!0),this.#i}#Qr(){let e=this.#t.length===0||this.#He,r=new Promise(n=>{e?this.#s=n:n()}).then(()=>{let n=this.#t;if(n.length===0)return;if(this.#o.coalesce!=="merge"){let s=this.#o.coalesce==="replace-latest"?n.pop():n.shift();if(this.#o.coalesce==="replace-latest"&&(this.#t.length=0),s.user&&!s.forceCompact){this.#re=s.user;let o=this.getSessionMode();this.#g.emit("step",{type:"user",previousId:this.getLastCompletionId(),displayPrompt:s.displayPrompt,user:s.user,role:s.user.role,compacting:!1,idempotencyKey:s.idempotencyKey,sessionMode:s.sessionMode??o})}if(s.systemReminders)for(let o of s.systemReminders)this.queueSystemReminder(o);return this.#i=s,this.#re=s.user,this.#i.softContextWindow&&(this.#b=Math.min(this.#b??3e4,this.#i.softContextWindow)),this.#Ge(),s}for(let s of n)if(s.systemReminders)for(let o of s.systemReminders)this.queueSystemReminder(o);let i=b4(n);if(!i.dropAbortedPrompt&&this.#i){let s=i.idempotencyKey;i=P4(this.#i,i),i.idempotencyKey=s}return this.clearMessageQueue(!0),this.#i=i,this.#re=i.user,i});return{shouldWait:e,promise:r}}#Ge(){this.#g.emit("step",{type:"message-queue",queue:this.#t.map(e=>({idempotencyKey:e.idempotencyKey,displayPrompt:e.displayPrompt,user:e.user}))})}#yt(e,r=!1){r&&(this.#v={}),Object.assign(this.#v,e),this.#g.emit("step",{type:"metadata",...this.#v})}async waitForSetupCommand(e){let r=this.#h;if(!r)return{state:"installed",shouldProceed:!0};if(r.setupState==="installing")try{await Wc(r.setupCommandPromise,e)}catch{}let n=r.setupState;return n==="not-installed"||n==="install-failed"||n==="install-aborted"?{state:n,shouldProceed:!0}:{state:"installed",shouldProceed:!0}}async waitForDevServer(e,r,n){if(!this.#h&&this.#u?.serverUrl)return{shouldProceed:!0,message:"Dev server is ready.",serverUrl:this.#u.serverUrl};let i=await this.waitForSetupCommand(e);if(!i.shouldProceed)return{shouldProceed:!1,message:`Project setup command did not completed. State: ${i.state}`};let s=this.#h;if(s){await s.ensureDevCommand(e);let o=await s.waitUntilServer(e,r,n);return o.ok?{shouldProceed:!0,message:"Dev server is ready.",serverUrl:s.serverUrl?.toString()}:{shouldProceed:!1,message:o.message,serverUrl:void 0}}return{shouldProceed:!1,message:"Dev server is not ready.",serverUrl:void 0}}async getNamedAgentConfig(e,r,n){let i=this.getSessionContext(),s=i.customAgents,o=e?s.find(K=>K.name.toLowerCase()===e.toLowerCase()):void 0,a=o?.name??"explorer",{mcpServers:A=!1,model:c,systemPrompt:u,subagent_type:l,includeMemories:d,needDevServer:g,needValidation:p,queueMode:f,asyncSubAgents:m,resetAfterRun:C=!1,reasoning:I,softContextWindow:y,maxTimeoutMs:B}={mcpServers:o?.mcpServers,subagent_type:a,systemPrompt:o?.systemPrompt,softContextWindow:o?.softContextWindow,model:(()=>{let K=o?.name??a,j=K?this.#le?.[K]:void 0;if(typeof j=="string")return j;if(Array.isArray(j)&&j.length){let ee=K,U=this.#fe.get(ee)??0;return this.#fe.set(ee,U+1),j[U%j.length]}if(o?.roundRobinModels?.length){let ee=o.name,U=this.#fe.get(ee)??0;return this.#fe.set(ee,U+1),o.roundRobinModels[U%o.roundRobinModels.length]}return o?.model})(),includeMemories:o?.includeMemories,needDevServer:o?.needDevServer,needValidation:o?.needValidation,resetAfterRun:o?.resetAfterRun,queueMode:o?.queueBehavior??o?.queueMode,asyncSubAgents:o?.asyncSubAgents,reasoning:o?.reasoning??this.#gt,maxTimeoutMs:o?.maxTimeoutMs},E=(this.#D??[]).filter(K=>K!=="Agent");E.includes("ExplorationMetadata")||E.push("ExplorationMetadata");let Q=D4(this.#u,o?.tools??E),v=c,D=this.#h;if(g&&n){if(!D)return{success:!1,response:`The ${l} agent can not be used on this session. Do no try again.`};if(D.httpServerState.state==="stopped"||D.httpServerState.state==="connecting"||D.httpServerState.state==="error-fetch")try{if(D.state==="not-installed")throw new Error(`The ${l} agent can not be used until the setupCommand finish successfully. However, the dev server is not installed.`);if(D.state==="install-failed")throw new Error(`The ${l} agent can not be used until the setupCommand finish successfully. However, last time we try to run the install script, it failed.`);if(D.state==="install-aborted")throw new Error(`The ${l} agent can not be used until the setupCommand finish successfully. However, last time we try to run the install script, it was aborted.`);await this.waitForSetupCommand(n),await D.ensureDevCommand(n)}catch(j){return{success:!1,response:j instanceof Error?j.message:String(j)}}if(p&&D.validateCommand&&this.#ne){let j=await D.runValidateCommand(void 0,n);if(j.status==="failure")return{success:!1,response:`The Agent could not start yet, because the validate command failed:
|
|
1887
1887
|
<command>
|
|
1888
1888
|
${j.command}
|
|
1889
1889
|
</command>
|
|
@@ -1903,9 +1903,9 @@ ${H}`),v.length>0&&(H=`<browser_automation_ui_issues>${JSON.stringify(v,null,2)}
|
|
|
1903
1903
|
|
|
1904
1904
|
${H}`}}this.#yt({gif_id:m.gif_id,gif_frames:Je,timeline_id:ke,recording_id:m.recording_id,...s.replayId?{replay_id:s.replayId,replay_url:`${Ne}/replay/${s.replayId}`}:{}},!1)}catch(X){this.#r.warn(`[${a}] Failed to generate recording (non-critical): ${X instanceof Error?X.message:String(X)}`),this.#e.Sentry?.captureException(X,{level:"warning",tags:{component:"gif-generator",operation:"generateGifFromImages",subagent_type:a},extra:{sessionId:A.getSessionId(),frameCount:C.getFrameCount()}})}let he={success:!0,response:H,metadata:m,sessionId:f,lastTurn:Y};return d(he),he}catch(U){let Y={success:!1,response:`Agent task failed: ${U instanceof Error?U.message:String(U)}`,metadata:{important_files:[]}};return d(Y),Y}finally{l||d(B("finally_safety_net")),clearTimeout(Q),this.#Fe.delete(c),p.removeEventListener("abort",ee);try{await j()}catch(U){this.#r.warn(`[${a}] Cleanup failed: ${U instanceof Error?U.message:String(U)}`)}if(s.resetAfterRun&&o)try{await this.resetToCommitHash(o,!1)}catch(U){this.#r.warn(`[${a}] Failed to reset changes: ${U instanceof Error?U.message:String(U)}`)}}}getRunningSubAgents(){return Array.from(this.#Fe.entries()).map(([e,r])=>{let n=0,i="unknown";try{let s=r.session.getSessionContext();n=s.turns.length,i=s.state}catch{}return{id:e,subagentType:r.subagentType,description:r.description,startedAt:r.startedAt,resumed:r.resumed,turns:n,state:i,toolsRunning:r.session.toolsRunning()}})}canHandleTool(e){let n=(this.#J.get(e)??0)>0,i=this.#z.has(e);return n||i}setSessionCanHandleTools(e){for(let r of e)this.#z.add(r)}clearSessionCanHandleTools(){this.#z.clear()}setProxyOrigin(e,r){if(e!==this.#qe||r!==this.#$e){this.#qe=e,this.#$e=r;let n=this.getProxyConfig();n.proxyDestination&&n.proxyDefaultOrigin&&this.queueSystemReminder({text:`The dev server is running at ${n.proxyDefaultOrigin}. e.g. for taking screenshots of a "/foo" route take a screenshot of ${n.proxyDefaultOrigin}/foo`,tag:"reminder:url"})}}async#Dr(e,r,n){let i=this.getProxyConfig();if(i.proxyOrigin&&!i.proxyDestination)return;let s=await KA(this.#a,"/codegen/get-browser-connection",{sessionId:e,projectId:this.#E,branchName:this.#y,proxyOrigin:i.proxyOrigin,proxyDefaultOrigin:i.proxyDefaultOrigin,proxyDst:i.proxyDestination,recordReplay:n?.recordReplay===!0},{signal:r,debug:this.#A});if(typeof s?.wsUrl=="string")return{wsUrl:s.wsUrl,uuid:s.uuid,disconnectUrl:s.disconnectUrl}}getTurns(){let e=this.getSessionContext();return structuredClone(e.turns)}getSessionContext(){if(!this.#n)throw new Error("Session context not initialized");return this.#n}async runSetupCommand(){return await this.#h?.runSetupCommand()}abortSetupCommand(){return this.#h?.abortSetupCommand()}abortValidateCommand(){return this.#h?.abortValidateCommand()}toolsRunning(){return this.#X.length>0}abortAllTools(){for(let e of this.#X)e.abortController.abort()}toolFullfilment(e,r){return typeof r=="string"&&(r={toolResult:r,isError:!1}),this.fulfillToolCall(e,r)?!0:this.resumePersistedToolFulfilment(e,r)}#wr(e){let r=this.getSessionId();if(!r)return;let n={name:e.name,input:e.input,messageValid:e.messageValid,createdAt:Date.now()};this.#v.pendingToolFulfilments||(this.#v.pendingToolFulfilments={}),this.#v.pendingToolFulfilments[e.id]=n;let i=xB(this.#e,this.#a,"/codegen/pending-tool-fulfilment",{sessionId:r,toolCallId:e.id,action:"set",snapshot:n},this.#A).catch(()=>{});this.#Oe.set(e.id,i),i.finally(()=>{this.#Oe.get(e.id)===i&&this.#Oe.delete(e.id)})}async#Qt(e){let r=!!this.#v.pendingToolFulfilments?.[e]||this.#oe.has(e);if(this.#v.pendingToolFulfilments&&delete this.#v.pendingToolFulfilments[e],this.#oe.delete(e),!r)return;let n=this.getSessionId();if(!n)return;let i=this.#Oe.get(e);i&&await i,await xB(this.#e,this.#a,"/codegen/pending-tool-fulfilment",{sessionId:n,toolCallId:e,action:"clear"},this.#A).catch(()=>{})}resumePersistedToolFulfilment(e,r){if(!this.#oe.get(e))return!1;this.#Qt(e);let i=typeof r=="string"?r:r?.toolResult??"";return this.#r.debug(`(resumePersistedToolFulfilment): resuming ${e} after reboot`),this.sendMessage({userPrompt:`Answers to the previously asked questions:
|
|
1905
1905
|
${i}`}),!0}cancelAllPendingToolFulfilments(e){for(let[r,n]of Array.from(this.#Z.entries()))n.messageValid&&e?this.fulfillToolCall(r,{toolResult:"The user answered with a follow-up message (see the next user message in the conversation).",isError:!1,title:"Resolved by user message"}):this.fulfillToolCall(r,{toolResult:"Aborted by the user. So the task could not be completed.",isError:!0,title:"Aborted by the user."});this.#Z.clear();for(let r of Array.from(this.#oe.keys()))this.#Qt(r)}fulfillToolCall(e,r){let n=this.#Z.get(e);return n?(n.resolve(r),this.#Z.delete(e),!0):!1}abortToolCall(e,r){let n=this.#X.find(s=>s.id===e),i=rn(r??"The user manually aborted the tool call.");if(n)return n.abortController.abort(i),!0;if(this.#X.length===0){let s=new AbortController;return s.abort(i),this.#X.push({id:e,abortController:s,input:{id:e},name:"Bash"}),!0}return!1}async acceptCode(){if(this.#wt()){let e=this.getLinesStats();await this.sendFeedback({position:this.#m,acceptedLines:e.net,linesOfCodeAdded:e.added,linesOfCodeRemoved:e.removed})}}async abort(e){this.#A&&this.#r.debug(`(abort): ${JSON.stringify(e)}`);let r=!1,n=!0;return typeof e=="boolean"?r=e:(r=e?.cleanCurrentMessage??!1,n=e?.flushMessageQueue??!0),r&&(this.#i=void 0,this.#Ze=0,this.clearMessageQueue()),this.#He=!n,this.cancelAllPendingToolFulfilments(),this.#pe=0,this.#c?(this.#c.abort(),this.#c=void 0,!0):!1}async stopEventLoop(){this.#r.info("Stopping event loop"),await this.abort({cleanCurrentMessage:!0}),this.#S?.abort(),this.#S=void 0,this.#s&&this.#s()}requestRefresh(){this.#g.emit("step",{type:"builder-action",action:"refresh",metadata:{}})}async configureDevOrchestrator(e){let r=this.#h,n={devCommand:!1,hosts:!1,setupCommand:!1,proxyServer:!1,validateCommand:!1,env:!1,fileOverrides:!1,setupResult:void 0,devResult:void 0,validateResult:void 0};if(r){let i=[];if(e.env&&(e.replaceEnvs&&(r.environmentVariables.length>0&&(n.env=!0),r.clearEnvVariables()),Object.entries(e.env).forEach(([s,o])=>{r.setEnvVariable(s,o??void 0)&&(n.env=!0)}),this.queueSystemReminder({text:`The system has the following environment variables:
|
|
1906
|
-
${cw(this.#ht(),{skipCommandSecurity:this.#u?.skipCommandSecurity})}`,tag:"reminder:environment-variables"})),e.proxyServer?i.push(r?.setProxyServer(e.proxyServer).then(s=>{n.proxyServer=s.updatedProxyServer,n.hosts=s.updatedHosts})):e.proxyPort&&i.push(r?.setPort(e.proxyPort).then(s=>n.proxyServer=s)),e.fileOverrides&&(n.fileOverrides=r.setFileOverrides(e.fileOverrides)),e.setupCommand!==void 0||e.setupDependencies!==void 0?i.push(r.setSetupCommand({setupDependencies:e.setupDependencies,setupCommand:e.setupCommand,forceRestart:e.forceSetupCommand}).then(s=>{n.setupCommand=!!s,n.setupResult=s??void 0})):(e.forceSetupCommand||n.fileOverrides||n.env&&r.setupState!=="installed")&&i.push(r?.runSetupCommand().then(s=>{n.setupCommand=!!s,n.setupResult=s??void 0})),e.devCommand!==void 0?i.push(r.setDevCommand(e.devCommand??void 0,e.forceDevCommand||n.env).then(s=>{n.devCommand=s.status==="success",n.devResult=s??void 0})):(e.forceDevCommand||n.env)&&i.push(r?.restart().then(s=>{n.devCommand=!0,n.devResult=s??void 0})),e.autoDetectDevServer!==void 0&&i.push(r.setAutoDetectSettings(e.autoDetectDevServer,e.autoDetectDevServerPatterns).then(s=>n.proxyServer=n.proxyServer||s)),e.validateCommand!==void 0&&i.push(r.runValidateCommand(e.validateCommand).then(s=>n.validateResult=s)),await Promise.allSettled(i),n.env){let s=!1;for(let o of this.#w.values())(o.state==="running"||o.state==="starting")&&(o.stale=!0,s=!0);s&&this.#ye()}}return n}#br(){for(let e of Array.from(this.#w.keys()))try{this.disposeTerminal({terminalId:e})}catch{}this.#w.clear()}async#Dt(){if(this.#Q.debounceTimer&&clearTimeout(this.#Q.debounceTimer),this.#Q.pendingEvents=[],this.#Q.listeners.clear(),this.#Q.watcher){try{await this.#Q.watcher.close()}catch{}this.#Q.watcher=null}}#vr(){if(this.#Q.watcher)return;let e=this.#f.map(A=>A.path),r=new Map;for(let A of this.#f)r.set(A.path,
|
|
1906
|
+
${cw(this.#ht(),{skipCommandSecurity:this.#u?.skipCommandSecurity})}`,tag:"reminder:environment-variables"})),e.proxyServer?i.push(r?.setProxyServer(e.proxyServer).then(s=>{n.proxyServer=s.updatedProxyServer,n.hosts=s.updatedHosts})):e.proxyPort&&i.push(r?.setPort(e.proxyPort).then(s=>n.proxyServer=s)),e.fileOverrides&&(n.fileOverrides=r.setFileOverrides(e.fileOverrides)),e.setupCommand!==void 0||e.setupDependencies!==void 0?i.push(r.setSetupCommand({setupDependencies:e.setupDependencies,setupCommand:e.setupCommand,forceRestart:e.forceSetupCommand}).then(s=>{n.setupCommand=!!s,n.setupResult=s??void 0})):(e.forceSetupCommand||n.fileOverrides||n.env&&r.setupState!=="installed")&&i.push(r?.runSetupCommand().then(s=>{n.setupCommand=!!s,n.setupResult=s??void 0})),e.devCommand!==void 0?i.push(r.setDevCommand(e.devCommand??void 0,e.forceDevCommand||n.env).then(s=>{n.devCommand=s.status==="success",n.devResult=s??void 0})):(e.forceDevCommand||n.env)&&i.push(r?.restart().then(s=>{n.devCommand=!0,n.devResult=s??void 0})),e.autoDetectDevServer!==void 0&&i.push(r.setAutoDetectSettings(e.autoDetectDevServer,e.autoDetectDevServerPatterns).then(s=>n.proxyServer=n.proxyServer||s)),e.validateCommand!==void 0&&i.push(r.runValidateCommand(e.validateCommand).then(s=>n.validateResult=s)),await Promise.allSettled(i),n.env){let s=!1;for(let o of this.#w.values())(o.state==="running"||o.state==="starting")&&(o.stale=!0,s=!0);s&&this.#ye()}}return n}#br(){for(let e of Array.from(this.#w.keys()))try{this.disposeTerminal({terminalId:e})}catch{}this.#w.clear()}async#Dt(){if(this.#Q.debounceTimer&&clearTimeout(this.#Q.debounceTimer),this.#Q.pendingEvents=[],this.#Q.listeners.clear(),this.#Q.watcher){try{await this.#Q.watcher.close()}catch{}this.#Q.watcher=null}}#vr(){if(this.#Q.watcher)return;let e=this.#f.map(A=>A.path),r=new Map;for(let A of this.#f)r.set(A.path,k4(A.path));let n=A=>{for(let c of this.#f)if(A.startsWith(c.path+"/")||A===c.path)return c.path;return null},i=A=>{let c=n(A);if(!c)return!1;let u=this.#e.relative(c,A).replace(/\\/g,"/");if(!u)return!1;if(this.#Wt(u))return!0;let l=r.get(c);return l?l(u):!1},s,o=!1;try{s=tye.default.watch(e,{ignored:i,ignoreInitial:!0,persistent:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:100},ignorePermissionErrors:!0,followSymlinks:!1,usePolling:!0,interval:1e3,binaryInterval:3e5,atomic:!0})}catch(A){this.#e.Sentry?.captureException(A,{tags:{operation:"global-file-watch-init"}}),this.#r.error(`Failed to initialize file watcher: ${A instanceof Error?A.message:String(A)}`),this.#r.error("File watching will be disabled. Code generation will still work but may not detect all changes automatically.");return}let a=(A,c)=>{let u=n(c),l=u?this.#e.relative(u,c).replace(/\\/g,"/"):this.#e.relative(this.primaryGitPath,c).replace(/\\/g,"/");if(this.#f.length>1&&u){let g=this.#f.find(p=>p.path===u);g&&!this.#K()&&(l=`${g.folderName}/${l}`)}let d={type:"folder-watch",watchId:"global",event:A,path:l,timestamp:Date.now()};this.#Q.pendingEvents.push(d),this.#Q.debounceTimer&&clearTimeout(this.#Q.debounceTimer),this.#Q.debounceTimer=setTimeout(()=>{let g=this.#Q.pendingEvents;this.#Q.pendingEvents=[];for(let p of g)for(let f of this.#Q.listeners)try{f(p)}catch(m){this.#e.Sentry?.captureException(m)}},this.#Q.debounceMs)};s.on("add",A=>a("add",A)).on("change",A=>a("change",A)).on("unlink",A=>a("unlink",A)).on("addDir",A=>a("addDir",A)).on("unlinkDir",A=>a("unlinkDir",A)).on("error",A=>{o||(o=!0,this.#e.Sentry?.captureException(A,{tags:{operation:"global-file-watch"}}),this.#r.error(`File watcher error: ${A instanceof Error?A.message:String(A)}`),this.#r.error("Closing file watcher to prevent further errors. File watching will be disabled."),this.#Dt().catch(()=>{}))}),this.#Q.watcher=s,this.#r.debug(`Initialized global file watcher on: ${e.join(", ")}`)}subscribeToFileChanges(e){return this.#Q.listeners.size===0&&this.#vr(),this.#Q.listeners.add(e),this.#r.debug(`Subscribed to file changes(${this.#Q.listeners.size} active listeners)`),async()=>{this.#Q.listeners.delete(e),this.#r.debug(`Unsubscribed from file changes(${this.#Q.listeners.size} remaining listeners)`),this.#Q.listeners.size===0&&this.#Q.watcher&&(await this.#Dt(),this.#r.debug("Closed global file watcher (no more listeners)"))}}async tsServerInit(){try{return this.#l?{ok:!0,cwd:this.#d}:(this.#l=new Hv(this.#d),this.#l.setEventHandler(e=>{for(let r of this.#et)r(e)}),await this.#l.start(),{ok:!0,cwd:this.#d})}catch(e){return this.#l=null,{ok:!1,error:e?.message||"Failed to start tsserver"}}}async tsServerOpenFile(e,r){this.#l&&await this.#l.openFile(e,r)}async tsServerChangeFile(e,r){this.#l&&await this.#l.changeFile(e,r)}async tsServerCloseFile(e){this.#l&&await this.#l.closeFile(e)}async tsServerGetCompletions(e,r,n,i){return this.#l?this.#l.getCompletions(e,r,n,i):{success:!1,body:null}}async tsServerGetCompletionDetails(e,r,n,i){return this.#l?this.#l.getCompletionDetails(e,r,n,i):{success:!1,body:null}}async tsServerGetDefinition(e,r,n){return this.#l?this.#l.getDefinition(e,r,n):{success:!1,body:null}}async tsServerGetTypeDefinition(e,r,n){return this.#l?this.#l.getTypeDefinition(e,r,n):{success:!1,body:null}}async tsServerGetQuickInfo(e,r,n){return this.#l?this.#l.getQuickInfo(e,r,n):{success:!1,body:null}}async tsServerGetReferences(e,r,n){return this.#l?this.#l.getReferences(e,r,n):{success:!1,body:null}}async tsServerGetSignatureHelp(e,r,n){return this.#l?this.#l.getSignatureHelp(e,r,n):{success:!1,body:null}}async tsServerRequestDiagnostics(e){this.#l&&await this.#l.requestDiagnostics(e)}async tsServerGetRenameLocations(e,r,n){return this.#l?this.#l.getRenameLocations(e,r,n):{success:!1,body:null}}async tsServerGetNavTree(e){return this.#l?this.#l.getNavTree(e):{success:!1,body:null}}async tsServerOrganizeImports(e){return this.#l?this.#l.organizeImports(e):{success:!1,body:null}}async tsServerGetInlayHints(e){return this.#l?this.#l.getInlayHints(e):{success:!1,body:null}}async tsServerGetCodeFixes(e,r,n,i,s,o){return this.#l?this.#l.getCodeFixes(e,r,n,i,s,o):{success:!1,body:null}}async tsServerGetApplicableRefactors(e,r,n,i,s){return this.#l?this.#l.getApplicableRefactors(e,r,n,i,s):{success:!1,body:null}}async tsServerGetEditsForRefactor(e,r,n,i,s,o,a){return this.#l?this.#l.getEditsForRefactor(e,r,n,i,s,o,a):{success:!1,body:null}}async tsServerGetImplementation(e,r,n){return this.#l?this.#l.getImplementation(e,r,n):{success:!1,body:null}}async tsServerGetSelectionRange(e,r){return this.#l?this.#l.getSelectionRange(e,r):{success:!1,body:null}}async tsServerGetLinkedEditingRange(e,r,n){return this.#l?this.#l.getLinkedEditingRange(e,r,n):{success:!1,body:null}}async tsServerGetFormatRange(e,r,n,i,s){return this.#l?this.#l.getFormatRange(e,r,n,i,s):{success:!1,body:null}}subscribeToDiagnostics(e){return this.#et.add(e),()=>{this.#et.delete(e)}}async close(e){if(this.#Ye)return;if(this.#r.info("Closing code gen server",{reason:e?.reason}),this.#Ye=!0,this.#p&&(delete process.env.DEBUG,this.#p=!1),this.#Ke.forEach(n=>n()),this.#br(),await this.#Dt(),this.#l&&(this.#l.dispose(),this.#l=null),this.#et.clear(),this.#U)try{this.#r.debug("Cleaning up local MCP servers"),await this.#U.cleanup()}catch(n){this.#e.Sentry?.captureException(n,{level:"warning",tags:{operation:"local-mcp-cleanup"}})}await this.stopEventLoop(),await this.waitUntilState("close",5e3),this.#g.removeAllListeners(),await Promise.allSettled(this.#de);let r=e?.uploadGitBackup??!1;if(r){let n=await this.needsBackup();this.#A&&this.#r.debug(`Closing code gen server: ${JSON.stringify({uploadGitBackup:r,needsBackup:n})}`),n&&await this.uploadBackup()}else this.#A&&this.#r.debug(`Closing code gen server: ${JSON.stringify({uploadGitBackup:r})}`)}async#F(){if(this.#f.length===0||this.#ze)return null;let r=(await this.#$(async i=>this.#xr(i))).results.filter(i=>i.success&&i.result).map(i=>i.result);if(r.length===0)return null;for(let i of r)this.#g.emit("step",i);return this.#j=r,this.#O(this.#Sr(r),"updateBranchUnpushedStatus",!1),r.some(i=>i.hasMergeConflict)&&await this.#De(),r[0]}async#Sr(e){if(!this.#E||!this.#y||!this.#a.builderPublicKey||!this.#a.userId||!this.#a.builderPrivateKey)return;let r=e.some(n=>n.ahead>0||n.isSessionDirty);try{let n=new URL("/projects/branches",Ne);n.searchParams.set("apiKey",this.#a.builderPublicKey),n.searchParams.set("userId",this.#a.userId),n.searchParams.set("projectId",this.#E),n.searchParams.set("branchName",this.#y);let i=await Fe(n,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#a.builderPrivateKey}`},body:JSON.stringify({hasUnpushedChanges:r}),signal:AbortSignal.timeout(1e4)},this.#A);i.ok||this.#r.error(`Failed to update branch unpushed status: ${i.status} ${i.statusText}`,{loggerOptions:{debug:!0}})}catch(n){this.#r.error("Failed to update branch unpushed status:",n,{loggerOptions:{debug:!0}})}}async sendMessageToOrgAgent(e){try{let r=new URL("/projects/org-agent/send-message",Ne);this.#a.builderPublicKey&&r.searchParams.set("apiKey",this.#a.builderPublicKey),this.#a.userId&&r.searchParams.set("userId",this.#a.userId);let n=await Fe(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#a.builderPrivateKey}`},body:JSON.stringify(e),signal:AbortSignal.timeout(1e4)},this.#A),i=await n.json();return n.ok?{status:"success"}:{status:"error",error:i.error??`HTTP ${n.status}`}}catch(r){return{status:"error",error:r?.message??"Unknown error"}}}queueGitStatusReminder(e){if(this.#j.length===0||this.#M)return;let r=this.#j.map(n=>Qye(n,this.gitEnabledFolders,e));this.queueSystemReminder({text:r.join(`
|
|
1907
1907
|
|
|
1908
|
-
`),tag:"reminder:git-status"})}async manualCommit(e){if(!this.#I)return!1;let r=this.getSessionContext();if(!r.beforeCommit){let n=await this.#H();Object.keys(n).length>0&&(r.beforeCommit=So(n))}return await this.commitWorkInProgress(e.commitMessage,[e.add]),await this.#ie(!0),!0}getLastSuggestedAction(){return this.#Ae}async#De(){let e=this.getSessionContext();if(e.state==="generating"||e.state==="close")return this.#Ae=void 0,!1;let r=await this.#mt(!0,"all");return e=this.getSessionContext(),e.state!=="generating"&&e.state!=="close"?(this.#Ae=r,this.#g.emit("step",{type:"wait-for-input",id:this.getLastCompletionId()??"initial",state:e.state,suggestion:r,sessionMode:e.sessionMode,hasPlanToApply:this.#Ie,modelOverride:this.#q}),!0):!1}async#xr(e){this.#xe++;try{let r=this.getCommitMode(),n=this.#I?this.getFeatureBranch():e.branchName,i=this.#Be(e),s=e.path,o=e.folderName===this.#f[0]?.folderName,a=this.getSessionContext(),A=!1,c=!1,u="",l=null;try{let B=await this.git(["rev-parse","--absolute-git-dir"],{cwd:s});l=this.#e.join(B.trim(),"FETCH_HEAD"),vl.default.existsSync(l)&&vl.default.unlinkSync(l)}catch(B){this.#e.Sentry?.captureException(B,{tags:{operation:"codegen-git",endpoint:"getGitStatus"},extra:{fetchHeadFilePath:l,isCheckingGitStatus:this.#xe,folderName:e.folderName}}),l=null}try{u=await this.git(["fetch","--no-tags","origin",i],{cwd:s}),A=!0}catch{A=!1}let d=await this.#e.getRepoInfo(s),g=al(a.beforeCommit,e.folderName,this.gitRepoContexts[0]?.folderName);!o&&!e.initialCommit&&d.commit&&(e.initialCommit=d.commit),!g&&e.initialCommit&&(g=e.initialCommit);let p=this.#wt(e.folderName),f=p?1:0,m=0;if(A){if(n!==i)try{await this.git(["--no-pager","diff","--quiet",`refs/remotes/origin/${n}...refs/remotes/origin/${i}`],{cwd:s}),c=!1}catch{c=!0}else c=!0;try{let B=vH(await this.git(["rev-list","--left-right","--count","HEAD...FETCH_HEAD"],{cwd:s}));f=B.ahead,m=B.behind}catch(B){let E=null;if(l)try{E=await this.#e.readFile(this.#e.join(s,".git/FETCH_HEAD")),E=`FETCH_HEAD: ${E} `}catch(Q){E=`FETCH_HEAD FAILED: ${String(Q)} `}else E="FETCH_HEAD MISSING";this.#e.Sentry?.captureException(B,{tags:{operation:"codegen-git",endpoint:"getGitStatus"},extra:{fetchOutput:u,fetchHead:E,remoteBranch:i,currentBranch:d.currentBranch,currentCommit:d.commit,isCheckingGitStatus:this.#xe,folderName:e.folderName}})}}else if(!A&&r!=="commits")try{let B=await this.#ot(s),E=vH(await this.git(["--no-pager","rev-list","--left-right","--count",`HEAD...${B}`],{cwd:s}));f=E.ahead,m=E.behind}catch{g&&g!==d.commit&&(f=Math.max(f,1))}let C=await this.#te(s),I=C.length>0,y=await this.#_r(s);return{type:"git",folderName:e.folderName,remoteBranchExists:A,remoteBranchHasChanges:c,hasGeneratingPlaceholder:await this.#Pr(),isSessionDirty:p||!!g&&g!==d.commit,canSync:(f>0||m>0||y)&&!I,canPush:(f>0||m>0)&&!I,hasStagedChanges:y,canPull:m>0&&A,ahead:f,hasMergeConflict:I,commitMode:r,behind:m,currentCommit:d.commit,currentBranch:d.currentBranch,pendingValidation:this.#ne,remoteBranch:i,unmergedFiles:C}}finally{this.#xe--}}#qt(){let e=this.getSessionContext();return{type:"session",title:e.title,beforeCommit:e.beforeCommit,createdUnixTime:e.createdUnixTime,updatedUnixTime:e.updatedUnixTime,turns:e.turns.length,id:e.sessionId,lastCompletionId:this.getLastCompletionId(),sessionMode:e.sessionMode,fusionConfig:rv(this.#u),hasBrowserAutomation:e.customAgents.some(r=>r.name==="browser-testing"),customInstructions:e.customInstructions.filter(r=>!r.hideUI&&(r.userInvocable??!0)).map(r=>({name:r.name,description:r.description??"",type:r.type??"always",glob:r.glob,isSkill:r.isSkill??r.filePath?.toLowerCase().includes("/skills/")??!1,userInvocable:r.userInvocable,scope:r.scope,pluginName:r.pluginName})),hasPlanToApply:this.#Ie}}#$t(){let e=this.getSessionContext(),r=e.turns,n=[];n.push(this.#qt()),Object.keys(this.#v).length>0&&n.push({type:"metadata",...this.#v}),this.#t.length>0&&n.push({type:"message-queue",queue:this.#t.map(s=>({idempotencyKey:s.idempotencyKey,displayPrompt:s.displayPrompt,user:s.user}))});let i;for(let s of r){n.push({type:"user",previousId:i,displayPrompt:s.userMessage?s.userMessage.displayPrompt??s.userMessage.userPrompt:void 0,attachments:s.userMessage?.attachments,id:s.completionId,user:s.user,role:s.user.role,compacting:!1,idempotencyKey:s.userMessage?.idempotencyKey??"",sessionMode:e.sessionMode}),i=s.completionId;for(let o of s.actions)if(o.type==="tool"||o.type==="text"||o.type==="thinking")if(n.push({type:"start",name:o.type,content:"",id:o.id??"",filePath:o.filePath??"",title:o.actionTitle??o.artifactTitle??o.filePath??""}),n.push({type:"delta",name:o.type,delta:o.content}),o.type==="tool"){if(n.push({type:o.type,id:o.id,name:o.filePath,content:o.content}),o.filePath==="UpdateSetupValue"||o.filePath==="ProposeConfig")try{let a=JSON.parse(o.content);if(o.filePath==="UpdateSetupValue")n.push({type:"update_setup_value",field:a.field,value:a.value,reason:a.reason});else{let A=a.config,c=A!=null&&!A.installCommand?.command&&(!A.runtimeDependencies||A.runtimeDependencies.length===0);n.push({type:"propose_config",config:A,message:a.message,noDependencies:c})}}catch{}}else o.type==="thinking"?n.push({type:"thinking",content:o.content}):o.type==="text"&&n.push({type:"text",content:o.content})}return n}connectToEventLoop(e,r,n){let i=n?.canHandleTools??[];if(e){let s=[],o=this.getSessionContext();s.push({type:"state",newState:"replay",abortable:!1,previousState:o.state}),this.#se&&s.push(this.#se),s.push(...this.#j),s.push(...this.#$t()),this.#Z.forEach(c=>{s.push({type:"tool-call-request",id:c.id,name:c.name,input:c.input})}),this.#oe.forEach(c=>{this.#Z.has(c.id)||s.push({type:"tool-call-request",id:c.id,name:c.name,input:c.input})});let a=this.#ve?Fa(this.#ve):void 0;if(a)switch(a.type){case"file":case"diff":case"text":case"thinking":case"suggestion":case"tool":s.push({type:"start",id:a.id,name:a.type,filePath:a.filePath??"",title:a.actionTitle??a.artifactTitle??"",content:""}),s.push({type:"delta",name:a.type,delta:a.content});break}s.push({type:"terminals",terminals:this.#Bt()});let A=this.#h;A?(s.push({type:"dev-server",devServerState:A.devState,setupState:A.setupState,httpServerState:A.httpServerState.state,devCommand:A.devCommand,setupCommand:A.setupCommand,proxyServer:A.proxyTarget,proxyServerSelection:A.proxyServerSelection,remoteAddress:A.httpServerState.remoteAddress,remotePort:A.httpServerState.remotePort,proxyServerReachable:!!this.#u?.isLocal,validateState:A.validateCommandState}),A.setupState!=="installed"&&s.push({type:"stdio",id:"setupCommand",command:A.setupCommand??"",content:A.getSetupWrite(),source:"run-command",stream:"stdout"}),s.push({type:"stdio",id:"devServer",command:A.devCommand,content:A.getDevWrite(),source:"run-command",stream:"stdout"})):r({type:"dev-server",devServerState:"running",setupState:"installed",httpServerState:"ok-2xx",devCommand:this.#u?.devCommand,setupCommand:this.#u?.setupCommand,proxyServer:this.#u?.serverUrl,proxyServerSelection:"hardcoded",remoteAddress:void 0,remotePort:void 0,proxyServerReachable:!!this.#u?.isLocal,validateState:"unset"}),s.push({type:"state",newState:o.state,abortable:o.state==="generating",previousState:"replay"}),this.#ae&&o.state!=="generating"&&s.push({type:"wait-for-input",id:this.getLastCompletionId()??"initial",state:o.state,suggestion:this.#Ae,sessionMode:o.sessionMode,hasPlanToApply:this.#Ie}),r({type:"batch",steps:s})}this.#g.on("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)+1);return this.waitForEventLoop(),()=>{this.#g.off("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)-1)}}waitUntilPendingPromises(e){let r=Uo();return this.#r.debug(`(waitUntilPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#de),e).then(()=>Sl()).then(()=>{this.#r.debug(`(waitUntilPendingPromises-${r}): finished`)})}waitUntilBlockingPendingPromises(e){let r=Uo();return this.#r.debug(`(waitUntilBlockingPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#We),e).then(()=>Sl()).then(()=>{this.#r.debug(`(waitUntilBlockingPendingPromises-${r}): finished`)})}waitUntilIdle(e){let r=Uo();return this.waitForEventLoop(),this.#r.debug(`(waitUntilIdle-${r}): started`),Wc(Sl().then(()=>this.waitUntilPendingPromises()).then(()=>{let n=this.getSessionContext();return this.#r.debug(`(waitUntilIdle-${r}): starting in ${n.state} `),n.state==="generating"?(0,cx.once)(this.#g,"idle"):Promise.resolve(void 0)}).then(()=>this.waitUntilPendingPromises()).then(()=>{this.#r.debug(`(waitUntilIdle-${r}): idle reached in ${this.getSessionContext().state} `)}),e)}async#Vt(e){let r=this.#h;if(!r)throw new Error("Dev server not found");let n=await r.runValidateCommand(void 0,e);return n.status==="success"&&(this.#ne=!1,this.#I&&(await this.#It()).length===0&&(await this.#st()||await this.manualCommit({add:".",commitMessage:"Validate command fixes"}))),n}waitForEventLoop(){return this.#ae?this.#ae:this.#ae=this.#Fr()}async#Fr(){if(this.#ae||this.#S)throw new Error("Event loop already started");this.#r.debug("(eventLoop): started");let e=mye(),r=c=>{c.type==="error"&&this.#pe>0&&(eye.includes(c.code)||(c.restoreCredits=this.#pe,this.#pe=0,uye(this.#e,this.#a,s.sessionId,c.restoreCredits).catch(l=>{this.#e.Sentry?.captureException(l)})));let u=["ExitPlanMode","TodoWrite","TaskCreate","TaskUpdate"];if(c.type==="tool_result"&&u.includes(c.result.tool_name)&&(this.#r.debug("emitting ClientDevtoolsToolResultV1",{toolName:c.result.tool_name,projectId:this.#E,branchName:this.#y}),KA(this.#a,"/events/publish",{event:nie,extraData:{toolUseId:c.result.tool_use_id,toolName:c.result.tool_name??"",result:c.result.content,isError:c.result.is_error,sessionId:s.sessionId,projectId:this.#E,branchName:this.#y},extraAttributes:{toolName:c.result.tool_name??"",projectId:this.#E,branchName:this.#y}},{debug:this.#A})),c.type==="tool"&&c.name==="Agent"){let l;try{l=JSON.parse(c.content)?.description}catch{}let d=JSON.stringify({description:l});this.#r.debug("emitting ClientDevtoolsToolCallV1",{toolName:c.name,projectId:this.#E,branchName:this.#y}),KA(this.#a,"/events/publish",{event:rie,extraData:{toolUseId:c.id,toolName:c.name,content:d,sessionId:s.sessionId,projectId:this.#E,branchName:this.#y},extraAttributes:{toolName:c.name,projectId:this.#E,branchName:this.#y}},{debug:this.#A})}this.#g.emit("step",c)};this.#S=new AbortController;let n=this.#S.signal,i=this.#h,s=this.getSessionContext(),o=()=>this.getLastCompletionId();this.#e.Sentry?.setContext("codeGen",{sessionId:s.sessionId,get completionId(){return o()}}),await this.#O(this.#F(),"initial-emitGitStatus");let a=setInterval(()=>{this.canHandleTool("GetScreenshot")&&(this.#xe>0||this.#F().catch(()=>{}))},6e4),A=()=>clearInterval(a);if(this.#Ke.push(A),process.env.FUSION_IDE_PORT){let c=setInterval(()=>{qie().then(u=>{let l=JSON.stringify(u);l!==this.#vt&&(this.#vt=l,this.#g.emit("step",{type:"ide",context:u}),this.queueSystemReminder({text:u?Vie(u):"",tag:"reminder:ide-context"}))}).catch(()=>{})},1e3);this.#Ke.push(()=>clearInterval(c))}this.queueGitStatusReminder({trigger:"session-start"}),i?.setupState==="not-installed"&&this.runSetupCommand();try{let c=0;for(;!n.aborted;){c++,this.#c=void 0;let u=this.#Qr();if(this.#r.debug(`(eventLoop-${c}): started (shouldWait: ${u.shouldWait})`),u.shouldWait){await this.#jt();let g=await this.#De();if(n.aborted)break;g&&Eye(u.promise,500).then(p=>{p&&(this.#r.debug(`(eventLoop-${c}): emitting idle on next message wait`),this.#g.emit("idle"))})}let l=await u.promise;if(n.aborted)break;if(!l)continue;this.#c=new AbortController;let d=Qn([n,this.#c.signal]);try{if(this.#Ae=void 0,l.logsCheckpoint&&i?.addCheckpoint(),d?.aborted)throw rn(d.reason);this.#V("generating"),i?.abortValidateCommand();let g=l.syncChanges??this.#Ve;g&&(this.#r.debug(`(eventLoop-${c}): syncing changes from remote`),await this.syncChangesFromRemote(g),await this.#mt(!1,"critical")),l.sessionMode&&l.sessionMode!==s.sessionMode&&this.switchSessionMode(l.sessionMode),await this.#kr(l,d,r),this.#V("success");let p=l.autoPush??this.#N??"none";if(p!=="none"&&this.#I&&(this.#r.debug(`(eventLoop-${c}): autoPush: ${p}`),await this.waitUntilBlockingPendingPromises(),(await this.#It()).length===0)){let m=(()=>{switch(p){case"force-push":return{actor:"agent",forcePush:!0,pullFirst:!1};case"merge-push":return{actor:"agent",pullFirst:!0,forcePush:!1};case"ff-push":return{actor:"agent",requireFastForward:!0,pullFirst:!1};case"safe-push":return{actor:"agent",pullFirst:!0,abortOnMergeConflict:!0};default:return{actor:"agent"}}})();if(this.#f.length>1)for(let C of this.#f)await this.#Ue({...m,folderName:C.folderName});else await this.#Ue(m)}this.#Ae=void 0}catch(g){g instanceof Error?g.name==="AbortError"?(r({type:"user-abort",hasContinueMessage:this.#t.length>0}),this.#V("abort")):g instanceof qe?(this.#i=void 0,r({type:"error",code:"cli-network-error",message:g.message}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):g instanceof dt?(this.#i=void 0,r({type:"error",code:"unknown",message:"An internal error occurred. Please try again."}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):g instanceof oi?(this.#i=void 0,r({type:"error",code:g.code,message:g.message}),eye.includes(g.code)||this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):(this.#i=void 0,r({type:"error",code:"cli-genetic-error",message:g.message,metadata:{error:g}}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):this.#V("error")}this.#zt++}}catch(c){throw this.#e.Sentry?.captureException(c,{level:"fatal"}),c}finally{A(),this.#S=void 0,this.#ae=void 0,e()}this.#r.debug("(eventLoop): emitting idle on close"),this.#g.emit("idle"),this.#V("close")}async#kr(e,r,n){this.#pe=0,this.#ne=!1;let i=this.getSessionContext(),s=e.displayPrompt||e.userPrompt||"";s&&this.#Xe.push(s);let o;if(e.agentType&&e.agentType!==this.#M){let Q=await this.getNamedAgentConfig(e.agentType,this.getSessionId(),r);Q.success&&(o={enabledTools:this.#D,modelOverride:this.#q,systemPromptOverride:this.#ce,position:this.#m,includeMemories:this.#k},this.#D=Q.options.enabledTools,this.#q=Q.options.modelOverride,this.#ce=Q.options.systemPromptOverride,this.#m=Q.options.position,this.#k=Q.options.includeMemories)}let a=e.maxCompletions??this.#u?.maxAgentCompletions,A=a??ux,c=a??sye,u=0,l=0,d=!0,g=!1,p=!1,f=!1,m,C=0,I=0,y=!1,B=0;try{for(;;B++){if(this.#r.debug(`(agentCompletion-${B}): started`),this.#e.connectionTracker.getConnectionCount()>0&&l>=A||l>=c){n({type:"error",code:"ask-to-continue",message:"The agent has been working for a while. Do you want to continue?"});break}if(r?.aborted)throw rn(r.reason);try{if(this.cancelAllPendingToolFulfilments(),m||(m=await this.#Nr(e,d,r,n),m.modelOverride=e.modelOverride,m.reasoning=e.reasoning,m.agentModelOverrides=e.agentModelOverrides),m.user.role==="user"){let v=m.files.filter(D=>(D.importance??0)>2.5&&D.content).map(D=>({filePath:D.filePath,size:D.content?.length??0,isCustomInstruction:!1,wasIncluded:D.wasIncluded}));i.customInstructions.forEach(D=>{D.filePath&&D.type==="always"&&v.push({filePath:D.filePath,size:D.content?.length??0,isCustomInstruction:!0,wasIncluded:!0})}),n({type:"user-input",prompt:m.userMessage?.displayPrompt??m.userPrompt,files:v})}try{let v=await this.#Rr(i,m,r,n),{shouldContinue:D,completions:S,filesChanged:b}=v;if(this.#A&&this.#r.debug(`(agentCompletion-${B}): completion: ${JSON.stringify(v)}`),d=!1,m=void 0,u=0,g||=b,p||=b,f||=v.navigatePreviewCalled,l+=S,this.#ne||=b,this.#i=void 0,b&&this.#h?.addCheckpoint(),r?.aborted)throw rn(r.reason);let x=this.#yr();if(x){let O=x.syncChanges??this.#Ve;O&&await this.syncChangesFromRemote(O)}let{hasHealthIssue:P}=await this.#sr();if(x){this.#r.debug(`(agentCompletion-${B}): consumed queued messages`),d=!0,e=x,l=0;continue}if(!D){if(r?.aborted)throw rn(r.reason);let O=this.getSessionMode();if((O==="planning"||O==="auto-planning")&&!this.#Ie&&!y&&I<3){this.#r.debug(`(agentCompletion-${B}): adding reminder for missing plan`),y=!0,I++,this.queueSystemReminder({text:"Remember to always write the plan file and call the ExitPlanMode tool before finishing. Also, prefer using AskUserQuestion tool to ask questions to the user."});continue}if(P&&I<3){this.#r.debug(`(agentCompletion-${B}): has health issue, continuing`),I++;continue}let J=this.#h,_=e.runValidateCommand??!0;if(J?.validateCommand&&_&&C<2&&this.#ne&&O==="normal"){p=!0,C++,n({type:"start",name:"validate-command",id:"validate-command",title:"Validate Command",content:""});let K=e.autoPush;this.#r.debug(`(agentCompletion-${B}): running validate command`),this.#Vt(r).then(j=>{if(this.#r.debug(`(validate-command): result status ${j.status}`),j.status==="failure"&&j.code){let ee=j.output?Ia(j.output,100,500):"";this.sendMessage({user:e.user,maxCompletions:e.maxCompletions,runValidateCommand:!0,userPrompt:`The validate command failed with code ${j.code}):
|
|
1908
|
+
`),tag:"reminder:git-status"})}async manualCommit(e){if(!this.#I)return!1;let r=this.getSessionContext();if(!r.beforeCommit){let n=await this.#H();Object.keys(n).length>0&&(r.beforeCommit=So(n))}return await this.commitWorkInProgress(e.commitMessage,[e.add]),await this.#ie(!0),!0}getLastSuggestedAction(){return this.#Ae}async#De(){let e=this.getSessionContext();if(e.state==="generating"||e.state==="close")return this.#Ae=void 0,!1;let r=await this.#mt(!0,"all");return e=this.getSessionContext(),e.state!=="generating"&&e.state!=="close"?(this.#Ae=r,this.#g.emit("step",{type:"wait-for-input",id:this.getLastCompletionId()??"initial",state:e.state,suggestion:r,sessionMode:e.sessionMode,hasPlanToApply:this.#Ie,modelOverride:this.#q}),!0):!1}async#xr(e){this.#xe++;try{let r=this.getCommitMode(),n=this.#I?this.getFeatureBranch():e.branchName,i=this.#Be(e),s=e.path,o=e.folderName===this.#f[0]?.folderName,a=this.getSessionContext(),A=!1,c=!1,u="",l=null;try{let B=await this.git(["rev-parse","--absolute-git-dir"],{cwd:s});l=this.#e.join(B.trim(),"FETCH_HEAD"),vl.default.existsSync(l)&&vl.default.unlinkSync(l)}catch(B){this.#e.Sentry?.captureException(B,{tags:{operation:"codegen-git",endpoint:"getGitStatus"},extra:{fetchHeadFilePath:l,isCheckingGitStatus:this.#xe,folderName:e.folderName}}),l=null}try{u=await this.git(["fetch","--no-tags","origin",i],{cwd:s}),A=!0}catch{A=!1}let d=await this.#e.getRepoInfo(s),g=al(a.beforeCommit,e.folderName,this.gitRepoContexts[0]?.folderName);!o&&!e.initialCommit&&d.commit&&(e.initialCommit=d.commit),!g&&e.initialCommit&&(g=e.initialCommit);let p=this.#wt(e.folderName),f=p?1:0,m=0;if(A){if(n!==i)try{await this.git(["--no-pager","diff","--quiet",`refs/remotes/origin/${n}...refs/remotes/origin/${i}`],{cwd:s}),c=!1}catch{c=!0}else c=!0;try{let B=v4(await this.git(["rev-list","--left-right","--count","HEAD...FETCH_HEAD"],{cwd:s}));f=B.ahead,m=B.behind}catch(B){let E=null;if(l)try{E=await this.#e.readFile(this.#e.join(s,".git/FETCH_HEAD")),E=`FETCH_HEAD: ${E} `}catch(Q){E=`FETCH_HEAD FAILED: ${String(Q)} `}else E="FETCH_HEAD MISSING";this.#e.Sentry?.captureException(B,{tags:{operation:"codegen-git",endpoint:"getGitStatus"},extra:{fetchOutput:u,fetchHead:E,remoteBranch:i,currentBranch:d.currentBranch,currentCommit:d.commit,isCheckingGitStatus:this.#xe,folderName:e.folderName}})}}else if(!A&&r!=="commits")try{let B=await this.#ot(s),E=v4(await this.git(["--no-pager","rev-list","--left-right","--count",`HEAD...${B}`],{cwd:s}));f=E.ahead,m=E.behind}catch{g&&g!==d.commit&&(f=Math.max(f,1))}let C=await this.#te(s),I=C.length>0,y=await this.#_r(s);return{type:"git",folderName:e.folderName,remoteBranchExists:A,remoteBranchHasChanges:c,hasGeneratingPlaceholder:await this.#Pr(),isSessionDirty:p||!!g&&g!==d.commit,canSync:(f>0||m>0||y)&&!I,canPush:(f>0||m>0)&&!I,hasStagedChanges:y,canPull:m>0&&A,ahead:f,hasMergeConflict:I,commitMode:r,behind:m,currentCommit:d.commit,currentBranch:d.currentBranch,pendingValidation:this.#ne,remoteBranch:i,unmergedFiles:C}}finally{this.#xe--}}#qt(){let e=this.getSessionContext();return{type:"session",title:e.title,beforeCommit:e.beforeCommit,createdUnixTime:e.createdUnixTime,updatedUnixTime:e.updatedUnixTime,turns:e.turns.length,id:e.sessionId,lastCompletionId:this.getLastCompletionId(),sessionMode:e.sessionMode,fusionConfig:rv(this.#u),hasBrowserAutomation:e.customAgents.some(r=>r.name==="browser-testing"),customInstructions:e.customInstructions.filter(r=>!r.hideUI&&(r.userInvocable??!0)).map(r=>({name:r.name,description:r.description??"",type:r.type??"always",glob:r.glob,isSkill:r.isSkill??r.filePath?.toLowerCase().includes("/skills/")??!1,userInvocable:r.userInvocable,scope:r.scope,pluginName:r.pluginName})),hasPlanToApply:this.#Ie}}#$t(){let e=this.getSessionContext(),r=e.turns,n=[];n.push(this.#qt()),Object.keys(this.#v).length>0&&n.push({type:"metadata",...this.#v}),this.#t.length>0&&n.push({type:"message-queue",queue:this.#t.map(s=>({idempotencyKey:s.idempotencyKey,displayPrompt:s.displayPrompt,user:s.user}))});let i;for(let s of r){n.push({type:"user",previousId:i,displayPrompt:s.userMessage?s.userMessage.displayPrompt??s.userMessage.userPrompt:void 0,attachments:s.userMessage?.attachments,id:s.completionId,user:s.user,role:s.user.role,compacting:!1,idempotencyKey:s.userMessage?.idempotencyKey??"",sessionMode:e.sessionMode}),i=s.completionId;for(let o of s.actions)if(o.type==="tool"||o.type==="text"||o.type==="thinking")if(n.push({type:"start",name:o.type,content:"",id:o.id??"",filePath:o.filePath??"",title:o.actionTitle??o.artifactTitle??o.filePath??""}),n.push({type:"delta",name:o.type,delta:o.content}),o.type==="tool"){if(n.push({type:o.type,id:o.id,name:o.filePath,content:o.content}),o.filePath==="UpdateSetupValue"||o.filePath==="ProposeConfig")try{let a=JSON.parse(o.content);if(o.filePath==="UpdateSetupValue")n.push({type:"update_setup_value",field:a.field,value:a.value,reason:a.reason});else{let A=a.config,c=A!=null&&!A.installCommand?.command&&(!A.runtimeDependencies||A.runtimeDependencies.length===0);n.push({type:"propose_config",config:A,message:a.message,noDependencies:c})}}catch{}}else o.type==="thinking"?n.push({type:"thinking",content:o.content}):o.type==="text"&&n.push({type:"text",content:o.content})}return n}connectToEventLoop(e,r,n){let i=n?.canHandleTools??[];if(e){let s=[],o=this.getSessionContext();s.push({type:"state",newState:"replay",abortable:!1,previousState:o.state}),this.#se&&s.push(this.#se),s.push(...this.#j),s.push(...this.#$t()),this.#Z.forEach(c=>{s.push({type:"tool-call-request",id:c.id,name:c.name,input:c.input})}),this.#oe.forEach(c=>{this.#Z.has(c.id)||s.push({type:"tool-call-request",id:c.id,name:c.name,input:c.input})});let a=this.#ve?Fa(this.#ve):void 0;if(a)switch(a.type){case"file":case"diff":case"text":case"thinking":case"suggestion":case"tool":s.push({type:"start",id:a.id,name:a.type,filePath:a.filePath??"",title:a.actionTitle??a.artifactTitle??"",content:""}),s.push({type:"delta",name:a.type,delta:a.content});break}s.push({type:"terminals",terminals:this.#Bt()});let A=this.#h;A?(s.push({type:"dev-server",devServerState:A.devState,setupState:A.setupState,httpServerState:A.httpServerState.state,devCommand:A.devCommand,setupCommand:A.setupCommand,proxyServer:A.proxyTarget,proxyServerSelection:A.proxyServerSelection,remoteAddress:A.httpServerState.remoteAddress,remotePort:A.httpServerState.remotePort,proxyServerReachable:!!this.#u?.isLocal,validateState:A.validateCommandState}),A.setupState!=="installed"&&s.push({type:"stdio",id:"setupCommand",command:A.setupCommand??"",content:A.getSetupWrite(),source:"run-command",stream:"stdout"}),s.push({type:"stdio",id:"devServer",command:A.devCommand,content:A.getDevWrite(),source:"run-command",stream:"stdout"})):r({type:"dev-server",devServerState:"running",setupState:"installed",httpServerState:"ok-2xx",devCommand:this.#u?.devCommand,setupCommand:this.#u?.setupCommand,proxyServer:this.#u?.serverUrl,proxyServerSelection:"hardcoded",remoteAddress:void 0,remotePort:void 0,proxyServerReachable:!!this.#u?.isLocal,validateState:"unset"}),s.push({type:"state",newState:o.state,abortable:o.state==="generating",previousState:"replay"}),this.#ae&&o.state!=="generating"&&s.push({type:"wait-for-input",id:this.getLastCompletionId()??"initial",state:o.state,suggestion:this.#Ae,sessionMode:o.sessionMode,hasPlanToApply:this.#Ie}),r({type:"batch",steps:s})}this.#g.on("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)+1);return this.waitForEventLoop(),()=>{this.#g.off("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)-1)}}waitUntilPendingPromises(e){let r=Uo();return this.#r.debug(`(waitUntilPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#de),e).then(()=>Sl()).then(()=>{this.#r.debug(`(waitUntilPendingPromises-${r}): finished`)})}waitUntilBlockingPendingPromises(e){let r=Uo();return this.#r.debug(`(waitUntilBlockingPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#We),e).then(()=>Sl()).then(()=>{this.#r.debug(`(waitUntilBlockingPendingPromises-${r}): finished`)})}waitUntilIdle(e){let r=Uo();return this.waitForEventLoop(),this.#r.debug(`(waitUntilIdle-${r}): started`),Wc(Sl().then(()=>this.waitUntilPendingPromises()).then(()=>{let n=this.getSessionContext();return this.#r.debug(`(waitUntilIdle-${r}): starting in ${n.state} `),n.state==="generating"?(0,cx.once)(this.#g,"idle"):Promise.resolve(void 0)}).then(()=>this.waitUntilPendingPromises()).then(()=>{this.#r.debug(`(waitUntilIdle-${r}): idle reached in ${this.getSessionContext().state} `)}),e)}async#Vt(e){let r=this.#h;if(!r)throw new Error("Dev server not found");let n=await r.runValidateCommand(void 0,e);return n.status==="success"&&(this.#ne=!1,this.#I&&(await this.#It()).length===0&&(await this.#st()||await this.manualCommit({add:".",commitMessage:"Validate command fixes"}))),n}waitForEventLoop(){return this.#ae?this.#ae:this.#ae=this.#Fr()}async#Fr(){if(this.#ae||this.#S)throw new Error("Event loop already started");this.#r.debug("(eventLoop): started");let e=mye(),r=c=>{c.type==="error"&&this.#pe>0&&(eye.includes(c.code)||(c.restoreCredits=this.#pe,this.#pe=0,uye(this.#e,this.#a,s.sessionId,c.restoreCredits).catch(l=>{this.#e.Sentry?.captureException(l)})));let u=["ExitPlanMode","TodoWrite","TaskCreate","TaskUpdate"];if(c.type==="tool_result"&&u.includes(c.result.tool_name)&&(this.#r.debug("emitting ClientDevtoolsToolResultV1",{toolName:c.result.tool_name,projectId:this.#E,branchName:this.#y}),KA(this.#a,"/events/publish",{event:nie,extraData:{toolUseId:c.result.tool_use_id,toolName:c.result.tool_name??"",result:c.result.content,isError:c.result.is_error,sessionId:s.sessionId,projectId:this.#E,branchName:this.#y},extraAttributes:{toolName:c.result.tool_name??"",projectId:this.#E,branchName:this.#y}},{debug:this.#A})),c.type==="tool"&&c.name==="Agent"){let l;try{l=JSON.parse(c.content)?.description}catch{}let d=JSON.stringify({description:l});this.#r.debug("emitting ClientDevtoolsToolCallV1",{toolName:c.name,projectId:this.#E,branchName:this.#y}),KA(this.#a,"/events/publish",{event:rie,extraData:{toolUseId:c.id,toolName:c.name,content:d,sessionId:s.sessionId,projectId:this.#E,branchName:this.#y},extraAttributes:{toolName:c.name,projectId:this.#E,branchName:this.#y}},{debug:this.#A})}this.#g.emit("step",c)};this.#S=new AbortController;let n=this.#S.signal,i=this.#h,s=this.getSessionContext(),o=()=>this.getLastCompletionId();this.#e.Sentry?.setContext("codeGen",{sessionId:s.sessionId,get completionId(){return o()}}),await this.#O(this.#F(),"initial-emitGitStatus");let a=setInterval(()=>{this.canHandleTool("GetScreenshot")&&(this.#xe>0||this.#F().catch(()=>{}))},6e4),A=()=>clearInterval(a);if(this.#Ke.push(A),process.env.FUSION_IDE_PORT){let c=setInterval(()=>{qie().then(u=>{let l=JSON.stringify(u);l!==this.#vt&&(this.#vt=l,this.#g.emit("step",{type:"ide",context:u}),this.queueSystemReminder({text:u?Vie(u):"",tag:"reminder:ide-context"}))}).catch(()=>{})},1e3);this.#Ke.push(()=>clearInterval(c))}this.queueGitStatusReminder({trigger:"session-start"}),i?.setupState==="not-installed"&&this.runSetupCommand();try{let c=0;for(;!n.aborted;){c++,this.#c=void 0;let u=this.#Qr();if(this.#r.debug(`(eventLoop-${c}): started (shouldWait: ${u.shouldWait})`),u.shouldWait){await this.#jt();let g=await this.#De();if(n.aborted)break;g&&Eye(u.promise,500).then(p=>{p&&(this.#r.debug(`(eventLoop-${c}): emitting idle on next message wait`),this.#g.emit("idle"))})}let l=await u.promise;if(n.aborted)break;if(!l)continue;this.#c=new AbortController;let d=Qn([n,this.#c.signal]);try{if(this.#Ae=void 0,l.logsCheckpoint&&i?.addCheckpoint(),d?.aborted)throw rn(d.reason);this.#V("generating"),i?.abortValidateCommand();let g=l.syncChanges??this.#Ve;g&&(this.#r.debug(`(eventLoop-${c}): syncing changes from remote`),await this.syncChangesFromRemote(g),await this.#mt(!1,"critical")),l.sessionMode&&l.sessionMode!==s.sessionMode&&this.switchSessionMode(l.sessionMode),await this.#kr(l,d,r),this.#V("success");let p=l.autoPush??this.#N??"none";if(p!=="none"&&this.#I&&(this.#r.debug(`(eventLoop-${c}): autoPush: ${p}`),await this.waitUntilBlockingPendingPromises(),(await this.#It()).length===0)){let m=(()=>{switch(p){case"force-push":return{actor:"agent",forcePush:!0,pullFirst:!1};case"merge-push":return{actor:"agent",pullFirst:!0,forcePush:!1};case"ff-push":return{actor:"agent",requireFastForward:!0,pullFirst:!1};case"safe-push":return{actor:"agent",pullFirst:!0,abortOnMergeConflict:!0};default:return{actor:"agent"}}})();if(this.#f.length>1)for(let C of this.#f)await this.#Ue({...m,folderName:C.folderName});else await this.#Ue(m)}this.#Ae=void 0}catch(g){g instanceof Error?g.name==="AbortError"?(r({type:"user-abort",hasContinueMessage:this.#t.length>0}),this.#V("abort")):g instanceof qe?(this.#i=void 0,r({type:"error",code:"cli-network-error",message:g.message}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):g instanceof dt?(this.#i=void 0,r({type:"error",code:"unknown",message:"An internal error occurred. Please try again."}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):g instanceof oi?(this.#i=void 0,r({type:"error",code:g.code,message:g.message}),eye.includes(g.code)||this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):(this.#i=void 0,r({type:"error",code:"cli-genetic-error",message:g.message,metadata:{error:g}}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#V("error")):this.#V("error")}this.#zt++}}catch(c){throw this.#e.Sentry?.captureException(c,{level:"fatal"}),c}finally{A(),this.#S=void 0,this.#ae=void 0,e()}this.#r.debug("(eventLoop): emitting idle on close"),this.#g.emit("idle"),this.#V("close")}async#kr(e,r,n){this.#pe=0,this.#ne=!1;let i=this.getSessionContext(),s=e.displayPrompt||e.userPrompt||"";s&&this.#Xe.push(s);let o;if(e.agentType&&e.agentType!==this.#M){let Q=await this.getNamedAgentConfig(e.agentType,this.getSessionId(),r);Q.success&&(o={enabledTools:this.#D,modelOverride:this.#q,systemPromptOverride:this.#ce,position:this.#m,includeMemories:this.#k},this.#D=Q.options.enabledTools,this.#q=Q.options.modelOverride,this.#ce=Q.options.systemPromptOverride,this.#m=Q.options.position,this.#k=Q.options.includeMemories)}let a=e.maxCompletions??this.#u?.maxAgentCompletions,A=a??ux,c=a??sye,u=0,l=0,d=!0,g=!1,p=!1,f=!1,m,C=0,I=0,y=!1,B=0;try{for(;;B++){if(this.#r.debug(`(agentCompletion-${B}): started`),this.#e.connectionTracker.getConnectionCount()>0&&l>=A||l>=c){n({type:"error",code:"ask-to-continue",message:"The agent has been working for a while. Do you want to continue?"});break}if(r?.aborted)throw rn(r.reason);try{if(this.cancelAllPendingToolFulfilments(),m||(m=await this.#Nr(e,d,r,n),m.modelOverride=e.modelOverride,m.reasoning=e.reasoning,m.agentModelOverrides=e.agentModelOverrides),m.user.role==="user"){let v=m.files.filter(D=>(D.importance??0)>2.5&&D.content).map(D=>({filePath:D.filePath,size:D.content?.length??0,isCustomInstruction:!1,wasIncluded:D.wasIncluded}));i.customInstructions.forEach(D=>{D.filePath&&D.type==="always"&&v.push({filePath:D.filePath,size:D.content?.length??0,isCustomInstruction:!0,wasIncluded:!0})}),n({type:"user-input",prompt:m.userMessage?.displayPrompt??m.userPrompt,files:v})}try{let v=await this.#Rr(i,m,r,n),{shouldContinue:D,completions:S,filesChanged:b}=v;if(this.#A&&this.#r.debug(`(agentCompletion-${B}): completion: ${JSON.stringify(v)}`),d=!1,m=void 0,u=0,g||=b,p||=b,f||=v.navigatePreviewCalled,l+=S,this.#ne||=b,this.#i=void 0,b&&this.#h?.addCheckpoint(),r?.aborted)throw rn(r.reason);let x=this.#yr();if(x){let O=x.syncChanges??this.#Ve;O&&await this.syncChangesFromRemote(O)}let{hasHealthIssue:P}=await this.#sr();if(x){this.#r.debug(`(agentCompletion-${B}): consumed queued messages`),d=!0,e=x,l=0;continue}if(!D){if(r?.aborted)throw rn(r.reason);let O=this.getSessionMode();if((O==="planning"||O==="auto-planning")&&!this.#Ie&&!y&&I<3){this.#r.debug(`(agentCompletion-${B}): adding reminder for missing plan`),y=!0,I++,this.queueSystemReminder({text:"Remember to always write the plan file and call the ExitPlanMode tool before finishing. Also, prefer using AskUserQuestion tool to ask questions to the user."});continue}if(P&&I<3){this.#r.debug(`(agentCompletion-${B}): has health issue, continuing`),I++;continue}let J=this.#h,_=e.runValidateCommand??!0;if(J?.validateCommand&&_&&C<2&&this.#ne&&O==="normal"){p=!0,C++,n({type:"start",name:"validate-command",id:"validate-command",title:"Validate Command",content:""});let K=e.autoPush;this.#r.debug(`(agentCompletion-${B}): running validate command`),this.#Vt(r).then(j=>{if(this.#r.debug(`(validate-command): result status ${j.status}`),j.status==="failure"&&j.code){let ee=j.output?Ia(j.output,100,500):"";this.sendMessage({user:e.user,maxCompletions:e.maxCompletions,runValidateCommand:!0,userPrompt:`The validate command failed with code ${j.code}):
|
|
1909
1909
|
<validate_command>
|
|
1910
1910
|
${j.command}
|
|
1911
1911
|
</validate_command>
|
|
@@ -1930,21 +1930,21 @@ ${Ia(g,30)}
|
|
|
1930
1930
|
${l}`):r.push(l))}catch(a){this.#e.Sentry?.captureException(a,{tags:{operation:"codegen-git",folderName:i.folderName}})}}if(e.length===0)return{files:[],diff:""};let n="";if(!this.#K()&&r.length>0)if(this.#f.length>1)n=`Notice: This is a multi-repo workspace with folders: ${this.#f.map(s=>s.folderName).join(", ")}. File paths are prefixed with their folder names when using Read/Write/Edit tools.
|
|
1931
1931
|
`;else{let i=this.gitEnabledFolder;i&&(n=`Notice that all the relative paths, are inside "${i.name}/", remember that when using Read/Write/Edit tools:
|
|
1932
1932
|
`)}return{files:e,diff:Sf(`${n}${r.join(`
|
|
1933
|
-
`)}`,1e4)}}catch(e){this.#e.Sentry?.captureException(e,{tags:{operation:"codegen-git"}});return}}#Lr(){return["status","--porcelain=v1","-z","--ignore-submodules=dirty"]}async#st(e){try{let r=this.#Lr();return(await this.git(r,{cwd:e})).trim().length===0}catch{return!1}}async#_r(e){try{return await this.git(["diff","--cached","--quiet"],{cwd:e}),!1}catch{return!0}}async#Ur(e,r){let n=r.applyResults;for(let s of n)this.#Jt(s.filePath);let i=[];for(let s of n)try{if(s.action==="delete"){let o=await this.deleteFile(s.filePath);o&&i.push(o)}else if(s.content){let o=await this.writeFile(s.filePath,s.content);o&&(this.#Xt.add(o),i.push(o))}}catch(o){e.Sentry?.captureException(o)}return i}#K(){return this.#C?.folders?.length===1||!this.#C?.folders?.length}resolveWorkspacePath(e,r){if(typeof e!="string")throw new TypeError(`resolveWorkspacePath: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);return cme({filePath:e,forceWorkspace:r,workspace:this.#C,workingDirectory:this.#d,sys:this.#e,canCollapseWorkspace:this.#K()})}#W(){try{let e=this.getSessionContext();return Fa(e.turns)?.user.principals}catch{return}}absolutePathToWorkspaceUrl(e){return ume({absolutePath:e,workspace:this.#C,workingDirectory:this.#d,sys:this.#e,canCollapseWorkspace:this.#K()})}async launchEditor(e={}){let r,n,i;return e.filePath?(r=this.resolveWorkspacePath(e.filePath,!1).resolvedPath,n=e.line??void 0,i=e.column??void 0):r=this.primaryGitPath,await this.#e.exists(r)?await this.#e.launchEditor({filePath:r,line:n,column:i}):{success:!1,message:`File not found: ${r}`}}async readFile(e,r){if(typeof e!="string")throw new TypeError(`readFile: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!r){let n=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{if(e==="AGENTS.md"&&this.#C?.agentsMD)return this.#C.agentsMD;let{resolvedPath:n}=this.resolveWorkspacePath(e,!!r);if(!r&&!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");let i=await this.#e.readFile(n);return i!==null?i:({resolvedPath:n}=this.resolveWorkspacePath(e,!0),await this.#e.readFile(n))}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}async readFileWithChecksum(e){let r=await this.readFile(e.filePath,e.skipAclCheck);if(r===null)return{content:null,checksum:null};let n=(0,wH.createHash)("md5").update(r).digest("hex");return e.previousChecksum&&n===e.previousChecksum?{content:null,checksum:n,notModified:!0}:{content:r,checksum:n}}async readBinaryFile(e){let r=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!r.allowed)throw new dt(`ACL denied: ${r.message}`);try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");let i=await this.#e.readBinaryFile(n);if(i===null){if({resolvedPath:n}=this.resolveWorkspacePath(e,!0),!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");i=await this.#e.readBinaryFile(n)}if(i)return Buffer.from(i).toString("base64")}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}async#ot(e){let r;e?r=this.#f.find(s=>s.path===e)?.branchName:r=this.gitEnabledFolder?.branchName;let n=r?r.startsWith("origin/")?r:`origin/${r}`:await this.getDefaultBranch(e);if(!n)throw new Error("Could not find parent branch");return n}async#bt(e){let r=this.#Te.get(e);if(r&&Date.now()-r.timestamp<t.#rt)return r.promise;let n=(async()=>{let i=await this.#ot(e);try{return(await this.git(["merge-base",i,"HEAD"],{cwd:e})).trim()}catch{return i}})().catch(i=>{throw this.#Te.get(e)?.promise===n&&this.#Te.delete(e),i});return this.#Te.set(e,{promise:n,timestamp:Date.now()}),n}async getFileAtRef(e,r,n){if(!this.#I)return null;try{let i,s;if(n)i=n,e.startsWith(i)?(s=e.substring(i.length),s.startsWith("/")&&(s=s.substring(1))):s=e;else{let{resolvedPath:u,workspaceFolder:l}=this.resolveWorkspacePath(e,!0);i=l?.path||this.#d,s=e,i&&u.startsWith(i)&&(s=u.substring(i.length),s.startsWith("/")&&(s=s.substring(1)))}let o=r??await this.#bt(i),a=`${i}:${o}:${s}`,A=this.#Me.get(a);if(A&&Date.now()-A.timestamp<t.#rt)return A.promise;let c=this.git(["show",`${o}:${s}`],{cwd:i}).catch(u=>{let l=u instanceof Error?u.message:String(u);return l.includes("does not exist")||l.includes("exists on disk")||this.#Me.get(a)?.promise===c&&this.#Me.delete(a),null});return this.#Me.set(a,{promise:c,timestamp:Date.now()}),c}catch{return null}}async#Gr(e){let r=this.#Ne.get(e);if(r&&Date.now()-r.timestamp<t.#rt)return r.promise;let n=(async()=>{try{let i=(await this.git(["branch","--show-current"],{cwd:e})).trim();if(i&&(await this.git(["ls-remote","--heads","origin",i],{cwd:e})).trim().length>0)return`origin/${i}`}catch{}return this.#bt(e)})().catch(i=>{throw this.#Ne.get(e)?.promise===n&&this.#Ne.delete(e),i});return this.#Ne.set(e,{promise:n,timestamp:Date.now()}),n}async#Or(e,r){return r==="remote-current-branch"?this.#Gr(e):this.#bt(e)}async getSingleFileDiff(e){if(e===null||typeof e!="string"&&typeof e!="object")throw new TypeError(`getSingleFileDiff: 'args' must be a string or object, received ${e===null?"null":typeof e}: ${_o(e)}`);let r=typeof e=="string"?{path:e}:e;if(typeof r.path!="string")throw new TypeError(`getSingleFileDiff: 'path' must be a string, received ${typeof r.path}: ${_o(r.path)}`);let n=typeof e=="object"?e.previousChecksum:void 0,i=typeof e=="object"&&e.mode?e.mode:"remote-parent-branch",{repoPath:s,relativePath:o}=this.#Gt(r.path,r.folderName),a=this.#e.join(s,o),A=this.#I?await this.#Or(s,i).catch(()=>null):null,[c,u]=await Promise.all([this.#e.readFile(a).catch(()=>null),A===null?Promise.resolve(null):this.getFileAtRef(o,A,s)]),l=u===null?"":`${u}`,d=c===null?"":`${c}`,g=(0,wH.createHash)("md5").update(`${l}\0${d}`).digest("hex"),p=u===null&&c!==null?"create":u!==null&&c===null?"delete":"update";return n===g?{oldContent:null,newContent:null,action:p,checksum:g,notModified:!0}:{oldContent:u,newContent:c,action:p,checksum:g}}async discardFileChanges(e){let r=typeof e=="string"?{filePath:e}:e;if(!this.#I)return{success:!1,error:"Git not configured"};try{let{repoPath:n,relativePath:i}=this.#Gt(r.filePath,r.folderName),s=this.#e.join(n,i),o=await this.#ot(n),a;try{a=(await this.git(["merge-base",o,"HEAD"],{cwd:n})).trim()}catch{a=o}let A=await this.getFileAtRef(i,a,n),u=(await this.git(["--no-pager","diff",`${a}`,"HEAD","--",i],{cwd:n})).trim().length>0,d=(await this.git(["status","--porcelain","--",i],{cwd:n})).trim().length>0;if(!u&&!d)return{success:!0};if(A===null){try{await this.#e.exists(s)&&await this.#e.unlink(s)}catch{}let f=this.#e.dirname(i);if(f&&f!==".")try{await this.git(["clean","-fd",f],{cwd:n})}catch{}}else try{await this.git(["restore",`--source=${a}`,"--",i],{cwd:n})}catch(f){return{success:!1,error:`Failed to restore file: ${f}`}}await this.git(["add","--",i],{cwd:n});let g=`Discard changes to ${i}`;await this.git(["commit","--no-gpg-sign","-m",g],{cwd:n});let p=(await this.git(["rev-parse","HEAD"],{cwd:n})).trim();try{await this.#F()}catch(f){this.#e.Sentry?.captureException(f,{tags:{operation:"discard-file-changes",step:"emit-git-status"}})}return{success:!0,commitHash:p}}catch(n){try{await this.#F()}catch(i){this.#e.Sentry?.captureException(i,{tags:{operation:"discard-file-changes",step:"emit-git-status"}})}return{success:!1,error:n instanceof Error?n.message:String(n)}}}async revertDiscard(e){let{commitHash:r,folderName:n}=e;if(!this.#I)return{success:!1,error:"Git not configured"};try{let i=this.#Le(n);await this.git(["revert","--no-edit",r],{cwd:i});try{await this.#F()}catch(s){this.#e.Sentry?.captureException(s,{tags:{operation:"revert-discard",step:"emit-git-status"}})}return{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}async fileExists(e){if(typeof e!="string")throw new TypeError(`fileExists: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);let r=n=>n.startsWith(this.#d)?this.#e.relative(this.#d,n):n;try{if(e==="AGENTS.md"&&this.#C?.agentsMD)return{absolutePath:e,recommendedPath:void 0,workspaceFolder:void 0,virtual:!0};let{resolvedPath:n,workspaceFolder:i}=this.resolveWorkspacePath(e,!1);return await this.#e.exists(n)?{absolutePath:n,recommendedPath:void 0,workspaceFolder:i,virtual:!1}:i?{absolutePath:void 0,recommendedPath:void 0,workspaceFolder:i,virtual:!1}:({resolvedPath:n,workspaceFolder:i}=this.resolveWorkspacePath(e,!0),await this.#e.exists(n)?{absolutePath:n,recommendedPath:r(n),workspaceFolder:i,virtual:!1}:{absolutePath:void 0,recommendedPath:r(n),workspaceFolder:i,virtual:!1})}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return{absolutePath:void 0,recommendedPath:void 0,workspaceFolder:void 0,virtual:!1}}readFileSync(e,r){if(!r){let n=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{if(e==="AGENTS.md"&&this.#C?.agentsMD)return this.#C.agentsMD;let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(this.#e.existsSync(n))return this.#e.readFileSync(n);if({resolvedPath:n}=this.resolveWorkspacePath(e,!0),this.#e.existsSync(n))return this.#e.readFileSync(n)}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}async writeFile(e,r,n){if(typeof e!="string")throw new TypeError(`writeFile: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!n){let i=mo(gi(e),"write",this.#u?.accessControl,this.#W());if(!i.allowed)throw new dt(`ACL denied: ${i.message}`)}try{let{resolvedPath:i}=this.resolveWorkspacePath(e,!!n);if(!n&&!ll({resolvedPath:i,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");return await this.#e.writeFile(i,r),i}catch(i){return this.#e.Sentry?.captureException(i,{extra:{filePath:e}}),null}}async listDir(e){if(typeof e!="string")throw new TypeError(`listDir: 'dirPath' must be a string, received ${typeof e}: ${_o(e)}`);let r=mo(gi(e),"list",this.#u?.accessControl,this.#W());if(!r.allowed)throw new dt(`ACL denied: ${r.message}`);try{let{resolvedPath:n,workspaceFolder:i}=this.resolveWorkspacePath(e,!1);if(!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");if(!await this.#e.exists(n))return[];let A=(await(0,rye.readdir)(n,{withFileTypes:!0})).map(c=>c.name+(c.isDirectory()?"/":""));if(this.#K()){let c=A.map(u=>Dn(this.#e.join(e,u)));return Ff({files:c,policy:this.#u?.accessControl,getDotFiles:!0})}if(i&&this.#C?.folders){let c=i.name||i.path,u=e;e.startsWith(c+"/")?u=e.substring(c.length+1):e===c&&(u="");let l=A.map(d=>{let g=u?this.#e.join(u,d):d,p=Dn(g);return`${c}/${p}`});return Ff({files:l,policy:this.#u?.accessControl,getDotFiles:!0})}return Ff({files:A,policy:this.#u?.accessControl,getDotFiles:!0})}catch(n){return this.#e.Sentry?.captureException(n,{extra:{dirPath:e}}),[]}}async listCustomInstructions(){return(await this.#_e()).filter(r=>!r.hideUI).map(r=>({id:r.id,name:r.name,description:r.description,type:r.type,isSkill:r.isSkill??r.filePath?.toLowerCase().includes("/skills/")??!1,disableModelInvocation:r.disableModelInvocation,userInvocable:r.userInvocable}))}async stat(e,r){if(typeof e!="string")throw new TypeError(`stat: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!r){let n=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(await this.#e.exists(n))return await this.#e.stat(n)}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}#Kr(e){let r=Dn(this.#e.resolve(e)),n=this.absolutePathToWorkspaceUrl(r);return n!==void 0?Dn(n):Dn(this.#e.relative(this.#d,r))}async#Hr(e){let r=[],n=async i=>{let s=this.#e.resolve(i);if(!ll({resolvedPath:s,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");r.push(s);let o;try{o=await this.#e.stat(s)}catch(A){if(A?.code==="ENOENT")return;throw A}if(!o.isDirectory())return;let a=await this.#e.readdir(s);for(let A of a){let c=A.endsWith("/")?A.slice(0,-1):A;await n(this.#e.join(s,c))}};return await n(e),r}async deleteFile(e,r){if(typeof e!="string")throw new TypeError(`deleteFile: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!r){let n=mo(gi(e),"write",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!!r);if(!r&&!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");if(!await this.#e.exists(n))return null;if((await this.#e.stat(n)).isDirectory()){if(!r){let s=await this.#Hr(n);for(let o of s){let a=mo(this.#Kr(o),"write",this.#u?.accessControl,this.#W());if(!a.allowed)throw new dt(`ACL denied: ${a.message}`)}}await this.#e.rm(n,{recursive:!0,force:!0})}else await this.#e.unlink(n);return n}catch(n){if(n instanceof dt)throw n;return this.#e.Sentry?.captureException(n,{extra:{filePath:e}}),null}}getLinesStats(){let e=this.#n?.turns.reduce((r,n)=>{let i=n.applyResults.reduce((s,o)=>({added:s.added+o.addedLines,removed:s.removed+o.removedLines}),{added:0,removed:0});return{added:r.added+i.added,removed:r.removed+i.removed}},{added:0,removed:0})??{added:0,removed:0};return{...e,net:e.added-e.removed}}async getDiffFromRemote({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i}){if(!this.#I)return[];let s=this.#Le(i);try{let o=(await this.git(["branch","--show-current"],{cwd:s})).trim();if(!o)throw new Error("Could not determine current branch");let a=!1;try{a=(await this.git(["remote"],{cwd:s})).includes("origin")}catch(d){throw this.#r.warn("No git remotes configured, cannot get diff from remote"),d}if(!a){this.#r.warn("Origin remote not found, trying to get diff from main branch");try{return await this.getDiffFromParentBranch({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i})}catch(d){throw this.#r.warn("Failed to get diff from main branch:",d),d}}let A=!1,c;try{let d=`origin/${o}`;if(A=(await this.git(["ls-remote","--heads","origin",o],{cwd:s})).trim().length>0,A)c=d;else return await this.getDiffFromParentBranch({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i})}catch(d){throw this.#r.warn("Failed to check remote branches:",d),d}let u=["diff",c];r?u.push("--raw","--numstat","--no-renames"):e!==void 0&&u.push(`-U${e}`),u.push("--"),n&&n.length>0&&u.push(...n);let l=await this.git(u,{cwd:s});return!l||l.trim()===""?[]:uH(l,r)}catch(o){throw o instanceof Tp||this.#r.error("getDiffFromRemote error:",o),o}}async getDiff({mode:e="remote-parent-branch",numberOfContextLines:r,includeFilesOnly:n,filePaths:i,folderName:s}){if(!this.#I)return{state:"error",error:new Error("Git not configured")};try{switch(e){case"remote-parent-branch":return{state:"success",diff:await this.getDiffFromParentBranch({numberOfContextLines:r,includeFilesOnly:n,filePaths:i,folderName:s})};case"remote-current-branch":return{state:"success",diff:await this.getDiffFromRemote({numberOfContextLines:r,includeFilesOnly:n,filePaths:i,folderName:s})};default:throw new Error(`Unknown diff mode: ${e}`)}}catch(o){return o instanceof Tp?{state:"error",error:o}:(this.#r.error(`getDiff error for mode '${e}':`,o),this.#e.Sentry?.captureException(o),{state:"error",error:o instanceof Error?o:new Error(String(o))})}}async getDefaultBranch(e){let r=e??"__primary__",n=this.#tt.get(r);if(n)return n;let i=this.#Jr(e).catch(s=>{throw this.#tt.get(r)===i&&this.#tt.delete(r),s});return this.#tt.set(r,i),i}async#Jr(e){try{let n=(await this.git(["remote","show","origin"],{cwd:e})).match(/HEAD branch: (.+)/);if(n)return`origin/${n[1].trim()}`}catch{}try{if((await this.git(["ls-remote","--heads","origin","main"],{cwd:e})).trim().length>0)return"origin/main"}catch{}try{if((await this.git(["ls-remote","--heads","origin","master"],{cwd:e})).trim().length>0)return"origin/master"}catch{}try{let n=(await this.git(["ls-remote","--heads","origin"],{cwd:e})).trim().split(`
|
|
1934
|
-
`).map(i=>i.split(" ")[1]).filter(i=>i&&!i.includes("HEAD"));if(n.length>0)return`origin/${n[0].replace("refs/heads/","")}`}catch{}throw new Error("Could not determine default branch. No remote branches found.")}async getDiffFromParentBranch({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i}){let s=this.#Le(i);try{if(!(await this.git(["branch","--show-current"],{cwd:s})).trim())throw new Error("Could not determine current branch");let a=await this.#ot(s),A;try{A=(await this.git(["merge-base",a,"HEAD"],{cwd:s})).trim()}catch(l){throw l instanceof Go&&l.code===128?new Tp(a,{cause:l}):l}let c=["--no-pager","diff",A];r?c.push("--raw","--numstat","--no-renames"):e!==void 0&&c.push(`-U${e}`),c.push("--"),n&&n.length>0&&c.push(...n);let u=await this.git(c,{cwd:s});return!u||u.trim()===""?[]:
|
|
1933
|
+
`)}`,1e4)}}catch(e){this.#e.Sentry?.captureException(e,{tags:{operation:"codegen-git"}});return}}#Lr(){return["status","--porcelain=v1","-z","--ignore-submodules=dirty"]}async#st(e){try{let r=this.#Lr();return(await this.git(r,{cwd:e})).trim().length===0}catch{return!1}}async#_r(e){try{return await this.git(["diff","--cached","--quiet"],{cwd:e}),!1}catch{return!0}}async#Ur(e,r){let n=r.applyResults;for(let s of n)this.#Jt(s.filePath);let i=[];for(let s of n)try{if(s.action==="delete"){let o=await this.deleteFile(s.filePath);o&&i.push(o)}else if(s.content){let o=await this.writeFile(s.filePath,s.content);o&&(this.#Xt.add(o),i.push(o))}}catch(o){e.Sentry?.captureException(o)}return i}#K(){return this.#C?.folders?.length===1||!this.#C?.folders?.length}resolveWorkspacePath(e,r){if(typeof e!="string")throw new TypeError(`resolveWorkspacePath: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);return cme({filePath:e,forceWorkspace:r,workspace:this.#C,workingDirectory:this.#d,sys:this.#e,canCollapseWorkspace:this.#K()})}#W(){try{let e=this.getSessionContext();return Fa(e.turns)?.user.principals}catch{return}}absolutePathToWorkspaceUrl(e){return ume({absolutePath:e,workspace:this.#C,workingDirectory:this.#d,sys:this.#e,canCollapseWorkspace:this.#K()})}async launchEditor(e={}){let r,n,i;return e.filePath?(r=this.resolveWorkspacePath(e.filePath,!1).resolvedPath,n=e.line??void 0,i=e.column??void 0):r=this.primaryGitPath,await this.#e.exists(r)?await this.#e.launchEditor({filePath:r,line:n,column:i}):{success:!1,message:`File not found: ${r}`}}async readFile(e,r){if(typeof e!="string")throw new TypeError(`readFile: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!r){let n=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{if(e==="AGENTS.md"&&this.#C?.agentsMD)return this.#C.agentsMD;let{resolvedPath:n}=this.resolveWorkspacePath(e,!!r);if(!r&&!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");let i=await this.#e.readFile(n);return i!==null?i:({resolvedPath:n}=this.resolveWorkspacePath(e,!0),await this.#e.readFile(n))}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}async readFileWithChecksum(e){let r=await this.readFile(e.filePath,e.skipAclCheck);if(r===null)return{content:null,checksum:null};let n=(0,w4.createHash)("md5").update(r).digest("hex");return e.previousChecksum&&n===e.previousChecksum?{content:null,checksum:n,notModified:!0}:{content:r,checksum:n}}async readBinaryFile(e){let r=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!r.allowed)throw new dt(`ACL denied: ${r.message}`);try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");let i=await this.#e.readBinaryFile(n);if(i===null){if({resolvedPath:n}=this.resolveWorkspacePath(e,!0),!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");i=await this.#e.readBinaryFile(n)}if(i)return Buffer.from(i).toString("base64")}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}async#ot(e){let r;e?r=this.#f.find(s=>s.path===e)?.branchName:r=this.gitEnabledFolder?.branchName;let n=r?r.startsWith("origin/")?r:`origin/${r}`:await this.getDefaultBranch(e);if(!n)throw new Error("Could not find parent branch");return n}async#bt(e){let r=this.#Te.get(e);if(r&&Date.now()-r.timestamp<t.#rt)return r.promise;let n=(async()=>{let i=await this.#ot(e);try{return(await this.git(["merge-base",i,"HEAD"],{cwd:e})).trim()}catch{return i}})().catch(i=>{throw this.#Te.get(e)?.promise===n&&this.#Te.delete(e),i});return this.#Te.set(e,{promise:n,timestamp:Date.now()}),n}async getFileAtRef(e,r,n){if(!this.#I)return null;try{let i,s;if(n)i=n,e.startsWith(i)?(s=e.substring(i.length),s.startsWith("/")&&(s=s.substring(1))):s=e;else{let{resolvedPath:u,workspaceFolder:l}=this.resolveWorkspacePath(e,!0);i=l?.path||this.#d,s=e,i&&u.startsWith(i)&&(s=u.substring(i.length),s.startsWith("/")&&(s=s.substring(1)))}let o=r??await this.#bt(i),a=`${i}:${o}:${s}`,A=this.#Me.get(a);if(A&&Date.now()-A.timestamp<t.#rt)return A.promise;let c=this.git(["show",`${o}:${s}`],{cwd:i}).catch(u=>{let l=u instanceof Error?u.message:String(u);return l.includes("does not exist")||l.includes("exists on disk")||this.#Me.get(a)?.promise===c&&this.#Me.delete(a),null});return this.#Me.set(a,{promise:c,timestamp:Date.now()}),c}catch{return null}}async#Gr(e){let r=this.#Ne.get(e);if(r&&Date.now()-r.timestamp<t.#rt)return r.promise;let n=(async()=>{try{let i=(await this.git(["branch","--show-current"],{cwd:e})).trim();if(i&&(await this.git(["ls-remote","--heads","origin",i],{cwd:e})).trim().length>0)return`origin/${i}`}catch{}return this.#bt(e)})().catch(i=>{throw this.#Ne.get(e)?.promise===n&&this.#Ne.delete(e),i});return this.#Ne.set(e,{promise:n,timestamp:Date.now()}),n}async#Or(e,r){return r==="remote-current-branch"?this.#Gr(e):this.#bt(e)}async getSingleFileDiff(e){if(e===null||typeof e!="string"&&typeof e!="object")throw new TypeError(`getSingleFileDiff: 'args' must be a string or object, received ${e===null?"null":typeof e}: ${_o(e)}`);let r=typeof e=="string"?{path:e}:e;if(typeof r.path!="string")throw new TypeError(`getSingleFileDiff: 'path' must be a string, received ${typeof r.path}: ${_o(r.path)}`);let n=typeof e=="object"?e.previousChecksum:void 0,i=typeof e=="object"&&e.mode?e.mode:"remote-parent-branch",{repoPath:s,relativePath:o}=this.#Gt(r.path,r.folderName),a=this.#e.join(s,o),A=this.#I?await this.#Or(s,i).catch(()=>null):null,[c,u]=await Promise.all([this.#e.readFile(a).catch(()=>null),A===null?Promise.resolve(null):this.getFileAtRef(o,A,s)]),l=u===null?"":`${u}`,d=c===null?"":`${c}`,g=(0,w4.createHash)("md5").update(`${l}\0${d}`).digest("hex"),p=u===null&&c!==null?"create":u!==null&&c===null?"delete":"update";return n===g?{oldContent:null,newContent:null,action:p,checksum:g,notModified:!0}:{oldContent:u,newContent:c,action:p,checksum:g}}async discardFileChanges(e){let r=typeof e=="string"?{filePath:e}:e;if(!this.#I)return{success:!1,error:"Git not configured"};try{let{repoPath:n,relativePath:i}=this.#Gt(r.filePath,r.folderName),s=this.#e.join(n,i),o=await this.#ot(n),a;try{a=(await this.git(["merge-base",o,"HEAD"],{cwd:n})).trim()}catch{a=o}let A=await this.getFileAtRef(i,a,n),u=(await this.git(["--no-pager","diff",`${a}`,"HEAD","--",i],{cwd:n})).trim().length>0,d=(await this.git(["status","--porcelain","--",i],{cwd:n})).trim().length>0;if(!u&&!d)return{success:!0};if(A===null){try{await this.#e.exists(s)&&await this.#e.unlink(s)}catch{}let f=this.#e.dirname(i);if(f&&f!==".")try{await this.git(["clean","-fd",f],{cwd:n})}catch{}}else try{await this.git(["restore",`--source=${a}`,"--",i],{cwd:n})}catch(f){return{success:!1,error:`Failed to restore file: ${f}`}}await this.git(["add","--",i],{cwd:n});let g=`Discard changes to ${i}`;await this.git(["commit","--no-gpg-sign","-m",g],{cwd:n});let p=(await this.git(["rev-parse","HEAD"],{cwd:n})).trim();try{await this.#F()}catch(f){this.#e.Sentry?.captureException(f,{tags:{operation:"discard-file-changes",step:"emit-git-status"}})}return{success:!0,commitHash:p}}catch(n){try{await this.#F()}catch(i){this.#e.Sentry?.captureException(i,{tags:{operation:"discard-file-changes",step:"emit-git-status"}})}return{success:!1,error:n instanceof Error?n.message:String(n)}}}async revertDiscard(e){let{commitHash:r,folderName:n}=e;if(!this.#I)return{success:!1,error:"Git not configured"};try{let i=this.#Le(n);await this.git(["revert","--no-edit",r],{cwd:i});try{await this.#F()}catch(s){this.#e.Sentry?.captureException(s,{tags:{operation:"revert-discard",step:"emit-git-status"}})}return{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}async fileExists(e){if(typeof e!="string")throw new TypeError(`fileExists: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);let r=n=>n.startsWith(this.#d)?this.#e.relative(this.#d,n):n;try{if(e==="AGENTS.md"&&this.#C?.agentsMD)return{absolutePath:e,recommendedPath:void 0,workspaceFolder:void 0,virtual:!0};let{resolvedPath:n,workspaceFolder:i}=this.resolveWorkspacePath(e,!1);return await this.#e.exists(n)?{absolutePath:n,recommendedPath:void 0,workspaceFolder:i,virtual:!1}:i?{absolutePath:void 0,recommendedPath:void 0,workspaceFolder:i,virtual:!1}:({resolvedPath:n,workspaceFolder:i}=this.resolveWorkspacePath(e,!0),await this.#e.exists(n)?{absolutePath:n,recommendedPath:r(n),workspaceFolder:i,virtual:!1}:{absolutePath:void 0,recommendedPath:r(n),workspaceFolder:i,virtual:!1})}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return{absolutePath:void 0,recommendedPath:void 0,workspaceFolder:void 0,virtual:!1}}readFileSync(e,r){if(!r){let n=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{if(e==="AGENTS.md"&&this.#C?.agentsMD)return this.#C.agentsMD;let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(this.#e.existsSync(n))return this.#e.readFileSync(n);if({resolvedPath:n}=this.resolveWorkspacePath(e,!0),this.#e.existsSync(n))return this.#e.readFileSync(n)}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}async writeFile(e,r,n){if(typeof e!="string")throw new TypeError(`writeFile: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!n){let i=mo(gi(e),"write",this.#u?.accessControl,this.#W());if(!i.allowed)throw new dt(`ACL denied: ${i.message}`)}try{let{resolvedPath:i}=this.resolveWorkspacePath(e,!!n);if(!n&&!ll({resolvedPath:i,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");return await this.#e.writeFile(i,r),i}catch(i){return this.#e.Sentry?.captureException(i,{extra:{filePath:e}}),null}}async listDir(e){if(typeof e!="string")throw new TypeError(`listDir: 'dirPath' must be a string, received ${typeof e}: ${_o(e)}`);let r=mo(gi(e),"list",this.#u?.accessControl,this.#W());if(!r.allowed)throw new dt(`ACL denied: ${r.message}`);try{let{resolvedPath:n,workspaceFolder:i}=this.resolveWorkspacePath(e,!1);if(!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");if(!await this.#e.exists(n))return[];let A=(await(0,rye.readdir)(n,{withFileTypes:!0})).map(c=>c.name+(c.isDirectory()?"/":""));if(this.#K()){let c=A.map(u=>Dn(this.#e.join(e,u)));return Ff({files:c,policy:this.#u?.accessControl,getDotFiles:!0})}if(i&&this.#C?.folders){let c=i.name||i.path,u=e;e.startsWith(c+"/")?u=e.substring(c.length+1):e===c&&(u="");let l=A.map(d=>{let g=u?this.#e.join(u,d):d,p=Dn(g);return`${c}/${p}`});return Ff({files:l,policy:this.#u?.accessControl,getDotFiles:!0})}return Ff({files:A,policy:this.#u?.accessControl,getDotFiles:!0})}catch(n){return this.#e.Sentry?.captureException(n,{extra:{dirPath:e}}),[]}}async listCustomInstructions(){return(await this.#_e()).filter(r=>!r.hideUI).map(r=>({id:r.id,name:r.name,description:r.description,type:r.type,isSkill:r.isSkill??r.filePath?.toLowerCase().includes("/skills/")??!1,disableModelInvocation:r.disableModelInvocation,userInvocable:r.userInvocable}))}async stat(e,r){if(typeof e!="string")throw new TypeError(`stat: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!r){let n=mo(gi(e),"read",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(await this.#e.exists(n))return await this.#e.stat(n)}catch(n){this.#e.Sentry?.captureException(n,{extra:{filePath:e}})}return null}#Kr(e){let r=Dn(this.#e.resolve(e)),n=this.absolutePathToWorkspaceUrl(r);return n!==void 0?Dn(n):Dn(this.#e.relative(this.#d,r))}async#Hr(e){let r=[],n=async i=>{let s=this.#e.resolve(i);if(!ll({resolvedPath:s,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");r.push(s);let o;try{o=await this.#e.stat(s)}catch(A){if(A?.code==="ENOENT")return;throw A}if(!o.isDirectory())return;let a=await this.#e.readdir(s);for(let A of a){let c=A.endsWith("/")?A.slice(0,-1):A;await n(this.#e.join(s,c))}};return await n(e),r}async deleteFile(e,r){if(typeof e!="string")throw new TypeError(`deleteFile: 'filePath' must be a string, received ${typeof e}: ${_o(e)}`);if(!r){let n=mo(gi(e),"write",this.#u?.accessControl,this.#W());if(!n.allowed)throw new dt(`ACL denied: ${n.message}`)}try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!!r);if(!r&&!ll({resolvedPath:n,workingDirectory:this.#d,workspace:this.#C,sys:this.#e}))throw new dt("Access denied: path outside working directory");if(!await this.#e.exists(n))return null;if((await this.#e.stat(n)).isDirectory()){if(!r){let s=await this.#Hr(n);for(let o of s){let a=mo(this.#Kr(o),"write",this.#u?.accessControl,this.#W());if(!a.allowed)throw new dt(`ACL denied: ${a.message}`)}}await this.#e.rm(n,{recursive:!0,force:!0})}else await this.#e.unlink(n);return n}catch(n){if(n instanceof dt)throw n;return this.#e.Sentry?.captureException(n,{extra:{filePath:e}}),null}}getLinesStats(){let e=this.#n?.turns.reduce((r,n)=>{let i=n.applyResults.reduce((s,o)=>({added:s.added+o.addedLines,removed:s.removed+o.removedLines}),{added:0,removed:0});return{added:r.added+i.added,removed:r.removed+i.removed}},{added:0,removed:0})??{added:0,removed:0};return{...e,net:e.added-e.removed}}async getDiffFromRemote({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i}){if(!this.#I)return[];let s=this.#Le(i);try{let o=(await this.git(["branch","--show-current"],{cwd:s})).trim();if(!o)throw new Error("Could not determine current branch");let a=!1;try{a=(await this.git(["remote"],{cwd:s})).includes("origin")}catch(d){throw this.#r.warn("No git remotes configured, cannot get diff from remote"),d}if(!a){this.#r.warn("Origin remote not found, trying to get diff from main branch");try{return await this.getDiffFromParentBranch({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i})}catch(d){throw this.#r.warn("Failed to get diff from main branch:",d),d}}let A=!1,c;try{let d=`origin/${o}`;if(A=(await this.git(["ls-remote","--heads","origin",o],{cwd:s})).trim().length>0,A)c=d;else return await this.getDiffFromParentBranch({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i})}catch(d){throw this.#r.warn("Failed to check remote branches:",d),d}let u=["diff",c];r?u.push("--raw","--numstat","--no-renames"):e!==void 0&&u.push(`-U${e}`),u.push("--"),n&&n.length>0&&u.push(...n);let l=await this.git(u,{cwd:s});return!l||l.trim()===""?[]:u4(l,r)}catch(o){throw o instanceof Tp||this.#r.error("getDiffFromRemote error:",o),o}}async getDiff({mode:e="remote-parent-branch",numberOfContextLines:r,includeFilesOnly:n,filePaths:i,folderName:s}){if(!this.#I)return{state:"error",error:new Error("Git not configured")};try{switch(e){case"remote-parent-branch":return{state:"success",diff:await this.getDiffFromParentBranch({numberOfContextLines:r,includeFilesOnly:n,filePaths:i,folderName:s})};case"remote-current-branch":return{state:"success",diff:await this.getDiffFromRemote({numberOfContextLines:r,includeFilesOnly:n,filePaths:i,folderName:s})};default:throw new Error(`Unknown diff mode: ${e}`)}}catch(o){return o instanceof Tp?{state:"error",error:o}:(this.#r.error(`getDiff error for mode '${e}':`,o),this.#e.Sentry?.captureException(o),{state:"error",error:o instanceof Error?o:new Error(String(o))})}}async getDefaultBranch(e){let r=e??"__primary__",n=this.#tt.get(r);if(n)return n;let i=this.#Jr(e).catch(s=>{throw this.#tt.get(r)===i&&this.#tt.delete(r),s});return this.#tt.set(r,i),i}async#Jr(e){try{let n=(await this.git(["remote","show","origin"],{cwd:e})).match(/HEAD branch: (.+)/);if(n)return`origin/${n[1].trim()}`}catch{}try{if((await this.git(["ls-remote","--heads","origin","main"],{cwd:e})).trim().length>0)return"origin/main"}catch{}try{if((await this.git(["ls-remote","--heads","origin","master"],{cwd:e})).trim().length>0)return"origin/master"}catch{}try{let n=(await this.git(["ls-remote","--heads","origin"],{cwd:e})).trim().split(`
|
|
1934
|
+
`).map(i=>i.split(" ")[1]).filter(i=>i&&!i.includes("HEAD"));if(n.length>0)return`origin/${n[0].replace("refs/heads/","")}`}catch{}throw new Error("Could not determine default branch. No remote branches found.")}async getDiffFromParentBranch({numberOfContextLines:e,includeFilesOnly:r,filePaths:n,folderName:i}){let s=this.#Le(i);try{if(!(await this.git(["branch","--show-current"],{cwd:s})).trim())throw new Error("Could not determine current branch");let a=await this.#ot(s),A;try{A=(await this.git(["merge-base",a,"HEAD"],{cwd:s})).trim()}catch(l){throw l instanceof Go&&l.code===128?new Tp(a,{cause:l}):l}let c=["--no-pager","diff",A];r?c.push("--raw","--numstat","--no-renames"):e!==void 0&&c.push(`-U${e}`),c.push("--"),n&&n.length>0&&c.push(...n);let u=await this.git(c,{cwd:s});return!u||u.trim()===""?[]:u4(u,r)}catch(o){throw o instanceof Tp||this.#r.error("getDiffFromParentBranch error:",o),o}}},D4=(t,e)=>e.filter(r=>!t?.disabledTools?.includes(r))});async function xl(t){try{await R0(t)}catch{console.log(`
|
|
1935
1935
|
Could not open browser automatically.`),console.log(`Please open this URL manually:
|
|
1936
1936
|
${t}
|
|
1937
|
-
`)}}var TB=L(()=>{"use strict";h();$_()});async function gx(t,e,r){let n=t.isAbsolute(e)?e:t.resolve(t.cwd(),e),i=await t.readFile(n);if(!i)throw new Error(`Failed to read ${r} file: ${n}`);return $.info(`\u{1F4C4} Loaded ${r} from file: ${n}`),i}async function xft(t,e,r){let n=r.httpsServerFiles?.key,i=r.httpsServerFiles?.cert,s=r.httpsServerFiles?.ca,o={...r.httpsServerOptions,key:n?await gx(t,n,"key"):r.httpsServerOptions?.key,cert:i?await gx(t,i,"cert"):r.httpsServerOptions?.cert,ca:s?await gx(t,s,"ca"):r.httpsServerOptions?.ca},a=Object.fromEntries(Object.entries(o).filter(([A,c])=>c!==void 0));if(Object.keys(a).length!==0)return a}async function Fl(t,e){let r=t.cwd(),n=!!e.local||!e.projectId,i={workingDirectory:r,projectId:e.projectId,branchName:e.branchName,commitMode:"commits",mode:"init-and-launch",isLocal:n,allowedCommands:["npm *","pnpm *","yarn *","yarn","bun *","bun","gh *","wc *","gradle *","gradle","rg *","./gradlew *","./gradlew","expo *","expo","adb *","adb","vp *","vp","git *","export *","rails *","gem *","bundle *","rake *","echo *","cd *","find *","ls *","rm *","cp *","mv *","pwd","curl *","npx tsc *","head *","lsof *","kill *","ps *","tr *","awk *","cat *","grep *","sed *","tail *","touch *","mkdir *","tee *","true","uniq *","test *","false","npx *","sort *","env","dirname","basename *","realpath *","readlink *","stat *","file *","diff *","xargs *","chmod *","which *","whoami","uname *","uname","date","date *","printenv *","sleep *","netlify *","node *","tsx *","builderio *","builder *","open *","xcrun *","xcodebuild *","xcode-select *","xed *","agvtool *"]};if(e.configJson)try{let d=JSON.parse(e.configJson);i=Object.assign({},i,d),i.isLocal?n=!0:i.projectId&&(n=!1,i.isLocal=!1)}catch(d){t.Sentry?.captureException(d)}else{let d=await Dye(t,e);if(d&&await t.exists(d))try{let g=await t.readFile(d);if(g){let p=JSON.parse(g);i=Object.assign({},i,p)}}catch(g){t.Sentry?.captureException(g)}}i.command&&(i.devCommand||(i.devCommand=i.command),delete i.command);let s=e.c||e.command,o=e.p||e.port,a=e.installCommand,A=e.serverUrl,c=e.interactive&&!e.configJson&&!e.fusionInit&&n&&!e.chat;if(A)c=!1,i.serverUrl=A,s||(i.devCommand="");else if(s&&o){c=!1;let d="http://localhost";if(i.serverUrl)try{let g=new URL(i.serverUrl);d=`${g.protocol}//${g.hostname}`}catch{d="http://localhost"}i.serverUrl=`${d}:${o}`,i.devCommand=s}else s&&i.autoDetectDevServer&&(c=!1,i.devCommand=s);s&&o&&(c=!1),o&&!A&&(i.serverUrl=`http://localhost:${o}`),a&&(i.setupCommand=a),s&&(i.devCommand=s),s&&!i.serverUrl&&(i.autoDetectDevServer=!0,i.autoSuggestPort=!0),typeof e.authenticateProxy=="boolean"&&(i.authenticateProxy=e.authenticateProxy),typeof e.privacyMode=="boolean"&&e.privacyMode&&(i.privacyMode=Object.assign({},i.privacyMode,{enabled:!0})),typeof e.autoDetectDevServer=="boolean"&&(i.autoDetectDevServer=e.autoDetectDevServer);let u=e.runInPty??e["run-in-pty"];if(typeof u=="boolean"&&(i.runInPty=u),typeof e.https=="boolean"&&(i.https=e.https),e.localHttpsDomain&&(i.localHttpsDomain=e.localHttpsDomain),typeof e.nativeApp=="boolean"&&(i.nativeApp=e.nativeApp),e.disabledTools){let d=e.disabledTools.split(",").map(g=>g.trim());i.disabledTools=d}if(i.httpsServerOptions=await xft(t,e,i),c&&!e.chat){if(!i.devCommand){let d=await lr({message:"Enter the command to run for the dev server (e.g. 'npm run dev')",placeholder:"npm run dev",validate:g=>{if(g.trim()===""||g.length===0)return"Command cannot be empty"}});if(je(d))return Ke("Goodbye! \u{1F44B}"),await(0,
|
|
1937
|
+
`)}}var TB=L(()=>{"use strict";h();$_()});async function gx(t,e,r){let n=t.isAbsolute(e)?e:t.resolve(t.cwd(),e),i=await t.readFile(n);if(!i)throw new Error(`Failed to read ${r} file: ${n}`);return $.info(`\u{1F4C4} Loaded ${r} from file: ${n}`),i}async function xft(t,e,r){let n=r.httpsServerFiles?.key,i=r.httpsServerFiles?.cert,s=r.httpsServerFiles?.ca,o={...r.httpsServerOptions,key:n?await gx(t,n,"key"):r.httpsServerOptions?.key,cert:i?await gx(t,i,"cert"):r.httpsServerOptions?.cert,ca:s?await gx(t,s,"ca"):r.httpsServerOptions?.ca},a=Object.fromEntries(Object.entries(o).filter(([A,c])=>c!==void 0));if(Object.keys(a).length!==0)return a}async function Fl(t,e){let r=t.cwd(),n=!!e.local||!e.projectId,i={workingDirectory:r,projectId:e.projectId,branchName:e.branchName,commitMode:"commits",mode:"init-and-launch",isLocal:n,allowedCommands:["npm *","pnpm *","yarn *","yarn","bun *","bun","gh *","wc *","gradle *","gradle","rg *","./gradlew *","./gradlew","expo *","expo","adb *","adb","vp *","vp","git *","export *","rails *","gem *","bundle *","rake *","echo *","cd *","find *","ls *","rm *","cp *","mv *","pwd","curl *","npx tsc *","head *","lsof *","kill *","ps *","tr *","awk *","cat *","grep *","sed *","tail *","touch *","mkdir *","tee *","true","uniq *","test *","false","npx *","sort *","env","dirname","basename *","realpath *","readlink *","stat *","file *","diff *","xargs *","chmod *","which *","whoami","uname *","uname","date","date *","printenv *","sleep *","netlify *","node *","tsx *","builderio *","builder *","open *","xcrun *","xcodebuild *","xcode-select *","xed *","agvtool *"]};if(e.configJson)try{let d=JSON.parse(e.configJson);i=Object.assign({},i,d),i.isLocal?n=!0:i.projectId&&(n=!1,i.isLocal=!1)}catch(d){t.Sentry?.captureException(d)}else{let d=await Dye(t,e);if(d&&await t.exists(d))try{let g=await t.readFile(d);if(g){let p=JSON.parse(g);i=Object.assign({},i,p)}}catch(g){t.Sentry?.captureException(g)}}i.command&&(i.devCommand||(i.devCommand=i.command),delete i.command);let s=e.c||e.command,o=e.p||e.port,a=e.installCommand,A=e.serverUrl,c=e.interactive&&!e.configJson&&!e.fusionInit&&n&&!e.chat;if(A)c=!1,i.serverUrl=A,s||(i.devCommand="");else if(s&&o){c=!1;let d="http://localhost";if(i.serverUrl)try{let g=new URL(i.serverUrl);d=`${g.protocol}//${g.hostname}`}catch{d="http://localhost"}i.serverUrl=`${d}:${o}`,i.devCommand=s}else s&&i.autoDetectDevServer&&(c=!1,i.devCommand=s);s&&o&&(c=!1),o&&!A&&(i.serverUrl=`http://localhost:${o}`),a&&(i.setupCommand=a),s&&(i.devCommand=s),s&&!i.serverUrl&&(i.autoDetectDevServer=!0,i.autoSuggestPort=!0),typeof e.authenticateProxy=="boolean"&&(i.authenticateProxy=e.authenticateProxy),typeof e.privacyMode=="boolean"&&e.privacyMode&&(i.privacyMode=Object.assign({},i.privacyMode,{enabled:!0})),typeof e.autoDetectDevServer=="boolean"&&(i.autoDetectDevServer=e.autoDetectDevServer);let u=e.runInPty??e["run-in-pty"];if(typeof u=="boolean"&&(i.runInPty=u),typeof e.https=="boolean"&&(i.https=e.https),e.localHttpsDomain&&(i.localHttpsDomain=e.localHttpsDomain),typeof e.nativeApp=="boolean"&&(i.nativeApp=e.nativeApp),e.disabledTools){let d=e.disabledTools.split(",").map(g=>g.trim());i.disabledTools=d}if(i.httpsServerOptions=await xft(t,e,i),c&&!e.chat){if(!i.devCommand){let d=await lr({message:"Enter the command to run for the dev server (e.g. 'npm run dev')",placeholder:"npm run dev",validate:g=>{if(g.trim()===""||g.length===0)return"Command cannot be empty"}});if(je(d))return Ke("Goodbye! \u{1F44B}"),await(0,L4.exit)(1);i.devCommand=d}if(!i.serverUrl){let d=await lr({message:"Enter the dev server URL to proxy to (e.g. http://localhost:3000)",placeholder:"http://localhost:3000",validate:p=>{let f=p.trim();if(!f)return"Dev server URL cannot be empty";if(/^\d+$/.test(f)){let m=Number(f);return m<0||m>65535?"Invalid port number, must be between 0 and 65535":void 0}try{new URL(f)}catch{return"Enter a valid URL or port number"}}});if(je(d))return Ke("Goodbye! \u{1F44B}"),await(0,L4.exit)(1);let g=d.trim();/^\d+$/.test(g)?i.serverUrl=`http://localhost:${g}`:i.serverUrl=new URL(g).href}await _4(t,i,e)}if(e.sessionId&&(i.sessionId=e.sessionId),typeof i.fusionServerPort=="string"){let d=parseInt(i.fusionServerPort);if(!isNaN(d))i.fusionServerPort=d;else throw new Error(`Invalid fusionServerPort: ${i.fusionServerPort}. Expected a number between 0 and 65535, got "${i.fusionServerPort}".`)}let l=i.privacyMode?.encryptionKeyPath;if(l&&i.privacyMode)try{let g=(await gx(t,l,"encryption key")).trim();i.privacyMode.encryptKey=g,delete i.privacyMode.encryptionKeyPath}catch(d){let g=new Error(`Failed to load encryption key from path: ${l}`,{cause:d});throw t.Sentry?.captureException(g),$.warn(g.message),g}return i}async function _4(t,e,r){let n=await Dye(t,r);await t.writeFile(n,JSON.stringify(Fft(e,"workingDirectory","projectId","authenticateProxy","privacyMode"),null,2))}function wye(t,e){let r=rv(e);t.Sentry?.setTag("isLocal",r.isLocal),t.Sentry?.setTag("commitMode",r.commitMode),t.Sentry?.setTag("pvcCreationSource",r.pvcCreationSource??"unknown"),t.Sentry?.setTag("snapshot",r.syncBranch?"true":"false");let n=r.workspace?.folders.find(i=>i.enableGit)?.originalRepoUrl;if(n){let i=gI.some(s=>n.endsWith(s))?n:"custom-repo";t.Sentry?.setTag("repoUrl",i)}t.Sentry?.setContext("fusionConfig",{...r}),t.Sentry?.getCurrentScope().setContext("fusionConfig",{...r})}var L4,Dye,Fft,NB=L(()=>{"use strict";h();Hs();rr();L4=require("process");Ap();Dye=async(t,e)=>{if(e.configPath){let A=t.resolve(t.cwd(),e.configPath);if(await t.exists(A))return A;throw new Error(`Fusion config file not found: ${A}`)}let r=["builder.config.json","fusion.config.json"],n=t.cwd(),i=t.join(n,r[0]),s=t.join(n,r[1]),o=await t.exists(i),a=await t.exists(s);if(o&&a)throw new Error(`Both builder.config.json and fusion.config.json were found in your project.
|
|
1938
1938
|
Please use only builder.config.json and remove fusion.config.json.
|
|
1939
|
-
You can migrate any settings from fusion.config.json to builder.config.json before removing it.`);for(let A of r){let c=t.join(n,A);if(await t.exists(c))return c}return t.join(n,r[0])},Fft=(t,...e)=>{let r={};if(t&&typeof t=="object")for(let n in t)(!t.hasOwnProperty||t.hasOwnProperty(n))&&(e.includes(n)||(r[n]=t[n]));return r}});function Rft(t){let e=[".npm",".local",".cache"];try{let r=`/${t}`,n=`/${t}-backup`;if(ei.existsSync(n)){let i=ei.readdirSync(n);for(let s of i)if(!e.includes(s)){let o=Ei.join(r,s);if(!ei.existsSync(o))try{ei.cpSync(Ei.join(n,s),o,{recursive:!0,force:!0})}catch(a){GH.error(`Failed to restore ${s} for ${t}: ${a}`)}}}}catch(r){GH.error(`Failed to restore ${t} backup: ${r}`)}}var ei,ti,Ei,UH,vye,px,GH,kft,bye,em,OH=L(()=>{"use strict";h();ei=z(require("node:fs"),1),ti=z(require("fs/promises"),1),Ei=z(require("node:path"),1);da();Ic();Hs();UH=z(require("dns/promises"),1);Bt();vye=z(require("net"),1),px=require("undici");Ov();xo();Ap();xo();GH=ve("Init"),kft=t=>!!(t.name&&t.path),bye=t=>!!(t.name&&t.path&&t.repoName&&t.repoUrl),em=class{logIdCounter=0;initStatusLogs=[];sys;config;debug=!0;#n=GH;initState={isRunning:!1,isComplete:!1,success:!1,currentStep:"initial",error:void 0,repos:[]};constructor(e){this.sys=e.sys,this.config=e,this.debug=e.debug??!0}async checkout(e,r,n){let i=r?["checkout","-B",e,r]:["checkout","-B",e];await this.git(i,n)}async execAsync(e,r,n,i){return Ws(e,r,{cwd:n,sys:this.sys,retry:i})}async git(e,r,n,i,s){return Ws("git",e,{cwd:r,sys:this.sys,retry:n,skipLogging:s,timeout:i??(e[0].includes("clone")?600*1e3:60*1e3)})}async performBackup({sys:e,credentials:r,fusionConfig:n,volumePath:i,repositories:s,isConnectedToProvider:o,forcedFullBackup:a}){try{this.#n.info("Performing backup operation");let A=s.filter(p=>p.enableGit);if(A.length===0)throw new Error("No repository with git enabled found for backup");if(!n.branchName)throw new Error("Backup mode: No branch name found");if(!n.projectId)throw new Error("Backup mode: No project ID found");let c=[];for(let p of A){let f=Ei.join(i,p.path);if(!ei.existsSync(f))throw new Error(`Backup mode: Repository directory does not exist at ${f}`);if(!ei.existsSync(Ei.join(f,".git")))throw new Error(`Backup mode: Git repository not initialized at ${f}`);let{featureBranch:m,currentBranch:C}=await iv({sys:e,gitWorkingDirectory:f,strict:!a});c.push({repo:p,repoPath:f,featureBranch:m,currentBranch:C})}let u={};for(let{repo:p,repoPath:f}of c)try{let m=await Ws("git",["rev-parse","HEAD"],{cwd:f,sys:e,skipLogging:!0});m.trim()&&(u[p.name||p.path]=m.trim())}catch{}await Gv(e,r,{commits:u,projectId:n.projectId,branchName:n.branchName},this.debug);let l=performance.now(),d=[];for(let{repo:p,repoPath:f,featureBranch:m,currentBranch:C}of c){this.#n.info(`Creating backup for AI branch: ${C} (${p.name||p.path})`);let I=await _v({sys:e,credentials:r,projectId:n.projectId,branchName:n.branchName,repoPath:f,aiBranch:C,featureBranch:m,workspace:n.workspace,isConnectedToProvider:o,forcedFullBackup:a,debug:!0,canAbortMerge:!1,folderName:p.name||p.path,repoUrl:p.originalRepoUrl??p.repoUrl});if(!I.success)throw new Error(`Backup upload failed for ${p.name||p.path}: ${I.reason||"Unknown error"}`);this.#n.info(`Backup uploaded successfully for ${p.name||p.path}`),d.push(I.backupEntry)}let g=performance.now()-l;await Uv(r,d,g,this.debug)}catch(A){let c=new Error("Failed to perform git backup",{cause:A});throw this.config.sys.Sentry?.captureException(c,{tags:{launchMode:this.config.fusionConfig.mode,forcedFullBackup:a,isConnectedToProvider:o}}),c}}async performRegularBackup(e){await this.performBackup({...e,isConnectedToProvider:!0,forcedFullBackup:!1})}async performOfflineBackup(e){await this.performBackup({...e,isConnectedToProvider:!1,forcedFullBackup:!1})}async performForcedFullBackup(e){await this.performBackup({...e,isConnectedToProvider:!1,forcedFullBackup:!0})}async init(){let e=this.config;this.clearInitLogs(),this.initState.isRunning=!0,this.initState.isComplete=!1;let r=e.fusionConfig.workspace?.folders?.filter(kft)??[];this.addInitLog("log",`Starting initialization with ${r.length} repositories`,{step:"init"});try{if(!r.length){let i="At least one repository must be configured";throw new Error(i)}if(!e.sys){let i="DevToolsSys is required in config";throw this.addInitLog("error",i,{step:"validation",error:i}),new Error(i)}let n=yE(e.fusionConfig);switch(e.fusionConfig.mode){case"backup":{try{await this.performRegularBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}catch(i){this.#n.info(`Online backup failed: ${i}. Attempting offline backup...`),await this.performOfflineBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}break}case"backup-force-full":{try{await this.performRegularBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}catch(i){this.#n.info(`Online backup failed: ${i}. Attempting offline backup...`);try{await this.performOfflineBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}catch(s){this.#n.info(`Offline backup failed: ${s}. Attempting forced full offline backup...`),await this.performForcedFullBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}}break}case"init-and-launch":{await this.step1CheckDirectories(n,r),this.addInitLog("log","Directories checked",{step:"check-directories"}),await this.step2ConfigureGitRepositories(n,r),this.addInitLog("log","Git repositories configured",{step:"configure-git-repos"}),await this.step3ConfigureGitUser(n,r),this.addInitLog("log","Git user configured",{step:"configure-git-user"}),await this.step4CollectRepoInfo(e,n,r),this.addInitLog("log","Repo info collected",{step:"collect-repo-info"});break}default:throw new Error(`Invalid mode: ${e.fusionConfig.mode}`)}return this.addInitLog("complete","Initialization completed successfully",{step:"init-success",success:!0}),!0}catch(n){let i=n instanceof Error?n.message:String(n),s=this.initStatusLogs.some(o=>o.type==="error"&&o.step&&o.step!=="init-failed");return this.addInitLog("complete",`Initialization failed with error: ${i}`,{step:s?void 0:"init-failed",success:!1,error:i}),e.sys.Sentry?.captureException(n,{tags:{operation:"init",...e.sentryTags}}),!1}}addInitLog(e,r,n){let i={id:++this.logIdCounter,timestamp:new Date().toISOString(),type:e,message:r,step:n?.step,error:n?.error,success:n?.success};this.#n.debug(`${i.type} ${i.message}`),this.initStatusLogs.push(i),this.initStatusLogs.length>1e3&&this.initStatusLogs.splice(0,this.initStatusLogs.length-1e3),n?.step&&(this.initState.currentStep=n.step),e==="complete"&&(this.initState.isComplete=!0,this.initState.isRunning=!1,this.initState.success=n?.success??!1,this.initState.error=n?.error??this.initState.error,n?.gitDiagnostics&&(this.initState.gitDiagnostics=n.gitDiagnostics)),e==="error"&&n?.error&&(this.initState.error=n.error,n?.gitDiagnostics&&(this.initState.gitDiagnostics=n.gitDiagnostics))}clearInitLogs(){this.initStatusLogs.length=0,this.logIdCounter=0,this.initState.isRunning=!1,this.initState.isComplete=!1,this.initState.success=!1,this.initState.currentStep="initial",this.initState.error=void 0,this.initState.gitDiagnostics=void 0}async hasFilesButNoGit(e){if(ei.existsSync(e))try{let n=(await ti.readdir(e)).length>0,i=ei.existsSync(Ei.join(e,".git"));return n&&!i}catch{return!1}return!1}async step1CheckDirectories(e,r){this.addInitLog("log","Checking directories",{step:"check-directories"}),ei.existsSync(e)||await ti.mkdir(e,{recursive:!0}),e.startsWith("/root")&&Rft("root"),this.addInitLog("log",`Volume directory exists: ${e}`,{step:"check-directories"});for(let n of r){let i=Ei.join(e,n.path);if(ei.existsSync(i))this.addInitLog("log",`Directory already exists: ${i}`,{step:"check-directories"});else{this.addInitLog("log",`Creating directory: ${i}`,{step:"create-directories"});try{await ti.mkdir(i,{recursive:!0})}catch(s){let o=`Failed to create directory for ${n.repoName} at ${i}: ${s}`;throw this.addInitLog("error",o,{step:"create-directories",error:o}),new Error(o,{cause:s})}}}}async step2ConfigureGitRepositories(e,r){this.addInitLog("log","Configuring git repositories",{step:"configure-git-repos"});let n=Ei.join(e,"temp-cloning"),i=async()=>{ei.existsSync(n)&&(this.addInitLog("log",`Removing temp cloning directory: ${n}`,{step:"configure-git-repos"}),await ti.rm(n,{recursive:!0,force:!0}))};await i(),this.addInitLog("log",`Creating temp cloning path: ${n}`,{step:"configure-git-repos"}),await ti.mkdir(n,{recursive:!0});let s=await this.fetchGitConfigsOnce(),o=r.find(a=>a.enableGit);try{for(let a of r){let A=Ei.join(e,a.path),c=a===o;this.addInitLog("log",`Processing repository: ${a.repoName}`,{step:"configure-git-repos"});let u=await this.isGitConfigured(A),l=!u;if(this.config.fusionConfig.rebuildGit&&u&&(this.addInitLog("log",`rebuildGit flag set, removing existing repo for ${a.repoName} to re-clone`,{step:"check-existing-git"}),await ti.rm(A,{recursive:!0,force:!0}),l=!0),u&&!l){if(a.enableGit&&s){let d=r.filter(g=>g.enableGit).length;this.applyGitConfig(a,s,c,d)}await this.cleanupLockFiles(A);try{a.enableGit?(this.addInitLog("log",`Git already configured for ${a.repoName}, validating repo`,{step:"check-existing-git"}),await this.validateGitRepo(A)):this.addInitLog("log",`Git already configured for ${a.repoName}, skipping validation because it's not main repo`,{step:"check-existing-git"})}catch(d){let g=`Git repo is in bad state for ${a.repoName}, will re-clone: ${d}`;this.config.sys.Sentry?.captureMessage(g,{level:"warning",tags:{operation:"init",...this.config.sentryTags},extra:{repoName:a.repoName,repoPath:A}}),this.addInitLog("error",g,{step:"check-existing-git",error:g})}if(!l){if(this.addInitLog("log","Git repo is in good state, checking remote URL",{step:"check-existing-git"}),a.initializationCommand){this.addInitLog("log","Skipping remote URL update because it has an initialization command",{step:"update-remote-url"});continue}if(!bye(a))throw new Error("Remote URL update failed because repoUrl is undefined");if(await this.getGitRemoteUrl(A))try{await this.git(["remote","set-url","origin",a.repoUrl],A)}catch(f){let m=`Failed to update git remote URL for ${a.repoName}: ${f}`;throw this.addInitLog("error",m,{step:"update-remote-url",error:m}),new Error(m)}else{this.addInitLog("log",`Adding remote origin for ${a.repoName}`,{step:"check-existing-git"});try{await this.git(["remote","add","origin",a.repoUrl],A)}catch(f){let m=`Failed to add git remote origin for ${a.repoName}: ${f}`;throw this.addInitLog("error",m,{step:"check-existing-git",error:m}),new Error(m)}}let g=this.config.fusionConfig.branchType==="code-review",p=this.config.fusionConfig.prNumber;if(g&&c&&p!=null){let f=this.config.fusionConfig.isFork,m=this.config.fusionConfig.featureBranch;if(!f&&!m)throw new Error(`Non-fork PR #${p} requires featureBranch in fusion config to know which branch to fetch from origin`);let C=m||`pr-${p}`,I=f?`pull/${p}/head`:C,y=this.config.fusionConfig.aiBranch||C;this.addInitLog("log",`${f?"Fork ":""}PR detected on already-cloned primary - syncing PR #${p} into branch ${y}`,{step:"clone-repo"});try{await this.git(["fetch","origin",I],A);let B=(await this.git(["rev-parse","FETCH_HEAD"],A)).trim();await this.checkout(y,B,A),this.addInitLog("log",`Checked out PR #${p} on branch ${y}`,{step:"clone-repo"})}catch(B){let E=`Failed to sync PR #${p} on primary repo ${a.repoName}: ${B}`;throw this.addInitLog("error",E,{step:"clone-repo",error:E}),new Error(E,{cause:B})}}if(this.config.fusionConfig.syncBranch&&a.enableGit&&(!g||!c)){let f=a.branchName||"main";try{let m=(await this.git(["rev-parse","HEAD"],A)).trim(),I=(await this.git(["ls-remote","origin",f],A)).trim().split(/\s/)[0]||"";m===I?this.addInitLog("log",`Snapshot git is already up-to-date with origin/${f}`,{step:"snapshot-git-sync"}):(this.addInitLog("log",`Snapshot git is behind origin/${f}, syncing...`,{step:"snapshot-git-sync"}),await this.git(["pull","--ff-only","origin",f],A),this.addInitLog("log",`Git synced to origin/${f}`,{step:"snapshot-git-sync"}))}catch(m){this.addInitLog("error",`Failed to sync git from snapshot: ${m}`,{step:"snapshot-git-sync",error:String(m)})}}if(this.config.fusionConfig.pvcCreationSource==="snapshot"&&a.backupMetadata&&a.enableGit){let f=this.config.fusionConfig.aiBranch||a.backupMetadata.check.backup.gitBranchName;if(await this.isBackupAlreadyApplied(A,f,a.backupMetadata.check.backup.lastCommitHash))this.addInitLog("log",`Backup already applied for ${a.repoName} (branch ${f} exists), skipping restore`,{step:"snapshot-backup-restore"}),await this.git(["checkout",f],A);else{this.addInitLog("log",`Snapshot volume detected with backup, downloading backup for ${a.repoName}`,{step:"snapshot-backup-restore"});let C=await s8(this.config.sys,a.backupMetadata);if(C.success)try{await this.restoreFromPartialBackup({repo:a,repoPath:A,backupResult:C}),this.addInitLog("log",`Restored backup on snapshot volume for ${a.repoName}`,{step:"snapshot-backup-restore"})}catch(I){throw this.addInitLog("error",`Failed to restore backup on snapshot volume: ${I}`,{step:"snapshot-backup-restore",error:String(I)}),I}else throw this.addInitLog("error",`Failed to download backup for snapshot restore: ${C.error}`,{step:"snapshot-backup-restore",error:C.error.message}),C.error}}}}if(l){if(await this.hasFilesButNoGit(A)){let m="Code directory already exists but is not a git repo";throw this.addInitLog("error",m,{step:"check-existing-git",error:m}),new Error(m)}let g=a.backupMetadata?await s8(this.config.sys,a.backupMetadata):void 0;if(g&&!g.success)throw this.addInitLog("error",`Failed to download backup for ${a.repoName}: ${g.error}`,{step:"clone-repo",error:g.error.message}),g.error;g?.success&&this.sys.Sentry?.setTag("backup",g.partial?"partial":"full");let p=Ei.join(n,a.path),f=!1;if(a.initializationCommand){this.addInitLog("log","Running initialization command.",{step:"init-command"});let m=await this.runInitializationCommand({repo:a,tempCloningDir:n,repoPath:p,initCommand:a.initializationCommand});if(f=m.outcome,f)this.addInitLog("log",`Successfully initialized ${a.repoName}`,{step:"init-command"});else{let C=m.error?.message||"Failed to run initialization command.";throw this.addInitLog("error",C,{step:"init-command",error:C}),new Error(C)}}else{if(!bye(a))throw new Error("repoUrl or repoName is undefined");if(this.addInitLog("log",`Cloning repository: ${a.repoName}`,{step:"clone-repo"}),f=await this.cloneRepository({repo:a,repoPath:p,backupResult:g,isPrimary:c}),f)this.addInitLog("log",`Successfully cloned ${a.repoName}`,{step:"clone-repo"});else{let m=`Failed to clone repository ${a.repoName}`;throw this.addInitLog("error",m,{step:"clone-repo",error:m}),new Error(m)}}if(g&&g.success&&g.partial)try{await this.restoreFromPartialBackup({repo:a,repoPath:p,backupResult:g})}catch(m){throw m}if(process.platform==="win32"&&ei.existsSync(A)){if((await ti.readdir(A)).length>0){let C=`Target directory ${A} already exists and is not empty. Cannot safely rename.`;throw this.addInitLog("error",C,{step:"configure-git-repos",error:C}),new Error(C)}this.addInitLog("log",`Removing empty directory before rename (Windows workaround): ${A}`,{step:"configure-git-repos"}),await ti.rm(A,{recursive:!0,force:!0})}await ti.rename(p,A),await this.markGitSafe(A)}}}catch(a){throw this.addInitLog("error",`Failed to configure git repositories: ${a}`,{step:"configure-git-repos",error:String(a)}),a}finally{await i()}}async step3ConfigureGitUser(e,r){this.addInitLog("log","Configuring git user",{step:"configure-git-user"});for(let n of r){let i=Ei.join(e,n.path);this.addInitLog("log",`Setting git user for ${n.repoName}`,{step:"configure-git-user"});try{await this.git(["config","user.email","builder-bot@builder.io"],i),await this.git(["config","user.name","Builder.io"],i)}catch(s){let o=`Failed to configure git user for ${n.repoName}: ${s}`;throw this.addInitLog("error",o,{step:"configure-git-user",error:o}),new Error(o)}}}async step4CollectRepoInfo(e,r,n){this.addInitLog("log","Collecting repo info",{step:"collect-repo-info"}),this.initState.repos=[];for(let i of n){let s=Ei.join(r,i.path);try{let o=await this.git(["rev-parse","HEAD"],s),a=await this.git(["branch","--show-current"],s),A={repoName:i.repoName||i.path,enabledGit:!!i.enableGit,lastCommitHash:o.trim(),branch:a.trim()};this.initState.repos.push(A),this.addInitLog("log",`Collected repo info: ${JSON.stringify(A)}`,{step:"collect-repo-info"})}catch(o){e.sys.Sentry?.captureException(o,{tags:{operation:"init",...e.sentryTags}})}}}async isGitConfigured(e){try{return await this.git(["rev-parse","--is-inside-work-tree"],e,void 0,void 0,!0),!0}catch{return!1}}async getGitRemoteUrl(e){try{return(await this.git(["config","--get","remote.origin.url"],e)).trim()}catch{return null}}isStandardGitHost(e){let r=["github.com","gitlab.com","bitbucket.org"];try{let n=new URL(e);return r.some(i=>n.hostname===i||n.hostname.endsWith(`.${i}`))}catch{return!1}}async checkHostConnectivity(e){try{let r=e.startsWith("git@")||e.startsWith("ssh://"),n,i;if(r){let s=e.match(/^(?:ssh:\/\/)?(?:[^@]+@)?([^/:]+)(?::|\/)/);if(!s)return{reachable:!1,error:"Invalid SSH repository URL format"};n=s[1],i=22}else{let s=e.match(/^https?:\/\/(?:[^@]+@)?([^/:?#]+)/);if(!s)return{reachable:!1,error:"Invalid repository URL format"};n=s[1],i=443}this.addInitLog("log",`Checking connectivity to host: ${n}:${i}`,{step:"clone-repo"});try{let s=[];try{s=await UH.default.resolve4(n),s.length>0&&this.addInitLog("log",`DNS resolved ${n} to IPv4: ${s.join(", ")}`,{step:"clone-repo"})}catch{s=await UH.default.resolve6(n),s.length>0&&this.addInitLog("log",`DNS resolved ${n} to IPv6: ${s.join(", ")}`,{step:"clone-repo"})}if(s.length===0)return{reachable:!1,hostname:n,error:`DNS resolution failed: no addresses found for ${n}`}}catch(s){let o=s instanceof Error?s.message:String(s);return{reachable:!1,hostname:n,error:`DNS resolution failed for ${n}: ${o}`}}try{let s=await this.checkConnectivityDirect(n,i);if(s.reachable)return s;let o=process.env.HTTP_PROXY||process.env.http_proxy;return o?(this.addInitLog("log",`Direct connection failed, trying proxy: ${o}`,{step:"clone-repo"}),await this.checkConnectivityViaProxy(n,i,o)):s}catch(s){let o=s instanceof Error?s.message:String(s);return{reachable:!1,hostname:n,error:`Connection attempt failed: ${o}`}}}catch(r){return{reachable:!1,error:`Unexpected error during connectivity check: ${r instanceof Error?r.message:String(r)}`}}}async checkConnectivityDirect(e,r){let i=vye.default.createConnection({host:e,port:r,timeout:5e3});return await new Promise(s=>{i.on("connect",()=>{i.destroy(),this.addInitLog("log",`Successfully connected to ${e}:${r}`,{step:"clone-repo"}),s({reachable:!0,hostname:e})}),i.on("error",o=>{i.destroy(),this.addInitLog("error",`Connection failed to ${e}:${r}: ${o.message}`,{step:"clone-repo",error:o.message}),s({reachable:!1,hostname:e,error:`Cannot connect to ${e}:${r}: ${o.message}`})}),i.on("timeout",()=>{i.destroy(),this.addInitLog("error",`Connection timeout to ${e}:${r} (${5e3/1e3}s)`,{step:"clone-repo",error:`Connection timeout to ${e}:${r} after ${5e3/1e3} seconds`}),s({reachable:!1,hostname:e,error:`Connection timeout to ${e}:${r} after ${5e3/1e3} seconds`})})})}async checkConnectivityViaProxy(e,r,n){try{this.addInitLog("log",`Attempting proxy connection to ${e}:${r} via proxy`,{step:"clone-repo"});let i=new URL(n),s=`${i.protocol}//${i.host}`,o=new px.ProxyAgent({uri:s,token:i.username&&i.password?`Basic ${Buffer.from(`${i.username}:${i.password}`).toString("base64")}`:void 0}),a=r===443?`https://${e}`:`http://${e}:${r}`;return await(0,px.fetch)(a,{dispatcher:o,signal:AbortSignal.timeout(3e4)}),this.addInitLog("log",`Successfully connected via proxy to ${e}:${r}`,{step:"clone-repo"}),{reachable:!0,hostname:e}}catch(i){return{reachable:!1,hostname:e,error:`Proxy connection failed: ${i instanceof Error?i.message:String(i)}`}}}async ensureParentDirExists(e){let r=Ei.dirname(e);return await ti.mkdir(r,{recursive:!0}),r}async cleanupLockFiles(e){let r=Ei.join(e,".git");try{let i=(await ti.readdir(r)).filter(o=>o.endsWith(".lock"));if(i.length===0)return;let s=[];for(let o of i){let a=Ei.join(r,o);try{await ti.unlink(a),s.push(o)}catch(A){this.config.sys.Sentry?.captureException(new Error(`Failed to remove ${o} for ${e}: ${A}`),{tags:{operation:"init",...this.config.sentryTags}})}}s.length>0&&this.config.sys.Sentry?.captureMessage(`Lock files found for ${e} and removed: ${s.join(", ")}`,{tags:{operation:"init",...this.config.sentryTags}})}catch(n){this.config.sys.Sentry?.captureException(new Error(`Failed to cleanup lock files for ${e}: ${n}`),{tags:{operation:"init",...this.config.sentryTags}})}}async validateGitRepo(e){try{await this.git(["fsck","--connectivity-only"],e)}catch(r){throw new Error("Git repo is in bad state",{cause:r})}}async isBackupAlreadyApplied(e,r,n){try{let i=(await this.git(["rev-parse","--verify",`refs/heads/${r}`],e)).trim();return i?(await this.git(["merge-base","--is-ancestor",n,i],e),!0):!1}catch{return!1}}async restoreFromPartialBackup({repo:e,repoPath:r,backupResult:n}){try{this.addInitLog("log",`Checking for git backup for ${e.repoName}`,{step:"apply-partial-backup"});let i=async()=>{try{await this.git(["remote","remove","backup"],r)}catch(s){this.addInitLog("error",`Failed to cleanup restore: ${s}`,{step:"apply-partial-backup",error:String(s)})}};if(!n.bundlePath){try{this.addInitLog("log",`Found empty git backup, applying it to ${e.repoName}`,{step:"apply-partial-backup"});let s=this.config.fusionConfig.aiBranch||n.gitBranchName;s&&await this.checkout(s,n.lastCommitHash||void 0,r)}catch(s){if(n.lastCommitHash)throw s;this.addInitLog("log",`Empty backup \u2014 could not create branch (repo may have no commits yet): ${s}`,{step:"apply-partial-backup"})}return}try{this.addInitLog("log",`Found git backup, applying it to ${e.repoName}`,{step:"apply-partial-backup"});try{await this.git(["remote","remove","backup"],r)}catch{}await this.git(["remote","add","backup",n.bundlePath],r),await this.git(["fetch","backup"],r);let s=n.gitBranchName,o=this.config.fusionConfig.aiBranch||s;o!==s?(this.addInitLog("log",`Creating new branch ${o} from backup/${s}`,{step:"apply-partial-backup"}),await this.git(["branch",o,`backup/${s}`],r),await this.git(["checkout",o],r)):await this.checkout(s,`backup/${s}`,r),this.addInitLog("log",`Successfully restored from backup to branch ${o}`,{step:"apply-partial-backup"}),await i(),this.addInitLog("log",`Cleaned up backup for ${e.repoName}`,{step:"apply-partial-backup"})}catch(s){throw await i(),this.addInitLog("error",String(s),{step:"apply-partial-backup",error:String(s)}),s}}catch(i){let s=new Error(`Failed to check git backup for ${e.repoName}. Cannot proceed without backup recovery.`,{cause:i});throw this.addInitLog("error",s.message,{step:"apply-partial-backup",error:String(i)}),s}}async initializeGitRepo(e,r){await this.git(["init"],e),await this.git(["add","."],e),await this.git(["branch","-M","main"],e),await this.git([...r?["-c","user.email=team@builder.io","-c","user.name=Builder.io"]:[],"commit","-m","Initial setup"],e)}async fetchGitConfigsOnce(){if(this.config.fusionConfig.projectId)try{let e=await hh(this.config.credentials,this.config.fusionConfig.projectId,this.debug);if(e.success)return Object.keys(e.gitConfigs).length>0?e.gitConfigs:void 0;e.gitDiagnostics&&(this.initState.gitDiagnostics=e.gitDiagnostics),this.config.sys.Sentry?.captureException(e.error,{tags:{operation:"init",endpoint:"fetch-git-configs",...this.config.sentryTags},extra:{gitDiagnostics:e.gitDiagnostics}})}catch(e){this.config.sys.Sentry?.captureException(new Error("Failed to fetch git configs in InitStateMachine",{cause:e instanceof Error?e:new Error(String(e))}),{tags:{operation:"init",endpoint:"fetch-git-configs",...this.config.sentryTags}})}}applyGitConfig(e,r,n,i){if(e.initializationCommand||e.repoUrl?.startsWith("ssh://")||e.repoUrl?.startsWith("git@"))return;let s;if(e.repoName&&r[e.repoName]?s=e.repoName:n&&(s=Object.keys(r)[0]),!s)return;let o=r[s];o?.url&&(e.repoUrl=o.url,n&&(e.repoName=s),(o.provider==="github"||o.provider==="selfHostedGithub")&&o.token&&(n&&(process.env.GH_TOKEN=o.token),i>1&&(process.env[lx(e.name)]=o.token)))}async runInitializationCommand({repo:e,tempCloningDir:r,repoPath:n,initCommand:i}){this.addInitLog("log",`Init command paths args: tempCloningDir: ${r} repoPath: ${n}`,{step:"init-command"});try{this.addInitLog("log",`Executing initialization command in ${r}`,{step:"init-command"});let s=process.env.SHELL||process.env.COMSPEC||"/bin/sh";try{let o=mA(s,i,{stdio:["ignore","pipe","pipe"],cwd:r,env:{...process.env,TERM:"dumb"}},!0),a=[],A=[];o.stdout?.on("data",c=>{a.push(c);let u=c.toString().trim();u&&this.addInitLog("log",u,{step:"init-command"})}),o.stderr?.on("data",c=>{A.push(c);let u=c.toString().trim();u&&this.addInitLog("error",u,{step:"init-command"})}),await new Promise((c,u)=>{o.on("error",l=>{u(l)}),o.on("close",l=>{if(l===0)c();else{let d=Buffer.concat(a).toString().trim(),g=Buffer.concat(A).toString().trim(),p=[`Command exited with code ${l}`,g&&`stderr: ${g}`,d&&`stdout: ${d}`].filter(Boolean).join(`
|
|
1939
|
+
You can migrate any settings from fusion.config.json to builder.config.json before removing it.`);for(let A of r){let c=t.join(n,A);if(await t.exists(c))return c}return t.join(n,r[0])},Fft=(t,...e)=>{let r={};if(t&&typeof t=="object")for(let n in t)(!t.hasOwnProperty||t.hasOwnProperty(n))&&(e.includes(n)||(r[n]=t[n]));return r}});function Rft(t){let e=[".npm",".local",".cache"];try{let r=`/${t}`,n=`/${t}-backup`;if(ei.existsSync(n)){let i=ei.readdirSync(n);for(let s of i)if(!e.includes(s)){let o=Ei.join(r,s);if(!ei.existsSync(o))try{ei.cpSync(Ei.join(n,s),o,{recursive:!0,force:!0})}catch(a){G4.error(`Failed to restore ${s} for ${t}: ${a}`)}}}}catch(r){G4.error(`Failed to restore ${t} backup: ${r}`)}}var ei,ti,Ei,U4,vye,px,G4,kft,bye,em,O4=L(()=>{"use strict";h();ei=z(require("node:fs"),1),ti=z(require("fs/promises"),1),Ei=z(require("node:path"),1);da();Ic();Hs();U4=z(require("dns/promises"),1);Bt();vye=z(require("net"),1),px=require("undici");Ov();xo();Ap();xo();G4=ve("Init"),kft=t=>!!(t.name&&t.path),bye=t=>!!(t.name&&t.path&&t.repoName&&t.repoUrl),em=class{logIdCounter=0;initStatusLogs=[];sys;config;debug=!0;#n=G4;initState={isRunning:!1,isComplete:!1,success:!1,currentStep:"initial",error:void 0,repos:[]};constructor(e){this.sys=e.sys,this.config=e,this.debug=e.debug??!0}async checkout(e,r,n){let i=r?["checkout","-B",e,r]:["checkout","-B",e];await this.git(i,n)}async execAsync(e,r,n,i){return Ws(e,r,{cwd:n,sys:this.sys,retry:i})}async git(e,r,n,i,s){return Ws("git",e,{cwd:r,sys:this.sys,retry:n,skipLogging:s,timeout:i??(e[0].includes("clone")?600*1e3:60*1e3)})}async performBackup({sys:e,credentials:r,fusionConfig:n,volumePath:i,repositories:s,isConnectedToProvider:o,forcedFullBackup:a}){try{this.#n.info("Performing backup operation");let A=s.filter(p=>p.enableGit);if(A.length===0)throw new Error("No repository with git enabled found for backup");if(!n.branchName)throw new Error("Backup mode: No branch name found");if(!n.projectId)throw new Error("Backup mode: No project ID found");let c=[];for(let p of A){let f=Ei.join(i,p.path);if(!ei.existsSync(f))throw new Error(`Backup mode: Repository directory does not exist at ${f}`);if(!ei.existsSync(Ei.join(f,".git")))throw new Error(`Backup mode: Git repository not initialized at ${f}`);let{featureBranch:m,currentBranch:C}=await iv({sys:e,gitWorkingDirectory:f,strict:!a});c.push({repo:p,repoPath:f,featureBranch:m,currentBranch:C})}let u={};for(let{repo:p,repoPath:f}of c)try{let m=await Ws("git",["rev-parse","HEAD"],{cwd:f,sys:e,skipLogging:!0});m.trim()&&(u[p.name||p.path]=m.trim())}catch{}await Gv(e,r,{commits:u,projectId:n.projectId,branchName:n.branchName},this.debug);let l=performance.now(),d=[];for(let{repo:p,repoPath:f,featureBranch:m,currentBranch:C}of c){this.#n.info(`Creating backup for AI branch: ${C} (${p.name||p.path})`);let I=await _v({sys:e,credentials:r,projectId:n.projectId,branchName:n.branchName,repoPath:f,aiBranch:C,featureBranch:m,workspace:n.workspace,isConnectedToProvider:o,forcedFullBackup:a,debug:!0,canAbortMerge:!1,folderName:p.name||p.path,repoUrl:p.originalRepoUrl??p.repoUrl});if(!I.success)throw new Error(`Backup upload failed for ${p.name||p.path}: ${I.reason||"Unknown error"}`);this.#n.info(`Backup uploaded successfully for ${p.name||p.path}`),d.push(I.backupEntry)}let g=performance.now()-l;await Uv(r,d,g,this.debug)}catch(A){let c=new Error("Failed to perform git backup",{cause:A});throw this.config.sys.Sentry?.captureException(c,{tags:{launchMode:this.config.fusionConfig.mode,forcedFullBackup:a,isConnectedToProvider:o}}),c}}async performRegularBackup(e){await this.performBackup({...e,isConnectedToProvider:!0,forcedFullBackup:!1})}async performOfflineBackup(e){await this.performBackup({...e,isConnectedToProvider:!1,forcedFullBackup:!1})}async performForcedFullBackup(e){await this.performBackup({...e,isConnectedToProvider:!1,forcedFullBackup:!0})}async init(){let e=this.config;this.clearInitLogs(),this.initState.isRunning=!0,this.initState.isComplete=!1;let r=e.fusionConfig.workspace?.folders?.filter(kft)??[];this.addInitLog("log",`Starting initialization with ${r.length} repositories`,{step:"init"});try{if(!r.length){let i="At least one repository must be configured";throw new Error(i)}if(!e.sys){let i="DevToolsSys is required in config";throw this.addInitLog("error",i,{step:"validation",error:i}),new Error(i)}let n=yE(e.fusionConfig);switch(e.fusionConfig.mode){case"backup":{try{await this.performRegularBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}catch(i){this.#n.info(`Online backup failed: ${i}. Attempting offline backup...`),await this.performOfflineBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}break}case"backup-force-full":{try{await this.performRegularBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}catch(i){this.#n.info(`Online backup failed: ${i}. Attempting offline backup...`);try{await this.performOfflineBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}catch(s){this.#n.info(`Offline backup failed: ${s}. Attempting forced full offline backup...`),await this.performForcedFullBackup({sys:e.sys,credentials:e.credentials,fusionConfig:e.fusionConfig,volumePath:n,repositories:r})}}break}case"init-and-launch":{await this.step1CheckDirectories(n,r),this.addInitLog("log","Directories checked",{step:"check-directories"}),await this.step2ConfigureGitRepositories(n,r),this.addInitLog("log","Git repositories configured",{step:"configure-git-repos"}),await this.step3ConfigureGitUser(n,r),this.addInitLog("log","Git user configured",{step:"configure-git-user"}),await this.step4CollectRepoInfo(e,n,r),this.addInitLog("log","Repo info collected",{step:"collect-repo-info"});break}default:throw new Error(`Invalid mode: ${e.fusionConfig.mode}`)}return this.addInitLog("complete","Initialization completed successfully",{step:"init-success",success:!0}),!0}catch(n){let i=n instanceof Error?n.message:String(n),s=this.initStatusLogs.some(o=>o.type==="error"&&o.step&&o.step!=="init-failed");return this.addInitLog("complete",`Initialization failed with error: ${i}`,{step:s?void 0:"init-failed",success:!1,error:i}),e.sys.Sentry?.captureException(n,{tags:{operation:"init",...e.sentryTags}}),!1}}addInitLog(e,r,n){let i={id:++this.logIdCounter,timestamp:new Date().toISOString(),type:e,message:r,step:n?.step,error:n?.error,success:n?.success};this.#n.debug(`${i.type} ${i.message}`),this.initStatusLogs.push(i),this.initStatusLogs.length>1e3&&this.initStatusLogs.splice(0,this.initStatusLogs.length-1e3),n?.step&&(this.initState.currentStep=n.step),e==="complete"&&(this.initState.isComplete=!0,this.initState.isRunning=!1,this.initState.success=n?.success??!1,this.initState.error=n?.error??this.initState.error,n?.gitDiagnostics&&(this.initState.gitDiagnostics=n.gitDiagnostics)),e==="error"&&n?.error&&(this.initState.error=n.error,n?.gitDiagnostics&&(this.initState.gitDiagnostics=n.gitDiagnostics))}clearInitLogs(){this.initStatusLogs.length=0,this.logIdCounter=0,this.initState.isRunning=!1,this.initState.isComplete=!1,this.initState.success=!1,this.initState.currentStep="initial",this.initState.error=void 0,this.initState.gitDiagnostics=void 0}async hasFilesButNoGit(e){if(ei.existsSync(e))try{let n=(await ti.readdir(e)).length>0,i=ei.existsSync(Ei.join(e,".git"));return n&&!i}catch{return!1}return!1}async step1CheckDirectories(e,r){this.addInitLog("log","Checking directories",{step:"check-directories"}),ei.existsSync(e)||await ti.mkdir(e,{recursive:!0}),e.startsWith("/root")&&Rft("root"),this.addInitLog("log",`Volume directory exists: ${e}`,{step:"check-directories"});for(let n of r){let i=Ei.join(e,n.path);if(ei.existsSync(i))this.addInitLog("log",`Directory already exists: ${i}`,{step:"check-directories"});else{this.addInitLog("log",`Creating directory: ${i}`,{step:"create-directories"});try{await ti.mkdir(i,{recursive:!0})}catch(s){let o=`Failed to create directory for ${n.repoName} at ${i}: ${s}`;throw this.addInitLog("error",o,{step:"create-directories",error:o}),new Error(o,{cause:s})}}}}async step2ConfigureGitRepositories(e,r){this.addInitLog("log","Configuring git repositories",{step:"configure-git-repos"});let n=Ei.join(e,"temp-cloning"),i=async()=>{ei.existsSync(n)&&(this.addInitLog("log",`Removing temp cloning directory: ${n}`,{step:"configure-git-repos"}),await ti.rm(n,{recursive:!0,force:!0}))};await i(),this.addInitLog("log",`Creating temp cloning path: ${n}`,{step:"configure-git-repos"}),await ti.mkdir(n,{recursive:!0});let s=await this.fetchGitConfigsOnce(),o=r.find(a=>a.enableGit);try{for(let a of r){let A=Ei.join(e,a.path),c=a===o;this.addInitLog("log",`Processing repository: ${a.repoName}`,{step:"configure-git-repos"});let u=await this.isGitConfigured(A),l=!u;if(this.config.fusionConfig.rebuildGit&&u&&(this.addInitLog("log",`rebuildGit flag set, removing existing repo for ${a.repoName} to re-clone`,{step:"check-existing-git"}),await ti.rm(A,{recursive:!0,force:!0}),l=!0),u&&!l){if(a.enableGit&&s){let d=r.filter(g=>g.enableGit).length;this.applyGitConfig(a,s,c,d)}await this.cleanupLockFiles(A);try{a.enableGit?(this.addInitLog("log",`Git already configured for ${a.repoName}, validating repo`,{step:"check-existing-git"}),await this.validateGitRepo(A)):this.addInitLog("log",`Git already configured for ${a.repoName}, skipping validation because it's not main repo`,{step:"check-existing-git"})}catch(d){let g=`Git repo is in bad state for ${a.repoName}, will re-clone: ${d}`;this.config.sys.Sentry?.captureMessage(g,{level:"warning",tags:{operation:"init",...this.config.sentryTags},extra:{repoName:a.repoName,repoPath:A}}),this.addInitLog("error",g,{step:"check-existing-git",error:g})}if(!l){if(this.addInitLog("log","Git repo is in good state, checking remote URL",{step:"check-existing-git"}),a.initializationCommand){this.addInitLog("log","Skipping remote URL update because it has an initialization command",{step:"update-remote-url"});continue}if(!bye(a))throw new Error("Remote URL update failed because repoUrl is undefined");if(await this.getGitRemoteUrl(A))try{await this.git(["remote","set-url","origin",a.repoUrl],A)}catch(f){let m=`Failed to update git remote URL for ${a.repoName}: ${f}`;throw this.addInitLog("error",m,{step:"update-remote-url",error:m}),new Error(m)}else{this.addInitLog("log",`Adding remote origin for ${a.repoName}`,{step:"check-existing-git"});try{await this.git(["remote","add","origin",a.repoUrl],A)}catch(f){let m=`Failed to add git remote origin for ${a.repoName}: ${f}`;throw this.addInitLog("error",m,{step:"check-existing-git",error:m}),new Error(m)}}let g=this.config.fusionConfig.branchType==="code-review",p=this.config.fusionConfig.prNumber;if(g&&c&&p!=null){let f=this.config.fusionConfig.isFork,m=this.config.fusionConfig.featureBranch;if(!f&&!m)throw new Error(`Non-fork PR #${p} requires featureBranch in fusion config to know which branch to fetch from origin`);let C=m||`pr-${p}`,I=f?`pull/${p}/head`:C,y=this.config.fusionConfig.aiBranch||C;this.addInitLog("log",`${f?"Fork ":""}PR detected on already-cloned primary - syncing PR #${p} into branch ${y}`,{step:"clone-repo"});try{await this.git(["fetch","origin",I],A);let B=(await this.git(["rev-parse","FETCH_HEAD"],A)).trim();await this.checkout(y,B,A),this.addInitLog("log",`Checked out PR #${p} on branch ${y}`,{step:"clone-repo"})}catch(B){let E=`Failed to sync PR #${p} on primary repo ${a.repoName}: ${B}`;throw this.addInitLog("error",E,{step:"clone-repo",error:E}),new Error(E,{cause:B})}}if(this.config.fusionConfig.syncBranch&&a.enableGit&&(!g||!c)){let f=a.branchName||"main";try{let m=(await this.git(["rev-parse","HEAD"],A)).trim(),I=(await this.git(["ls-remote","origin",f],A)).trim().split(/\s/)[0]||"";m===I?this.addInitLog("log",`Snapshot git is already up-to-date with origin/${f}`,{step:"snapshot-git-sync"}):(this.addInitLog("log",`Snapshot git is behind origin/${f}, syncing...`,{step:"snapshot-git-sync"}),await this.git(["pull","--ff-only","origin",f],A),this.addInitLog("log",`Git synced to origin/${f}`,{step:"snapshot-git-sync"}))}catch(m){this.addInitLog("error",`Failed to sync git from snapshot: ${m}`,{step:"snapshot-git-sync",error:String(m)})}}if(this.config.fusionConfig.pvcCreationSource==="snapshot"&&a.backupMetadata&&a.enableGit){let f=this.config.fusionConfig.aiBranch||a.backupMetadata.check.backup.gitBranchName;if(await this.isBackupAlreadyApplied(A,f,a.backupMetadata.check.backup.lastCommitHash))this.addInitLog("log",`Backup already applied for ${a.repoName} (branch ${f} exists), skipping restore`,{step:"snapshot-backup-restore"}),await this.git(["checkout",f],A);else{this.addInitLog("log",`Snapshot volume detected with backup, downloading backup for ${a.repoName}`,{step:"snapshot-backup-restore"});let C=await s8(this.config.sys,a.backupMetadata);if(C.success)try{await this.restoreFromPartialBackup({repo:a,repoPath:A,backupResult:C}),this.addInitLog("log",`Restored backup on snapshot volume for ${a.repoName}`,{step:"snapshot-backup-restore"})}catch(I){throw this.addInitLog("error",`Failed to restore backup on snapshot volume: ${I}`,{step:"snapshot-backup-restore",error:String(I)}),I}else throw this.addInitLog("error",`Failed to download backup for snapshot restore: ${C.error}`,{step:"snapshot-backup-restore",error:C.error.message}),C.error}}}}if(l){if(await this.hasFilesButNoGit(A)){let m="Code directory already exists but is not a git repo";throw this.addInitLog("error",m,{step:"check-existing-git",error:m}),new Error(m)}let g=a.backupMetadata?await s8(this.config.sys,a.backupMetadata):void 0;if(g&&!g.success)throw this.addInitLog("error",`Failed to download backup for ${a.repoName}: ${g.error}`,{step:"clone-repo",error:g.error.message}),g.error;g?.success&&this.sys.Sentry?.setTag("backup",g.partial?"partial":"full");let p=Ei.join(n,a.path),f=!1;if(a.initializationCommand){this.addInitLog("log","Running initialization command.",{step:"init-command"});let m=await this.runInitializationCommand({repo:a,tempCloningDir:n,repoPath:p,initCommand:a.initializationCommand});if(f=m.outcome,f)this.addInitLog("log",`Successfully initialized ${a.repoName}`,{step:"init-command"});else{let C=m.error?.message||"Failed to run initialization command.";throw this.addInitLog("error",C,{step:"init-command",error:C}),new Error(C)}}else{if(!bye(a))throw new Error("repoUrl or repoName is undefined");if(this.addInitLog("log",`Cloning repository: ${a.repoName}`,{step:"clone-repo"}),f=await this.cloneRepository({repo:a,repoPath:p,backupResult:g,isPrimary:c}),f)this.addInitLog("log",`Successfully cloned ${a.repoName}`,{step:"clone-repo"});else{let m=`Failed to clone repository ${a.repoName}`;throw this.addInitLog("error",m,{step:"clone-repo",error:m}),new Error(m)}}if(g&&g.success&&g.partial)try{await this.restoreFromPartialBackup({repo:a,repoPath:p,backupResult:g})}catch(m){throw m}if(process.platform==="win32"&&ei.existsSync(A)){if((await ti.readdir(A)).length>0){let C=`Target directory ${A} already exists and is not empty. Cannot safely rename.`;throw this.addInitLog("error",C,{step:"configure-git-repos",error:C}),new Error(C)}this.addInitLog("log",`Removing empty directory before rename (Windows workaround): ${A}`,{step:"configure-git-repos"}),await ti.rm(A,{recursive:!0,force:!0})}await ti.rename(p,A),await this.markGitSafe(A)}}}catch(a){throw this.addInitLog("error",`Failed to configure git repositories: ${a}`,{step:"configure-git-repos",error:String(a)}),a}finally{await i()}}async step3ConfigureGitUser(e,r){this.addInitLog("log","Configuring git user",{step:"configure-git-user"});for(let n of r){let i=Ei.join(e,n.path);this.addInitLog("log",`Setting git user for ${n.repoName}`,{step:"configure-git-user"});try{await this.git(["config","user.email","builder-bot@builder.io"],i),await this.git(["config","user.name","Builder.io"],i)}catch(s){let o=`Failed to configure git user for ${n.repoName}: ${s}`;throw this.addInitLog("error",o,{step:"configure-git-user",error:o}),new Error(o)}}}async step4CollectRepoInfo(e,r,n){this.addInitLog("log","Collecting repo info",{step:"collect-repo-info"}),this.initState.repos=[];for(let i of n){let s=Ei.join(r,i.path);try{let o=await this.git(["rev-parse","HEAD"],s),a=await this.git(["branch","--show-current"],s),A={repoName:i.repoName||i.path,enabledGit:!!i.enableGit,lastCommitHash:o.trim(),branch:a.trim()};this.initState.repos.push(A),this.addInitLog("log",`Collected repo info: ${JSON.stringify(A)}`,{step:"collect-repo-info"})}catch(o){e.sys.Sentry?.captureException(o,{tags:{operation:"init",...e.sentryTags}})}}}async isGitConfigured(e){try{return await this.git(["rev-parse","--is-inside-work-tree"],e,void 0,void 0,!0),!0}catch{return!1}}async getGitRemoteUrl(e){try{return(await this.git(["config","--get","remote.origin.url"],e)).trim()}catch{return null}}isStandardGitHost(e){let r=["github.com","gitlab.com","bitbucket.org"];try{let n=new URL(e);return r.some(i=>n.hostname===i||n.hostname.endsWith(`.${i}`))}catch{return!1}}async checkHostConnectivity(e){try{let r=e.startsWith("git@")||e.startsWith("ssh://"),n,i;if(r){let s=e.match(/^(?:ssh:\/\/)?(?:[^@]+@)?([^/:]+)(?::|\/)/);if(!s)return{reachable:!1,error:"Invalid SSH repository URL format"};n=s[1],i=22}else{let s=e.match(/^https?:\/\/(?:[^@]+@)?([^/:?#]+)/);if(!s)return{reachable:!1,error:"Invalid repository URL format"};n=s[1],i=443}this.addInitLog("log",`Checking connectivity to host: ${n}:${i}`,{step:"clone-repo"});try{let s=[];try{s=await U4.default.resolve4(n),s.length>0&&this.addInitLog("log",`DNS resolved ${n} to IPv4: ${s.join(", ")}`,{step:"clone-repo"})}catch{s=await U4.default.resolve6(n),s.length>0&&this.addInitLog("log",`DNS resolved ${n} to IPv6: ${s.join(", ")}`,{step:"clone-repo"})}if(s.length===0)return{reachable:!1,hostname:n,error:`DNS resolution failed: no addresses found for ${n}`}}catch(s){let o=s instanceof Error?s.message:String(s);return{reachable:!1,hostname:n,error:`DNS resolution failed for ${n}: ${o}`}}try{let s=await this.checkConnectivityDirect(n,i);if(s.reachable)return s;let o=process.env.HTTP_PROXY||process.env.http_proxy;return o?(this.addInitLog("log",`Direct connection failed, trying proxy: ${o}`,{step:"clone-repo"}),await this.checkConnectivityViaProxy(n,i,o)):s}catch(s){let o=s instanceof Error?s.message:String(s);return{reachable:!1,hostname:n,error:`Connection attempt failed: ${o}`}}}catch(r){return{reachable:!1,error:`Unexpected error during connectivity check: ${r instanceof Error?r.message:String(r)}`}}}async checkConnectivityDirect(e,r){let i=vye.default.createConnection({host:e,port:r,timeout:5e3});return await new Promise(s=>{i.on("connect",()=>{i.destroy(),this.addInitLog("log",`Successfully connected to ${e}:${r}`,{step:"clone-repo"}),s({reachable:!0,hostname:e})}),i.on("error",o=>{i.destroy(),this.addInitLog("error",`Connection failed to ${e}:${r}: ${o.message}`,{step:"clone-repo",error:o.message}),s({reachable:!1,hostname:e,error:`Cannot connect to ${e}:${r}: ${o.message}`})}),i.on("timeout",()=>{i.destroy(),this.addInitLog("error",`Connection timeout to ${e}:${r} (${5e3/1e3}s)`,{step:"clone-repo",error:`Connection timeout to ${e}:${r} after ${5e3/1e3} seconds`}),s({reachable:!1,hostname:e,error:`Connection timeout to ${e}:${r} after ${5e3/1e3} seconds`})})})}async checkConnectivityViaProxy(e,r,n){try{this.addInitLog("log",`Attempting proxy connection to ${e}:${r} via proxy`,{step:"clone-repo"});let i=new URL(n),s=`${i.protocol}//${i.host}`,o=new px.ProxyAgent({uri:s,token:i.username&&i.password?`Basic ${Buffer.from(`${i.username}:${i.password}`).toString("base64")}`:void 0}),a=r===443?`https://${e}`:`http://${e}:${r}`;return await(0,px.fetch)(a,{dispatcher:o,signal:AbortSignal.timeout(3e4)}),this.addInitLog("log",`Successfully connected via proxy to ${e}:${r}`,{step:"clone-repo"}),{reachable:!0,hostname:e}}catch(i){return{reachable:!1,hostname:e,error:`Proxy connection failed: ${i instanceof Error?i.message:String(i)}`}}}async ensureParentDirExists(e){let r=Ei.dirname(e);return await ti.mkdir(r,{recursive:!0}),r}async cleanupLockFiles(e){let r=Ei.join(e,".git");try{let i=(await ti.readdir(r)).filter(o=>o.endsWith(".lock"));if(i.length===0)return;let s=[];for(let o of i){let a=Ei.join(r,o);try{await ti.unlink(a),s.push(o)}catch(A){this.config.sys.Sentry?.captureException(new Error(`Failed to remove ${o} for ${e}: ${A}`),{tags:{operation:"init",...this.config.sentryTags}})}}s.length>0&&this.config.sys.Sentry?.captureMessage(`Lock files found for ${e} and removed: ${s.join(", ")}`,{tags:{operation:"init",...this.config.sentryTags}})}catch(n){this.config.sys.Sentry?.captureException(new Error(`Failed to cleanup lock files for ${e}: ${n}`),{tags:{operation:"init",...this.config.sentryTags}})}}async validateGitRepo(e){try{await this.git(["fsck","--connectivity-only"],e)}catch(r){throw new Error("Git repo is in bad state",{cause:r})}}async isBackupAlreadyApplied(e,r,n){try{let i=(await this.git(["rev-parse","--verify",`refs/heads/${r}`],e)).trim();return i?(await this.git(["merge-base","--is-ancestor",n,i],e),!0):!1}catch{return!1}}async restoreFromPartialBackup({repo:e,repoPath:r,backupResult:n}){try{this.addInitLog("log",`Checking for git backup for ${e.repoName}`,{step:"apply-partial-backup"});let i=async()=>{try{await this.git(["remote","remove","backup"],r)}catch(s){this.addInitLog("error",`Failed to cleanup restore: ${s}`,{step:"apply-partial-backup",error:String(s)})}};if(!n.bundlePath){try{this.addInitLog("log",`Found empty git backup, applying it to ${e.repoName}`,{step:"apply-partial-backup"});let s=this.config.fusionConfig.aiBranch||n.gitBranchName;s&&await this.checkout(s,n.lastCommitHash||void 0,r)}catch(s){if(n.lastCommitHash)throw s;this.addInitLog("log",`Empty backup \u2014 could not create branch (repo may have no commits yet): ${s}`,{step:"apply-partial-backup"})}return}try{this.addInitLog("log",`Found git backup, applying it to ${e.repoName}`,{step:"apply-partial-backup"});try{await this.git(["remote","remove","backup"],r)}catch{}await this.git(["remote","add","backup",n.bundlePath],r),await this.git(["fetch","backup"],r);let s=n.gitBranchName,o=this.config.fusionConfig.aiBranch||s;o!==s?(this.addInitLog("log",`Creating new branch ${o} from backup/${s}`,{step:"apply-partial-backup"}),await this.git(["branch",o,`backup/${s}`],r),await this.git(["checkout",o],r)):await this.checkout(s,`backup/${s}`,r),this.addInitLog("log",`Successfully restored from backup to branch ${o}`,{step:"apply-partial-backup"}),await i(),this.addInitLog("log",`Cleaned up backup for ${e.repoName}`,{step:"apply-partial-backup"})}catch(s){throw await i(),this.addInitLog("error",String(s),{step:"apply-partial-backup",error:String(s)}),s}}catch(i){let s=new Error(`Failed to check git backup for ${e.repoName}. Cannot proceed without backup recovery.`,{cause:i});throw this.addInitLog("error",s.message,{step:"apply-partial-backup",error:String(i)}),s}}async initializeGitRepo(e,r){await this.git(["init"],e),await this.git(["add","."],e),await this.git(["branch","-M","main"],e),await this.git([...r?["-c","user.email=team@builder.io","-c","user.name=Builder.io"]:[],"commit","-m","Initial setup"],e)}async fetchGitConfigsOnce(){if(this.config.fusionConfig.projectId)try{let e=await hh(this.config.credentials,this.config.fusionConfig.projectId,this.debug);if(e.success)return Object.keys(e.gitConfigs).length>0?e.gitConfigs:void 0;e.gitDiagnostics&&(this.initState.gitDiagnostics=e.gitDiagnostics),this.config.sys.Sentry?.captureException(e.error,{tags:{operation:"init",endpoint:"fetch-git-configs",...this.config.sentryTags},extra:{gitDiagnostics:e.gitDiagnostics}})}catch(e){this.config.sys.Sentry?.captureException(new Error("Failed to fetch git configs in InitStateMachine",{cause:e instanceof Error?e:new Error(String(e))}),{tags:{operation:"init",endpoint:"fetch-git-configs",...this.config.sentryTags}})}}applyGitConfig(e,r,n,i){if(e.initializationCommand||e.repoUrl?.startsWith("ssh://")||e.repoUrl?.startsWith("git@"))return;let s;if(e.repoName&&r[e.repoName]?s=e.repoName:n&&(s=Object.keys(r)[0]),!s)return;let o=r[s];o?.url&&(e.repoUrl=o.url,n&&(e.repoName=s),(o.provider==="github"||o.provider==="selfHostedGithub")&&o.token&&(n&&(process.env.GH_TOKEN=o.token),i>1&&(process.env[lx(e.name)]=o.token)))}async runInitializationCommand({repo:e,tempCloningDir:r,repoPath:n,initCommand:i}){this.addInitLog("log",`Init command paths args: tempCloningDir: ${r} repoPath: ${n}`,{step:"init-command"});try{this.addInitLog("log",`Executing initialization command in ${r}`,{step:"init-command"});let s=process.env.SHELL||process.env.COMSPEC||"/bin/sh";try{let o=mA(s,i,{stdio:["ignore","pipe","pipe"],cwd:r,env:{...process.env,TERM:"dumb"}},!0),a=[],A=[];o.stdout?.on("data",c=>{a.push(c);let u=c.toString().trim();u&&this.addInitLog("log",u,{step:"init-command"})}),o.stderr?.on("data",c=>{A.push(c);let u=c.toString().trim();u&&this.addInitLog("error",u,{step:"init-command"})}),await new Promise((c,u)=>{o.on("error",l=>{u(l)}),o.on("close",l=>{if(l===0)c();else{let d=Buffer.concat(a).toString().trim(),g=Buffer.concat(A).toString().trim(),p=[`Command exited with code ${l}`,g&&`stderr: ${g}`,d&&`stdout: ${d}`].filter(Boolean).join(`
|
|
1940
1940
|
`);u(new Error(p))}})})}catch(o){let a=new Error("Failed to execute initCommand.",{cause:o});return this.addInitLog("error",a.message+`: ${o}`,{step:"init-command",error:String(o)}),{outcome:!1,error:a}}return{outcome:!0}}catch(s){return this.addInitLog("error",`Failed to run initialization command: ${s}`,{step:"init-command",error:String(s)}),{outcome:!1,error:s instanceof Error?s:new Error(String(s))}}}async cloneRepository({repo:e,repoPath:r,backupResult:n,isPrimary:i}){let s=[e.branchName??"main",null,"main","master"];if(n&&n.success&&!n.partial){if(!n.bundlePath)throw new Error("Full backups must have a bundle path");this.addInitLog("log",`Downloaded full git backup, cloning it to ${r}`,{step:"clone-repo"});try{let a=await this.ensureParentDirExists(r);await this.git(["clone",n.bundlePath,r],a,void 0,600*1e3),await this.markGitSafe(r);for(let u of s)if(u)try{await this.git(["checkout",u],r)}catch{continue}await this.checkout(n.gitBranchName,n.lastCommitHash,r);let A=(await this.git(["branch","--show-current"],r)).trim(),c=(await this.git(["rev-parse","HEAD"],r)).trim();if(A!==n.gitBranchName)throw new Error(`Backup branch ${n.gitBranchName} does not match local branch ${A}`);if(c!==n.lastCommitHash)throw new Error(`Backup commit hash ${n.lastCommitHash} does not match local commit hash ${c}`);return!0}catch(a){throw this.addInitLog("error",`Failed to clone git backup for ${e.repoName}: ${a}`,{step:"clone-repo",error:String(a)}),a}}let o=process.env.TEST_NEEDS_GIT_INIT==="1";if(!this.isStandardGitHost(e.repoUrl)){this.addInitLog("log",`Non-standard git host detected, checking connectivity to ${e.repoUrl}`,{step:"clone-repo"});let a=await this.checkHostConnectivity(e.repoUrl);if(!a.reachable){let A=`Git host unreachable: ${a.hostname||"unknown host"}. ${a.error||"Network connectivity check failed"}. This host may be behind a firewall or VPN.`,c=a.error?s0(a.error):null,u={provider:FL(e.repoUrl),hostname:a.hostname||"",sourceIp:"",repoName:e.repoName||"",issue:"network",...c&&{connectivityErrorCode:c.connectivityErrorCode,checkType:c.checkType,likelyCause:i0(c.connectivityErrorCode)}};throw this.addInitLog("error",A,{step:"clone-repo",error:A,gitDiagnostics:u}),this.config.sys.Sentry?.captureException(new Error("Git host unreachable"),{tags:{operation:"init",...this.config.sentryTags},extra:{repo:e,connectivityResult:a,gitDiagnostics:u}}),new Error(A)}this.addInitLog("log",`Host connectivity verified for ${a.hostname}`,{step:"clone-repo"})}for(let a of s)try{let A=process.env.FUSION_TEMPLATE_DIR&&process.env.FUSION_TEMPLATE_DIR.trim().length>0?process.env.FUSION_TEMPLATE_DIR:"/template";if(ei.existsSync(A)&&e.repoName===yf){if(this.addInitLog("log",`Starting copy of template to ${r}`,{step:"clone-repo"}),await this.execAsync("rm",["-rf",r],"/"),await this.execAsync("cp",["-a",A,r],"/"),this.addInitLog("log",`Copied from template for ${e.repoName}`,{step:"clone-repo"}),o)try{await this.initializeGitRepo(r,o)}catch(c){let u=`Failed to initialize git repo for ${e.repoName} after template copy: ${c}`;throw this.addInitLog("error",u,{step:"clone-repo",error:String(c)}),new Error(u)}return!0}else{let c=FL(e.repoUrl),u=c==="github"||c==="gitlab"||c==="selfHostedGithub",l=e.resetGit!==void 0?e.resetGit:kL.includes(e.repoName),d=n&&n.success&&n.partial,g=this.config.fusionConfig.isFork&&this.config.fusionConfig.prNumber,p=l&&e.enableGit&&!d&&!g,f=!e.enableGit||p?["clone","--depth","1"]:u?["clone","--filter=blob:none"]:["clone"];a&&f.push("-b",a),f.push(e.repoUrl,r),this.addInitLog("log",`Cloning repository: ${e.repoName} with branch: ${a||"default"}`,{step:"clone-repo"});let m=await this.ensureParentDirExists(r);if(await this.git(f,m,void 0,600*1e3),await this.markGitSafe(r),this.config.fusionConfig.isFork&&this.config.fusionConfig.prNumber&&i){let C=this.config.fusionConfig.prNumber,I=this.config.fusionConfig.featureBranch||`pr-${C}`;this.addInitLog("log",`Fork PR detected - fetching PR #${C} using refs/pulls/${C}/head into branch ${I}`,{step:"clone-repo"});try{await this.git(["fetch","origin",`pull/${C}/head:${I}`],r),await this.git(["switch",I],r),this.addInitLog("log",`Successfully checked out fork PR #${C} on branch ${I}`,{step:"clone-repo"})}catch(y){let B=`Failed to fetch fork PR #${C}: ${y}`;throw this.addInitLog("error",B,{step:"clone-repo",error:String(y)}),new Error(B,{cause:y})}}return p&&(ei.rmSync(Ei.join(r,".git"),{recursive:!0,force:!0}),await this.initializeGitRepo(r,o),this.addInitLog("log",`Cleared git history for ${e.repoName}`,{step:"clone-repo"})),!0}}catch(A){this.addInitLog("error",`Clone failed for branch ${a||"default"}: ${A}`,{step:"clone-repo",error:String(A)}),await ti.rm(r,{recursive:!0,force:!0}).catch(()=>{});continue}return!1}async markGitSafe(e){try{let r=await this.git(["config","--global","--get-all","safe.directory"],e);if(r.trim().split(`
|
|
1941
|
-
`).includes(e))return r}catch{}return this.git(["config","--global","--add","safe.directory",e],e)}}});function Tft(t){let e=["figma/manifest.json"];for(let r of t.frames??[])r.htmlGcsPath&&e.push(`figma/${(0,kl.basename)(r.htmlGcsPath)}`),r.screenshotGcsPath&&e.push(`figma/${(0,kl.basename)(r.screenshotGcsPath)}`);for(let r of t.assets??[])e.push(`figma/${r.localPath}`);for(let r of t.textSources??[])e.push(r.localPath);return e}function Sye(t){try{let e=new URL(t);return e.username||e.password?(e.username="",e.password="",e.toString()):t}catch{return"<repo>"}}async function xye(t,e,r,n){let{url:i,localDir:s}=r;if(!r.connectedProjectId&&!NL.test(i)){n(`skip clone \u2014 refusing non-github URL: ${Sye(i)}`);return}let o=t.join(e,s);if(await t.exists(o)){n(`skip clone \u2014 ${s} already present`);return}n(`cloning ${Sye(i)} \u2192 sources/${s}`);try{await Ws("git",["clone","--depth","1","--single-branch",i,o],{sys:t,timeout:12e4,retry:1}),n(`cloned ${s}`)}catch{n(`clone failed for ${s}`)}}async function Fye(t){let{sys:e,credentials:r,jobId:n,workspaceRoot:i}=t,s=t.log??(()=>{}),o=e.join(i,".builder","sources"),a=e.join(o,"figma","manifest.json");if(await e.exists(a))try{let d=await(0,Np.readFile)(a,"utf-8"),g=JSON.parse(d),p=Tft(g);if((await Promise.all(p.map(m=>e.exists(e.join(o,m))))).every(Boolean)&&!(!!g.githubRepo?.connectedProjectId&&!await e.exists(e.join(o,g.githubRepo.localDir))))return s(`skip \u2014 manifest + all ${p.length} files already present`),g.githubRepo&&await xye(e,o,g.githubRepo,s),{written:0,skipped:!0,sourcesDir:o}}catch{}let A=new URL(`${Ne}/design-systems/v1/decode-jobs/${encodeURIComponent(n)}/hydration`);r.builderPublicKey&&A.searchParams.set("apiKey",r.builderPublicKey),s(`GET ${A.pathname}${A.search}`);let c=await Fe(A.toString(),{method:"GET",headers:{"Content-Type":"application/json",...r.builderPrivateKey?{Authorization:`Bearer ${r.builderPrivateKey}`}:{}}});if(!c.ok){let d=await c.text().catch(()=>"");throw new Error(`figma hydration request failed: ${c.status} ${c.statusText} ${d}`)}let u=await c.json();if(s(`hydration endpoint: status=${u.status} files=${u.files.length}`),u.status!=="complete"||!u.files.length)throw new Error(`figma decode job not ready for hydration (status=${u.status})`);await(0,Np.mkdir)(o,{recursive:!0});let l=(0,kl.resolve)(o);return await Promise.all(u.files.map(async d=>{let g=e.join(o,d.localPath);if(!(0,kl.resolve)(g).startsWith(l+"/"))throw new Error(`path traversal in manifest localPath: ${d.localPath}`);await(0,Np.mkdir)((0,kl.dirname)(g),{recursive:!0});let p=await Fe(d.downloadUrl,{method:"GET"});if(!p.ok)throw new Error(`failed to download ${d.localPath}: ${p.status}`);let f=Buffer.from(await p.arrayBuffer());await(0,Np.writeFile)(g,f)})),s(`wrote ${u.files.length} files into ${o}`),u.manifest?.githubRepo&&await xye(e,o,u.manifest.githubRepo,s),{written:u.files.length,skipped:!1,sourcesDir:o}}var Np,kl,kye=L(()=>{"use strict";h();Hs();Np=require("node:fs/promises"),kl=require("node:path");yr();hr();kr();xo()});function Nye(){process.on("SIGINT",dx),process.on("SIGTERM",dx)}function Mye(){process.removeListener("SIGINT",dx),process.removeListener("SIGTERM",dx)}var Rye,Tye,dx,
|
|
1941
|
+
`).includes(e))return r}catch{}return this.git(["config","--global","--add","safe.directory",e],e)}}});function Tft(t){let e=["figma/manifest.json"];for(let r of t.frames??[])r.htmlGcsPath&&e.push(`figma/${(0,kl.basename)(r.htmlGcsPath)}`),r.screenshotGcsPath&&e.push(`figma/${(0,kl.basename)(r.screenshotGcsPath)}`);for(let r of t.assets??[])e.push(`figma/${r.localPath}`);for(let r of t.textSources??[])e.push(r.localPath);return e}function Sye(t){try{let e=new URL(t);return e.username||e.password?(e.username="",e.password="",e.toString()):t}catch{return"<repo>"}}async function xye(t,e,r,n){let{url:i,localDir:s}=r;if(!r.connectedProjectId&&!NL.test(i)){n(`skip clone \u2014 refusing non-github URL: ${Sye(i)}`);return}let o=t.join(e,s);if(await t.exists(o)){n(`skip clone \u2014 ${s} already present`);return}n(`cloning ${Sye(i)} \u2192 sources/${s}`);try{await Ws("git",["clone","--depth","1","--single-branch",i,o],{sys:t,timeout:12e4,retry:1}),n(`cloned ${s}`)}catch{n(`clone failed for ${s}`)}}async function Fye(t){let{sys:e,credentials:r,jobId:n,workspaceRoot:i}=t,s=t.log??(()=>{}),o=e.join(i,".builder","sources"),a=e.join(o,"figma","manifest.json");if(await e.exists(a))try{let d=await(0,Np.readFile)(a,"utf-8"),g=JSON.parse(d),p=Tft(g);if((await Promise.all(p.map(m=>e.exists(e.join(o,m))))).every(Boolean)&&!(!!g.githubRepo?.connectedProjectId&&!await e.exists(e.join(o,g.githubRepo.localDir))))return s(`skip \u2014 manifest + all ${p.length} files already present`),g.githubRepo&&await xye(e,o,g.githubRepo,s),{written:0,skipped:!0,sourcesDir:o}}catch{}let A=new URL(`${Ne}/design-systems/v1/decode-jobs/${encodeURIComponent(n)}/hydration`);r.builderPublicKey&&A.searchParams.set("apiKey",r.builderPublicKey),s(`GET ${A.pathname}${A.search}`);let c=await Fe(A.toString(),{method:"GET",headers:{"Content-Type":"application/json",...r.builderPrivateKey?{Authorization:`Bearer ${r.builderPrivateKey}`}:{}}});if(!c.ok){let d=await c.text().catch(()=>"");throw new Error(`figma hydration request failed: ${c.status} ${c.statusText} ${d}`)}let u=await c.json();if(s(`hydration endpoint: status=${u.status} files=${u.files.length}`),u.status!=="complete"||!u.files.length)throw new Error(`figma decode job not ready for hydration (status=${u.status})`);await(0,Np.mkdir)(o,{recursive:!0});let l=(0,kl.resolve)(o);return await Promise.all(u.files.map(async d=>{let g=e.join(o,d.localPath);if(!(0,kl.resolve)(g).startsWith(l+"/"))throw new Error(`path traversal in manifest localPath: ${d.localPath}`);await(0,Np.mkdir)((0,kl.dirname)(g),{recursive:!0});let p=await Fe(d.downloadUrl,{method:"GET"});if(!p.ok)throw new Error(`failed to download ${d.localPath}: ${p.status}`);let f=Buffer.from(await p.arrayBuffer());await(0,Np.writeFile)(g,f)})),s(`wrote ${u.files.length} files into ${o}`),u.manifest?.githubRepo&&await xye(e,o,u.manifest.githubRepo,s),{written:u.files.length,skipped:!1,sourcesDir:o}}var Np,kl,kye=L(()=>{"use strict";h();Hs();Np=require("node:fs/promises"),kl=require("node:path");yr();hr();kr();xo()});function Nye(){process.on("SIGINT",dx),process.on("SIGTERM",dx)}function Mye(){process.removeListener("SIGINT",dx),process.removeListener("SIGTERM",dx)}var Rye,Tye,dx,K4=L(()=>{"use strict";h();Rye=z(require("@sentry/node"),1),Tye=z(require("@amplitude/analytics-node"),1),dx=async()=>{let t=process.env.BUILDER_DISABLE_AMPLITUDE==="true",e=[Rye.flush()];t||e.push(Tye.flush().promise),await Promise.allSettled(e),process.exit(0)}});function Pye(){let t,e=[],n=performance.now();return{consumeDelays:()=>{let i=[...e];return e.length=0,i},start:()=>{t||(n=performance.now(),t=setInterval(()=>{try{let i=performance.now(),s=i-n,o=Math.max(0,s-5e3);e.push(o),n=i}catch(i){Nft.error("Error sampling:",i)}},5e3),t.unref())},stop:()=>{t&&(clearInterval(t),t=void 0)}}}var Nft,Lye=L(()=>{"use strict";h();Bt();Nft=ve("EventLoopMonitor")});function Uye(){let t=process.constrainedMemory?.();if(t){let{rss:r}=process.memoryUsage();return Math.min(1,r/t)}let e=_ye.getHeapStatistics();return Math.min(1,1-e.total_available_size/e.heap_size_limit)}var _ye,Gye=L(()=>{"use strict";h();_ye=z(require("v8"),1)});function Pft(){try{let t=Oye.statfsSync(Mft),e=t.bsize*t.blocks,r=t.bsize*t.bavail;if(e===0)return;let n=e-r,i=Math.min(1,Math.max(0,n/e));return{bytes:n,ratio:i}}catch{return}}function Lft(){try{let t=Ra.totalmem(),e=Ra.freemem();if(t===0)return;let r=t-e,n=Math.min(1,Math.max(0,r/t));return{bytes:r,ratio:n}}catch{return}}function Kye(t,e,r,n){let i=null,s=Pye(),o,a,A=async()=>{try{let c=new URL(`${Ne}/projects/machine-status`);e.builderPublicKey&&c.searchParams.set("apiKey",e.builderPublicKey),e.userId&&c.searchParams.set("userId",e.userId);let u=nv(),l;u&&r.machine?l={...r.machine,environment:n.fusionEnvironment}:u||(l={cpus:Ra.cpus().length,memory:Math.round(Ra.totalmem()/(1024*1024*1024)),platform:Ra.platform(),arch:Ra.arch(),environment:"local"});let d=s.consumeDelays(),g=Uye(),p=Pft(),f=Lft();n.diskUsage=p?.ratio,n.memoryUsage=f?.ratio,p!==void 0&&(o=o===void 0?p.bytes:Math.max(o,p.bytes)),f!==void 0&&(a=a===void 0?f.bytes:Math.max(a,f.bytes));let m={status:"ok",state:n.state,setupState:n.setupState,devState:n.devState,editorReady:n.editorReady,editorReadyAt:n.editorReadyAt,editorReadySource:n.editorReadySource,httpServerState:n.httpServerState,initState:n.initState,errorMessage:n.errorMessage,devToolsVersion:n.devToolsVersion,idleTime:performance.now()-n.lastRequestTime,upTime:performance.now()-n.startTime,processId:n.processId,launchPhase:n.launchPhase,launchPhaseUpdatedAt:n.launchPhaseUpdatedAt,machine:l,projectId:r.projectId,detectedServerUrl:n.detectedServerUrl,_attemptDryRunBackupOutcome:n._attemptDryRunBackupOutcome,workingDirectory:n.workingDirectory,fusionEnvironment:n.fusionEnvironment,containerState:n.containerState,containerStateAgeMs:performance.now()-n.containerStateTimestamp,containerStateTimestamp:n.containerStateTimestamp,wsClients:t.connectionTracker.getConnectionCount(),httpClients:n.httpClients,eventLoopDelays:d.length>0?d:void 0,memoryPressure:g,diskUsage:p?.ratio,memoryUsage:f?.ratio},C={"Content-Type":"application/json"};e.builderPrivateKey&&(C.Authorization=`Bearer ${e.builderPrivateKey}`),await Fe(c,{method:"POST",body:JSON.stringify(m),headers:C,keepalive:!0,signal:AbortSignal.timeout(5e3)})}catch{}};return{start:()=>{if(i)return;s.start(),A();let c=30*1e3;i=setInterval(A,c)},stop:()=>{i&&(clearInterval(i),i=null),s.stop()},getPeakUsage:()=>({peakDiskUsage:o,peakMemoryUsage:a})}}var Ra,Oye,Mft,Hye=L(()=>{"use strict";h();yr();hr();Ap();Lye();Gye();Ra=z(require("node:os"),1),Oye=z(require("node:fs"),1),Mft="/root"});async function fx(t,e,r){try{let n=new URL(`${Ne}/projects/metrics`);e.builderPublicKey&&n.searchParams.set("apiKey",e.builderPublicKey),e.userId&&n.searchParams.set("userId",e.userId);let i={"Content-Type":"application/json"};e.builderPrivateKey&&(i.Authorization=`Bearer ${e.builderPrivateKey}`),await Fe(n,{method:"POST",body:JSON.stringify(r),headers:i,keepalive:!0,signal:AbortSignal.timeout(5e3)})}catch(n){t.Sentry?.captureException(new Error("Failed to push metrics",{cause:n}))}}var H4=L(()=>{"use strict";h();yr();hr()});var zc,Jye,Mp,hx,J4,j4,jye,_ft,Yye=L(()=>{"use strict";h();O4();zc=require("node:fs"),Jye=require("fs/promises");H4();rr();zr();Bt();Mp=ve("DryRunBackup"),hx="/app-backup-test",J4="/app/.mark",j4={operation:"dry-run-backup-git",dryRunBackupGit:"true"},jye=async(t,e)=>{let r=await _ft(t,e);return r&&(r.success?$.success("\u2705 Dry run backup git succeeded"):($.error(`\u274C Dry run backup git failed: ${r.error}`),t.sys.Sentry?.captureException(new Error(`Attempted dry run backup failed: ${r.error}`),{tags:j4})),fx(t.sys,t.credentials,{counters:[{key:"projects_backup_dry_run_ended",value:1,attributes:{outcome:r.success?"success":r.error??"unknown",version:ht}}]}),r)},_ft=async({sys:t,fusionConfig:e,credentials:r},n)=>{function i(s){let o=e.workspace?.folders.find(c=>c.backupMetadata)?.backupMetadata?.check,a=n.repos.find(c=>c.enabledGit),A=s.initState.repos.find(c=>c.enabledGit);return JSON.stringify({backupCheck:o,mainRepo:a,backupMainRepo:A},null,2)}try{let s=process.env.FLY_MACHINE_ID??"unknown";if((0,zc.existsSync)(J4)&&(0,zc.readFileSync)(J4,"utf8")===s)return null;if((0,zc.writeFileSync)(J4,s),$.info("Attempting dry run backup git"),n.currentStep!=="init-success")return{success:!1,error:"main-init-failed"};(0,zc.existsSync)(hx)&&await(0,Jye.rm)(hx,{recursive:!0,force:!0}),(0,zc.mkdirSync)(hx,{recursive:!0});let o=new em({sys:t,fusionConfig:{...e,_attemptDryRunBackupGit:!1,workingDirectory:hx},debug:!0,credentials:r,sentryTags:j4}),a=await o.init(),A=i(o);if(!a)return Mp.error(`\u274C Backup failed: ${o.initState.currentStep}
|
|
1942
1942
|
${A}`),{success:!1,error:`backup-failed:${o.initState.currentStep}`};let c=o.initState.repos.find(d=>d.enabledGit);if(!c)return Mp.error(`\u274C Backup repo not found
|
|
1943
1943
|
${A}`),{success:!1,error:"backup-repo-not-found"};let u=n.repos.find(d=>d.enabledGit);if(!u)return Mp.error(`\u274C Main repo not found
|
|
1944
1944
|
${A}`),{success:!1,error:"main-repo-not-found"};if(c.branch!==u.branch)return Mp.error(`\u274C Backup branch mismatch: ${c.branch} !== ${u.branch}
|
|
1945
1945
|
${A}`),{success:!1,error:"backup-branch-mismatch"};let l=e.workspace?.folders.find(d=>d.backupMetadata)?.backupMetadata;if(l){if(c.branch!==l.check.backup.gitBranchName)return Mp.error(`\u274C Backup branch mismatch: ${c.branch} !== ${l.check.backup.gitBranchName}
|
|
1946
1946
|
${A}`),{success:!1,error:"backup-branch-mismatch-in-metadata"};if(c.lastCommitHash!==l.check.backup.lastCommitHash)return Mp.error(`\u274C Backup commit hash mismatch: ${c.lastCommitHash} !== ${l.check.backup.lastCommitHash}
|
|
1947
|
-
${A}`),{success:!1,error:"backup-commit-hash-mismatch-in-metadata"}}return c.lastCommitHash!==u.lastCommitHash?(Mp.error(`\u274C Backup commit hash mismatch: ${c.lastCommitHash} !== ${u.lastCommitHash}`),{success:!1,error:"backup-commit-hash-mismatch"}):{success:!0}}catch(s){return t.Sentry?.captureException(s,{tags:
|
|
1947
|
+
${A}`),{success:!1,error:"backup-commit-hash-mismatch-in-metadata"}}return c.lastCommitHash!==u.lastCommitHash?(Mp.error(`\u274C Backup commit hash mismatch: ${c.lastCommitHash} !== ${u.lastCommitHash}`),{success:!1,error:"backup-commit-hash-mismatch"}):{success:!0}}catch(s){return t.Sentry?.captureException(s,{tags:j4}),{success:!1,error:"error"}}}});function Y4(t){Object.assign(qye,t)}function q4(t){return!!qye[t]}var qye,$ye=L(()=>{"use strict";h();qye={}});async function Wye(t,e){let r=e.lockFile?.filePath;if(!r)return;let n=e.lockFile?.conflictBehavior;if(!n)return;let i=e.projectId,s=e.branchName,o=e.fusionServerPort;if(Qs.existsSync(r)){Pn.info(`Lock file already exists at: ${r}`);let A=null;try{let c=Qs.readFileSync(r,"utf8");A=JSON.parse(c)}catch(c){Pn.warn("Failed to read existing lock file, treating as corrupted and removing:",c),t.Sentry?.captureMessage("Corrupted lock file detected and removed",{level:"warning",extra:{lockFilePath:r,error:String(c)}});try{Qs.unlinkSync(r)}catch(u){Pn.warn("Failed to remove corrupted lock file:",u)}}if(A)if(Ww(A.pid))switch(n){case"exit":Pn.error("Another instance is already running."),Pn.error(`Existing process PID: ${A.pid}`),Pn.error(`Existing process started at: ${new Date(A.createdAt).toISOString()}`),process.exit(-10);case"replace":Pn.info("Replacing existing lock file (conflictBehavior: replace)"),Pn.info(`Previous process PID: ${A.pid}`);break;case"kill":if(Pn.info("Attempting to kill existing process (conflictBehavior: kill)"),A.pid===process.pid){Pn.info("Skipping kill, same process");break}Pn.info(`Attempting to kill process ${A.pid}...`);let c=await Os(t,A.pid);c&&(Pn.error(`Failed to kill process ${A.pid}, exiting...`,c),process.exit(-10)),Pn.info(`Process ${A.pid} terminated successfully`);break}else{Pn.info(`Found stale lock file (process ${A.pid} is no longer running), removing and continuing...`),t.Sentry?.captureMessage("Stale lock file detected and removed",{level:"warning",extra:{pid:A.pid,createdAt:A.createdAt,projectId:A.projectId,branchId:A.branchId,lockFilePath:r}});try{Qs.unlinkSync(r)}catch(c){Pn.warn("Failed to remove stale lock file:",c)}}}let a={cwd:process.cwd(),projectId:i,branchId:s,pid:process.pid,createdAt:Date.now(),port:o};try{let A=Vye.dirname(r);Qs.existsSync(A)||Qs.mkdirSync(A,{recursive:!0}),Qs.writeFileSync(r,JSON.stringify(a,null,2),"utf8"),Pn.info(`Lock file created at: ${r}`);let c=!1,u=()=>{if(!c){try{Qs.existsSync(r)&&(Qs.unlinkSync(r),Pn.info(`Lock file removed: ${r}`))}catch(l){Pn.error(`Failed to remove lock file at ${r}:`,l)}c=!0}};process.on("exit",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.on("uncaughtException",u),process.on("unhandledRejection",u)}catch(A){throw Pn.error(`Failed to create lock file at ${r}:`,A),A}}var Qs,Vye,Pn,zye=L(()=>{"use strict";h();Qs=z(require("node:fs"),1),Vye=z(require("node:path"),1);da();Bt();Pn=ve("LockFile")});var Zye,Xye=L(()=>{Zye=`You are a Practical Code Review Agent focused on finding real bugs and issues that matter.
|
|
1948
1948
|
|
|
1949
1949
|
## Role
|
|
1950
1950
|
|
|
@@ -4054,12 +4054,12 @@ When you encounter an obstacle, do not use destructive actions as a shortcut. In
|
|
|
4054
4054
|
Has MCP access for integrations like Slack, Jira, GitHub, Linear, and Sentry; can connect new MCP servers with ConnectMCP; and can use browser automation, web research, shell, media, and org workspace files.
|
|
4055
4055
|
Use instead of SpawnBranch for integration lookups, MCP setup, browser/web tasks, org metadata, skill work, scripts, and other non-codebase investigations.
|
|
4056
4056
|
Provide clear, specific instructions for what to accomplish and what to report back.
|
|
4057
|
-
`,Wht=["mcp:chrome","Read","Grep","Glob","Bash","Edit","Write","Media","WebFetch","WebSearch","Skill","ReadBranch","TaskCreate","TaskUpdate","TaskList"],zht="gpt5-mini",XQe={name:$ht,description:Vht,tools:Wht,systemPrompt:zQe,model:zht,position:"org-worker",needDevServer:!1,mcpServers:!0,includeMemories:!1}});function Zht(t){try{let e=eDe.readFileSync(t,"utf-8");return JSON.parse(e).jobs??[]}catch{return[]}}function emt(t,e){if(t.length!==e.length)return!0;let r=new Map(t.map(n=>[n.id,n]));for(let n of e){let i=r.get(n.id);if(!i||i.cron!==n.cron||i.prompt!==n.prompt||i.enabled!==n.enabled||i.description!==n.description)return!0}return!1}async function tmt(t,e){let r=new URL("/projects/org-agent/cron-jobs/sync",e.apiHost);r.searchParams.set("apiKey",e.ownerId);let n=await Fe(r.toString(),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.privateKey}`},body:JSON.stringify({projectId:e.projectId,branchName:e.branchName,jobs:t})});if(!n.ok)throw new Error(`Cron config sync failed: ${n.status} ${n.statusText}`)}function tDe(t){let{cronFilePath:e,syncIntervalMs:r=3e4,...n}=t,i=null;function s(){let a=Zht(e);(i===null||emt(i,a))&&tmt(a,n).then(()=>{i=a}).catch(A=>{Xht.error("Failed to sync cron configs to service:",A)})}s();let o=setInterval(s,r);return()=>{clearInterval(o)}}var eDe,Xht,rDe=L(()=>{"use strict";h();eDe=z(require("node:fs"),1);hr();Bt();Xht=ve("CronChecker")});function
|
|
4057
|
+
`,Wht=["mcp:chrome","Read","Grep","Glob","Bash","Edit","Write","Media","WebFetch","WebSearch","Skill","ReadBranch","TaskCreate","TaskUpdate","TaskList"],zht="gpt5-mini",XQe={name:$ht,description:Vht,tools:Wht,systemPrompt:zQe,model:zht,position:"org-worker",needDevServer:!1,mcpServers:!0,includeMemories:!1}});function Zht(t){try{let e=eDe.readFileSync(t,"utf-8");return JSON.parse(e).jobs??[]}catch{return[]}}function emt(t,e){if(t.length!==e.length)return!0;let r=new Map(t.map(n=>[n.id,n]));for(let n of e){let i=r.get(n.id);if(!i||i.cron!==n.cron||i.prompt!==n.prompt||i.enabled!==n.enabled||i.description!==n.description)return!0}return!1}async function tmt(t,e){let r=new URL("/projects/org-agent/cron-jobs/sync",e.apiHost);r.searchParams.set("apiKey",e.ownerId);let n=await Fe(r.toString(),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.privateKey}`},body:JSON.stringify({projectId:e.projectId,branchName:e.branchName,jobs:t})});if(!n.ok)throw new Error(`Cron config sync failed: ${n.status} ${n.statusText}`)}function tDe(t){let{cronFilePath:e,syncIntervalMs:r=3e4,...n}=t,i=null;function s(){let a=Zht(e);(i===null||emt(i,a))&&tmt(a,n).then(()=>{i=a}).catch(A=>{Xht.error("Failed to sync cron configs to service:",A)})}s();let o=setInterval(s,r);return()=>{clearInterval(o)}}var eDe,Xht,rDe=L(()=>{"use strict";h();eDe=z(require("node:fs"),1);hr();Bt();Xht=ve("CronChecker")});function V4(t){let e=Math.floor(t/1e3);if(e<60)return"just now";let r=Math.floor(e/60);if(r<60)return`${r} minute${r===1?"":"s"} ago`;let n=Math.floor(r/60);if(n<24)return`${n} hour${n===1?"":"s"} ago`;let i=Math.floor(n/24);if(i<30)return`${i} day${i===1?"":"s"} ago`;let s=Math.floor(i/30);return`${s} month${s===1?"":"s"} ago`}function $4(t,e){if(!t)return;let r=e.get(t);return r?.name||r?.email||t}function mx(t,e,r){if(!t)return;let n=e.get(t);if(!n)return t;if(!r?.omit?.length)return n;let i={...n};for(let s of r.omit)delete i[s];return i}function imt(t,e){let r={...t};for(let n of rmt)delete r[n];for(let n of nmt){let i=r[n];typeof i=="string"&&(r[n]=mx(i,e)??i)}return r}function smt(t){let r=new Date(t.createdAt).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC");if(t.senderType==="user"){let n=t.senderDisplayName||t.senderId||"unknown";return`==== [USER] ${r} (${n})
|
|
4058
4058
|
${t.markdown}`}return`==== [AGENT] ${r}
|
|
4059
4059
|
${t.markdown}`}function omt(t,e){ws.rmSync(e,{recursive:!0,force:!0});let r=new Map;for(let n of t){let i=n.channelId||"_no-channel";if(i.includes(".."))continue;let s=r.get(i);s||(s=[],r.set(i,s)),s.push(n)}for(let[n,i]of r){i.sort((a,A)=>a.createdAt-A.createdAt);let s=Ds.join(e,n);ws.mkdirSync(s,{recursive:!0});let o=i.map(smt).join(`
|
|
4060
4060
|
|
|
4061
|
-
`);ws.writeFileSync(Ds.join(s,"thread.log"),o)}}function amt(t,e,r,n){let i=Date.now(),s=[];s.push(`# ${t.name}`),s.push(""),t.repoDescription&&(s.push(`> ${t.repoDescription}`),s.push("")),s.push("## Project Info"),s.push(""),s.push(`- **Project ID:** ${t.id}`),s.push(`- **Project Name:** ${t.name}`),t.repoFullName&&s.push(`- **Repository:** ${t.repoFullName}`),t.repoUrl&&s.push(`- **Repo URL:** ${t.repoUrl}`);let o=$
|
|
4062
|
-
`)}async function Cx(t){let{sys:e,ownerId:r,privateKey:n,outputDir:i}=t,s=Ds.join(i,"org","projects"),o=Ds.join(i,"org");ws.mkdirSync(s,{recursive:!0}),ws.mkdirSync(o,{recursive:!0});let a=new URL("/projects/org-tree",Ne);a.searchParams.set("apiKey",r);let A=await fetch(a,{headers:{Authorization:`Bearer ${n}`}});if(!A.ok)throw new Error(`Failed to fetch org tree: ${A.status} ${A.statusText}`);let c=await A.json(),u=c.projects??[],l=c.branches??[],d=c.users??[],g=c.memories??[],p=c.messages??[];if(c.environmentVariables)for(let b of c.environmentVariables)process.env[b.key]=b.value;let f=new Map(d.map(b=>[b.userId,b])),m=new Map(u.map(b=>[b.id,b])),C=new Map;for(let b of l)b.state==="active"&&C.set(b.projectId,(C.get(b.projectId)??0)+1);function I(b){let x=b.repoFullName??b.id;return x.split("/").pop()===b.name?x:Ds.join(x,b.name)}for(let b of u){let x=Ds.join(s,I(b));ws.mkdirSync(x,{recursive:!0});let P=l.filter(_=>_.projectId===b.id).map(_=>imt(_,f));ws.writeFileSync(Ds.join(x,"project.json"),JSON.stringify({...b,branches:P},null,2));let O=l.filter(_=>_.projectId===b.id);ws.writeFileSync(Ds.join(x,"AGENTS.md"),amt(b,C.get(b.id)??0,f,O));let J=g.filter(_=>_.projectId===b.id);J.length>0&&await nx(e,J,Ds.join(x,"memories"))}let y=Date.now();function B(b){return{branchName:b.name,friendlyName:b.friendlyName,description:b.description,url:`https://builder.io/app/projects/${b.projectId}/${b.name}`,projectId:b.projectId,projectName:m.get(b.projectId)?.name,state:b.state,createdAt:typeof b.createdAt=="number"?b.createdAt:void 0,updatedAt:b.lastUpdatedAt,metadata:b.metadata,lastUpdatedAgo:VH(y-(typeof b.lastUpdatedAt=="number"?b.lastUpdatedAt:y)),createdBy:mx(b.createdBy,f,{omit:["jobFunctions"]}),deletedBy:mx(b.deletedBy,f,{omit:["jobFunctions"]}),deletedAt:b.deletedAt,archiveReason:b.archiveReason,pr:b.prNumber&&b.prUrl?{prNumber:b.prNumber,prUrl:b.prUrl,prStatus:b.prStatus,prStatusUpdatedAt:b.prStatusUpdatedAt}:void 0,prsByFolder:b.prInfoByFolder?Object.fromEntries(Object.entries(b.prInfoByFolder).map(([x,P])=>[x,{prNumber:P.prNumber,prUrl:P.prUrl,prStatus:P.status,updatedAt:P.updatedAt}])):void 0}}let E=y-10080*60*1e3,Q=l.filter(b=>b.state==="active"&&typeof b.lastUpdatedAt=="number"&&b.lastUpdatedAt>E).map(B);ws.writeFileSync(Ds.join(o,"active-branches.json"),JSON.stringify(Q,null,2));let v=l.filter(b=>b.state==="deleted"||b.state==="archived").map(B);ws.writeFileSync(Ds.join(o,"archived-branches.json"),JSON.stringify(v,null,2));let D=new Map;for(let b of l){let x=D.get(b.projectId)??[];x.push(b),D.set(b.projectId,x)}let S=u.map(b=>{let x=D.get(b.id)??[],P=new Map;for(let J of x)J.createdBy&&P.set(J.createdBy,(P.get(J.createdBy)??0)+1);let O=[...P.entries()].sort((J,_)=>_[1]-J[1]).map(([J,_])=>{let K=mx(J,f,{omit:["jobFunctions"]});return{...typeof K=="object"?K:{userId:K},branchCount:_}});return{projectId:b.id,projectName:b.name,repoUrl:b.repoUrl,description:b.description??b.repoDescription,branchCount:C.get(b.id)??0,url:`https://builder.io/app/projects/${b.id}`,moreInfoPath:`org/projects/${I(b)}/`,topUsers:O}}).sort((b,x)=>x.branchCount-b.branchCount||b.projectName.localeCompare(x.projectName));if(ws.writeFileSync(Ds.join(o,"projects.json"),JSON.stringify(S,null,2)),p.length>0){let b=Ds.join(i,"org","channels");omt(p,b)}}var ws,Ds,rmt,nmt,WH=L(()=>{"use strict";h();ws=z(require("node:fs"),1),Ds=z(require("node:path"),1);yr();BH();rmt=["kubePodName","kubeNamespace","kubePvcName","kubeHostname","needsCleanup","appName","machineId","lastMachineIdRemovedAt","volumeId","secondaryVolumeId","volumeName","ipv4","ipv6","vscodeTunnelUrl","vscodeTunnelName","vscodeTunnelExpiresAt","backups","backup","lastServerVersion","lastServerStateDate","lastServerState","lastActivityAt","lastCommitDate","lastUpdatedAt","useHomeDir","useCloudHomeDir","type","legacyId","ownerId","isFork","hidden"],nmt=["createdBy","deletedBy","lastUpdateBy","archivedBy"]});function nDe(t){ZH=t}async function tm(){if(ZH){if(zH){XH=!0;return}zH=!0;try{await ZH()}finally{zH=!1,XH&&(XH=!1,tm())}}}var ZH,zH,XH,e4=L(()=>{"use strict";h();zH=!1,XH=!1});function cmt(){let{FUSION_SNAPSHOT_MODE:t,FUSION_TRIGGER_EVENT_ID:e,FUSION_PROJECT_ID:r}=process.env;return t!=="1"?null:!e||!r?(Pp.error("FUSION_SNAPSHOT_MODE=1 but required env vars missing \u2014 cannot attach snapshot lifecycle"),null):{triggerEventId:e,projectId:r}}function oDe(t){let e=cmt();if(!e)return;Pp.info("Snapshot mode activated",{projectId:e.projectId,triggerEventId:e.triggerEventId}),t(async()=>{try{await Amt("npm",["cache","clean","--force"]),Pp.info("npm cache cleaned before snapshot")}catch(n){Pp.warn("Failed to clean npm cache \u2014 continuing anyway",{error:n instanceof Error?n.message:String(n)})}Pp.info("Dev server ready \u2014 exiting for snapshot capture"),process.exit(0)}),process.on("SIGTERM",()=>{Pp.info("SIGTERM received in snapshot mode \u2014 exiting"),process.exit(143)});let r=n=>{let i=n instanceof Error?n.message:String(n);Pp.error("Uncaught error in snapshot mode",{error:i}),process.exit(1)};process.on("uncaughtException",r),process.on("unhandledRejection",n=>r(n instanceof Error?n:new Error(String(n))))}var iDe,sDe,Amt,Pp,aDe=L(()=>{"use strict";h();iDe=require("node:child_process"),sDe=require("node:util");Bt();Amt=(0,sDe.promisify)(iDe.execFile),Pp=ve("SnapshotMode")});async function lmt(t){return new Promise(e=>{let r=Dx.createServer();r.listen(t,()=>{r.once("close",()=>{e(!0)}),r.close()}),r.on("error",()=>{e(!1)})})}async function ADe(t){let e=t,r=100;for(let n=0;n<r;n++){if(await lmt(e))return e;e=Math.floor(Math.random()*16384)+49152}throw new Error(`Could not find an available port after ${r} attempts`)}async function gmt(t,e){let r=parseInt(process.env.FUSION_SERVER_PORT??""),n=isNaN(r)?umt:r,i,s=t.fusionServerPort;if(s!==void 0)i=s,xe.info(`\u{1F50D} Using configured HTTP port: ${i}`);else{let a=e;i=n,a&&(i=await ADe(n),i!==n&&xe.info(`\u26A0\uFE0F Port ${n} is in use, using port ${i} instead`))}if(!t.https)return{httpPort:i};let o=t.httpsServerOptions?.port??await ADe(i+1);return{httpPort:i,httpsPort:o}}function cDe(t,e,r){if(t.jsonOutput){let n={type:"server_error",data:{error:e,details:r,timestamp:Date.now()}};console.log(JSON.stringify(n))}}function hDe(t){let{signal:e,sys:r,sharedState:n}=t,i=zs?.getRunningSubAgents().length??0;return{signal:e,pid:process.pid,uptimeMs:Math.round(performance.now()-n.startTime),state:n.state,launchPhase:n.launchPhase,setupState:n.setupState,devState:n.devState,containerState:n.containerState,containerStateAgeMs:performance.now()-n.containerStateTimestamp,sinceLastRequestMs:Math.round(performance.now()-n.lastRequestTime),activeOperations:n.activeOperations,runningSubAgents:i,wsClients:r.connectionTracker.getConnectionCount(),httpClients:n.httpClients}}function LB(t){let e=zs?.explainBusy(),n=t.state==="initial"||t.state==="init-running"||t.state==="closing"||t.setupState==="installing"||t.activeOperations>0||!!e?.isBusy?"busy":"idle";t.containerState!==n&&(n==="idle"?xe.debug("Container state changed to idle"):xe.debug(`Container state changed to busy. state=${t.state} setupState=${t.setupState} activeOperations=${t.activeOperations} codegenBusy=${JSON.stringify(e)}`),t.containerState=n,t.containerStateTimestamp=performance.now())}function Na(t,e){t.launchPhase!==e&&(t.launchPhase=e,t.launchPhaseUpdatedAt=performance.now(),xe.info(`Launch phase: ${e}`))}function Bx({sys:t,sharedState:e,phase:r,operation:n,error:i}){Na(e,r);let s=i instanceof Error?i.message:String(i);e.state="init-error",e.isFinalState=!0,e.errorMessage=s,xe.error(`Launch error (${n}): ${s} ${JSON.stringify({processId:e.processId,launchPhase:e.launchPhase,state:e.state,editorReady:e.editorReady})}`),t.Sentry?.captureException(i,{level:"fatal",tags:{operation:n,launchPhase:r},extra:{processId:e.processId,state:e.state,editorReady:e.editorReady,editorReadyAt:e.editorReadyAt,editorReadySource:e.editorReadySource,launchPhaseUpdatedAt:e.launchPhaseUpdatedAt}})}async function mDe({sys:t,args:e,existingSession:r}){r&&(Oo=Promise.resolve(r),zs=r);let n=process.env.FLY_APP_NAME?{flyAppName:process.env.FLY_APP_NAME,flyMachineId:process.env.FLY_MACHINE_ID,flyRegion:process.env.FLY_REGION,flyPublicIp:process.env.FLY_PUBLIC_IP,flyVmMemoryMb:process.env.FLY_VM_MEMORY_MB,flyPrimaryRegion:process.env.PRIMARY_REGION}:void 0;n&&(t.Sentry?.setContext("flyIo",n),t.Sentry?.getCurrentScope().setContext("flyIo",n));let i=await Fl(t,e);if(wye(t,i),e.fusionInit&&sY(!0),i.privacyMode?.encryptKey&&!await XS(i.privacyMode.encryptKey))throw new Error("Invalid encryption key: key failed validation");await Wye(t,i);let s=await pmt(t,e,i),o=performance.now(),a="initial",A=!1,c={status:"ok",get state(){return a},set state(Q){a!==Q&&i.projectId&&i.branchName&&o8(t,s,{projectId:i.projectId,branchName:i.branchName,lastServerVersion:ht,lastServerState:Q},!1),a=Q},isFinalState:!1,get editorReady(){return A},set editorReady(Q){if(A&&!Q){let v=new Error("Attempted to unset editorReady");xe.error(`Ignoring editorReady regression: ${JSON.stringify({processId:process.pid,launchPhase:c.launchPhase,state:c.state,editorReadyAt:c.editorReadyAt,editorReadySource:c.editorReadySource})}`),t.Sentry?.captureException(v,{tags:{operation:"editor-ready-regression"},extra:{processId:process.pid,launchPhase:c.launchPhase,state:c.state,editorReadyAt:c.editorReadyAt,editorReadySource:c.editorReadySource}});return}!A&&Q&&(c.editorReadyAt=Date.now(),c.editorReadySource=c.launchPhase,xe.info(`Editor ready: ${JSON.stringify({processId:process.pid,source:c.editorReadySource,upTime:performance.now()-o})}`)),A=Q},initState:void 0,setupState:void 0,devState:void 0,httpServerState:void 0,errorMessage:void 0,devToolsVersion:ht,lastRequestTime:o,startTime:o,processId:process.pid,launchPhase:"state-created",launchPhaseUpdatedAt:performance.now(),workingDirectory:process.cwd(),httpClients:0,containerState:"busy",containerStateTimestamp:performance.now(),activeOperations:0,detectedServerUrl:i.autoDetectDevServer?void 0:i.serverUrl,fusionEnvironment:process.env.FUSION_ENVIRONMENT==="cloud"||process.env.FUSION_ENVIRONMENT==="cloud-v2"?process.env.FUSION_ENVIRONMENT:"unknown"},u;Na(c,"server-starting");let l,d,g,p,f,m;try{({app:l,proxyUrl:d,server:g,httpsServer:p,httpsProxyUrl:f,customHttpsProxyUrl:m}=await dmt(s,i,c,t,e))}catch(Q){throw Bx({sys:t,sharedState:c,phase:"server-error",operation:"setup-server",error:Q}),Q}Na(c,"server-listening"),Rl||(Rl=Kye(t,s,i,c)),Rl&&Rl.start(),setInterval(()=>{LB(c)},5e3);let C=Emt(t,i,n),I=!1,y=!1,B=!1,E=Q=>async()=>{LB(c);let v=hDe({signal:Q,sys:t,sharedState:c});xe.info(`Shutdown requested: signal=${Q} uptimeMs=${v.uptimeMs} containerState=${v.containerState} containerStateAgeMs=${v.containerStateAgeMs} sinceLastRequestMs=${v.sinceLastRequestMs}`,v);let D=!i.isLocal&&i.projectId&&i.branchName&&process.env.FUSION_ENVIRONMENT?.startsWith("cloud");v.containerState==="busy"&&D&&t.Sentry?.captureException(new Error("Shutdown requested while container was busy"),{extra:{...v,completionId:zs?.getLastCompletionId()},tags:{operation:"shutdown",setupState:v.setupState,launchPhase:v.launchPhase}});let S=zs?.getRunningSubAgents()??[];if(S.length>0&&t.Sentry?.captureMessage(`Pod shutdown with ${S.length} subagent(s) still running`,{level:"error",tags:{operation:"subagent-abrupt-shutdown",signal:Q,sessionId:zs?.getSessionId()},extra:{shutdownContext:v,subAgents:S.map(b=>({id:b.id,subagentType:b.subagentType,ranForMs:Date.now()-b.startedAt,turns:b.turns,state:b.state,toolsRunning:b.toolsRunning,resumed:b.resumed}))}}),c.state==="init-running"){xe.info("Init is running, skipping"),B=!0;return}if(I){xe.info("Server already closing, skipping");return}c.state="closing",I=!0,setTimeout(()=>{I=!1},1e3),xe.info("Closing server gracefully");try{g.closeAllConnections(),p&&p.closeAllConnections(),C(),Rl&&(Rl.stop(),Rl=null);let b=[new Promise(x=>g.close(x))];if(p&&b.push(new Promise(x=>p.close(x))),await Promise.race([Promise.all(b),new Promise(x=>setTimeout(x,1e3))]),u&&(await u.close(),u=void 0),!y&&c.initState?.success){y=!0;let x=await Ta();c.state="closing",x&&(xe.info("Closing codeGenServer"),Ix&&(Ix(),Ix=void 0),Ex&&(clearInterval(Ex),Ex=void 0),await x.close({uploadGitBackup:!!i.autoBackupGit,reason:`signal-${Q}`}),Oo=void 0)}await t.Sentry?.flush(2e3),process.env.BUILDER_DISABLE_AMPLITUDE!=="true"&&await fDe.flush().promise,process.exit(0)}catch(b){t.Sentry?.captureException(b);let x=b instanceof Error?b.message:String(b);xe.error(`\u274C FAILED TO CLOSE SERVER: ${x}`),process.exit(1)}};if(Mye(),process.on("SIGTERM",E("SIGTERM")),process.on("SIGINT",E("SIGINT")),e.fusionInit){c.state="init-running";let Q={operation:"fusion-init",mode:i.mode??""},v=new em({sys:t,fusionConfig:i,debug:!0,credentials:s,sentryTags:Q});c.initState=v.initState,c.initStatusLogs=v.initStatusLogs;let D=await v.init();if(String(process.env.DEVTOOLS_SKIP_POST_INIT||"").toLowerCase().match(/^(1|true|yes)$/)&&process.exit(0),!D){xe.error("\u274C Initialization failed"),t.Sentry?.captureException(new Error("Initialization failed"),{level:"fatal",tags:Q,extra:{initState:v.initState}}),c.state="init-error",c.isFinalState=!0,c.errorMessage=v.initState.error,B&&await E("init-end")();return}if(xe.info("Initialization completed successfully"),c.state="init-complete",B){await E("init-end")();return}if(i.mode==="backup"||i.mode==="backup-force-full"){await E("init-end")();return}i._attemptDryRunBackupGit&&jye({sys:t,fusionConfig:i,debug:!0,credentials:s},v.initState).then(b=>{b&&(c._attemptDryRunBackupOutcome=b.success?"success":b.error)}).catch(b=>{t.Sentry?.captureException(b,{tags:{operation:"dry-run-backup-git",dryRunBackupGit:"true"}})})}try{u=fmt(t,i,c,e,s)}catch(Q){throw Bx({sys:t,sharedState:c,phase:"dev-server-error",operation:"setup-dev-server-orchestrator",error:Q}),Q}if(Na(c,"dev-server-configured"),e.fusionInit&&u){let Q=i.nativeApp?3e5:2e3;Na(c,"setup-command-waiting");try{await Promise.race([u.ensureSetupCommand(),new Promise(v=>setTimeout(v,Q))])}catch(v){throw Bx({sys:t,sharedState:c,phase:"setup-command-error",operation:"ensure-setup-command",error:v}),v}}Na(c,"launch-server-setup"),await hmt({sys:t,credentials:s,args:e,fusionConfig:i,proxyUrl:d,httpsProxyUrl:f,customHttpsProxyUrl:m,server:g,httpsServer:p,app:l,devServer:u,sharedState:c}),await Pt("launch",{...i,dev:!!e.dev})}async function pmt(t,e,r){let n;try{if(n=await Wt(t,e,{builderPrivateKey:!0,builderPublicKey:!0}),!n.builderPublicKey||!n.builderPrivateKey){let i="You need to be logged in to use the fusion command.";return cDe(e,i),xe.error(i),Ke("Please login first with: npx builder.io login"),await Me(1)}if(!n.timestamp&&!r.projectId){let i=await t.getDeviceId();if(i)try{let s=new URL(`${Ne}/fusion/cli-key`);s.searchParams.set("host",i),s.searchParams.set("apiKey",n.builderPublicKey);let o=await Fe(s.toString(),{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.builderPrivateKey}`},method:"GET"});if(!o.ok){let c=await o.text();throw new Error(`Failed to fetch original private key: ${c}`)}let A=(await o.json())?.key;A&&(n.builderPrivateKey=A,n.timestamp=new Date().toISOString(),bx(t,n))}catch(s){t.Sentry?.captureException(new Error("Failed to fetch original private key, using existing credentials",{cause:s}))}}xe.info(`Logged in as space: ${n.spaceName||n.builderPublicKey}`)}catch(i){let s="Authentication failed.";return cDe(e,s,i instanceof Error?i.message:String(i)),xe.error(s),Ke("Please login first with: npx builder.io login"),await Me(1)}return n}async function dmt(t,e,r,n,i){let s=!!e.isLocal||!!i?.local,{httpPort:o,httpsPort:a}=await gmt(e,s);e.nativeApp?xe.info(`\u{1F50D} Setting up Builder.io API server on port ${o} (Native App Mode)`):xe.info(`\u{1F50D} Setting up Builder.io server on port ${o}`);let A=(0,PB.default)();A.use((E,Q,v)=>{let D=E.url?.startsWith(Nl),S=D&&E.url?.includes("/status-v2"),b=D&&E.url?.includes("/editor-ready");!s&&D&&!S&&!b&&xe.debug(`[HTTP]: ${E.url}`),!S&&!b&&E.query._skip_activity!=="true"&&(r.lastRequestTime=performance.now()),v()});let c=t.builderPrivateKey,u=e.authenticateProxy??!1;CDe({sys:n,app:A,validBuilderPrivateKey:c,authenticateProxy:u,isLocal:s,sharedState:r,fusionConfig:e,launchLogger:xe});let l=lDe.createServer(A),d=1e3,g=60*d;l.keepAliveTimeout=1*g,l.headersTimeout=1*g+d;let p;if(e.https)try{let{port:E,...Q}=e.httpsServerOptions??{};p=gDe.createServer(Q,A),xe.info(`\u{1F50D} Setting up HTTPS server on port ${a}`)}catch(E){xe.error(`\u274C Failed to create HTTPS server: ${E instanceof Error?E.message:String(E)}`),p=void 0}let f=e.localHttpsDomain,m=`http://localhost:${o}`,C=a?`https://localhost:${a}`:void 0,I=f&&a?`https://${f}:${a}`:void 0,y=[new Promise((E,Q)=>{l.listen(o,async()=>{xe.info(`\u{1F680} Builder.io HTTP server running at ${m}`),xe.info("Available server URLs:"),xe.info(` HTTP (localhost): ${m}`),E(!0)}),l.on("error",v=>{xe.error(`\u274C Failed to create HTTP server: ${v instanceof Error?v.message:String(v)}`),Q(v)})})];return p&&y.push(new Promise((E,Q)=>{p.listen(a,async()=>{xe.info(`\u{1F680} Builder.io HTTPS server running at ${C}`),xe.info(` HTTPS (localhost): ${C}`),I&&xe.info(` HTTPS (custom domain): ${I}`),E(!0)}),p.on("error",v=>{xe.error(`\u274C Failed to create HTTPS server: ${v instanceof Error?v.message:String(v)}`),Q(v)})})),await Promise.all(y),{app:A,proxyUrl:I||C||m,server:l,httpsServer:p,httpsProxyUrl:C,customHttpsProxyUrl:I}}function fmt(t,e,r,n,i){if(e.nativeApp){e.devCommand?xe.info(`Running ${(0,MB.cyan)(e.devCommand)} in native app mode...`):xe.info("Native app mode: No dev command specified");let s=r4(t,e,n.fusionInit&&e.setupCommand?.trim()?"not-installed":"installed");return r.devState=s.devState,r.setupState=s.setupState,r.httpServerState="ok-2xx",s.emitter.on("devState",o=>{r.devState=o}),s.emitter.on("setupState",o=>{r.setupState=o}),s}if((n.serverUrl||n.chat)&&!n.command){n.chat||xe.info(`Proxying to existing dev server at ${(0,MB.cyan)(e.serverUrl)}...`),r.devState="running",r.setupState="installed",r.httpServerState="ok-2xx";return}else{e.devCommand&&xe.info(`Running ${(0,MB.cyan)(e.devCommand)} on host ${e.serverUrl?(0,MB.cyan)(e.serverUrl):"TBD"}...`);let s=r4(t,e,n.fusionInit?"not-installed":"installed");return r.devState=s.devState,r.setupState=s.setupState,r.httpServerState=s.httpServerState.state,s.emitter.on("devState",o=>{r.devState=o}),s.emitter.on("setupState",o=>{r.setupState=o}),s.emitter.on("httpServerState",o=>{r.httpServerState=o}),s.emitter.on("urlDetected",o=>{r.detectedServerUrl=o}),oDe(o=>{if(s.httpServerState.state==="ok-2xx"){o();return}let a=A=>{A==="ok-2xx"&&(s.emitter.off("httpServerState",a),o())};s.emitter.on("httpServerState",a)}),s.emitter.on("metrics",o=>{if(o.durations)for(let a of o.durations)process.env.DEBUG&&xe.debug(`[Metrics](${a.key}): ${a.ms}ms ${a.attributes?JSON.stringify(a.attributes):""}`);fx(t,i,o).catch(a=>{t.Sentry?.captureException(a,{tags:{operation:"push-metrics"}})})}),s}}async function hmt({sys:t,credentials:e,args:r,fusionConfig:n,app:i,server:s,httpsServer:o,proxyUrl:a,httpsProxyUrl:A,customHttpsProxyUrl:c,devServer:u,sharedState:l}){async function d({force:p=!1,forcedFullBackup:f=!1}={}){xe.info(`\u{1F4E6} Attempting backup${p?" (forced)":""}${f?" (full)":""}...`);let m=await Ta();if(!m)if(n.autoBackupGit&&l.initState?.success)m=await rm(t,e,n,u,void 0,l,void 0,n.privacyMode);else return xe.info("\u{1F51A} No active session"),{success:!0,message:"No active session",skipped:!0,reason:"no_active_session"};if(!(p||n.autoBackupGit))return xe.info("\u{1F51A} Auto backup git is disabled, skipping backup"),{success:!0,message:"Auto backup git is disabled, skipping backup",skipped:!0,reason:"auto_backup_git_disabled"};if(!m.isIdle())return xe.info("\u{1F51A} Not idle, skipping backup"),{success:!1,message:"Not idle, skipping backup",skipped:!0,reason:"not_idle"};if(!f&&!await m.needsBackup())return xe.info("\u2705 Already backed up after last request"),{success:!0,message:"Already backed up",skipped:!0,reason:"already_backed_up"};try{let y=await m.uploadBackup(f);return y.success&&xe.info("\u2705 Backup successful"),y}catch(y){let B=`Backup error: ${y instanceof Error?y.message:String(y)}`;return xe.error(`\u274C ${B}`),{success:!1,message:B,error:y instanceof Error?y:new Error(String(y))}}}async function g(p){LB(l);let f=hDe({signal:`graceful:${p}`,sys:t,sharedState:l}),m=n.autoShutdown??!1;xe.info(`\u{1F504} Attempting graceful ${m?"shutdown":"backup"}: reason=${p} uptimeMs=${f.uptimeMs} containerState=${f.containerState} containerStateAgeMs=${f.containerStateAgeMs} sinceLastRequestMs=${f.sinceLastRequestMs} runningSubAgents=${f.runningSubAgents}`,f);let C=()=>{n.autoShutdown&&(xe.info("\u{1F504} Shutting down process (self-initiated SIGTERM)"),process.kill(process.pid,"SIGTERM"))},I=await d({force:!1});return I.success?(C(),I):(xe.warn(`Graceful shutdown blocked by backup: reason=${p} backupReason=${I.reason??"unknown"} \u2014 pod will keep running until externally killed`),I)}try{let p=PB.default.Router();p.post("/generate",async(v,D)=>{try{xe.debug("(generate): started");let{prompt:S,userMessage:b,canHandleTools:x,fireAndForget:P,context:{featureFlags:O}}=v.body;if(!S&&!b)return D.status(400).json({error:"No prompt/userMessage provided"});D.socket?.setNoDelay(!0),D.setHeader("Content-Type","text/event-stream; charset=utf-8"),D.setHeader("Transfer-Encoding","chunked"),D.setHeader("X-Accel-Buffering","no"),D.setHeader("Cache-Control","no-cache"),D.setHeader("Connection","keep-alive"),O&&YH(O);let J=await rm(t,e,n,u,void 0,l,void 0,n.privacyMode);if(P){Array.isArray(x)&&x.length>0&&J.setSessionCanHandleTools(x),J.waitForEventLoop(),await J.sendMessage(S?{userPrompt:S}:b),D.status(200),D.write(JSON.stringify({type:"success",message:"Message sent"})+`
|
|
4061
|
+
`);ws.writeFileSync(Ds.join(s,"thread.log"),o)}}function amt(t,e,r,n){let i=Date.now(),s=[];s.push(`# ${t.name}`),s.push(""),t.repoDescription&&(s.push(`> ${t.repoDescription}`),s.push("")),s.push("## Project Info"),s.push(""),s.push(`- **Project ID:** ${t.id}`),s.push(`- **Project Name:** ${t.name}`),t.repoFullName&&s.push(`- **Repository:** ${t.repoFullName}`),t.repoUrl&&s.push(`- **Repo URL:** ${t.repoUrl}`);let o=$4(t.createdBy,r);o&&s.push(`- **Created by:** ${o}`),s.push(`- **Active branches:** ${e}`),t.archived&&s.push("- **Status:** Archived");let a=t.settings?.folders;if(a&&a.length>0){s.push(""),s.push("## Connected Repositories"),s.push(""),s.push("This project has access to additional repositories. Each connected repo may be read-only or read/write depending on its git configuration."),s.push("");for(let d of a){let g=d.enableGit?"read/write":"read-only";s.push(`- **${d.name}** (${g})`),s.push(` - URL: ${d.remoteUrl}`),d.includePath&&s.push(` - Include path: ${d.includePath}`)}}t.repoFullName&&(s.push(""),s.push("## GitHub CLI"),s.push(""),s.push("This is a GitHub repository. You can use `gh` CLI for quick lookups:"),s.push(`- \`gh pr list --repo ${t.repoFullName}\` \u2014 open PRs`),s.push(`- \`gh pr list --repo ${t.repoFullName} --state merged --limit 5\` \u2014 recent merged PRs`),s.push(`- \`gh issue list --repo ${t.repoFullName}\` \u2014 open issues`)),s.push(""),s.push("## Full Project Data"),s.push(""),s.push("See `project.json` in this directory for complete project configuration and all branch details.");let A=new Map;for(let d of n)d.createdBy&&A.set(d.createdBy,(A.get(d.createdBy)??0)+1);let c=[...A.entries()].sort((d,g)=>g[1]-d[1]).slice(0,2);if(c.length>0){s.push(""),s.push("## Top Users"),s.push(""),s.push("| User | Branches |"),s.push("|------|----------|");for(let[d,g]of c){let p=$4(d,r)??d;s.push(`| ${p} | ${g} |`)}}let u=n.filter(d=>d.state==="active"&&typeof d.lastUpdatedAt=="number").sort((d,g)=>(g.lastUpdatedAt??0)-(d.lastUpdatedAt??0)).slice(0,5);if(u.length>0){s.push(""),s.push("## Recent Branches"),s.push("");for(let d of u){let g=V4(i-d.lastUpdatedAt),p=$4(d.createdBy,r),f=p?`, by ${p}`:"";s.push(`- \`${d.friendlyName??d.name}\` \u2014 "${d.name}" (${g}${f})`)}}let l=n.filter(d=>d.prStatus==="merged"&&typeof d.lastUpdatedAt=="number").sort((d,g)=>(g.lastUpdatedAt??0)-(d.lastUpdatedAt??0)).slice(0,5);if(l.length>0){s.push(""),s.push("## Recent Merged PRs"),s.push("");for(let d of l){let g=V4(i-d.lastUpdatedAt),p=d.friendlyName?` \u2014 "${d.friendlyName}"`:"";s.push(`- PR #${d.prNumber}: \`${d.name}\`${p} (merged ${g})`)}}return s.push(""),s.push("## Available Tools"),s.push(""),s.push('- **SpawnBranch** \u2014 Create a new branch for a coding task: `SpawnBranch({ projectId: "...", message: "..." })`'),s.push(""),s.join(`
|
|
4062
|
+
`)}async function Cx(t){let{sys:e,ownerId:r,privateKey:n,outputDir:i}=t,s=Ds.join(i,"org","projects"),o=Ds.join(i,"org");ws.mkdirSync(s,{recursive:!0}),ws.mkdirSync(o,{recursive:!0});let a=new URL("/projects/org-tree",Ne);a.searchParams.set("apiKey",r);let A=await fetch(a,{headers:{Authorization:`Bearer ${n}`}});if(!A.ok)throw new Error(`Failed to fetch org tree: ${A.status} ${A.statusText}`);let c=await A.json(),u=c.projects??[],l=c.branches??[],d=c.users??[],g=c.memories??[],p=c.messages??[];if(c.environmentVariables)for(let b of c.environmentVariables)process.env[b.key]=b.value;let f=new Map(d.map(b=>[b.userId,b])),m=new Map(u.map(b=>[b.id,b])),C=new Map;for(let b of l)b.state==="active"&&C.set(b.projectId,(C.get(b.projectId)??0)+1);function I(b){let x=b.repoFullName??b.id;return x.split("/").pop()===b.name?x:Ds.join(x,b.name)}for(let b of u){let x=Ds.join(s,I(b));ws.mkdirSync(x,{recursive:!0});let P=l.filter(_=>_.projectId===b.id).map(_=>imt(_,f));ws.writeFileSync(Ds.join(x,"project.json"),JSON.stringify({...b,branches:P},null,2));let O=l.filter(_=>_.projectId===b.id);ws.writeFileSync(Ds.join(x,"AGENTS.md"),amt(b,C.get(b.id)??0,f,O));let J=g.filter(_=>_.projectId===b.id);J.length>0&&await nx(e,J,Ds.join(x,"memories"))}let y=Date.now();function B(b){return{branchName:b.name,friendlyName:b.friendlyName,description:b.description,url:`https://builder.io/app/projects/${b.projectId}/${b.name}`,projectId:b.projectId,projectName:m.get(b.projectId)?.name,state:b.state,createdAt:typeof b.createdAt=="number"?b.createdAt:void 0,updatedAt:b.lastUpdatedAt,metadata:b.metadata,lastUpdatedAgo:V4(y-(typeof b.lastUpdatedAt=="number"?b.lastUpdatedAt:y)),createdBy:mx(b.createdBy,f,{omit:["jobFunctions"]}),deletedBy:mx(b.deletedBy,f,{omit:["jobFunctions"]}),deletedAt:b.deletedAt,archiveReason:b.archiveReason,pr:b.prNumber&&b.prUrl?{prNumber:b.prNumber,prUrl:b.prUrl,prStatus:b.prStatus,prStatusUpdatedAt:b.prStatusUpdatedAt}:void 0,prsByFolder:b.prInfoByFolder?Object.fromEntries(Object.entries(b.prInfoByFolder).map(([x,P])=>[x,{prNumber:P.prNumber,prUrl:P.prUrl,prStatus:P.status,updatedAt:P.updatedAt}])):void 0}}let E=y-10080*60*1e3,Q=l.filter(b=>b.state==="active"&&typeof b.lastUpdatedAt=="number"&&b.lastUpdatedAt>E).map(B);ws.writeFileSync(Ds.join(o,"active-branches.json"),JSON.stringify(Q,null,2));let v=l.filter(b=>b.state==="deleted"||b.state==="archived").map(B);ws.writeFileSync(Ds.join(o,"archived-branches.json"),JSON.stringify(v,null,2));let D=new Map;for(let b of l){let x=D.get(b.projectId)??[];x.push(b),D.set(b.projectId,x)}let S=u.map(b=>{let x=D.get(b.id)??[],P=new Map;for(let J of x)J.createdBy&&P.set(J.createdBy,(P.get(J.createdBy)??0)+1);let O=[...P.entries()].sort((J,_)=>_[1]-J[1]).map(([J,_])=>{let K=mx(J,f,{omit:["jobFunctions"]});return{...typeof K=="object"?K:{userId:K},branchCount:_}});return{projectId:b.id,projectName:b.name,repoUrl:b.repoUrl,description:b.description??b.repoDescription,branchCount:C.get(b.id)??0,url:`https://builder.io/app/projects/${b.id}`,moreInfoPath:`org/projects/${I(b)}/`,topUsers:O}}).sort((b,x)=>x.branchCount-b.branchCount||b.projectName.localeCompare(x.projectName));if(ws.writeFileSync(Ds.join(o,"projects.json"),JSON.stringify(S,null,2)),p.length>0){let b=Ds.join(i,"org","channels");omt(p,b)}}var ws,Ds,rmt,nmt,W4=L(()=>{"use strict";h();ws=z(require("node:fs"),1),Ds=z(require("node:path"),1);yr();B4();rmt=["kubePodName","kubeNamespace","kubePvcName","kubeHostname","needsCleanup","appName","machineId","lastMachineIdRemovedAt","volumeId","secondaryVolumeId","volumeName","ipv4","ipv6","vscodeTunnelUrl","vscodeTunnelName","vscodeTunnelExpiresAt","backups","backup","lastServerVersion","lastServerStateDate","lastServerState","lastActivityAt","lastCommitDate","lastUpdatedAt","useHomeDir","useCloudHomeDir","type","legacyId","ownerId","isFork","hidden"],nmt=["createdBy","deletedBy","lastUpdateBy","archivedBy"]});function nDe(t){Z4=t}async function tm(){if(Z4){if(z4){X4=!0;return}z4=!0;try{await Z4()}finally{z4=!1,X4&&(X4=!1,tm())}}}var Z4,z4,X4,eH=L(()=>{"use strict";h();z4=!1,X4=!1});function cmt(){let{FUSION_SNAPSHOT_MODE:t,FUSION_TRIGGER_EVENT_ID:e,FUSION_PROJECT_ID:r}=process.env;return t!=="1"?null:!e||!r?(Pp.error("FUSION_SNAPSHOT_MODE=1 but required env vars missing \u2014 cannot attach snapshot lifecycle"),null):{triggerEventId:e,projectId:r}}function oDe(t){let e=cmt();if(!e)return;Pp.info("Snapshot mode activated",{projectId:e.projectId,triggerEventId:e.triggerEventId}),t(async()=>{try{await Amt("npm",["cache","clean","--force"]),Pp.info("npm cache cleaned before snapshot")}catch(n){Pp.warn("Failed to clean npm cache \u2014 continuing anyway",{error:n instanceof Error?n.message:String(n)})}Pp.info("Dev server ready \u2014 exiting for snapshot capture"),process.exit(0)}),process.on("SIGTERM",()=>{Pp.info("SIGTERM received in snapshot mode \u2014 exiting"),process.exit(143)});let r=n=>{let i=n instanceof Error?n.message:String(n);Pp.error("Uncaught error in snapshot mode",{error:i}),process.exit(1)};process.on("uncaughtException",r),process.on("unhandledRejection",n=>r(n instanceof Error?n:new Error(String(n))))}var iDe,sDe,Amt,Pp,aDe=L(()=>{"use strict";h();iDe=require("node:child_process"),sDe=require("node:util");Bt();Amt=(0,sDe.promisify)(iDe.execFile),Pp=ve("SnapshotMode")});async function lmt(t){return new Promise(e=>{let r=Dx.createServer();r.listen(t,()=>{r.once("close",()=>{e(!0)}),r.close()}),r.on("error",()=>{e(!1)})})}async function ADe(t){let e=t,r=100;for(let n=0;n<r;n++){if(await lmt(e))return e;e=Math.floor(Math.random()*16384)+49152}throw new Error(`Could not find an available port after ${r} attempts`)}async function gmt(t,e){let r=parseInt(process.env.FUSION_SERVER_PORT??""),n=isNaN(r)?umt:r,i,s=t.fusionServerPort;if(s!==void 0)i=s,xe.info(`\u{1F50D} Using configured HTTP port: ${i}`);else{let a=e;i=n,a&&(i=await ADe(n),i!==n&&xe.info(`\u26A0\uFE0F Port ${n} is in use, using port ${i} instead`))}if(!t.https)return{httpPort:i};let o=t.httpsServerOptions?.port??await ADe(i+1);return{httpPort:i,httpsPort:o}}function cDe(t,e,r){if(t.jsonOutput){let n={type:"server_error",data:{error:e,details:r,timestamp:Date.now()}};console.log(JSON.stringify(n))}}function hDe(t){let{signal:e,sys:r,sharedState:n}=t,i=zs?.getRunningSubAgents().length??0;return{signal:e,pid:process.pid,uptimeMs:Math.round(performance.now()-n.startTime),state:n.state,launchPhase:n.launchPhase,setupState:n.setupState,devState:n.devState,containerState:n.containerState,containerStateAgeMs:performance.now()-n.containerStateTimestamp,sinceLastRequestMs:Math.round(performance.now()-n.lastRequestTime),activeOperations:n.activeOperations,runningSubAgents:i,wsClients:r.connectionTracker.getConnectionCount(),httpClients:n.httpClients}}function LB(t){let e=zs?.explainBusy(),n=t.state==="initial"||t.state==="init-running"||t.state==="closing"||t.setupState==="installing"||t.activeOperations>0||!!e?.isBusy?"busy":"idle";t.containerState!==n&&(n==="idle"?xe.debug("Container state changed to idle"):xe.debug(`Container state changed to busy. state=${t.state} setupState=${t.setupState} activeOperations=${t.activeOperations} codegenBusy=${JSON.stringify(e)}`),t.containerState=n,t.containerStateTimestamp=performance.now())}function Na(t,e){t.launchPhase!==e&&(t.launchPhase=e,t.launchPhaseUpdatedAt=performance.now(),xe.info(`Launch phase: ${e}`))}function Bx({sys:t,sharedState:e,phase:r,operation:n,error:i}){Na(e,r);let s=i instanceof Error?i.message:String(i);e.state="init-error",e.isFinalState=!0,e.errorMessage=s,xe.error(`Launch error (${n}): ${s} ${JSON.stringify({processId:e.processId,launchPhase:e.launchPhase,state:e.state,editorReady:e.editorReady})}`),t.Sentry?.captureException(i,{level:"fatal",tags:{operation:n,launchPhase:r},extra:{processId:e.processId,state:e.state,editorReady:e.editorReady,editorReadyAt:e.editorReadyAt,editorReadySource:e.editorReadySource,launchPhaseUpdatedAt:e.launchPhaseUpdatedAt}})}async function mDe({sys:t,args:e,existingSession:r}){r&&(Oo=Promise.resolve(r),zs=r);let n=process.env.FLY_APP_NAME?{flyAppName:process.env.FLY_APP_NAME,flyMachineId:process.env.FLY_MACHINE_ID,flyRegion:process.env.FLY_REGION,flyPublicIp:process.env.FLY_PUBLIC_IP,flyVmMemoryMb:process.env.FLY_VM_MEMORY_MB,flyPrimaryRegion:process.env.PRIMARY_REGION}:void 0;n&&(t.Sentry?.setContext("flyIo",n),t.Sentry?.getCurrentScope().setContext("flyIo",n));let i=await Fl(t,e);if(wye(t,i),e.fusionInit&&sY(!0),i.privacyMode?.encryptKey&&!await XS(i.privacyMode.encryptKey))throw new Error("Invalid encryption key: key failed validation");await Wye(t,i);let s=await pmt(t,e,i),o=performance.now(),a="initial",A=!1,c={status:"ok",get state(){return a},set state(Q){a!==Q&&i.projectId&&i.branchName&&o8(t,s,{projectId:i.projectId,branchName:i.branchName,lastServerVersion:ht,lastServerState:Q},!1),a=Q},isFinalState:!1,get editorReady(){return A},set editorReady(Q){if(A&&!Q){let v=new Error("Attempted to unset editorReady");xe.error(`Ignoring editorReady regression: ${JSON.stringify({processId:process.pid,launchPhase:c.launchPhase,state:c.state,editorReadyAt:c.editorReadyAt,editorReadySource:c.editorReadySource})}`),t.Sentry?.captureException(v,{tags:{operation:"editor-ready-regression"},extra:{processId:process.pid,launchPhase:c.launchPhase,state:c.state,editorReadyAt:c.editorReadyAt,editorReadySource:c.editorReadySource}});return}!A&&Q&&(c.editorReadyAt=Date.now(),c.editorReadySource=c.launchPhase,xe.info(`Editor ready: ${JSON.stringify({processId:process.pid,source:c.editorReadySource,upTime:performance.now()-o})}`)),A=Q},initState:void 0,setupState:void 0,devState:void 0,httpServerState:void 0,errorMessage:void 0,devToolsVersion:ht,lastRequestTime:o,startTime:o,processId:process.pid,launchPhase:"state-created",launchPhaseUpdatedAt:performance.now(),workingDirectory:process.cwd(),httpClients:0,containerState:"busy",containerStateTimestamp:performance.now(),activeOperations:0,detectedServerUrl:i.autoDetectDevServer?void 0:i.serverUrl,fusionEnvironment:process.env.FUSION_ENVIRONMENT==="cloud"||process.env.FUSION_ENVIRONMENT==="cloud-v2"?process.env.FUSION_ENVIRONMENT:"unknown"},u;Na(c,"server-starting");let l,d,g,p,f,m;try{({app:l,proxyUrl:d,server:g,httpsServer:p,httpsProxyUrl:f,customHttpsProxyUrl:m}=await dmt(s,i,c,t,e))}catch(Q){throw Bx({sys:t,sharedState:c,phase:"server-error",operation:"setup-server",error:Q}),Q}Na(c,"server-listening"),Rl||(Rl=Kye(t,s,i,c)),Rl&&Rl.start(),setInterval(()=>{LB(c)},5e3);let C=Emt(t,i,n),I=!1,y=!1,B=!1,E=Q=>async()=>{LB(c);let v=hDe({signal:Q,sys:t,sharedState:c});xe.info(`Shutdown requested: signal=${Q} uptimeMs=${v.uptimeMs} containerState=${v.containerState} containerStateAgeMs=${v.containerStateAgeMs} sinceLastRequestMs=${v.sinceLastRequestMs}`,v);let D=!i.isLocal&&i.projectId&&i.branchName&&process.env.FUSION_ENVIRONMENT?.startsWith("cloud");v.containerState==="busy"&&D&&t.Sentry?.captureException(new Error("Shutdown requested while container was busy"),{extra:{...v,completionId:zs?.getLastCompletionId()},tags:{operation:"shutdown",setupState:v.setupState,launchPhase:v.launchPhase}});let S=zs?.getRunningSubAgents()??[];if(S.length>0&&t.Sentry?.captureMessage(`Pod shutdown with ${S.length} subagent(s) still running`,{level:"error",tags:{operation:"subagent-abrupt-shutdown",signal:Q,sessionId:zs?.getSessionId()},extra:{shutdownContext:v,subAgents:S.map(b=>({id:b.id,subagentType:b.subagentType,ranForMs:Date.now()-b.startedAt,turns:b.turns,state:b.state,toolsRunning:b.toolsRunning,resumed:b.resumed}))}}),c.state==="init-running"){xe.info("Init is running, skipping"),B=!0;return}if(I){xe.info("Server already closing, skipping");return}c.state="closing",I=!0,setTimeout(()=>{I=!1},1e3),xe.info("Closing server gracefully");try{g.closeAllConnections(),p&&p.closeAllConnections(),C(),Rl&&(Rl.stop(),Rl=null);let b=[new Promise(x=>g.close(x))];if(p&&b.push(new Promise(x=>p.close(x))),await Promise.race([Promise.all(b),new Promise(x=>setTimeout(x,1e3))]),u&&(await u.close(),u=void 0),!y&&c.initState?.success){y=!0;let x=await Ta();c.state="closing",x&&(xe.info("Closing codeGenServer"),Ix&&(Ix(),Ix=void 0),Ex&&(clearInterval(Ex),Ex=void 0),await x.close({uploadGitBackup:!!i.autoBackupGit,reason:`signal-${Q}`}),Oo=void 0)}await t.Sentry?.flush(2e3),process.env.BUILDER_DISABLE_AMPLITUDE!=="true"&&await fDe.flush().promise,process.exit(0)}catch(b){t.Sentry?.captureException(b);let x=b instanceof Error?b.message:String(b);xe.error(`\u274C FAILED TO CLOSE SERVER: ${x}`),process.exit(1)}};if(Mye(),process.on("SIGTERM",E("SIGTERM")),process.on("SIGINT",E("SIGINT")),e.fusionInit){c.state="init-running";let Q={operation:"fusion-init",mode:i.mode??""},v=new em({sys:t,fusionConfig:i,debug:!0,credentials:s,sentryTags:Q});c.initState=v.initState,c.initStatusLogs=v.initStatusLogs;let D=await v.init();if(String(process.env.DEVTOOLS_SKIP_POST_INIT||"").toLowerCase().match(/^(1|true|yes)$/)&&process.exit(0),!D){xe.error("\u274C Initialization failed"),t.Sentry?.captureException(new Error("Initialization failed"),{level:"fatal",tags:Q,extra:{initState:v.initState}}),c.state="init-error",c.isFinalState=!0,c.errorMessage=v.initState.error,B&&await E("init-end")();return}if(xe.info("Initialization completed successfully"),c.state="init-complete",B){await E("init-end")();return}if(i.mode==="backup"||i.mode==="backup-force-full"){await E("init-end")();return}i._attemptDryRunBackupGit&&jye({sys:t,fusionConfig:i,debug:!0,credentials:s},v.initState).then(b=>{b&&(c._attemptDryRunBackupOutcome=b.success?"success":b.error)}).catch(b=>{t.Sentry?.captureException(b,{tags:{operation:"dry-run-backup-git",dryRunBackupGit:"true"}})})}try{u=fmt(t,i,c,e,s)}catch(Q){throw Bx({sys:t,sharedState:c,phase:"dev-server-error",operation:"setup-dev-server-orchestrator",error:Q}),Q}if(Na(c,"dev-server-configured"),e.fusionInit&&u){let Q=i.nativeApp?3e5:2e3;Na(c,"setup-command-waiting");try{await Promise.race([u.ensureSetupCommand(),new Promise(v=>setTimeout(v,Q))])}catch(v){throw Bx({sys:t,sharedState:c,phase:"setup-command-error",operation:"ensure-setup-command",error:v}),v}}Na(c,"launch-server-setup"),await hmt({sys:t,credentials:s,args:e,fusionConfig:i,proxyUrl:d,httpsProxyUrl:f,customHttpsProxyUrl:m,server:g,httpsServer:p,app:l,devServer:u,sharedState:c}),await Pt("launch",{...i,dev:!!e.dev})}async function pmt(t,e,r){let n;try{if(n=await Wt(t,e,{builderPrivateKey:!0,builderPublicKey:!0}),!n.builderPublicKey||!n.builderPrivateKey){let i="You need to be logged in to use the fusion command.";return cDe(e,i),xe.error(i),Ke("Please login first with: npx builder.io login"),await Me(1)}if(!n.timestamp&&!r.projectId){let i=await t.getDeviceId();if(i)try{let s=new URL(`${Ne}/fusion/cli-key`);s.searchParams.set("host",i),s.searchParams.set("apiKey",n.builderPublicKey);let o=await Fe(s.toString(),{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.builderPrivateKey}`},method:"GET"});if(!o.ok){let c=await o.text();throw new Error(`Failed to fetch original private key: ${c}`)}let A=(await o.json())?.key;A&&(n.builderPrivateKey=A,n.timestamp=new Date().toISOString(),bx(t,n))}catch(s){t.Sentry?.captureException(new Error("Failed to fetch original private key, using existing credentials",{cause:s}))}}xe.info(`Logged in as space: ${n.spaceName||n.builderPublicKey}`)}catch(i){let s="Authentication failed.";return cDe(e,s,i instanceof Error?i.message:String(i)),xe.error(s),Ke("Please login first with: npx builder.io login"),await Me(1)}return n}async function dmt(t,e,r,n,i){let s=!!e.isLocal||!!i?.local,{httpPort:o,httpsPort:a}=await gmt(e,s);e.nativeApp?xe.info(`\u{1F50D} Setting up Builder.io API server on port ${o} (Native App Mode)`):xe.info(`\u{1F50D} Setting up Builder.io server on port ${o}`);let A=(0,PB.default)();A.use((E,Q,v)=>{let D=E.url?.startsWith(Nl),S=D&&E.url?.includes("/status-v2"),b=D&&E.url?.includes("/editor-ready");!s&&D&&!S&&!b&&xe.debug(`[HTTP]: ${E.url}`),!S&&!b&&E.query._skip_activity!=="true"&&(r.lastRequestTime=performance.now()),v()});let c=t.builderPrivateKey,u=e.authenticateProxy??!1;CDe({sys:n,app:A,validBuilderPrivateKey:c,authenticateProxy:u,isLocal:s,sharedState:r,fusionConfig:e,launchLogger:xe});let l=lDe.createServer(A),d=1e3,g=60*d;l.keepAliveTimeout=1*g,l.headersTimeout=1*g+d;let p;if(e.https)try{let{port:E,...Q}=e.httpsServerOptions??{};p=gDe.createServer(Q,A),xe.info(`\u{1F50D} Setting up HTTPS server on port ${a}`)}catch(E){xe.error(`\u274C Failed to create HTTPS server: ${E instanceof Error?E.message:String(E)}`),p=void 0}let f=e.localHttpsDomain,m=`http://localhost:${o}`,C=a?`https://localhost:${a}`:void 0,I=f&&a?`https://${f}:${a}`:void 0,y=[new Promise((E,Q)=>{l.listen(o,async()=>{xe.info(`\u{1F680} Builder.io HTTP server running at ${m}`),xe.info("Available server URLs:"),xe.info(` HTTP (localhost): ${m}`),E(!0)}),l.on("error",v=>{xe.error(`\u274C Failed to create HTTP server: ${v instanceof Error?v.message:String(v)}`),Q(v)})})];return p&&y.push(new Promise((E,Q)=>{p.listen(a,async()=>{xe.info(`\u{1F680} Builder.io HTTPS server running at ${C}`),xe.info(` HTTPS (localhost): ${C}`),I&&xe.info(` HTTPS (custom domain): ${I}`),E(!0)}),p.on("error",v=>{xe.error(`\u274C Failed to create HTTPS server: ${v instanceof Error?v.message:String(v)}`),Q(v)})})),await Promise.all(y),{app:A,proxyUrl:I||C||m,server:l,httpsServer:p,httpsProxyUrl:C,customHttpsProxyUrl:I}}function fmt(t,e,r,n,i){if(e.nativeApp){e.devCommand?xe.info(`Running ${(0,MB.cyan)(e.devCommand)} in native app mode...`):xe.info("Native app mode: No dev command specified");let s=rH(t,e,n.fusionInit&&e.setupCommand?.trim()?"not-installed":"installed");return r.devState=s.devState,r.setupState=s.setupState,r.httpServerState="ok-2xx",s.emitter.on("devState",o=>{r.devState=o}),s.emitter.on("setupState",o=>{r.setupState=o}),s}if((n.serverUrl||n.chat)&&!n.command){n.chat||xe.info(`Proxying to existing dev server at ${(0,MB.cyan)(e.serverUrl)}...`),r.devState="running",r.setupState="installed",r.httpServerState="ok-2xx";return}else{e.devCommand&&xe.info(`Running ${(0,MB.cyan)(e.devCommand)} on host ${e.serverUrl?(0,MB.cyan)(e.serverUrl):"TBD"}...`);let s=rH(t,e,n.fusionInit?"not-installed":"installed");return r.devState=s.devState,r.setupState=s.setupState,r.httpServerState=s.httpServerState.state,s.emitter.on("devState",o=>{r.devState=o}),s.emitter.on("setupState",o=>{r.setupState=o}),s.emitter.on("httpServerState",o=>{r.httpServerState=o}),s.emitter.on("urlDetected",o=>{r.detectedServerUrl=o}),oDe(o=>{if(s.httpServerState.state==="ok-2xx"){o();return}let a=A=>{A==="ok-2xx"&&(s.emitter.off("httpServerState",a),o())};s.emitter.on("httpServerState",a)}),s.emitter.on("metrics",o=>{if(o.durations)for(let a of o.durations)process.env.DEBUG&&xe.debug(`[Metrics](${a.key}): ${a.ms}ms ${a.attributes?JSON.stringify(a.attributes):""}`);fx(t,i,o).catch(a=>{t.Sentry?.captureException(a,{tags:{operation:"push-metrics"}})})}),s}}async function hmt({sys:t,credentials:e,args:r,fusionConfig:n,app:i,server:s,httpsServer:o,proxyUrl:a,httpsProxyUrl:A,customHttpsProxyUrl:c,devServer:u,sharedState:l}){async function d({force:p=!1,forcedFullBackup:f=!1}={}){xe.info(`\u{1F4E6} Attempting backup${p?" (forced)":""}${f?" (full)":""}...`);let m=await Ta();if(!m)if(n.autoBackupGit&&l.initState?.success)m=await rm(t,e,n,u,void 0,l,void 0,n.privacyMode);else return xe.info("\u{1F51A} No active session"),{success:!0,message:"No active session",skipped:!0,reason:"no_active_session"};if(!(p||n.autoBackupGit))return xe.info("\u{1F51A} Auto backup git is disabled, skipping backup"),{success:!0,message:"Auto backup git is disabled, skipping backup",skipped:!0,reason:"auto_backup_git_disabled"};if(!m.isIdle())return xe.info("\u{1F51A} Not idle, skipping backup"),{success:!1,message:"Not idle, skipping backup",skipped:!0,reason:"not_idle"};if(!f&&!await m.needsBackup())return xe.info("\u2705 Already backed up after last request"),{success:!0,message:"Already backed up",skipped:!0,reason:"already_backed_up"};try{let y=await m.uploadBackup(f);return y.success&&xe.info("\u2705 Backup successful"),y}catch(y){let B=`Backup error: ${y instanceof Error?y.message:String(y)}`;return xe.error(`\u274C ${B}`),{success:!1,message:B,error:y instanceof Error?y:new Error(String(y))}}}async function g(p){LB(l);let f=hDe({signal:`graceful:${p}`,sys:t,sharedState:l}),m=n.autoShutdown??!1;xe.info(`\u{1F504} Attempting graceful ${m?"shutdown":"backup"}: reason=${p} uptimeMs=${f.uptimeMs} containerState=${f.containerState} containerStateAgeMs=${f.containerStateAgeMs} sinceLastRequestMs=${f.sinceLastRequestMs} runningSubAgents=${f.runningSubAgents}`,f);let C=()=>{n.autoShutdown&&(xe.info("\u{1F504} Shutting down process (self-initiated SIGTERM)"),process.kill(process.pid,"SIGTERM"))},I=await d({force:!1});return I.success?(C(),I):(xe.warn(`Graceful shutdown blocked by backup: reason=${p} backupReason=${I.reason??"unknown"} \u2014 pod will keep running until externally killed`),I)}try{let p=PB.default.Router();p.post("/generate",async(v,D)=>{try{xe.debug("(generate): started");let{prompt:S,userMessage:b,canHandleTools:x,fireAndForget:P,context:{featureFlags:O}}=v.body;if(!S&&!b)return D.status(400).json({error:"No prompt/userMessage provided"});D.socket?.setNoDelay(!0),D.setHeader("Content-Type","text/event-stream; charset=utf-8"),D.setHeader("Transfer-Encoding","chunked"),D.setHeader("X-Accel-Buffering","no"),D.setHeader("Cache-Control","no-cache"),D.setHeader("Connection","keep-alive"),O&&Y4(O);let J=await rm(t,e,n,u,void 0,l,void 0,n.privacyMode);if(P){Array.isArray(x)&&x.length>0&&J.setSessionCanHandleTools(x),J.waitForEventLoop(),await J.sendMessage(S?{userPrompt:S}:b),D.status(200),D.write(JSON.stringify({type:"success",message:"Message sent"})+`
|
|
4063
4063
|
`),D.end();return}let _=setInterval(async()=>{let j={type:"ping"};D.write(JSON.stringify(j)+`
|
|
4064
4064
|
`)},5e3),K=J.connectToEventLoop(!1,j=>{D.write(JSON.stringify(j)+`
|
|
4065
4065
|
`)},{canHandleTools:Array.isArray(x)?x:[]});try{await J.sendMessage(S?{userPrompt:S}:b),await J.waitUntilIdle()}catch(j){t.Sentry?.captureException(j);let ee=j instanceof Error?j.message:String(j);D.write(`${JSON.stringify({type:"error",message:`Error: ${ee}`})}
|
|
@@ -4067,7 +4067,7 @@ ${t.markdown}`}function omt(t,e){ws.rmSync(e,{recursive:!0,force:!0});let r=new
|
|
|
4067
4067
|
|
|
4068
4068
|
`),D.end()):D.status(500).json({error:b})}finally{xe.debug("(generate): finished")}}),p.post("/sync",async(v,D)=>{try{xe.debug("(sync): started");let b=await(await rm(t,e,n,u,void 0,l)).syncChangesFromRemote(v.body);D.json({ok:!0,result:b})}catch(S){t.Sentry?.captureException(S);let b=S instanceof Error?S.message:String(S);D.status(500).json({error:b})}finally{xe.debug("(sync): finished")}}),p.post("/tool-result",async(v,D)=>{try{let{toolCallId:S,result:b}=v.body;if(!S)return D.status(400).json({error:"No toolCallId provided"});let x=await Ta();if(!x)return D.status(404).json({error:"No active session found"});let P=typeof b=="string"?b:{toolResult:b?.toolResult??"",isError:!!b?.isError};if(!x.toolFullfilment(S,P))return D.status(404).json({error:"No pending tool call found with that id"});D.json({success:!0})}catch(S){t.Sentry?.captureException(S);let b=S instanceof Error?S.message:String(S);D.status(500).json({error:b})}}),p.post("/connect",async(v,D)=>{let{canHandleTools:S}=v.body;D.socket?.setNoDelay(!0),D.setHeader("X-Accel-Buffering","no"),D.setHeader("Cache-Control","no-cache"),D.setHeader("Connection","keep-alive");let b=await Ta();if(!b)return D.setHeader("Content-Type","application/json"),D.status(404).json({error:"No active session found"});try{xe.debug("(connect): started"),D.setHeader("Content-Type","text/event-stream; charset=utf-8"),D.setHeader("Transfer-Encoding","chunked");let x=setInterval(async()=>{let O={type:"ping"};D.write(JSON.stringify(O)+`
|
|
4069
4069
|
`)},5e3),P=b.connectToEventLoop(!1,O=>{D.write(JSON.stringify(O)+`
|
|
4070
|
-
`)},{canHandleTools:Array.isArray(S)?S:[]});try{await b.waitUntilIdle()}finally{P(),clearInterval(x)}}finally{D.end(),xe.debug("(connect): finished")}}),p.get("/get-zip",async(v,D)=>{l.activeOperations++;try{let b=await(await rm(t,e,n,u,void 0,l,void 0,n.privacyMode)).archiveProject();D.setHeader("Content-Type","application/zip"),D.setHeader("Content-Disposition",`attachment; filename="${t.basename(b)}"`),await new Promise((x,P)=>{D.download(b,O=>{t.unlink(b).catch(J=>{t.Sentry?.captureException(J)}),O?P(O):x()})})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to create project archive",details:S instanceof Error?S.message:String(S)})}finally{l.activeOperations--}});let f=async(v,D)=>{l.activeOperations++;try{let b=await(await rm(t,e,n,u,void 0,l,void 0,n.privacyMode)).zipFolder(D);v.setHeader("Content-Type","application/zip"),v.setHeader("Content-Disposition",'attachment; filename="project.zip"'),await new Promise((x,P)=>{v.download(b,O=>{t.unlink(b).catch(J=>{t.Sentry?.captureException(J)}),O?P(O):x()})})}catch(S){t.Sentry?.captureException(S),v.status(500).json({error:"Failed to create project archive",details:S instanceof Error?S.message:String(S)})}finally{l.activeOperations--}};if(p.get("/download-zip",async(v,D)=>{await f(D,".")}),p.get("/download-zip/*folderName",async(v,D)=>{let S=v.params.folderName,b=Array.isArray(S)?S.join("/"):S;if(xe.debug("folderName",b),typeof b!="string"){D.status(400).json({error:"Invalid folder name"});return}let x=b.length===0?".":b;await f(D,x)}),p.post("/shutdown",async(v,D)=>{try{let S=await g("api-request");S?.success?D.json(S):D.status(500).json(S)}catch(S){t.Sentry?.captureException(S),D.status(500).json({success:!1,error:"Failed to shutdown",details:S instanceof Error?S.message:String(S)})}}),p.post("/backup",async(v,D)=>{l.activeOperations++;try{let{force:S=!1,forcedFullBackup:b=!1}=v.body||{},x=await d({force:S,forcedFullBackup:b});x?.success?D.json(x):D.status(500).json(x)}catch(S){t.Sentry?.captureException(S),D.status(500).json({success:!1,error:"Failed to backup",details:S instanceof Error?S.message:String(S)})}finally{l.activeOperations--}}),p.get("/tunnel/status",async(v,D)=>{try{let{getTunnelManager:S,VSCodeTunnelManager:b}=await Promise.resolve().then(()=>(oh(),QE));if(!b.isEnabled()){D.json({enabled:!1,status:"stopped",message:"VS Code tunnel is not enabled",name:null,url:null,vscodeUri:null,cursorUri:null,webUrl:null,error:null,workspacePath:b.getWorkspacePath()});return}let x=S();D.json({enabled:!0,...x.getInfo()})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to get tunnel status",details:S instanceof Error?S.message:String(S)})}}),p.post("/tunnel/start",async(v,D)=>{try{let{getTunnelManager:S,VSCodeTunnelManager:b}=await Promise.resolve().then(()=>(oh(),QE));if(!b.isEnabled()){D.status(400).json({error:"VS Code tunnel has been disabled for this environment."});return}let x=S();if(x.getStatus()==="running"){D.json({message:"Tunnel already running",enabled:!0,...x.getInfo()});return}let O=b.getTunnelName(n.projectId,n.branchName),J=b.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${O}`),x.on("error",j=>{xe.error(`\u274C VS Code tunnel error: ${j}`),t.Sentry?.captureException(new Error(String(j)),{tags:{operation:"vscode-tunnel-error-event"}})});let _=await x.start({name:O,workspacePath:J,acceptLicense:!0,autoRestart:!0}),K=_.status==="running"?"Tunnel started":_.status==="starting"?"Tunnel starting":`Tunnel ${_.status}`;D.json({message:K,enabled:!0,..._})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to start tunnel",details:S instanceof Error?S.message:String(S)})}}),p.post("/tunnel/stop",async(v,D)=>{try{let{getTunnelManager:S,VSCodeTunnelManager:b}=await Promise.resolve().then(()=>(oh(),QE));if(!b.isEnabled()){D.status(400).json({error:"VS Code tunnel is not enabled"});return}let x=S();await x.stop(),xe.info("\u{1F517} VS Code tunnel stopped"),D.json({message:"Tunnel stopped",enabled:!0,...x.getInfo()})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to stop tunnel",details:S instanceof Error?S.message:String(S)})}}),p.get("/download-gif/:filePath",async(v,D)=>{try{let S=v.params.filePath;if(!S||typeof S!="string"){D.status(400).json({error:"Session ID is required"});return}if(!/^[a-zA-Z0-9\._-]+$/.test(S)){D.status(400).json({error:"Invalid session ID format"});return}if(S.length>200){D.status(400).json({error:"Session ID too long"});return}let b=t.join(pDe.default.homedir(),".builder","recordings"),x=t.join(b,S),P;try{P=(await t.stat(x)).size,xe.debug(`[download-gif] File found: ${x} (${P} bytes)`)}catch{try{let j=await
|
|
4070
|
+
`)},{canHandleTools:Array.isArray(S)?S:[]});try{await b.waitUntilIdle()}finally{P(),clearInterval(x)}}finally{D.end(),xe.debug("(connect): finished")}}),p.get("/get-zip",async(v,D)=>{l.activeOperations++;try{let b=await(await rm(t,e,n,u,void 0,l,void 0,n.privacyMode)).archiveProject();D.setHeader("Content-Type","application/zip"),D.setHeader("Content-Disposition",`attachment; filename="${t.basename(b)}"`),await new Promise((x,P)=>{D.download(b,O=>{t.unlink(b).catch(J=>{t.Sentry?.captureException(J)}),O?P(O):x()})})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to create project archive",details:S instanceof Error?S.message:String(S)})}finally{l.activeOperations--}});let f=async(v,D)=>{l.activeOperations++;try{let b=await(await rm(t,e,n,u,void 0,l,void 0,n.privacyMode)).zipFolder(D);v.setHeader("Content-Type","application/zip"),v.setHeader("Content-Disposition",'attachment; filename="project.zip"'),await new Promise((x,P)=>{v.download(b,O=>{t.unlink(b).catch(J=>{t.Sentry?.captureException(J)}),O?P(O):x()})})}catch(S){t.Sentry?.captureException(S),v.status(500).json({error:"Failed to create project archive",details:S instanceof Error?S.message:String(S)})}finally{l.activeOperations--}};if(p.get("/download-zip",async(v,D)=>{await f(D,".")}),p.get("/download-zip/*folderName",async(v,D)=>{let S=v.params.folderName,b=Array.isArray(S)?S.join("/"):S;if(xe.debug("folderName",b),typeof b!="string"){D.status(400).json({error:"Invalid folder name"});return}let x=b.length===0?".":b;await f(D,x)}),p.post("/shutdown",async(v,D)=>{try{let S=await g("api-request");S?.success?D.json(S):D.status(500).json(S)}catch(S){t.Sentry?.captureException(S),D.status(500).json({success:!1,error:"Failed to shutdown",details:S instanceof Error?S.message:String(S)})}}),p.post("/backup",async(v,D)=>{l.activeOperations++;try{let{force:S=!1,forcedFullBackup:b=!1}=v.body||{},x=await d({force:S,forcedFullBackup:b});x?.success?D.json(x):D.status(500).json(x)}catch(S){t.Sentry?.captureException(S),D.status(500).json({success:!1,error:"Failed to backup",details:S instanceof Error?S.message:String(S)})}finally{l.activeOperations--}}),p.get("/tunnel/status",async(v,D)=>{try{let{getTunnelManager:S,VSCodeTunnelManager:b}=await Promise.resolve().then(()=>(oh(),QE));if(!b.isEnabled()){D.json({enabled:!1,status:"stopped",message:"VS Code tunnel is not enabled",name:null,url:null,vscodeUri:null,cursorUri:null,webUrl:null,error:null,workspacePath:b.getWorkspacePath()});return}let x=S();D.json({enabled:!0,...x.getInfo()})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to get tunnel status",details:S instanceof Error?S.message:String(S)})}}),p.post("/tunnel/start",async(v,D)=>{try{let{getTunnelManager:S,VSCodeTunnelManager:b}=await Promise.resolve().then(()=>(oh(),QE));if(!b.isEnabled()){D.status(400).json({error:"VS Code tunnel has been disabled for this environment."});return}let x=S();if(x.getStatus()==="running"){D.json({message:"Tunnel already running",enabled:!0,...x.getInfo()});return}let O=b.getTunnelName(n.projectId,n.branchName),J=b.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${O}`),x.on("error",j=>{xe.error(`\u274C VS Code tunnel error: ${j}`),t.Sentry?.captureException(new Error(String(j)),{tags:{operation:"vscode-tunnel-error-event"}})});let _=await x.start({name:O,workspacePath:J,acceptLicense:!0,autoRestart:!0}),K=_.status==="running"?"Tunnel started":_.status==="starting"?"Tunnel starting":`Tunnel ${_.status}`;D.json({message:K,enabled:!0,..._})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to start tunnel",details:S instanceof Error?S.message:String(S)})}}),p.post("/tunnel/stop",async(v,D)=>{try{let{getTunnelManager:S,VSCodeTunnelManager:b}=await Promise.resolve().then(()=>(oh(),QE));if(!b.isEnabled()){D.status(400).json({error:"VS Code tunnel is not enabled"});return}let x=S();await x.stop(),xe.info("\u{1F517} VS Code tunnel stopped"),D.json({message:"Tunnel stopped",enabled:!0,...x.getInfo()})}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to stop tunnel",details:S instanceof Error?S.message:String(S)})}}),p.get("/download-gif/:filePath",async(v,D)=>{try{let S=v.params.filePath;if(!S||typeof S!="string"){D.status(400).json({error:"Session ID is required"});return}if(!/^[a-zA-Z0-9\._-]+$/.test(S)){D.status(400).json({error:"Invalid session ID format"});return}if(S.length>200){D.status(400).json({error:"Session ID too long"});return}let b=t.join(pDe.default.homedir(),".builder","recordings"),x=t.join(b,S),P;try{P=(await t.stat(x)).size,xe.debug(`[download-gif] File found: ${x} (${P} bytes)`)}catch{try{let j=await tH.default.promises.readdir(b);xe.debug(`[download-gif] File NOT found: ${x}. Recordings dir contains: [${j.join(", ")}]`)}catch{xe.debug(`[download-gif] File NOT found: ${x}. Recordings dir does not exist: ${b}`)}D.status(404).json({error:"GIF not found for this session",path:x});return}let O=dDe.default.extname(S).toLowerCase(),J={".gif":"image/gif",".webp":"image/webp",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".json":"application/json"};D.setHeader("Content-Type",J[O]||"application/octet-stream"),D.setHeader("Content-Disposition",`inline; filename="${S}"`),D.setHeader("Content-Length",P);let _=tH.default.createReadStream(x);_.on("error",K=>{t.Sentry?.captureException(K),xe.error(`[download-gif] Stream error: ${K.message}`),D.headersSent||D.status(500).json({error:"Failed to read file",details:K.message})}),_.pipe(D)}catch(S){t.Sentry?.captureException(S),D.status(500).json({error:"Failed to download GIF",details:S instanceof Error?S.message:String(S)})}}),p.get("/local-history",async(v,D)=>{try{let S=t.getCwdDir(),b=await Pv(t,S);D.json({history:b})}catch(S){D.status(500).json({error:"Failed to read local history",details:S instanceof Error?S.message:String(S)})}}),n?.autoBackupGit||n.autoShutdown){let b=(n.autoShutdownThresholdMinutes??60)*60,x=b*1e3,P=!1,O=setInterval(async()=>{let J=performance.now()-l.containerStateTimestamp;if(l.containerState==="idle"&&J>x){if(P){xe.info("\u23F0 Shutdown already in progress");return}xe.info(`\u23F0 Threshold reached (${Math.round(b)} seconds without requests)`),P=!0;try{(await g("inactivity-timeout"))?.success&&clearInterval(O)}catch(_){let K=new Error("Failed to gracefully shutdown server",{cause:_});t.Sentry?.captureException(K,{tags:{operation:"shutdown"}})}finally{P=!1}}},1e3*10);process.on("exit",()=>clearInterval(O))}let m;if(!n.nativeApp){let v=bs(n.serverUrl),D=IDe(),S=!u&&v?wx(v,t):void 0,b=(x,P,O)=>{if(x.url?.startsWith(Tl)){O();return}else{let J=u?.proxyMiddleware??S,_=bs(typeof x.headers["fusion-forwarded-target"]=="string"?x.headers["fusion-forwarded-target"].toLowerCase():void 0),K=x.headers["fusion-forwarded-default-origin"]==="true",j=J&&K;if(_&&CA(_)&&!j&&_.origin!==J?.target.origin){D.web(x,P,{target:_.origin,...uDe(_.protocol)&&{secure:!1,agent:Qx}});return}else if(J)J(x,P,O);else{P.status(502).json({error:"The proxy is not ready yet. Dev Server URL is configured."});return}}};i.use("/",b),m=(x,P,O)=>{let{pathname:J}=new URL(x.url??"/","wss://base.url"),_=u?.proxyMiddleware??S,K=bs(typeof x.headers["fusion-forwarded-target"]=="string"?x.headers["fusion-forwarded-target"].toLowerCase():void 0),j=x.headers["fusion-forwarded-default-origin"]==="true",ee=_&&j;if(K&&CA(K)&&!ee&&Bmt(K.origin)!==_?.target.origin){t.debug(`Pass through WebSocket connection for: ${J} to ${K.origin}`),D.ws(x,P,O,{target:K.origin,...uDe(K.protocol)&&{secure:!1,agent:Qx}},U=>{U&&(t.debug(`Proxy error: ${U}`),P.writable&&P.write(`HTTP/1.1 500 Internal Server Error\r
|
|
4071
4071
|
\r
|
|
4072
4072
|
`),P.destroy())});return}else if(_)try{t.debug(`Proxying WebSocket connection to: ${J}`),_.upgrade(x,P,O)}catch(U){t.debug(`WebSocket proxy error: ${U}`),P.writable&&P.write(`HTTP/1.1 500 Internal Server Error\r
|
|
4073
4073
|
\r
|
|
@@ -4077,7 +4077,7 @@ ${t.markdown}`}function omt(t,e){ws.rmSync(e,{recursive:!0,force:!0});let r=new
|
|
|
4077
4077
|
\r
|
|
4078
4078
|
`),D.destroy();return}C.handleUpgrade(v,D,S,function(O){O.emit("connection",O,v)})}else if(m)m(v,D,S);else{t.debug(`Native app mode: Rejecting WebSocket connection to: ${b}`),D.writable&&D.write(`HTTP/1.1 404 Not Found\r
|
|
4079
4079
|
\r
|
|
4080
|
-
`),D.destroy();return}};s.on("upgrade",I),o?.on("upgrade",I),Cmt({ws:C,sys:t,credentials:e,fusionConfig:n,devServer:u,sharedState:l}),Na(l,"websocket-ready"),l.state="ready",Na(l,"state-ready");try{let{getTunnelManager:v,VSCodeTunnelManager:D}=await Promise.resolve().then(()=>(oh(),QE));if(D.isEnabled()&&D.isAutoStartEnabled()){let S=D.getTunnelName(n.projectId,n.branchName),b=D.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${S}`);let x=v();x.on("error",P=>{xe.error(`\u274C VS Code tunnel error: ${P}`),t.Sentry?.captureException(new Error(String(P)),{tags:{operation:"vscode-tunnel-error-event"}})}),x.start({name:S,workspacePath:b,acceptLicense:!0,autoRestart:!0}).then(P=>{P.status==="running"&&P.webUrl&&(xe.info(`\u2705 VS Code tunnel ready: ${P.webUrl}`),P.vscodeUri&&xe.info(` VS Code: ${P.vscodeUri}`),P.cursorUri&&xe.info(` Cursor: ${P.cursorUri}`))}).catch(P=>{xe.error(`\u274C VS Code tunnel failed: ${P.message}`),t.Sentry?.captureException(P,{tags:{operation:"vscode-tunnel-auto-start"}})})}}catch(v){t.Sentry?.captureException(v,{tags:{operation:"vscode-tunnel-init"}})}Na(l,"editor-url-building");let y=r.app||r.nativeApp?"builder://":r.dev?"http://localhost:1234":"https://builder.io",B=new URL(`${y}/app/projects/local`);B.searchParams.set("localEditUrl",a);let E=await t.getDeviceId();if(E&&B.searchParams.set("host",E),e.builderPublicKey&&B.searchParams.set("spaceId",e.builderPublicKey),r.chat&&B.searchParams.set("chatOnly","true"),Na(l,"editor-url-ready"),l.editorReady=!0,Na(l,"editor-ready"),r.jsonOutput){let v={type:"server_ready",data:{proxyUrl:a,httpsProxyUrl:A,customHttpsProxyUrl:c,fusionEditorUrl:n.nativeApp?null:B.href,urlHost:y,command:n.devCommand,serverUrl:n.serverUrl,credentials:e,nativeApp:n.nativeApp}};console.log(JSON.stringify(v))}if(r.open===!1)n.isLocal&&xe.info(`\u{1F517} Access Builder.io at: ${B.href}`);else{xe.info(`OPEN BROWSER: ${B.href}`);try{await xl(B.href)}catch(v){xe.error(`Failed to open browser: ${v instanceof Error?v.message:String(v)}`),t.Sentry?.captureException(v,{tags:{operation:"open-browser",launchPhase:l.launchPhase},extra:{processId:l.processId,editorReady:l.editorReady,editorReadyAt:l.editorReadyAt}})}}}catch(p){Bx({sys:t,sharedState:l,phase:"launch-error",operation:"setup-launch-server",error:p})}}function Cmt({ws:t,sys:e,fusionConfig:r,credentials:n,devServer:i,sharedState:s}){let o=!1;t.register("initializeSession",async u=>{let l,d,g,p;if(typeof u[0]=="object"&&u[0]?{sessionId:l,customInstructions:d,privacyMode:g,forceSessionReload:p}=u[0]:typeof u[0]=="string"&&(l=u[0]),p&&r.isLocal&&l&&zs&&zs.getSessionId()!==l){yx?.abort(),o=!1;let m=zs;Oo=void 0,zs=void 0,m.close({reason:"forceSessionReload"})}else if(p&&r.isLocal&&l&&!zs&&Oo){yx?.abort(),o=!1;let m=Oo;Oo=void 0,m.then(C=>C.close({uploadGitBackup:!1,reason:"forceSessionReload"})).catch(()=>{})}let f=await rm(e,n,r,i,l,s,d,g||r.privacyMode);return o||(o=!0,KA(n,"/events/publish",{event:Zne,extraData:{sessionId:f.getSessionId(),sessionType:r.branchType??"interactive",projectId:r.projectId,branchName:r.branchName,platform:process.platform}})),f.getSessionId()}),t.register("connectToEventLoop",async(u,l)=>{let d=await Ta();if(!d)throw new Error("Server not found");let g=t.clients().get(l);if(!g)throw new Error("Client not found");let p=d.getSessionId(),f=d.connectToEventLoop(!0,m=>{t.notify(`${p}/event`,l,[JSON.stringify(m)])},{canHandleTools:["AskUserQuestion","GetScreenshot","ExitPlanMode","NavigatePreview","ProposeEnvVariable"]});g.on("close",f)}),t.register("setFeatureFlags",async u=>{YH(u[0])});function a(u){t.register(u,async([l,...d])=>{s.lastRequestTime=performance.now();let g=Uo();!r.isLocal&&process.env.DEBUG&&xe.debug(`[WS](${u}-${g}): ${JSON.stringify(d)}`);let p=performance.now();try{let f=await Ta();if(!f)throw new Error("Server not found");let m=f[u];if(typeof m!="function")throw new Error(`Method ${u} not found on codeGenServer`);let C=await m.apply(f,d);if(!r.isLocal){let I=Math.round(performance.now()-p);xe.info(`[WS](${u}-${g}): success [${I}ms]`)}return C}catch(f){if(!r.isLocal){let m=Math.round(performance.now()-p);xe.warn(`[WS](${u}-${g}): error [${m}ms]`)}throw f instanceof dt||e.Sentry?.captureException(f,{tags:{functionName:u},extra:{args:d}}),f}})}mmt.forEach(u=>{a(u)});let A=new Map;t.register("subscribeToDiagnostics",async(u,l)=>{s.lastRequestTime=performance.now();let[d]=u,g=await Ta();if(!g)throw new Error("Server not found");let p=t.clients().get(l);if(!p)throw new Error("Client not found");let f=A.get(l);f&&(f(),A.delete(l));let m=g.subscribeToDiagnostics(C=>t.notify(`${d}/tsserver-event`,l,C));return A.set(l,m),p.once("close",()=>{m(),A.delete(l)}),{ok:!0}}),t.register("unsubscribeFromDiagnostics",async(u,l)=>{let d=A.get(l);return d&&(d(),A.delete(l)),{ok:!0}}),t.register("ping",()=>({version:ht,supports:["customInstructions","newChat","clearSession","appCustomInstructions","fileWatcher","discardChanges","searchFileTree","listDir","listCustomInstructions","tsserver"]})),t.register("getProcessInfo",()=>(s.lastRequestTime=performance.now(),r.isLocal?{pid:process.pid,cwd:process.cwd(),localMode:!0}:{error:"Process info only available in local mode"})),t.register("getBuilderRules",async()=>{s.lastRequestTime=performance.now();let u=await Ta();if(!u){let l=e.resolve(e.getAppRootDir(),".builderrules");return await e.exists(l)?await e.readFile(l):null}try{return await u.readFile(".builderrules",!0)}catch{return null}}),t.register("setBuilderRules",async u=>{s.lastRequestTime=performance.now();let l=await Ta(),d=u[1];if(!l){let g=e.resolve(e.getAppRootDir(),".builderrules");d?await e.writeFile(g,d):await e.exists(g)&&await e.unlink(g);return}d?await l.writeFile(".builderrules",d,!0):await l.deleteFile(".builderrules",!0)}),t.register("subscribeTerminal",async(u,l)=>{s.lastRequestTime=performance.now();let[d,{terminalId:g}]=u,p=t.clients().get(l);if(!p)throw new Error("Client not found");let f=await Ta();if(!f)throw new Error("Server not found");let m=f.subscribeTerminal({terminalId:g,onData:C=>t.notify(`${d}/terminal/${g}`,l,[C]),onExit:C=>t.notify(`${d}/terminal/${g}/exit`,l,[C])});return m&&p.on("close",m),{ok:!0,created:!!m}});let c=new Map;t.register("subscribeToFileChanges",async(u,l)=>{s.lastRequestTime=performance.now();let[d]=u,g=await Ta();if(!g)throw new Error("Server not found");let p=t.clients().get(l);if(!p)throw new Error("Client not found");let f=c.get(l);f&&(await f(),c.delete(l));let m=g.subscribeToFileChanges(C=>t.notify(`${d}/file-changes`,l,C));return c.set(l,m),p.once("close",async()=>{await m(),c.delete(l)}),{ok:!0}}),t.register("unsubscribeFromFileChanges",async(u,l)=>{let d=c.get(l);return d&&(await d(),c.delete(l)),{ok:!0}})}async function Imt(t,e,r,n,i,s,o,a,A){let c=[],l=!A?.enabled&&r.projectId&&r.branchName&&process.env.FUSION_ENVIRONMENT?.startsWith("cloud")&&(typeof r.browserAutomationInstructions=="string"||qH("fusion-direct-browser")),d=r.branchType==="code-review",g=qH("fusion-enable-browser-agents-main-branch");l&&(d||g)&&(c.push(SQe),c.push(RQe)),d&&(c.push(Xh),c.push(eQe),c.push(iQe)),r.branchType==="setup-project"&&(c.push(Xh),c.push(JQe)),r.branchType==="org-agent"&&(c.push($Qe),c.push(XQe)),r.branchType==="design-system-indexing"&&(c.push(AQe),c.push(gQe),c.push(hQe),c.push(EQe),c.push(DQe)),r.branchType||(c.push(Xh),c.push(ix),c.push(PQe),c.push(GQe));let p=new ka({sys:t,credentials:e,position:"fusion",sessionOrCompletionId:r.sessionId??i,maxTokens:8e4,mcpServers:!0,autoImportLocalMCPs:!0,fusionConfig:r,privacyMode:A,builtInMCPServerConfig:r.mcpServers,builtInCustomInstructions:a??[],builtInCustomAgents:c,agentType:r.agentType,devServerOrchestrator:n,git:!!r.projectId,fusionStatusMonitor:Rl??void 0,gitAutoInit:!0,persistSessionLocally:r.isLocal});r.projectId&&p.setDebug(!0);try{if(r.isLocal){let f=await EDe();if(f)throw Zr(f),f}r.branchType==="design-system-indexing"&&r.figmaDecodeJobId&&await Fye({sys:t,credentials:e,jobId:r.figmaDecodeJobId,workspaceRoot:p.primaryGitPath}),await p.initializeSession()}catch(f){throw o.aborted||(s.state="session-error",s.errorMessage=f instanceof Error?f.message:String(f)),f}if(o.aborted||(s.state="active-session",s.isFinalState=!0,s.sessionId=p.getSessionId()),!o.aborted&&r.branchType==="org-agent"){let f=t.join(p.primaryGitPath,"cron-jobs.json"),m=e.builderPrivateKey??e.builderPublicKey,C=e.builderPublicKey;m&&C&&r.projectId&&r.branchName&&(Ix=tDe({cronFilePath:f,apiHost:Ne,projectId:r.projectId,branchName:r.branchName,ownerId:C,privateKey:m}));let I=e.builderPrivateKey??e.builderPublicKey,y=e.builderPublicKey;if(I&&y){let B=p.bashWorkingDirectory,E=120*1e3;nDe(async()=>{try{await Cx({sys:t,ownerId:y,privateKey:I,outputDir:B})}catch(Q){xe.error(`Org tree sync failed: ${Q instanceof Error?Q.message:String(Q)}`)}}),tm(),Ex=setInterval(tm,E)}}return p}function Ta(){return Oo||Promise.resolve(void 0)}function rm(t,e,r,n,i,s,o,a){if(!Oo){yx=new AbortController;let A=Imt(t,e,r,n,i,s,yx.signal,o,a);Oo=A,A.then(c=>{Oo===A&&(zs=c)}).catch(()=>{})}return Oo}function Emt(t,e,r){if(e.isLocal)return()=>{};let s=24*(3600*1e3),o=Date.now(),a=setInterval(()=>{let A=Date.now()-o,c=Math.floor(A/s);c>1&&t.Sentry?.captureException(new Error(`Rogue devtools detected: ${c} days`),{extra:{timeSinceStart:A},contexts:{flyIo:r,fusionConfig:{...e}}})},s*2);return()=>clearInterval(a)}function uDe(t){return t==="https:"||t==="wss:"}function Bmt(t){return t.startsWith("ws://")?t.replace("ws://","http://"):t.startsWith("wss://")?t.replace("wss://","https://"):t}var PB,lDe,gDe,Dx,t4,pDe,dDe,fDe,MB,xe,umt,Oo,zs,yx,Rl,Ix,Ex,mmt,ymt,n4=L(()=>{"use strict";h();PB=z(JG(),1),lDe=z(require("node:http"),1),gDe=z(require("node:https"),1),Dx=z(require("net"),1),t4=z(require("node:fs"),1),pDe=z(require("node:os"),1),dDe=z(require("node:path"),1),fDe=z(require("@amplitude/analytics-node"),1),MB=z(Ir(),1);kr();Ns();Ls();rhe();Zh();rr();Bt();i4();TB();Hs();NB();OH();kB();s4();yr();hr();kye();Ic();KH();zr();Hye();t8();Yye();Ov();$ye();HH();zye();tQe();sQe();cQe();pQe();mQe();BQe();wQe();xQe();TQe();LQe();OQe();QH();yH();jQe();VQe();ZQe();rDe();WH();e4();lH();xi();pI();xo();aDe();xe=ve("Launch"),umt=48752;Rl=null;mmt=["stopEventLoop","abort","abortToolCall","abortSetupCommand","abortValidateCommand","setPrivacyMode","clearSession","loadHistory","loadMoreTurns","getAllFiles","searchFiles","searchFileTree","sendFeedback","setCustomInstructions","setProxyOrigin","sendMessage","queueSystemReminder","clearMessageQueue","flushMessageQueue","updateMessage","configureDevOrchestrator","restoreFromCompletionId","restoreBeforeCompletionId","undoLastUserMessage","pushChanges","abortMerge","setDefaultAutoPush","syncChangesFromRemote","pushRepoV2","readFile","readFileWithChecksum","readBinaryFile","writeFile","deleteFile","fileExists","listDir","manualCommit","uploadBackup","getDiff","getSingleFileDiff","toolFullfilment","createTerminal","writeTerminal","switchSessionMode","switchModelOverride","updateTerminal","signalTerminal","disposeTerminal","restartTerminal","collectRepoMetrics","launchEditor","discardFileChanges","revertDiscard","listCustomInstructions","tsServerInit","tsServerOpenFile","tsServerChangeFile","tsServerCloseFile","tsServerGetCompletions","tsServerGetCompletionDetails","tsServerGetDefinition","tsServerGetTypeDefinition","tsServerGetQuickInfo","tsServerGetReferences","tsServerGetSignatureHelp","tsServerRequestDiagnostics","tsServerGetRenameLocations","tsServerGetNavTree","tsServerOrganizeImports","tsServerGetInlayHints","tsServerGetCodeFixes","tsServerGetApplicableRefactors","tsServerGetEditsForRefactor","tsServerGetImplementation","tsServerGetSelectionRange","tsServerGetLinkedEditingRange","tsServerGetFormatRange","getLocalMcpStatus","refreshMcpStatus","authenticateMcpServer","clearMcpAuth","reconnectMcpServer","setMcpServerDisabled"];ymt=t=>(e,r,n)=>{t.httpClients++;let i=!0,s=()=>{i&&(i=!1,t.httpClients--)};r.once("finish",s),r.once("close",s),n()}});var BDe,yDe,QDe,DDe,o4,Qmt,Tl,Nl,Dmt,CDe,wmt,i4=L(()=>{"use strict";h();BDe=z(JG(),1),yDe=z(fde(),1),QDe=require("node:child_process"),DDe=require("node:util"),o4=z(require("node:path"),1);Ap();$G();oh();n4();Qmt=(0,DDe.promisify)(QDe.execFile),Tl="/_builder.io",Nl=Tl+"/api",Dmt={STATUS:"/status",PROXY_STATUS:"/proxy-status",STATUS_V2:"/status-v2",INIT_LOGS:"/init-logs",TUNNEL_STATUS:"/tunnel/status",GIT_HEALTH:"/git-health",EDITOR_READY:"/editor-ready"},CDe=({sys:t,app:e,validBuilderPrivateKey:r,authenticateProxy:n,isLocal:i,sharedState:s,fusionConfig:o,launchLogger:a})=>{e.set("etag",!1),e.use((0,yDe.default)()),e.use((A,c,u)=>{if(A.path.startsWith(Tl)){let l=A.headers.origin||"*";if(c.header("Access-Control-Allow-Origin",l),c.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),c.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Builder-Private-Key, sentry-trace, baggage"),c.header("Access-Control-Allow-Credentials","true"),c.header("Connection","close"),A.method==="OPTIONS")return c.status(204).end()}u()}),i||e.use(wmt({validBuilderPrivateKey:r,authenticateProxy:n})),e.get(Nl+"/status-v2",(A,c)=>{LB(s);let u;if(up.isEnabled()){let g=WG().getInfo();u={enabled:!0,status:g.status,name:g.name,url:g.url,vscodeUri:g.vscodeUri,cursorUri:g.cursorUri,webUrl:g.webUrl,error:g.error,workspacePath:g.workspacePath}}else u={enabled:!1,status:"stopped",name:null,url:null,vscodeUri:null,cursorUri:null,webUrl:null,error:null,workspacePath:up.getWorkspacePath()};let l={status:"ok",state:s.state,setupState:s.setupState,devState:s.devState,editorReady:s.editorReady,editorReadyAt:s.editorReadyAt,editorReadySource:s.editorReadySource,httpServerState:s.httpServerState,initState:s.initState,errorMessage:s.errorMessage,devToolsVersion:s.devToolsVersion,idleTime:performance.now()-s.lastRequestTime,upTime:performance.now()-s.startTime,processId:s.processId,launchPhase:s.launchPhase,launchPhaseUpdatedAt:s.launchPhaseUpdatedAt,machine:s.machine,projectId:s.projectId,detectedServerUrl:s.detectedServerUrl,_attemptDryRunBackupOutcome:s._attemptDryRunBackupOutcome,workingDirectory:s.workingDirectory,fusionEnvironment:s.fusionEnvironment,containerState:s.containerState,containerStateAgeMs:performance.now()-s.containerStateTimestamp,containerStateTimestamp:s.containerStateTimestamp,wsClients:t.connectionTracker.getConnectionCount(),httpClients:s.httpClients,tunnel:u,diskUsage:s.diskUsage,memoryUsage:s.memoryUsage,sessionId:s.sessionId};c.status(200).json(l)}),e.get(Nl+"/editor-ready",(A,c)=>{s.isFinalState&&(s.state==="init-error"||s.state==="session-error"||s.state==="error")?(a.error(`[EDITOR-READY]: ${JSON.stringify(s)}`),c.status(503).json({ready:s.editorReady,error:!0})):c.status(200).json({ready:s.editorReady,error:!1})}),e.get(Nl+"/init-logs",(A,c)=>{c.status(200).json({initStatusLogs:s.initStatusLogs||[],initState:s.initState})}),e.post(Nl+"/resolve-schema-merge",BDe.default.json({limit:"15mb"}),async(A,c)=>{let u=A.body,l=u?.mainRef,d=u?.branchRef;if(!l||typeof l!="string"){c.status(400).json({success:!1,error:"mainRef is required"});return}if(!d||typeof d!="string"){c.status(400).json({success:!1,error:"branchRef is required"});return}let g=yE(o),f=(o.workspace?.folders??[]).find(I=>I.path&&I.enableGit),m=f?.path?o4.join(g,f.path):g,C=await av({cwd:m,mainRef:l,branchRef:d});c.status(C.success?200:422).json(C)}),e.get(Nl+"/git-health",async(A,c)=>{let u=yE(o),l=o.workspace?.folders??[];for(let d of l){if(!d.path||!d.enableGit)continue;let g=o4.join(u,d.path);try{await Qmt("git",["fsck","--connectivity-only"],{cwd:g,timeout:15e3})}catch{c.status(200).json({healthy:!1});return}}c.status(200).json({healthy:!0})})},wmt=({validBuilderPrivateKey:t,authenticateProxy:e})=>(r,n,i)=>{let s=r.path.startsWith(Tl);if(Object.values(Dmt).some(A=>r.path.includes(A))){i();return}if(!s&&!e){i();return}let a=r.headers["X-Builder-Private-Key"]||r.headers["x-builder-private-key"]||r.cookies.builderPrivateKey;if(t&&a===t){r.cookies.builderPrivateKey||n.cookie("builderPrivateKey",t,{httpOnly:!0,sameSite:"lax",maxAge:1440*60*1e3}),i();return}return n.status(401).json({error:"Authentication required."})}});var a4,Xc,Ln,IDe,wx,bmt,vmt,Smt,wDe,bDe,xmt,Qx,s4=L(()=>{"use strict";h();a4=z(Tae(),1);i4();kB();Bt();Xc=()=>!!process.env.DEBUG_FUSION_PROXY,Ln=ve("Proxy",{debug:Xc}),IDe=()=>{let t=(0,a4.createProxyServer)({changeOrigin:!0,ws:!0});return t.on("proxyReqWs",(e,r,n)=>{Xc()&&Ln.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(r.headers,null,2));let i=bs(e.getHeader("fusion-forwarded-target"));e.removeHeader("fusion-forwarded-target"),e.removeHeader("fusion-forwarded-default-origin"),e.removeHeader("x-forwarded-proto"),e.removeHeader("x-forwarded-host"),e.removeHeader("x-forwarded-port"),e.removeHeader("x-forwarded-for"),e.removeHeader("fly-client-ip"),e.removeHeader("fly-forwarded-port"),e.removeHeader("fly-forwarded-proto"),e.removeHeader("fly-forwarded-ssl"),e.removeHeader("fly-region"),i&&(e.host=i.host,e.setHeader("Host",i.host)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("proxyReq",(e,r,n)=>{Xc()&&(Ln.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(r.headers,null,2)),Ln.debug("proxyReq: removing headers. Initial host:",e.host));let i=bs(e.getHeader("fusion-forwarded-target"));e.removeHeader("fusion-forwarded-target"),e.removeHeader("fusion-forwarded-default-origin"),e.removeHeader("x-forwarded-proto"),e.removeHeader("x-forwarded-host"),e.removeHeader("x-forwarded-port"),e.removeHeader("x-forwarded-for"),e.removeHeader("fly-client-ip"),e.removeHeader("fly-forwarded-port"),e.removeHeader("fly-forwarded-proto"),e.removeHeader("fly-forwarded-ssl"),e.removeHeader("fly-region"),i&&(e.host=i.host,e.setHeader("Host",i.host)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("error",e=>{Ln.error(`Proxy error: ${e.message}`)}),t},wx=(t,e)=>{let r=(0,a4.createProxyServer)(xmt(t));return r.on("proxyReqWs",(o,a,A)=>{Xc()&&Ln.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(a.headers,null,2));let c=bs(o.getHeader("fusion-forwarded-target"));o.removeHeader("fusion-forwarded-target"),o.removeHeader("fusion-forwarded-default-origin"),o.removeHeader("accept-encoding"),o.removeHeader("x-forwarded-proto"),o.removeHeader("x-forwarded-host"),o.removeHeader("x-forwarded-port"),o.removeHeader("x-forwarded-for"),o.removeHeader("fly-client-ip"),o.removeHeader("fly-forwarded-port"),o.removeHeader("fly-forwarded-proto"),o.removeHeader("fly-forwarded-ssl"),o.removeHeader("fly-region"),c?(o.host=c.host,o.setHeader("Host",c.host)):(o.host=t.host,o.setHeader("Host",t.host),o.hasHeader("origin")&&o.setHeader("origin",t.origin)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",o.host))}),r.on("proxyReq",(o,a,A)=>{Xc()&&(Ln.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(a.headers,null,2)),Ln.debug("proxyReq: removing headers. Initial host:",o.host));let c=bs(o.getHeader("fusion-forwarded-target"));o.removeHeader("fusion-forwarded-target"),o.removeHeader("fusion-forwarded-default-origin"),o.removeHeader("accept-encoding"),o.removeHeader("x-forwarded-proto"),o.removeHeader("x-forwarded-host"),o.removeHeader("x-forwarded-port"),o.removeHeader("x-forwarded-for"),o.removeHeader("fly-client-ip"),o.removeHeader("fly-forwarded-port"),o.removeHeader("fly-forwarded-proto"),o.removeHeader("fly-forwarded-ssl"),o.removeHeader("fly-region"),c?(o.host=c.host,o.setHeader("Host",c.host)):(o.host=t.host,o.setHeader("Host",t.host),o.hasHeader("origin")&&o.setHeader("origin",t.origin)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",o.host))}),r.on("proxyRes",(o,a,A)=>{try{let c=o.statusCode||200,u=o.headers["content-type"]||"",l=parseInt(o.headers["content-length"]||"0"),d=1024*1024,g=()=>{Object.keys(o.headers).forEach(f=>{if(bDe(f))return;let m=o.headers[f]||"";A.setHeader(f,m)}),A.statusCode=c},p=bmt(a);if(u&&u.includes("text/html")&&c===200&&!p){let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{wDe(f,o,A,c)});return}else if(p||c!==200||l>d||u&&!u.includes("text/html")){g(),Ln.debug("proxyRes: piping to response"),o.pipe(A);return}else{let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{vmt({body:f})?wDe(f,o,A,c):(g(),Ln.debug("proxyRes: ending response with body"),A.end(f))})}}catch{A.headersSent||(A.statusCode=500,A.end("Error handling proxy response"))}}),r.on("error",(o,a,A)=>{e.debug(`Proxy error: ${o.message}`),Ln.error("Proxy error:",o)}),Object.assign((o,a,A)=>{if(o.path.startsWith(Tl))return A();r.web(o,a)},{upgrade:(o,a,A)=>{r.ws(o,a,A,c=>{c&&(e.debug(`WebSocket proxy error for ${o.url}: ${c.message}`),a.writable&&a.write(`HTTP/1.1 500 Internal Server Error\r
|
|
4080
|
+
`),D.destroy();return}};s.on("upgrade",I),o?.on("upgrade",I),Cmt({ws:C,sys:t,credentials:e,fusionConfig:n,devServer:u,sharedState:l}),Na(l,"websocket-ready"),l.state="ready",Na(l,"state-ready");try{let{getTunnelManager:v,VSCodeTunnelManager:D}=await Promise.resolve().then(()=>(oh(),QE));if(D.isEnabled()&&D.isAutoStartEnabled()){let S=D.getTunnelName(n.projectId,n.branchName),b=D.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${S}`);let x=v();x.on("error",P=>{xe.error(`\u274C VS Code tunnel error: ${P}`),t.Sentry?.captureException(new Error(String(P)),{tags:{operation:"vscode-tunnel-error-event"}})}),x.start({name:S,workspacePath:b,acceptLicense:!0,autoRestart:!0}).then(P=>{P.status==="running"&&P.webUrl&&(xe.info(`\u2705 VS Code tunnel ready: ${P.webUrl}`),P.vscodeUri&&xe.info(` VS Code: ${P.vscodeUri}`),P.cursorUri&&xe.info(` Cursor: ${P.cursorUri}`))}).catch(P=>{xe.error(`\u274C VS Code tunnel failed: ${P.message}`),t.Sentry?.captureException(P,{tags:{operation:"vscode-tunnel-auto-start"}})})}}catch(v){t.Sentry?.captureException(v,{tags:{operation:"vscode-tunnel-init"}})}Na(l,"editor-url-building");let y=r.app||r.nativeApp?"builder://":r.dev?"http://localhost:1234":"https://builder.io",B=new URL(`${y}/app/projects/local`);B.searchParams.set("localEditUrl",a);let E=await t.getDeviceId();if(E&&B.searchParams.set("host",E),e.builderPublicKey&&B.searchParams.set("spaceId",e.builderPublicKey),r.chat&&B.searchParams.set("chatOnly","true"),Na(l,"editor-url-ready"),l.editorReady=!0,Na(l,"editor-ready"),r.jsonOutput){let v={type:"server_ready",data:{proxyUrl:a,httpsProxyUrl:A,customHttpsProxyUrl:c,fusionEditorUrl:n.nativeApp?null:B.href,urlHost:y,command:n.devCommand,serverUrl:n.serverUrl,credentials:e,nativeApp:n.nativeApp}};console.log(JSON.stringify(v))}if(r.open===!1)n.isLocal&&xe.info(`\u{1F517} Access Builder.io at: ${B.href}`);else{xe.info(`OPEN BROWSER: ${B.href}`);try{await xl(B.href)}catch(v){xe.error(`Failed to open browser: ${v instanceof Error?v.message:String(v)}`),t.Sentry?.captureException(v,{tags:{operation:"open-browser",launchPhase:l.launchPhase},extra:{processId:l.processId,editorReady:l.editorReady,editorReadyAt:l.editorReadyAt}})}}}catch(p){Bx({sys:t,sharedState:l,phase:"launch-error",operation:"setup-launch-server",error:p})}}function Cmt({ws:t,sys:e,fusionConfig:r,credentials:n,devServer:i,sharedState:s}){let o=!1;t.register("initializeSession",async u=>{let l,d,g,p;if(typeof u[0]=="object"&&u[0]?{sessionId:l,customInstructions:d,privacyMode:g,forceSessionReload:p}=u[0]:typeof u[0]=="string"&&(l=u[0]),p&&r.isLocal&&l&&zs&&zs.getSessionId()!==l){yx?.abort(),o=!1;let m=zs;Oo=void 0,zs=void 0,m.close({reason:"forceSessionReload"})}else if(p&&r.isLocal&&l&&!zs&&Oo){yx?.abort(),o=!1;let m=Oo;Oo=void 0,m.then(C=>C.close({uploadGitBackup:!1,reason:"forceSessionReload"})).catch(()=>{})}let f=await rm(e,n,r,i,l,s,d,g||r.privacyMode);return o||(o=!0,KA(n,"/events/publish",{event:Zne,extraData:{sessionId:f.getSessionId(),sessionType:r.branchType??"interactive",projectId:r.projectId,branchName:r.branchName,platform:process.platform}})),f.getSessionId()}),t.register("connectToEventLoop",async(u,l)=>{let d=await Ta();if(!d)throw new Error("Server not found");let g=t.clients().get(l);if(!g)throw new Error("Client not found");let p=d.getSessionId(),f=d.connectToEventLoop(!0,m=>{t.notify(`${p}/event`,l,[JSON.stringify(m)])},{canHandleTools:["AskUserQuestion","GetScreenshot","ExitPlanMode","NavigatePreview","ProposeEnvVariable"]});g.on("close",f)}),t.register("setFeatureFlags",async u=>{Y4(u[0])});function a(u){t.register(u,async([l,...d])=>{s.lastRequestTime=performance.now();let g=Uo();!r.isLocal&&process.env.DEBUG&&xe.debug(`[WS](${u}-${g}): ${JSON.stringify(d)}`);let p=performance.now();try{let f=await Ta();if(!f)throw new Error("Server not found");let m=f[u];if(typeof m!="function")throw new Error(`Method ${u} not found on codeGenServer`);let C=await m.apply(f,d);if(!r.isLocal){let I=Math.round(performance.now()-p);xe.info(`[WS](${u}-${g}): success [${I}ms]`)}return C}catch(f){if(!r.isLocal){let m=Math.round(performance.now()-p);xe.warn(`[WS](${u}-${g}): error [${m}ms]`)}throw f instanceof dt||e.Sentry?.captureException(f,{tags:{functionName:u},extra:{args:d}}),f}})}mmt.forEach(u=>{a(u)});let A=new Map;t.register("subscribeToDiagnostics",async(u,l)=>{s.lastRequestTime=performance.now();let[d]=u,g=await Ta();if(!g)throw new Error("Server not found");let p=t.clients().get(l);if(!p)throw new Error("Client not found");let f=A.get(l);f&&(f(),A.delete(l));let m=g.subscribeToDiagnostics(C=>t.notify(`${d}/tsserver-event`,l,C));return A.set(l,m),p.once("close",()=>{m(),A.delete(l)}),{ok:!0}}),t.register("unsubscribeFromDiagnostics",async(u,l)=>{let d=A.get(l);return d&&(d(),A.delete(l)),{ok:!0}}),t.register("ping",()=>({version:ht,supports:["customInstructions","newChat","clearSession","appCustomInstructions","fileWatcher","discardChanges","searchFileTree","listDir","listCustomInstructions","tsserver"]})),t.register("getProcessInfo",()=>(s.lastRequestTime=performance.now(),r.isLocal?{pid:process.pid,cwd:process.cwd(),localMode:!0}:{error:"Process info only available in local mode"})),t.register("getBuilderRules",async()=>{s.lastRequestTime=performance.now();let u=await Ta();if(!u){let l=e.resolve(e.getAppRootDir(),".builderrules");return await e.exists(l)?await e.readFile(l):null}try{return await u.readFile(".builderrules",!0)}catch{return null}}),t.register("setBuilderRules",async u=>{s.lastRequestTime=performance.now();let l=await Ta(),d=u[1];if(!l){let g=e.resolve(e.getAppRootDir(),".builderrules");d?await e.writeFile(g,d):await e.exists(g)&&await e.unlink(g);return}d?await l.writeFile(".builderrules",d,!0):await l.deleteFile(".builderrules",!0)}),t.register("subscribeTerminal",async(u,l)=>{s.lastRequestTime=performance.now();let[d,{terminalId:g}]=u,p=t.clients().get(l);if(!p)throw new Error("Client not found");let f=await Ta();if(!f)throw new Error("Server not found");let m=f.subscribeTerminal({terminalId:g,onData:C=>t.notify(`${d}/terminal/${g}`,l,[C]),onExit:C=>t.notify(`${d}/terminal/${g}/exit`,l,[C])});return m&&p.on("close",m),{ok:!0,created:!!m}});let c=new Map;t.register("subscribeToFileChanges",async(u,l)=>{s.lastRequestTime=performance.now();let[d]=u,g=await Ta();if(!g)throw new Error("Server not found");let p=t.clients().get(l);if(!p)throw new Error("Client not found");let f=c.get(l);f&&(await f(),c.delete(l));let m=g.subscribeToFileChanges(C=>t.notify(`${d}/file-changes`,l,C));return c.set(l,m),p.once("close",async()=>{await m(),c.delete(l)}),{ok:!0}}),t.register("unsubscribeFromFileChanges",async(u,l)=>{let d=c.get(l);return d&&(await d(),c.delete(l)),{ok:!0}})}async function Imt(t,e,r,n,i,s,o,a,A){let c=[],l=!A?.enabled&&r.projectId&&r.branchName&&process.env.FUSION_ENVIRONMENT?.startsWith("cloud")&&(typeof r.browserAutomationInstructions=="string"||q4("fusion-direct-browser")),d=r.branchType==="code-review",g=q4("fusion-enable-browser-agents-main-branch");l&&(d||g)&&(c.push(SQe),c.push(RQe)),d&&(c.push(Xh),c.push(eQe),c.push(iQe)),r.branchType==="setup-project"&&(c.push(Xh),c.push(JQe)),r.branchType==="org-agent"&&(c.push($Qe),c.push(XQe)),r.branchType==="design-system-indexing"&&(c.push(AQe),c.push(gQe),c.push(hQe),c.push(EQe),c.push(DQe)),r.branchType||(c.push(Xh),c.push(ix),c.push(PQe),c.push(GQe));let p=new ka({sys:t,credentials:e,position:"fusion",sessionOrCompletionId:r.sessionId??i,maxTokens:8e4,mcpServers:!0,autoImportLocalMCPs:!0,fusionConfig:r,privacyMode:A,builtInMCPServerConfig:r.mcpServers,builtInCustomInstructions:a??[],builtInCustomAgents:c,agentType:r.agentType,devServerOrchestrator:n,git:!!r.projectId,fusionStatusMonitor:Rl??void 0,gitAutoInit:!0,persistSessionLocally:r.isLocal});r.projectId&&p.setDebug(!0);try{if(r.isLocal){let f=await EDe();if(f)throw Zr(f),f}r.branchType==="design-system-indexing"&&r.figmaDecodeJobId&&await Fye({sys:t,credentials:e,jobId:r.figmaDecodeJobId,workspaceRoot:p.primaryGitPath}),await p.initializeSession()}catch(f){throw o.aborted||(s.state="session-error",s.errorMessage=f instanceof Error?f.message:String(f)),f}if(o.aborted||(s.state="active-session",s.isFinalState=!0,s.sessionId=p.getSessionId()),!o.aborted&&r.branchType==="org-agent"){let f=t.join(p.primaryGitPath,"cron-jobs.json"),m=e.builderPrivateKey??e.builderPublicKey,C=e.builderPublicKey;m&&C&&r.projectId&&r.branchName&&(Ix=tDe({cronFilePath:f,apiHost:Ne,projectId:r.projectId,branchName:r.branchName,ownerId:C,privateKey:m}));let I=e.builderPrivateKey??e.builderPublicKey,y=e.builderPublicKey;if(I&&y){let B=p.bashWorkingDirectory,E=120*1e3;nDe(async()=>{try{await Cx({sys:t,ownerId:y,privateKey:I,outputDir:B})}catch(Q){xe.error(`Org tree sync failed: ${Q instanceof Error?Q.message:String(Q)}`)}}),tm(),Ex=setInterval(tm,E)}}return p}function Ta(){return Oo||Promise.resolve(void 0)}function rm(t,e,r,n,i,s,o,a){if(!Oo){yx=new AbortController;let A=Imt(t,e,r,n,i,s,yx.signal,o,a);Oo=A,A.then(c=>{Oo===A&&(zs=c)}).catch(()=>{})}return Oo}function Emt(t,e,r){if(e.isLocal)return()=>{};let s=24*(3600*1e3),o=Date.now(),a=setInterval(()=>{let A=Date.now()-o,c=Math.floor(A/s);c>1&&t.Sentry?.captureException(new Error(`Rogue devtools detected: ${c} days`),{extra:{timeSinceStart:A},contexts:{flyIo:r,fusionConfig:{...e}}})},s*2);return()=>clearInterval(a)}function uDe(t){return t==="https:"||t==="wss:"}function Bmt(t){return t.startsWith("ws://")?t.replace("ws://","http://"):t.startsWith("wss://")?t.replace("wss://","https://"):t}var PB,lDe,gDe,Dx,tH,pDe,dDe,fDe,MB,xe,umt,Oo,zs,yx,Rl,Ix,Ex,mmt,ymt,nH=L(()=>{"use strict";h();PB=z(JG(),1),lDe=z(require("node:http"),1),gDe=z(require("node:https"),1),Dx=z(require("net"),1),tH=z(require("node:fs"),1),pDe=z(require("node:os"),1),dDe=z(require("node:path"),1),fDe=z(require("@amplitude/analytics-node"),1),MB=z(Ir(),1);kr();Ns();Ls();rhe();Zh();rr();Bt();iH();TB();Hs();NB();O4();kB();sH();yr();hr();kye();Ic();K4();zr();Hye();t8();Yye();Ov();$ye();H4();zye();tQe();sQe();cQe();pQe();mQe();BQe();wQe();xQe();TQe();LQe();OQe();Q4();y4();jQe();VQe();ZQe();rDe();W4();eH();l4();xi();pI();xo();aDe();xe=ve("Launch"),umt=48752;Rl=null;mmt=["stopEventLoop","abort","abortToolCall","abortSetupCommand","abortValidateCommand","setPrivacyMode","clearSession","loadHistory","loadMoreTurns","getAllFiles","searchFiles","searchFileTree","sendFeedback","setCustomInstructions","setProxyOrigin","sendMessage","queueSystemReminder","clearMessageQueue","flushMessageQueue","updateMessage","configureDevOrchestrator","restoreFromCompletionId","restoreBeforeCompletionId","undoLastUserMessage","pushChanges","abortMerge","setDefaultAutoPush","syncChangesFromRemote","pushRepoV2","readFile","readFileWithChecksum","readBinaryFile","writeFile","deleteFile","fileExists","listDir","manualCommit","uploadBackup","getDiff","getSingleFileDiff","toolFullfilment","createTerminal","writeTerminal","switchSessionMode","switchModelOverride","updateTerminal","signalTerminal","disposeTerminal","restartTerminal","collectRepoMetrics","launchEditor","discardFileChanges","revertDiscard","listCustomInstructions","tsServerInit","tsServerOpenFile","tsServerChangeFile","tsServerCloseFile","tsServerGetCompletions","tsServerGetCompletionDetails","tsServerGetDefinition","tsServerGetTypeDefinition","tsServerGetQuickInfo","tsServerGetReferences","tsServerGetSignatureHelp","tsServerRequestDiagnostics","tsServerGetRenameLocations","tsServerGetNavTree","tsServerOrganizeImports","tsServerGetInlayHints","tsServerGetCodeFixes","tsServerGetApplicableRefactors","tsServerGetEditsForRefactor","tsServerGetImplementation","tsServerGetSelectionRange","tsServerGetLinkedEditingRange","tsServerGetFormatRange","getLocalMcpStatus","refreshMcpStatus","authenticateMcpServer","clearMcpAuth","reconnectMcpServer","setMcpServerDisabled"];ymt=t=>(e,r,n)=>{t.httpClients++;let i=!0,s=()=>{i&&(i=!1,t.httpClients--)};r.once("finish",s),r.once("close",s),n()}});var BDe,yDe,QDe,DDe,oH,Qmt,Tl,Nl,Dmt,CDe,wmt,iH=L(()=>{"use strict";h();BDe=z(JG(),1),yDe=z(fde(),1),QDe=require("node:child_process"),DDe=require("node:util"),oH=z(require("node:path"),1);Ap();$G();oh();nH();Qmt=(0,DDe.promisify)(QDe.execFile),Tl="/_builder.io",Nl=Tl+"/api",Dmt={STATUS:"/status",PROXY_STATUS:"/proxy-status",STATUS_V2:"/status-v2",INIT_LOGS:"/init-logs",TUNNEL_STATUS:"/tunnel/status",GIT_HEALTH:"/git-health",EDITOR_READY:"/editor-ready"},CDe=({sys:t,app:e,validBuilderPrivateKey:r,authenticateProxy:n,isLocal:i,sharedState:s,fusionConfig:o,launchLogger:a})=>{e.set("etag",!1),e.use((0,yDe.default)()),e.use((A,c,u)=>{if(A.path.startsWith(Tl)){let l=A.headers.origin||"*";if(c.header("Access-Control-Allow-Origin",l),c.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),c.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Builder-Private-Key, sentry-trace, baggage"),c.header("Access-Control-Allow-Credentials","true"),c.header("Connection","close"),A.method==="OPTIONS")return c.status(204).end()}u()}),i||e.use(wmt({validBuilderPrivateKey:r,authenticateProxy:n})),e.get(Nl+"/status-v2",(A,c)=>{LB(s);let u;if(up.isEnabled()){let g=WG().getInfo();u={enabled:!0,status:g.status,name:g.name,url:g.url,vscodeUri:g.vscodeUri,cursorUri:g.cursorUri,webUrl:g.webUrl,error:g.error,workspacePath:g.workspacePath}}else u={enabled:!1,status:"stopped",name:null,url:null,vscodeUri:null,cursorUri:null,webUrl:null,error:null,workspacePath:up.getWorkspacePath()};let l={status:"ok",state:s.state,setupState:s.setupState,devState:s.devState,editorReady:s.editorReady,editorReadyAt:s.editorReadyAt,editorReadySource:s.editorReadySource,httpServerState:s.httpServerState,initState:s.initState,errorMessage:s.errorMessage,devToolsVersion:s.devToolsVersion,idleTime:performance.now()-s.lastRequestTime,upTime:performance.now()-s.startTime,processId:s.processId,launchPhase:s.launchPhase,launchPhaseUpdatedAt:s.launchPhaseUpdatedAt,machine:s.machine,projectId:s.projectId,detectedServerUrl:s.detectedServerUrl,_attemptDryRunBackupOutcome:s._attemptDryRunBackupOutcome,workingDirectory:s.workingDirectory,fusionEnvironment:s.fusionEnvironment,containerState:s.containerState,containerStateAgeMs:performance.now()-s.containerStateTimestamp,containerStateTimestamp:s.containerStateTimestamp,wsClients:t.connectionTracker.getConnectionCount(),httpClients:s.httpClients,tunnel:u,diskUsage:s.diskUsage,memoryUsage:s.memoryUsage,sessionId:s.sessionId};c.status(200).json(l)}),e.get(Nl+"/editor-ready",(A,c)=>{s.isFinalState&&(s.state==="init-error"||s.state==="session-error"||s.state==="error")?(a.error(`[EDITOR-READY]: ${JSON.stringify(s)}`),c.status(503).json({ready:s.editorReady,error:!0})):c.status(200).json({ready:s.editorReady,error:!1})}),e.get(Nl+"/init-logs",(A,c)=>{c.status(200).json({initStatusLogs:s.initStatusLogs||[],initState:s.initState})}),e.post(Nl+"/resolve-schema-merge",BDe.default.json({limit:"15mb"}),async(A,c)=>{let u=A.body,l=u?.mainRef,d=u?.branchRef;if(!l||typeof l!="string"){c.status(400).json({success:!1,error:"mainRef is required"});return}if(!d||typeof d!="string"){c.status(400).json({success:!1,error:"branchRef is required"});return}let g=yE(o),f=(o.workspace?.folders??[]).find(I=>I.path&&I.enableGit),m=f?.path?oH.join(g,f.path):g,C=await av({cwd:m,mainRef:l,branchRef:d});c.status(C.success?200:422).json(C)}),e.get(Nl+"/git-health",async(A,c)=>{let u=yE(o),l=o.workspace?.folders??[];for(let d of l){if(!d.path||!d.enableGit)continue;let g=oH.join(u,d.path);try{await Qmt("git",["fsck","--connectivity-only"],{cwd:g,timeout:15e3})}catch{c.status(200).json({healthy:!1});return}}c.status(200).json({healthy:!0})})},wmt=({validBuilderPrivateKey:t,authenticateProxy:e})=>(r,n,i)=>{let s=r.path.startsWith(Tl);if(Object.values(Dmt).some(A=>r.path.includes(A))){i();return}if(!s&&!e){i();return}let a=r.headers["X-Builder-Private-Key"]||r.headers["x-builder-private-key"]||r.cookies.builderPrivateKey;if(t&&a===t){r.cookies.builderPrivateKey||n.cookie("builderPrivateKey",t,{httpOnly:!0,sameSite:"lax",maxAge:1440*60*1e3}),i();return}return n.status(401).json({error:"Authentication required."})}});var aH,Xc,Ln,IDe,wx,bmt,vmt,Smt,wDe,bDe,xmt,Qx,sH=L(()=>{"use strict";h();aH=z(Tae(),1);iH();kB();Bt();Xc=()=>!!process.env.DEBUG_FUSION_PROXY,Ln=ve("Proxy",{debug:Xc}),IDe=()=>{let t=(0,aH.createProxyServer)({changeOrigin:!0,ws:!0});return t.on("proxyReqWs",(e,r,n)=>{Xc()&&Ln.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(r.headers,null,2));let i=bs(e.getHeader("fusion-forwarded-target"));e.removeHeader("fusion-forwarded-target"),e.removeHeader("fusion-forwarded-default-origin"),e.removeHeader("x-forwarded-proto"),e.removeHeader("x-forwarded-host"),e.removeHeader("x-forwarded-port"),e.removeHeader("x-forwarded-for"),e.removeHeader("fly-client-ip"),e.removeHeader("fly-forwarded-port"),e.removeHeader("fly-forwarded-proto"),e.removeHeader("fly-forwarded-ssl"),e.removeHeader("fly-region"),i&&(e.host=i.host,e.setHeader("Host",i.host)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("proxyReq",(e,r,n)=>{Xc()&&(Ln.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(r.headers,null,2)),Ln.debug("proxyReq: removing headers. Initial host:",e.host));let i=bs(e.getHeader("fusion-forwarded-target"));e.removeHeader("fusion-forwarded-target"),e.removeHeader("fusion-forwarded-default-origin"),e.removeHeader("x-forwarded-proto"),e.removeHeader("x-forwarded-host"),e.removeHeader("x-forwarded-port"),e.removeHeader("x-forwarded-for"),e.removeHeader("fly-client-ip"),e.removeHeader("fly-forwarded-port"),e.removeHeader("fly-forwarded-proto"),e.removeHeader("fly-forwarded-ssl"),e.removeHeader("fly-region"),i&&(e.host=i.host,e.setHeader("Host",i.host)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("error",e=>{Ln.error(`Proxy error: ${e.message}`)}),t},wx=(t,e)=>{let r=(0,aH.createProxyServer)(xmt(t));return r.on("proxyReqWs",(o,a,A)=>{Xc()&&Ln.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(a.headers,null,2));let c=bs(o.getHeader("fusion-forwarded-target"));o.removeHeader("fusion-forwarded-target"),o.removeHeader("fusion-forwarded-default-origin"),o.removeHeader("accept-encoding"),o.removeHeader("x-forwarded-proto"),o.removeHeader("x-forwarded-host"),o.removeHeader("x-forwarded-port"),o.removeHeader("x-forwarded-for"),o.removeHeader("fly-client-ip"),o.removeHeader("fly-forwarded-port"),o.removeHeader("fly-forwarded-proto"),o.removeHeader("fly-forwarded-ssl"),o.removeHeader("fly-region"),c?(o.host=c.host,o.setHeader("Host",c.host)):(o.host=t.host,o.setHeader("Host",t.host),o.hasHeader("origin")&&o.setHeader("origin",t.origin)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",o.host))}),r.on("proxyReq",(o,a,A)=>{Xc()&&(Ln.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(a.headers,null,2)),Ln.debug("proxyReq: removing headers. Initial host:",o.host));let c=bs(o.getHeader("fusion-forwarded-target"));o.removeHeader("fusion-forwarded-target"),o.removeHeader("fusion-forwarded-default-origin"),o.removeHeader("accept-encoding"),o.removeHeader("x-forwarded-proto"),o.removeHeader("x-forwarded-host"),o.removeHeader("x-forwarded-port"),o.removeHeader("x-forwarded-for"),o.removeHeader("fly-client-ip"),o.removeHeader("fly-forwarded-port"),o.removeHeader("fly-forwarded-proto"),o.removeHeader("fly-forwarded-ssl"),o.removeHeader("fly-region"),c?(o.host=c.host,o.setHeader("Host",c.host)):(o.host=t.host,o.setHeader("Host",t.host),o.hasHeader("origin")&&o.setHeader("origin",t.origin)),Xc()&&(Ln.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),Ln.debug("proxyReq: removing headers. Final host:",o.host))}),r.on("proxyRes",(o,a,A)=>{try{let c=o.statusCode||200,u=o.headers["content-type"]||"",l=parseInt(o.headers["content-length"]||"0"),d=1024*1024,g=()=>{Object.keys(o.headers).forEach(f=>{if(bDe(f))return;let m=o.headers[f]||"";A.setHeader(f,m)}),A.statusCode=c},p=bmt(a);if(u&&u.includes("text/html")&&c===200&&!p){let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{wDe(f,o,A,c)});return}else if(p||c!==200||l>d||u&&!u.includes("text/html")){g(),Ln.debug("proxyRes: piping to response"),o.pipe(A);return}else{let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{vmt({body:f})?wDe(f,o,A,c):(g(),Ln.debug("proxyRes: ending response with body"),A.end(f))})}}catch{A.headersSent||(A.statusCode=500,A.end("Error handling proxy response"))}}),r.on("error",(o,a,A)=>{e.debug(`Proxy error: ${o.message}`),Ln.error("Proxy error:",o)}),Object.assign((o,a,A)=>{if(o.path.startsWith(Tl))return A();r.web(o,a)},{upgrade:(o,a,A)=>{r.ws(o,a,A,c=>{c&&(e.debug(`WebSocket proxy error for ${o.url}: ${c.message}`),a.writable&&a.write(`HTTP/1.1 500 Internal Server Error\r
|
|
4081
4081
|
\r
|
|
4082
4082
|
`),a.destroy())})},target:t})},bmt=t=>t.headers["x-builder-source"]==="desktop-app",vmt=({body:t})=>{if(!t)return!1;let e=t.trim();return e.startsWith("<!DOCTYPE html")||e.startsWith("<!doctype html")||e.startsWith("<html")||e.startsWith("<HTML")||/^\s*<\s*html[\s>]/i.test(e)},Smt=t=>{let e=[/data-reactroot/i,/id=["']__next["']/i,/__NEXT_DATA__/,/data-server-rendered=["']true["']/i,/id=["']__nuxt["']/i,/inertia-head-ssr-element/i,/ng-server-context=["'](ssr|ssg)["']/i,/_ngcontent-/,/_nghost-/,/data-hk=/,/<!--\[-->/,/<!--\]-->/,/class=["'][^"']*svelte-[a-z0-9]+/i,/q:container=/i,/q:render=/i,/<!--qv\s/],r=e.some(o=>o.test(t));if(!r)return{hasSSR:!1,hasHeaderSSR:!1};let n=t.search(/<body(?=[\s>])/i);if(n===-1)return{hasSSR:r,hasHeaderSSR:r};let i=t.substring(0,n),s=e.some(o=>o.test(i));return{hasSSR:r,hasHeaderSSR:s}},wDe=(t,e,r,n)=>{try{Object.keys(e.headers).forEach(a=>{if(!bDe(a)&&a.toLowerCase()!=="content-length"){let A=e.headers[a]||"";Ln.debug(`processHtmlContent: setting header "${a}" old->"${r.getHeader(a)||""}", new->"${A}"`),r.setHeader(a,A)}});let i=`<script>
|
|
4083
4083
|
// Flag to indicate this page is being proxied by Builder
|
|
@@ -4167,9 +4167,9 @@ ${t.markdown}`}function omt(t,e){ws.rmSync(e,{recursive:!0,force:!0});let r=new
|
|
|
4167
4167
|
document.currentScript.remove();
|
|
4168
4168
|
}
|
|
4169
4169
|
}
|
|
4170
|
-
</script>`,s=t.match(/<head(?=[\s>])[^>]*>/i),o=s&&!Smt(t).hasHeaderSSR?t.replace(s[0],s[0]+i):t+i;r.statusCode=n,r.end(o)}catch{r.headersSent||(r.statusCode=500,r.end("Error processing response"))}},bDe=t=>(t=t.toLowerCase(),t==="content-security-policy"||t==="x-frame-options"),xmt=t=>{let e=t.protocol==="https:";return{target:t.origin,changeOrigin:!0,selfHandleResponse:!0,ws:!0,...e&&{secure:!1,agent:Qx}}},Qx=new(require("https")).Agent({rejectUnauthorized:!1})});function Fmt(t){if(!/^[a-zA-Z0-9_-]+$/.test(t))return!1;try{let e=process.platform==="win32"?"where.exe":"which";return(0,_B.execSync)(`${e} ${t}`,{stdio:"ignore"}),!0}catch{return!1}}function kmt(t,e){try{let r=e||t.cwd()||process.cwd();return t.existsSync(t.join(r,"pnpm-lock.yaml"))?"pnpm install":t.existsSync(t.join(r,"yarn.lock"))?"yarn install":t.existsSync(t.join(r,"bun.lockb"))?"bun install":(t.existsSync(t.join(r,"package-lock.json")),"npm install")}catch{return"npm install"}}function Rmt(t,e,r){if(t!=="npm install")return t;if(Fmt("ni"))return"ni";{let n=t,i=kmt(e,r);return e.Sentry?.captureMessage(`ni command not found in PATH, falling back to detected command: ${i}`,{level:"warning",extra:{originalCommand:n,detectedCommand:i,workingDirectory:r}}),i}}function Tmt(t){if(!process.pkg)return;let e=nm.dirname(process.execPath),r=nm.join(e,"bin");if(global.__pkgNativeAddonPatched)return;global.__pkgNativeAddonPatched=!0;let n=require("module"),i=n._resolveFilename;n._resolveFilename=function(s,o,a,A){if(s.includes("@lydell/node-pty-")&&(s.endsWith("/pty.node")||s.endsWith("/conpty.node"))){let u=process.platform==="win32"?["conpty.node","pty.node"]:["pty.node"];for(let l of u){let d=nm.join(r,l);if(t.existsSync(d))return d}}if(s.includes("@lydell/node-pty-")&&s.endsWith("/spawn-helper")){let c=nm.join(r,"spawn-helper");if(t.existsSync(c))return c}return i.call(this,s,o,a,A)}}function Nmt(t){try{if(t&&(0,SDe.existsSync)(t))return t;let e=process.platform==="win32"?"where.exe mise":"which mise";return(0,_B.execSync)(e,{stdio:"ignore"}),"mise"}catch{return null}}function bs(t){if(t){if(typeof t=="string")try{return new URL(t)}catch{return}if(t instanceof URL)return t}}function
|
|
4170
|
+
</script>`,s=t.match(/<head(?=[\s>])[^>]*>/i),o=s&&!Smt(t).hasHeaderSSR?t.replace(s[0],s[0]+i):t+i;r.statusCode=n,r.end(o)}catch{r.headersSent||(r.statusCode=500,r.end("Error processing response"))}},bDe=t=>(t=t.toLowerCase(),t==="content-security-policy"||t==="x-frame-options"),xmt=t=>{let e=t.protocol==="https:";return{target:t.origin,changeOrigin:!0,selfHandleResponse:!0,ws:!0,...e&&{secure:!1,agent:Qx}}},Qx=new(require("https")).Agent({rejectUnauthorized:!1})});function Fmt(t){if(!/^[a-zA-Z0-9_-]+$/.test(t))return!1;try{let e=process.platform==="win32"?"where.exe":"which";return(0,_B.execSync)(`${e} ${t}`,{stdio:"ignore"}),!0}catch{return!1}}function kmt(t,e){try{let r=e||t.cwd()||process.cwd();return t.existsSync(t.join(r,"pnpm-lock.yaml"))?"pnpm install":t.existsSync(t.join(r,"yarn.lock"))?"yarn install":t.existsSync(t.join(r,"bun.lockb"))?"bun install":(t.existsSync(t.join(r,"package-lock.json")),"npm install")}catch{return"npm install"}}function Rmt(t,e,r){if(t!=="npm install")return t;if(Fmt("ni"))return"ni";{let n=t,i=kmt(e,r);return e.Sentry?.captureMessage(`ni command not found in PATH, falling back to detected command: ${i}`,{level:"warning",extra:{originalCommand:n,detectedCommand:i,workingDirectory:r}}),i}}function Tmt(t){if(!process.pkg)return;let e=nm.dirname(process.execPath),r=nm.join(e,"bin");if(global.__pkgNativeAddonPatched)return;global.__pkgNativeAddonPatched=!0;let n=require("module"),i=n._resolveFilename;n._resolveFilename=function(s,o,a,A){if(s.includes("@lydell/node-pty-")&&(s.endsWith("/pty.node")||s.endsWith("/conpty.node"))){let u=process.platform==="win32"?["conpty.node","pty.node"]:["pty.node"];for(let l of u){let d=nm.join(r,l);if(t.existsSync(d))return d}}if(s.includes("@lydell/node-pty-")&&s.endsWith("/spawn-helper")){let c=nm.join(r,"spawn-helper");if(t.existsSync(c))return c}return i.call(this,s,o,a,A)}}function Nmt(t){try{if(t&&(0,SDe.existsSync)(t))return t;let e=process.platform==="win32"?"where.exe mise":"which mise";return(0,_B.execSync)(e,{stdio:"ignore"}),"mise"}catch{return null}}function bs(t){if(t){if(typeof t=="string")try{return new URL(t)}catch{return}if(t instanceof URL)return t}}function rH(t,e,r){let n=new Ni(500),i=new Ni(200),s=new Ni(500),o=new Ni(500),a=new Ni(1e3),A,c=e.autoDetectDevServer??!1,u=e.autoDetectDevServerPatterns,l=0,d=e.autoSuggestPort??!1,g,p=c?void 0:bs(e.serverUrl),f,m=[],C,I=e.fileOverrides,y=e.devCommand?"stopped":"unset",B={state:"stopped",remoteAddress:void 0,remotePort:void 0},E=r,Q,v,D,S,b,x,P=!1,O=[],J=new vDe.default,_,K,j=nv()&&r==="not-installed",ee=!1,U,Y,H,Z,ue=e.devCommand??void 0,ge=0,he=e.setupCommand??void 0,X=e.validateCommand??void 0,we=X?"stopped":"unset",Je=e.setupDependencies??void 0,le=new AbortController,be=Nmt(e.miseLocationPath??process.env.MISE_INSTALL_PATH);function de(){O.push({all:new Ni(300),out:new Ni(300),err:new Ni(300)})}function ke(){if(!e.autoConfigureHosts||!p)return!1;let k=p.hostname;if(!CA(k)){if(Loe([{hostname:k,ip:"127.0.0.1"}],t.Sentry))return $.info(`Updated /etc/hosts with entry: 127.0.0.1 ${k}`),!0;$.warn(`Failed to update /etc/hosts for ${k}. Make sure the process has root/admin permissions.`)}return!1}function Qe(k){if(!I||I.length===0)return!0;let R=e.bashWorkingDirectory,M=q=>{$.info(q),k?.(q+`
|
|
4171
4171
|
`)};M(`
|
|
4172
|
-
======== Apply file overrides ========`);let G=j0(I,R,t.Sentry);if(G.success){for(let q of G.appliedFiles)M(` Applied: ${q.path} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);return!0}else{for(let q of G.failedFiles)M(` Failed: ${q.path}: ${q.error} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);for(let q of G.appliedFiles)M(` Applied: ${q.path} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);return!1}}async function rt(k,R){let M=e.nativeApp?3e4:5e3,G=e.nativeApp?1e4:3e3;return k=k??M,R=R??G,await Sl(),new Promise(q=>{if(y!=="running"&&y!=="starting")return q();let re,se=Te=>{re&&clearTimeout(re),re=setTimeout(()=>{Pe(),q()},Te)},Ie=Te=>{Te&&!Te.includes(HA)&&se(R)},Pe=()=>{J.off("stdout",Ie),J.off("stderr",Ie),re&&clearTimeout(re)};J.on("stdout",Ie),J.on("stderr",Ie),se(k)})}function nt(){if(y!=="running")return;let k=++l;rt(2e3).then(()=>{l===k&&(l=0)})}let Ut,$r=async()=>{let k=f?.getPid();return k?Mmt(k):[]},Ht=k=>{if(e.nativeApp)return Ut=void 0,!1;let R=ke();return p?(k&&(D=k),Ut=wx(p,t)):(D=void 0,Ut=void 0),R};function Ge(k){we!==k&&(we=k,J.emit("validateState",we))}function nn(k){y!==k&&(y=k,y!=="running"&&cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),J.emit("devState",y))}function At(){return{snapshot:e.syncBranch?"true":"false",environment:e.machine?.environment??"unknown",cpuKind:e.machine?.cpuKind??"unknown",region:e.machine?.region??"unknown",memory:`${e.machine?.memory??0}`,cpu:`${e.machine?.cpus??0}`,volumeSize:`${e.machine?.volumeSize??0}`}}function Et(k){E!==k&&(E=k,J.emit("setupState",E),E!=="installed"&&cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),E==="installed"&&et())}function cr(k){if(B.state===k.state&&B.remoteAddress===k.remoteAddress&&B.remotePort===k.remotePort)return;let R=B.state!==k.state;if(B=k,J.emit("httpServerData",B),R&&(J.emit("httpServerState",k.state),k.state==="ok-2xx"||k.state==="error-4xx"||k.state==="error-5xx")){let G=performance.now(),q=!P,re=k.state==="ok-2xx";P=!0;let se=[];b!==void 0&&(se.push({key:"dev_server_dev_command_time",ms:G-b,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),b=void 0),x!==void 0&&(se.push({key:"dev_server_total_setup_time",ms:G-x,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),x=void 0),se.length>0&&J.emit("metrics",{durations:se})}}function ze(){let{state:k}=B;return k!=="error-fetch"&&k!=="stopped"&&k!=="connecting"}async function qt(k,R){let G=e.https??!1?["https","http"]:["http","https"];for(let q of G)try{if(y!=="running"||k.aborted)return null;let re=new URL(`${q}://localhost:${R}`),se=q==="https"?
|
|
4172
|
+
======== Apply file overrides ========`);let G=j0(I,R,t.Sentry);if(G.success){for(let q of G.appliedFiles)M(` Applied: ${q.path} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);return!0}else{for(let q of G.failedFiles)M(` Failed: ${q.path}: ${q.error} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);for(let q of G.appliedFiles)M(` Applied: ${q.path} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);return!1}}async function rt(k,R){let M=e.nativeApp?3e4:5e3,G=e.nativeApp?1e4:3e3;return k=k??M,R=R??G,await Sl(),new Promise(q=>{if(y!=="running"&&y!=="starting")return q();let re,se=Te=>{re&&clearTimeout(re),re=setTimeout(()=>{Pe(),q()},Te)},Ie=Te=>{Te&&!Te.includes(HA)&&se(R)},Pe=()=>{J.off("stdout",Ie),J.off("stderr",Ie),re&&clearTimeout(re)};J.on("stdout",Ie),J.on("stderr",Ie),se(k)})}function nt(){if(y!=="running")return;let k=++l;rt(2e3).then(()=>{l===k&&(l=0)})}let Ut,$r=async()=>{let k=f?.getPid();return k?Mmt(k):[]},Ht=k=>{if(e.nativeApp)return Ut=void 0,!1;let R=ke();return p?(k&&(D=k),Ut=wx(p,t)):(D=void 0,Ut=void 0),R};function Ge(k){we!==k&&(we=k,J.emit("validateState",we))}function nn(k){y!==k&&(y=k,y!=="running"&&cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),J.emit("devState",y))}function At(){return{snapshot:e.syncBranch?"true":"false",environment:e.machine?.environment??"unknown",cpuKind:e.machine?.cpuKind??"unknown",region:e.machine?.region??"unknown",memory:`${e.machine?.memory??0}`,cpu:`${e.machine?.cpus??0}`,volumeSize:`${e.machine?.volumeSize??0}`}}function Et(k){E!==k&&(E=k,J.emit("setupState",E),E!=="installed"&&cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),E==="installed"&&et())}function cr(k){if(B.state===k.state&&B.remoteAddress===k.remoteAddress&&B.remotePort===k.remotePort)return;let R=B.state!==k.state;if(B=k,J.emit("httpServerData",B),R&&(J.emit("httpServerState",k.state),k.state==="ok-2xx"||k.state==="error-4xx"||k.state==="error-5xx")){let G=performance.now(),q=!P,re=k.state==="ok-2xx";P=!0;let se=[];b!==void 0&&(se.push({key:"dev_server_dev_command_time",ms:G-b,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),b=void 0),x!==void 0&&(se.push({key:"dev_server_total_setup_time",ms:G-x,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),x=void 0),se.length>0&&J.emit("metrics",{durations:se})}}function ze(){let{state:k}=B;return k!=="error-fetch"&&k!=="stopped"&&k!=="connecting"}async function qt(k,R){let G=e.https??!1?["https","http"]:["http","https"];for(let q of G)try{if(y!=="running"||k.aborted)return null;let re=new URL(`${q}://localhost:${R}`),se=q==="https"?AH.default:cH.default,Ie=await new Promise((Pe,Te)=>{let Ve=()=>{ut.destroy(),Te(rn(k.reason))};if(k.aborted){Te(rn(k.reason));return}k.addEventListener("abort",Ve);let ut=se.get(re,{rejectUnauthorized:!1,headers:{accept:"*/*","accept-language":"*","sec-fetch-mode":"cors","user-agent":"node","accept-encoding":"gzip, deflate"}},ur=>{ur.on("data",()=>{}),ur.on("end",()=>{k.removeEventListener("abort",Ve),Pe({status:ur.statusCode??0})})});ut.on("error",ur=>{k.removeEventListener("abort",Ve),Te(ur)})});if(k.aborted)return null;if(Ie.status>0&&Ie.status<400)return re}catch{continue}return null}async function Oe(){let k=0;for(;le;){le=new AbortController;let R=setTimeout(()=>{le?.abort()},2e4),M=le.signal,G=[Be(M).then(q=>{y!=="running"||E!=="installed"?(k=0,cr({state:"stopped",remoteAddress:void 0,remotePort:void 0})):l>0?(k=0,cr({state:"connecting",remoteAddress:void 0,remotePort:void 0})):q.state==="error-5xx"||q.state==="error-fetch"?performance.now()-ge>2e4&&(k++,k>3&&cr(q)):(k=0,cr(q))}),new Promise(q=>{let re=2500;B.state==="ok-2xx"?re=6e3:B.state==="error-fetch"?re=1e3:B.state==="connecting"&&(re=200),setTimeout(()=>{q()},re),le?.signal.addEventListener("abort",()=>{q()},{once:!0})})];d&&c&&g&&(!A||A==="terminal")&&!ze()&&G.push(qt(M,g).then(q=>{q&&!ze()&&(A="port",p?.href!==q?.href&&(p=q,Ht("port-env"),$.info(`Port auto-detected: ${p.href} (replacing configured URL)`),J.emit("urlDetected",p.href),nt()))})),await Promise.allSettled(G),clearTimeout(R)}}async function Be(k){if(e.nativeApp)return{state:y==="running"?"ok-2xx":"stopped",remoteAddress:void 0,remotePort:void 0};try{if(y!=="running")return{state:"stopped",remoteAddress:void 0,remotePort:void 0};if(!p)return{state:"stopped",remoteAddress:void 0,remotePort:void 0};if(k.aborted)return{state:"connecting",remoteAddress:void 0,remotePort:void 0};if(B.state==="stopped"||k.aborted)return{state:"connecting",remoteAddress:void 0,remotePort:void 0};if(!p)return{state:"stopped",remoteAddress:void 0,remotePort:void 0};let M=p.protocol==="https:"?AH.default:cH.default,G=p.href,q=await new Promise((re,se)=>{let Ie=()=>{Pe.destroy(),se(rn(k.reason))};if(k.aborted){se(rn(k.reason));return}k.addEventListener("abort",Ie);let Pe=M.get(G,{rejectUnauthorized:!1,headers:{accept:"*/*","accept-language":"*","sec-fetch-mode":"cors","user-agent":"node","accept-encoding":"gzip, deflate"}},Te=>{let Ve,ut;try{Ve=Te?.socket?.remotePort,ut=Te?.socket?.remoteAddress}catch{}let ur="";Te.on("data",$o=>{ur+=$o.toString()}),Te.on("end",()=>{k.removeEventListener("abort",Ie),re({status:Te.statusCode??0,body:ur,remoteAddress:ut,remotePort:Ve})})});Pe.on("error",Te=>{k.removeEventListener("abort",Ie),se(Te)})});if(k.aborted)return{state:"connecting",remoteAddress:void 0,remotePort:void 0};if(v=q.status,q.status>0&&q.status<400)return Q=void 0,{state:"ok-2xx",remoteAddress:q.remoteAddress,remotePort:q.remotePort};if(q.status>=400&&q.status<500)return Q=q.body,{state:"error-4xx",remoteAddress:q.remoteAddress,remotePort:q.remotePort};if(q.status>=500&&q.status<600)return Q=q.body,{state:"error-5xx",remoteAddress:q.remoteAddress,remotePort:q.remotePort}}catch(R){return v=void 0,R instanceof Error&&R.name==="AbortError"||k.aborted?B.state==="ok-2xx"?B:{state:"connecting",remoteAddress:void 0,remotePort:void 0}:(Q=String(R),{state:"error-fetch",remoteAddress:void 0,remotePort:void 0})}return{state:"connecting",remoteAddress:void 0,remotePort:void 0}}function Ce(){return y==="running"||y==="starting"?"running":E==="installed"?y:E}function V(k){let R=m.reduce((M,{key:G,value:q})=>(M[G]=q,M),{});return k?{...C,...R}:R}function te(k){let R={...e.environmentVariables?.reduce((M,{key:G,value:q})=>(M[G]=q,M),{}),...process.env,...V(k)};if(R.NPM_CONFIG_LOGLEVEL||(R.NPM_CONFIG_LOGLEVEL="info"),R.NPM_CONFIG_PROGRESS||(R.NPM_CONFIG_PROGRESS="true"),R.FORCE_COLOR||(R.FORCE_COLOR="3"),R.NPM_CONFIG_COLOR||(R.NPM_CONFIG_COLOR="always"),e.workspace&&e.workingDirectory){let M=t.resolve(process.cwd(),e.workingDirectory??"."),G=process.platform==="win32"?";":":",q=R.MISE_TRUSTED_CONFIG_PATHS||"";R.MISE_TRUSTED_CONFIG_PATHS=q?`${q}${G}${M}`:M}if(process.platform==="win32"&&be){let G=`${process.env.MISE_DATA_DIR||`${process.env.LOCALAPPDATA}\\mise`}\\shims`,q=R.PATH||R.Path||"";if(q.toLowerCase().includes(G.toLowerCase())||(q=`${G};${q}`),be!=="mise"&&be.includes("\\")){let re=be.substring(0,be.lastIndexOf("\\"));q.toLowerCase().includes(re.toLowerCase())||(q=`${re};${q}`)}R.PATH=q}return R}function oe(k){let R=`[tools]
|
|
4173
4173
|
`,M="";for(let G of k){if(G.type!=="mise")continue;G.tool==="maven"&&(M+=`mise plugin install maven
|
|
4174
4174
|
`);let q=G.tool,re,se=G.version??"latest";q==="maven"?q="asdf:mise-plugins/mise-maven":q==="php"?q="ubi:adwinying/php":q==="composer"&&(q="ubi:composer/composer",re='composer_dir=$(mise where ubi:composer/composer); [ -e "$composer_dir/composer.phar" ] && ln -sf "$composer_dir/composer.phar" "$composer_dir/composer"'),(q==="docker"||q==="docker-cli"||q==="docker-compose")&&t.existsSync("/usr/local/bin/setup-docker.sh")&&(re="/usr/local/bin/setup-docker.sh"),re?R+=`${JSON.stringify(q)} = { version = "${se}", postinstall = """${re}""" }
|
|
4175
4175
|
`:R+=`${JSON.stringify(q)} = '${se}'
|
|
@@ -4230,8 +4230,8 @@ ${HA} Starting dev command...
|
|
|
4230
4230
|
`);let Te=te(!0);g&&(Te.PORT=g.toString()),Te.AI_AGENT="builderio";let Ve=C===void 0,ut=pt({runInPty:e.runInPty,command:Pe,shell:re,cwd:e.bashWorkingDirectory??e.workingDirectory,env:Te,shouldLogin:Ve});f=ut,de();let ur=!1,$o=!1;ut.onSpawn(()=>{k.aborted||(ur=!0,ge=performance.now(),nn("starting"),rt().then(()=>{ur&&!k.aborted&&(ge=performance.now(),nn("running"),le?.abort(),Ie({status:"success"}))}))}),ut.onError(sn=>{k.aborted||(ur=!1,nn("failed"),t.Sentry?.captureException(sn),Ie({status:"failure",code:null,output:sn.message}))}),ut.onClose(sn=>{k.aborted||(ur=!1,nn("failed"),typeof sn=="number"&&!k.aborted&&zp(Buffer.from(`
|
|
4231
4231
|
|
|
4232
4232
|
exited with code ${sn}
|
|
4233
|
-
`)),J.emit("close",sn),Ie({status:"failure",code:sn,output:F(1,"all")}))});let bn=sn=>{if(c&&!A){let on=Toe(sn,u);on&&(p=bs(on.url),p&&(A="terminal",Ht("auto-detected"),le?.abort(),$.info(`URL auto-detected: ${p.href}`),J.emit("urlDetected",p.href),nt()))}},cu=()=>{if(!$o){$o=!0,s.write(vs),a.write(vs);let sn=O[O.length-1];sn&&(sn.out.write(vs),sn.all.write(vs)),J.emit("stdout",vs)}},Qy=sn=>{if(f!==ut)return;cu();let on=sn.toString();s.write(on),a.write(on),ge=performance.now();let Vr=O[O.length-1];Vr&&(Vr.out.write(on),Vr.all.write(on)),bn(on),J.emit("stdout",on)},zp=sn=>{if(f!==ut)return;cu();let on=sn.toString();o.write(on),a.write(on),ge=performance.now();let Vr=O[O.length-1];Vr&&(Vr.err.write(on),Vr.all.write(on)),bn(on),J.emit("stderr",on)};ut.stdout.on("data",Qy),ut.stderr.on("data",zp)}))}function ce({command:k,shell:R,cwd:M,env:G,shouldLogin:q}){let re=mA(R,k,{stdio:["inherit","pipe","pipe"],cwd:M,env:{...G,NODE_ENV:"development",TERM:G.TERM||"xterm-color"}},q);return{type:"devCommandProcess",getPid:()=>re.pid,getExitCode:()=>re.exitCode,kill:se=>re.kill(se),onSpawn:se=>re.on("spawn",se),onError:se=>re.on("error",se),onClose:se=>re.on("close",se),stdout:{on:(se,Ie)=>re.stdout?.on(se,Ie)},stderr:{on:(se,Ie)=>re.stderr?.on(se,Ie)},removeAllListeners:()=>re.removeAllListeners()}}function De({command:k,shell:R,cwd:M,env:G,pty:q,shouldLogin:re}){let se=G.TERM||"xterm-color",Ie=q.spawn(R,yL(k,R,re),{name:se,cols:80,rows:30,cwd:M,env:{...G,TERM:se}}),Pe=null;return{type:"devCommandProcess",getPid:()=>Ie.pid,getExitCode:()=>Pe,kill:Ve=>{try{return Ie.kill(Ve),!0}catch{return!1}},resize(Ve,ut){Ie.resize(Ve??Ie.cols,ut??Ie.rows)},write(Ve){Ie.write(Ve)},onSpawn:Ve=>{setTimeout(()=>Ve(),0)},onError:Ve=>{Ie.onExit(ut=>{ut.exitCode!==0&&Ve(new Error(`Process exited with code ${ut.exitCode}`))})},onClose:Ve=>{Ie.onExit(ut=>{Pe=ut.exitCode,Ve(ut.exitCode,null)})},stdout:{on:(Ve,ut)=>{Ve==="data"&&Ie.onData(ur=>{ut(Buffer.from(ur))})}},stderr:{on:(Ve,ut)=>{}},removeAllListeners:()=>{}}}function pt({runInPty:k,...R}){if(k!==!1){let M=
|
|
4234
|
-
`)}return Ht("hardcoded"),Oe(),E==="installed"&&(Qe(),wt()),{get proxyServerSelection(){return D},clearEnvVariables(){m=[]},setEnvVariable(k,R,M){let G=m.findIndex(re=>re.key===k),q=G>=0?m[G]:void 0;if(q?.value===R)return!1;if(q&&R===void 0)m.splice(G,1);else if(q&&R!==void 0)q.value=R,M?.secret!==void 0&&(q.isSecret=M.secret),M?.placeholder!==void 0&&(q.placeholder=M.placeholder),M?.explanation!==void 0&&(q.explanation=M.explanation);else if(R!==void 0)m.push({key:k,value:R,isSecret:M?.secret||!1,placeholder:M?.placeholder,explanation:M?.explanation});else return!1;return!0},async setSetupCommand(k){let R=k.setupCommand===void 0?he:k.setupCommand||void 0,M=k.setupDependencies===void 0?Je:k.setupDependencies||void 0;e._useNI&&(R=Rmt(R??"",t,e.workingDirectory));let G=!1;if(k.forceRestart&&(G=!0),he!==R&&(G=!0),JSON.stringify(M)!==JSON.stringify(Je)&&(G=!0),!G)return null;if(Je=M,he=R,y==="running")try{let q=f;f=void 0,await Os(t,q,k.signal),le?.abort(),nn(ue?"stopped":"unset")}catch(q){t.Sentry?.captureException(q)}return await tr(k.signal)},async runSetupCommand(k){return await tr(k)},async ensureSetupCommand(k){return(E==="install-failed"||E==="not-installed"||E==="installing")&&(K||await tr(k)),E==="installed"},get setupCommandPromise(){return K},abortSetupCommand(){return _e()},abortValidateCommand(){return gt()},async setDevCommand(k,R,M){return ue===k&&!R?{status:"success",code:null,output:"Same command, no restart"}:(ue=k,await wt(M))},getOpenPorts:$r,async setProxyServer(k){let R=bs(k);if(p?.href===R?.href)return{updatedProxyServer:!1,updatedHosts:!1};p=R,cr({state:"stopped",remoteAddress:void 0,remotePort:void 0});let M=Ht("hardcoded");return le?.abort(),{updatedProxyServer:!0,updatedHosts:M}},async setPort(k){return Number(p?.port)===k?!1:(p||(p=new URL(`http://localhost:${k}`)),p.port=k.toString(),D="hardcoded",cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),Ht("hardcoded"),le?.abort(),!0)},setFileOverrides(k){return I=k,!0},setFileOverride(k){let R=I??[],M=R.findIndex(q=>q.path===k.path),G=M>=0?R.map((q,re)=>re===M?k:q):[...R,k];return I=G,{fileOverrides:G,action:M>=0?"updated":"created"}},async setAutoDetectSettings(k,R){return c===k?!1:(c=k,R!==void 0&&(u=R),cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),Ht(void 0),le?.abort(),A=void 0,c&&y==="running"&&await wt(),!0)},get validateCommand(){return X||void 0},get validateCommandState(){return we},runValidateCommand(k,R){return k===null?(X=void 0,Ge("unset")):k!==void 0&&(X=k,Ge("stopped")),Rt(R)},ensureDevCommand:et,onClose(k){J.on("close",k)},addCheckpoint:de,emitter:J,getCheckpoints:F,getAllStdout(){return s.getContent()},getAllStderr(){return o.getContent()},getOutput(){return a.getContent()},getSetupWrite(){return n?.getWrite()},getDevWrite(){return s?.getWrite()},getSetupOutput(){return n.getContent()},getValidateOutput(){return i.getContent()},async getMiseActivationCommand(k){return await Re(k)},async waitUntilIdle(k,R){return rt(k,R)},async waitUntilServer(k,R=12e4,M=["ok-2xx","error-5xx","error-4xx"]){let G,q,re,se;try{if(await Sl(),k?.aborted)throw rn(k.reason);return await new Promise((Ie,Pe)=>{G=setTimeout(()=>{Ie({ok:!1,message:`The dev server is not responding. Timeout after ${R} ms.`})},R);let Te=!1;re=Ve=>{Te=Ve==="running",Ve!=="running"&&Ve!=="starting"&&Ie({ok:!1,message:"The dev server is not responding."})},q=Ve=>{if(!Te)return;let ut="";Ve==="stopped"?ut="The dev server is stopped.":Ve==="connecting"?ut="The dev server is connecting.":Ve==="error-fetch"?ut="The dev server is not responding.":ut=`The dev server is responding with ${Ve}.`,M.includes(Ve)?Ie({ok:!0,message:ut}):(Ve==="error-fetch"||Ve==="stopped")&&Ie({ok:!1,message:ut})},se=()=>{Pe(rn(k?.reason))},J.on("httpServerState",q),J.on("devState",re),k&&k.addEventListener("abort",se),re(y),q(B.state)})}finally{G!==void 0&&clearTimeout(G),q&&J.removeListener("httpServerState",q),re&&J.removeListener("devState",re),k&&se&&k.removeEventListener("abort",se)}},async restart(k){return wt(k)},get devCommandProcess(){return f},get httpServerState(){return B},get devCommand(){return ue??""},get proxyTarget(){return p?.href},get serverUrl(){return p},get environmentVariables(){return m},get envVars(){return V(!0)},get proxyPort(){if(p)return p.protocol==="https:"?Number(p.port)||443:Number(p.port)||80},get proxyMiddleware(){return Ut},get setupCommand(){return he},get setupDependencies(){return Je},get setupState(){return E},get hasSetupEnvVars(){return C!==void 0},get lastServerStatus(){return v},get lastServerBody(){return Q},get devState(){return y},get state(){return Ce()},get pid(){return f?.getPid()},get autoDetectedUrl(){return A!==void 0},get autoDetectDevServer(){return c},get autoDetectDevServerPatterns(){return u},async close(){try{le?.abort(),_?.abort(),H?.abort(),Y?.abort(),le=void 0,Y=void 0,U=void 0,K=void 0,_=void 0,he=void 0,J.removeAllListeners();let k=f;f=void 0,await Os(t,k),n.clear(),i.clear(),O=[],s.clear(),o.clear(),a.clear(),Wne()}catch(k){t.Sentry?.captureException(k)}}}}var vDe,_B,
|
|
4233
|
+
`)),J.emit("close",sn),Ie({status:"failure",code:sn,output:F(1,"all")}))});let bn=sn=>{if(c&&!A){let on=Toe(sn,u);on&&(p=bs(on.url),p&&(A="terminal",Ht("auto-detected"),le?.abort(),$.info(`URL auto-detected: ${p.href}`),J.emit("urlDetected",p.href),nt()))}},cu=()=>{if(!$o){$o=!0,s.write(vs),a.write(vs);let sn=O[O.length-1];sn&&(sn.out.write(vs),sn.all.write(vs)),J.emit("stdout",vs)}},Qy=sn=>{if(f!==ut)return;cu();let on=sn.toString();s.write(on),a.write(on),ge=performance.now();let Vr=O[O.length-1];Vr&&(Vr.out.write(on),Vr.all.write(on)),bn(on),J.emit("stdout",on)},zp=sn=>{if(f!==ut)return;cu();let on=sn.toString();o.write(on),a.write(on),ge=performance.now();let Vr=O[O.length-1];Vr&&(Vr.err.write(on),Vr.all.write(on)),bn(on),J.emit("stderr",on)};ut.stdout.on("data",Qy),ut.stderr.on("data",zp)}))}function ce({command:k,shell:R,cwd:M,env:G,shouldLogin:q}){let re=mA(R,k,{stdio:["inherit","pipe","pipe"],cwd:M,env:{...G,NODE_ENV:"development",TERM:G.TERM||"xterm-color"}},q);return{type:"devCommandProcess",getPid:()=>re.pid,getExitCode:()=>re.exitCode,kill:se=>re.kill(se),onSpawn:se=>re.on("spawn",se),onError:se=>re.on("error",se),onClose:se=>re.on("close",se),stdout:{on:(se,Ie)=>re.stdout?.on(se,Ie)},stderr:{on:(se,Ie)=>re.stderr?.on(se,Ie)},removeAllListeners:()=>re.removeAllListeners()}}function De({command:k,shell:R,cwd:M,env:G,pty:q,shouldLogin:re}){let se=G.TERM||"xterm-color",Ie=q.spawn(R,yL(k,R,re),{name:se,cols:80,rows:30,cwd:M,env:{...G,TERM:se}}),Pe=null;return{type:"devCommandProcess",getPid:()=>Ie.pid,getExitCode:()=>Pe,kill:Ve=>{try{return Ie.kill(Ve),!0}catch{return!1}},resize(Ve,ut){Ie.resize(Ve??Ie.cols,ut??Ie.rows)},write(Ve){Ie.write(Ve)},onSpawn:Ve=>{setTimeout(()=>Ve(),0)},onError:Ve=>{Ie.onExit(ut=>{ut.exitCode!==0&&Ve(new Error(`Process exited with code ${ut.exitCode}`))})},onClose:Ve=>{Ie.onExit(ut=>{Pe=ut.exitCode,Ve(ut.exitCode,null)})},stdout:{on:(Ve,ut)=>{Ve==="data"&&Ie.onData(ur=>{ut(Buffer.from(ur))})}},stderr:{on:(Ve,ut)=>{}},removeAllListeners:()=>{}}}function pt({runInPty:k,...R}){if(k!==!1){let M=x4(t);if(M)return De({...R,pty:M});k&&$.warn("Could not import node-pty for interactive terminal mode. Falling back to normal process.")}return ce({...R})}function F(k,R,M){return O.slice(-k).map(G=>R==="all"?G.all.getCompactContent({maxLines:M}):R==="out"?G.out.getCompactContent({maxLines:M}):R==="err"?G.err.getCompactContent({maxLines:M}):"").join(`
|
|
4234
|
+
`)}return Ht("hardcoded"),Oe(),E==="installed"&&(Qe(),wt()),{get proxyServerSelection(){return D},clearEnvVariables(){m=[]},setEnvVariable(k,R,M){let G=m.findIndex(re=>re.key===k),q=G>=0?m[G]:void 0;if(q?.value===R)return!1;if(q&&R===void 0)m.splice(G,1);else if(q&&R!==void 0)q.value=R,M?.secret!==void 0&&(q.isSecret=M.secret),M?.placeholder!==void 0&&(q.placeholder=M.placeholder),M?.explanation!==void 0&&(q.explanation=M.explanation);else if(R!==void 0)m.push({key:k,value:R,isSecret:M?.secret||!1,placeholder:M?.placeholder,explanation:M?.explanation});else return!1;return!0},async setSetupCommand(k){let R=k.setupCommand===void 0?he:k.setupCommand||void 0,M=k.setupDependencies===void 0?Je:k.setupDependencies||void 0;e._useNI&&(R=Rmt(R??"",t,e.workingDirectory));let G=!1;if(k.forceRestart&&(G=!0),he!==R&&(G=!0),JSON.stringify(M)!==JSON.stringify(Je)&&(G=!0),!G)return null;if(Je=M,he=R,y==="running")try{let q=f;f=void 0,await Os(t,q,k.signal),le?.abort(),nn(ue?"stopped":"unset")}catch(q){t.Sentry?.captureException(q)}return await tr(k.signal)},async runSetupCommand(k){return await tr(k)},async ensureSetupCommand(k){return(E==="install-failed"||E==="not-installed"||E==="installing")&&(K||await tr(k)),E==="installed"},get setupCommandPromise(){return K},abortSetupCommand(){return _e()},abortValidateCommand(){return gt()},async setDevCommand(k,R,M){return ue===k&&!R?{status:"success",code:null,output:"Same command, no restart"}:(ue=k,await wt(M))},getOpenPorts:$r,async setProxyServer(k){let R=bs(k);if(p?.href===R?.href)return{updatedProxyServer:!1,updatedHosts:!1};p=R,cr({state:"stopped",remoteAddress:void 0,remotePort:void 0});let M=Ht("hardcoded");return le?.abort(),{updatedProxyServer:!0,updatedHosts:M}},async setPort(k){return Number(p?.port)===k?!1:(p||(p=new URL(`http://localhost:${k}`)),p.port=k.toString(),D="hardcoded",cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),Ht("hardcoded"),le?.abort(),!0)},setFileOverrides(k){return I=k,!0},setFileOverride(k){let R=I??[],M=R.findIndex(q=>q.path===k.path),G=M>=0?R.map((q,re)=>re===M?k:q):[...R,k];return I=G,{fileOverrides:G,action:M>=0?"updated":"created"}},async setAutoDetectSettings(k,R){return c===k?!1:(c=k,R!==void 0&&(u=R),cr({state:"stopped",remoteAddress:void 0,remotePort:void 0}),Ht(void 0),le?.abort(),A=void 0,c&&y==="running"&&await wt(),!0)},get validateCommand(){return X||void 0},get validateCommandState(){return we},runValidateCommand(k,R){return k===null?(X=void 0,Ge("unset")):k!==void 0&&(X=k,Ge("stopped")),Rt(R)},ensureDevCommand:et,onClose(k){J.on("close",k)},addCheckpoint:de,emitter:J,getCheckpoints:F,getAllStdout(){return s.getContent()},getAllStderr(){return o.getContent()},getOutput(){return a.getContent()},getSetupWrite(){return n?.getWrite()},getDevWrite(){return s?.getWrite()},getSetupOutput(){return n.getContent()},getValidateOutput(){return i.getContent()},async getMiseActivationCommand(k){return await Re(k)},async waitUntilIdle(k,R){return rt(k,R)},async waitUntilServer(k,R=12e4,M=["ok-2xx","error-5xx","error-4xx"]){let G,q,re,se;try{if(await Sl(),k?.aborted)throw rn(k.reason);return await new Promise((Ie,Pe)=>{G=setTimeout(()=>{Ie({ok:!1,message:`The dev server is not responding. Timeout after ${R} ms.`})},R);let Te=!1;re=Ve=>{Te=Ve==="running",Ve!=="running"&&Ve!=="starting"&&Ie({ok:!1,message:"The dev server is not responding."})},q=Ve=>{if(!Te)return;let ut="";Ve==="stopped"?ut="The dev server is stopped.":Ve==="connecting"?ut="The dev server is connecting.":Ve==="error-fetch"?ut="The dev server is not responding.":ut=`The dev server is responding with ${Ve}.`,M.includes(Ve)?Ie({ok:!0,message:ut}):(Ve==="error-fetch"||Ve==="stopped")&&Ie({ok:!1,message:ut})},se=()=>{Pe(rn(k?.reason))},J.on("httpServerState",q),J.on("devState",re),k&&k.addEventListener("abort",se),re(y),q(B.state)})}finally{G!==void 0&&clearTimeout(G),q&&J.removeListener("httpServerState",q),re&&J.removeListener("devState",re),k&&se&&k.removeEventListener("abort",se)}},async restart(k){return wt(k)},get devCommandProcess(){return f},get httpServerState(){return B},get devCommand(){return ue??""},get proxyTarget(){return p?.href},get serverUrl(){return p},get environmentVariables(){return m},get envVars(){return V(!0)},get proxyPort(){if(p)return p.protocol==="https:"?Number(p.port)||443:Number(p.port)||80},get proxyMiddleware(){return Ut},get setupCommand(){return he},get setupDependencies(){return Je},get setupState(){return E},get hasSetupEnvVars(){return C!==void 0},get lastServerStatus(){return v},get lastServerBody(){return Q},get devState(){return y},get state(){return Ce()},get pid(){return f?.getPid()},get autoDetectedUrl(){return A!==void 0},get autoDetectDevServer(){return c},get autoDetectDevServerPatterns(){return u},async close(){try{le?.abort(),_?.abort(),H?.abort(),Y?.abort(),le=void 0,Y=void 0,U=void 0,K=void 0,_=void 0,he=void 0,J.removeAllListeners();let k=f;f=void 0,await Os(t,k),n.clear(),i.clear(),O=[],s.clear(),o.clear(),a.clear(),Wne()}catch(k){t.Sentry?.captureException(k)}}}}var vDe,_B,AH,cH,SDe,nm,vs,HA,x4,Mmt,kB=L(()=>{"use strict";h();da();Soe();vDe=z(require("node:events"),1),_B=require("node:child_process");K0();JI();Noe();rr();AH=z(require("node:https"),1),cH=z(require("node:http"),1);_oe();aU();SDe=require("node:fs");Yoe();Ic();sH();Ap();pI();nm=z(require("node:path"),1),vs="\x1B[2J\x1B[H",HA="[BUILDER.IO]";x4=t=>{let e,r;Tmt(t);try{e=require("@lydell/node-pty")}catch(n){r=n instanceof Error?n:new Error(String(n))}if(!e){let n=new Error("Could not import PTY library.",{cause:r});t.Sentry?.captureException(n,{extra:{nodeVersion:process.version,isPkgBundle:!!process.pkg}})}return e};Mmt=t=>{try{if(process.platform==="win32"){let e=(0,_B.execSync)(`netstat -ano | findstr :.*LISTENING | findstr ${t}`,{encoding:"utf8",timeout:5e3}),r=[],n=e.trim().split(`
|
|
4235
4235
|
`);for(let i of n)if(i.trim()){let s=i.trim().split(/\s+/);if(s.length>=2){let a=s[1].match(/:(\d+)$/);if(a){let A=parseInt(a[1],10);r.includes(A)||r.push(A)}}}return r}else{let e=(0,_B.execSync)(`parent=${t}
|
|
4236
4236
|
pids=$(ps -e -o pid=,ppid= |
|
|
4237
4237
|
awk -v root=$parent '
|
|
@@ -4246,7 +4246,7 @@ exited with code ${sn}
|
|
|
4246
4246
|
lsof -Pan -p "$parent,$(echo "$pids" | tr '
|
|
4247
4247
|
' ',')" -iTCP -sTCP:LISTEN
|
|
4248
4248
|
`,{encoding:"utf8",timeout:5e3}),r=[],n=e.trim().split(`
|
|
4249
|
-
`);for(let i of n)if(i.trim()){let s=i.trim().split(/\s+/);if(s.length>=9){let a=s[8].match(/:(\d+)$/);if(a){let A=parseInt(a[1],10);r.includes(A)||r.push(A)}}}return r}}catch{return[]}}});function xDe(t){return t instanceof Error?t.message:String(t)}function UB(t,e){if(
|
|
4249
|
+
`);for(let i of n)if(i.trim()){let s=i.trim().split(/\s+/);if(s.length>=9){let a=s[8].match(/:(\d+)$/);if(a){let A=parseInt(a[1],10);r.includes(A)||r.push(A)}}}return r}}catch{return[]}}});function xDe(t){return t instanceof Error?t.message:String(t)}function UB(t,e){if(uH(e).test(t))return!0;if(e.toLowerCase().includes("localhost")){let n=e.replace(/localhost/gi,"127.0.0.1");if(uH(n).test(t))return!0}else if(e.includes("127.0.0.1")){let n=e.replace(/127\.0\.0\.1/g,"localhost");if(uH(n).test(t))return!0}return!1}function uH(t){return t=String(t).replace(/\./g,"\\.").replace(/\?/g,".").replace(/\*/g,".*"),new RegExp(`^${t}$`,"i")}var vx,FDe=L(()=>{"use strict";h();vx=class{logger;currentOrigin=null;currentOriginPattern=null;currentDestination=null;currentOriginHost=null;constructor(e){this.logger=e}getCurrentOrigin(){return this.currentOrigin}getCurrentDestination(){return this.currentDestination}clearMapping(){this.currentOrigin=null,this.currentOriginPattern=null,this.currentDestination=null,this.currentOriginHost=null,this.logger?.info("[UrlMapper] Mapping cleared")}setMapping(e,r){if(e.includes("*")||!e.startsWith("https://")&&!e.startsWith("http://")){this.currentOriginPattern=e,this.currentOriginHost=null,this.currentOrigin=e;try{let i=new URL(r);this.currentDestination=`${i.protocol}//${i.hostname}${i.port?":"+i.port:""}`}catch(i){this.logger?.error(`[UrlMapper] Failed to parse destination URL: ${xDe(i)}`),this.currentDestination=r}this.logger?.info(`[UrlMapper] Set mapping (PATTERN): ${e} \u2192 ${r}`)}else{this.currentOriginPattern=null;try{let i=new URL(e),s=i.protocol==="https:"?"443":"80",o=i.port||s;this.currentOriginHost=`${i.hostname}:${o}`,this.currentOrigin=`${i.protocol}//${i.hostname}${i.port?":"+i.port:""}`;let a=new URL(r);this.currentDestination=`${a.protocol}//${a.hostname}${a.port?":"+a.port:""}`,this.logger?.info(`[UrlMapper] Set mapping (EXACT): ${e} \u2192 ${r}`),this.logger?.debug(`[UrlMapper] Normalized origin: ${this.currentOrigin} (host: ${this.currentOriginHost})`),this.logger?.debug(`[UrlMapper] Normalized destination: ${this.currentDestination}`)}catch(i){this.logger?.error(`[UrlMapper] Failed to parse origin/destination URL: ${xDe(i)}`),this.currentOriginHost=null,this.currentOrigin=e,this.currentDestination=r}}}getUpstream(e){if(!this.currentDestination)return null;if(this.currentOriginPattern){let r=this.currentOriginPattern.replace(/^https?:\/\//g,""),n=r.split(":")[0],i=e.split(":")[0];return UB(i,n)?(this.logger?.debug(`[UrlMapper] PATTERN MATCH FOUND getUpstream(${e}) matched hostname: ${n} -> ${this.currentDestination}`),this.currentDestination):UB(e,r)?(this.logger?.debug(`[UrlMapper] PATTERN MATCH FOUND getUpstream(${e}) matched host: ${r} -> ${this.currentDestination}`),this.currentDestination):(this.logger?.debug(`[UrlMapper] NO PATTERN MATCH getUpstream(${e}) !== ${r}`),null)}return this.currentOriginHost?UB(e,this.currentOriginHost)?(this.logger?.debug(`[UrlMapper] MATCH FOUND getUpstream(${e}) -> ${this.currentDestination}`),this.currentDestination):UB(`${e}:80`,this.currentOriginHost)?(this.logger?.debug(`[UrlMapper] MATCH FOUND getUpstream(${e}) (HTTP) -> ${this.currentDestination}`),this.currentDestination):UB(`${e}:443`,this.currentOriginHost)?(this.logger?.debug(`[UrlMapper] MATCH FOUND getUpstream(${e}) (TLS) -> ${this.currentDestination}`),this.currentDestination):(this.logger?.debug(`[UrlMapper] NO MATCH getUpstream(${e}) !== ${this.currentOriginHost}`),null):null}buildUpstreamUrl(e,r="/"){let n=r||"/";n=n.replace(/^\/+/,"/");let i=new URL(n,e),s=new URL(e);return s.pathname=i.pathname.replace(/\/+/g,"/"),s.search=i.search,s.hash=i.hash,s}mapUrl(e){let r=e.host,n=this.getUpstream(r);if(!n)return e;let i=e.pathname+e.search+e.hash;return this.buildUpstreamUrl(n,i)}isOriginHttps(e=443){let r=this.currentOrigin?.split("://")[0];return r==="http"||r==="https"?r==="https":e===443}}});var kDe,Pmt,lH,RDe=L(()=>{"use strict";h();kDe=z(require("node:os"),1);Bt();Pmt=ve("Priority"),lH=(t,e)=>{try{kDe.default.setPriority(t,e)}catch(r){Pmt.error(`Failed to set priority to ${e}: ${r}`)}}});async function*Lmt(t){for await(let e of of(t.body))if(e.length)try{yield JSON.parse(e)}catch{}}function _mt(t){t.toolContext.session.sendMessage({userPrompt:xie({originChannelId:t.originChannelId,senderDisplayName:t.senderDisplayName,projectId:t.projectId,branchName:t.branchName,content:t.content}),category:"background-subagent",user:{...t.toolContext.user,role:"agent",source:"builder.io"},queue:!0})}function Umt(t,e){return e??("builderUserId"in t.user?t.user.builderUserId:t.user.source==="builder.io"?t.user.userId:t.credentials.userId)}function TDe(t,e){let{credentials:r}=t,{project_id:n,message:i}=e,s,o=new Promise(g=>s=g),a=!1,A,c,u,l;return(async()=>{let g=new URL("/projects/branch",Ne);g.searchParams.set("apiKey",r.builderPublicKey);let p=Umt(t,e.builder_user_id);p&&g.searchParams.set("userId",p);let f=e.model&&e.model!=="auto"?ul(e.model):void 0,m=e.attachment_urls?.map(E=>({type:"url",value:E})),C=e.origin_channel_id??t.user.channelId,I={projectId:n,userMessage:{userPrompt:i,user:{...t.user,channelId:C,role:"user"},...e.session_mode&&{sessionMode:e.session_mode},...f&&{modelOverride:f},...m?.length&&{attachments:m}},hidden:e.hidden,actor:"org-agent",metadata:{origin_channel_id:C},autoArchiveOnIdle:e.auto_archive_on_idle,...e.git_base_branch&&{checkoutBranch:e.git_base_branch}},y=await Fe(g,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.builderPrivateKey}`},body:JSON.stringify(I)},t.debug);if(!y.ok){let E=await y.text();throw new Error(`Failed to spawn branch: ${E}`)}let B;for await(let E of Lmt(y))if(E.type==="branch-created")B=E;else if(E.type==="error")B=E;else if(!a&&E.type==="setting-up-container")a=!0,c||(c=E.projectName),u||(u=E.branchFriendlyName??void 0),l||(l=E.branchName),s(E);else{let Q=Bie(E);Q&&(A=Q.plan)}if(!B)throw new Error("Stream ended unexpectedly");return B})().then(g=>{a||s(null);let p=c??g.projectName??n,f=u??l??g.branchName,m=`https://builder.io/app/projects/${n}/${l??g.branchName}`;if(g.type!=="error"){let C=`Branch \`${f}\` in \`${p}\` completed.
|
|
4250
4250
|
- Url: \`${m}\`
|
|
4251
4251
|
|
|
4252
4252
|
==================
|
|
@@ -4258,7 +4258,7 @@ ${Ia(A,80)}`),_mt({toolContext:t,projectId:n,branchName:g.branchName,senderDispl
|
|
|
4258
4258
|
Link: [${g.branchFriendlyName??g.branchName}](${p})
|
|
4259
4259
|
|
|
4260
4260
|
The branch is still starting up, you will receive a report when it's ready. In the meantime show present this link to the user (same title).
|
|
4261
|
-
To send follow-up messages or additional context to this branch, use the tool SendMessage(channel_id="builder/branch/${n}/${g.branchName}").`,title:"SpawnBranch (async)"}})}var NDe=L(()=>{"use strict";h();Hs();Jv();hr();yr();lw();
|
|
4261
|
+
To send follow-up messages or additional context to this branch, use the tool SendMessage(channel_id="builder/branch/${n}/${g.branchName}").`,title:"SpawnBranch (async)"}})}var NDe=L(()=>{"use strict";h();Hs();Jv();hr();yr();lw();eH();HI()});function Zc(t){switch(Pt("cli help",{subcommand:t}),console.log(""),sr((0,ie.bgCyan)((0,ie.bold)((0,ie.white)(" help ")))+" "+(0,ie.dim)(ht)),t){case"add":case"generate":case"gen":case"g":sr(`${(0,ie.cyan)("\u2192")} ${(0,ie.bold)("Generate Figma Components")}
|
|
4262
4262
|
|
|
4263
4263
|
This command has been removed. You can create mapper files manually.
|
|
4264
4264
|
See: https://www.builder.io/c/docs/mapping-functions`);break;case"auth":$.info(`${(0,ie.cyan)("\u2192")} ${(0,ie.bold)("Authentication")}
|
|
@@ -4480,21 +4480,21 @@ ${(0,ie.yellow)("Examples:")}
|
|
|
4480
4480
|
`),[{command:"launch",description:"Launch Builder Fusion development server"},{command:"auth",description:"Authenticate with Builder.io"},{command:"index-repo",description:"Index your design system repository for AI code generation"},{command:"connect-repo",description:"Connect your git repository to Builder.io Fusion"},{command:"code",description:"Generate or modify code based on Figma designs"},{command:"figma publish",description:"Publish your Figma Mappings to Builder.io"},{command:"figma migrate",description:"Migrate existing Figma Mappings into the repo as local files"},{command:"add",description:"Add a component to your project"},{command:"push",description:"Push local changes to a Builder.io branch"},{command:"pull",description:"Pull changes from a Builder.io branch"}].forEach(({command:n,description:i})=>{$.info(`${(0,ie.cyan)("\u2192")} ${(0,ie.bgGreen)((0,ie.white)(` npx ${it()} ${n} `))}
|
|
4481
4481
|
${(0,ie.dim)(i)}
|
|
4482
4482
|
`)}),$.info(`For detailed help about a specific command, run:
|
|
4483
|
-
${(0,ie.cyan)(`npx ${it()} <command> --help`)}`)}Cn("bye \u{1F44B}")}var ie,GB=L(()=>{"use strict";h();rr();ie=z(Ir(),1);xt();Ls();zr()});function OB(){let{env:t}=
|
|
4484
|
-
`);let C=0,I=0;u(),process.env.CI||(r=setInterval(()=>{let y=
|
|
4483
|
+
${(0,ie.cyan)(`npx ${it()} <command> --help`)}`)}Cn("bye \u{1F44B}")}var ie,GB=L(()=>{"use strict";h();rr();ie=z(Ir(),1);xt();Ls();zr()});function OB(){let{env:t}=gH.default,{TERM:e,TERM_PROGRAM:r}=t;return gH.default.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var gH,pH=L(()=>{h();gH=z(require("node:process"),1)});var dH,im,KB,Gmt,Bi,fH,Sx,Omt,Kmt,Hmt,Jmt,Ml=L(()=>{"use strict";h();pH();dH=z(Ir(),1),im=z(xy(),1);Bt();KB=z(Ir(),1),Gmt=ve("Spinner"),Bi=()=>{let t=fH?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],e=fH?80:120,r,n=!1,i="",s="",o="",a=m=>{let C=m>1?"Something went wrong":"Canceled";n&&g(C,m)},A=(m,C)=>{Gmt.error(C,m),a(2)},c=()=>a(1),u=()=>{process.on("uncaughtExceptionMonitor",A),process.on("unhandledRejection",A),process.on("SIGINT",c),process.on("SIGTERM",c),process.on("exit",a)},l=()=>{process.removeListener("uncaughtExceptionMonitor",A),process.removeListener("unhandledRejection",A),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",c),process.removeListener("exit",a)},d=(m="")=>{n=!0,i=m.replace(/\.+$/,""),process.stdout.write(`${dH.default.gray(Omt)}
|
|
4484
|
+
`);let C=0,I=0;u(),process.env.CI||(r=setInterval(()=>{let y=dH.default.magenta(t[C]),B=".".repeat(Math.floor(I)).slice(0,3);process.stdout.write(im.cursor.move(-999,-o.split(`
|
|
4485
4485
|
`).length+1)),process.stdout.write(im.erase.down(o.split(`
|
|
4486
4486
|
`).length));let E=`${y} ${i}${B}${s}`;process.stdout.write(E),C=C+1<t.length?C+1:0,I=I<t.length?I+.125:0,o=E},e))},g=(m,C=0)=>{i=m??i,n=!1,clearInterval(r);let I=C===0?(0,KB.green)(Jmt):C===1?(0,KB.red)(Kmt):(0,KB.red)(Hmt);process.stdout.write(im.cursor.move(-999,-o.split(`
|
|
4487
4487
|
`).length+1)),process.stdout.write(im.erase.down(o.split(`
|
|
4488
4488
|
`).length)),process.stdout.write(`${I} ${i}
|
|
4489
|
-
`),o=i,l()};return{start:d,stop:g,message:(m="")=>{i=m??i},extra:(m="")=>{s=m}}},
|
|
4489
|
+
`),o=i,l()};return{start:d,stop:g,message:(m="")=>{i=m??i},extra:(m="")=>{s=m}}},fH=OB(),Sx=(t,e)=>fH?t:e,Omt=Sx("\u2502","|"),Kmt=Sx("\u25A0","x"),Hmt=Sx("\u25B2","x"),Jmt=Sx("\u25C7","o")});async function om(t,e={}){let r=new URL("/design-systems/v1",Ne);r.searchParams.set("apiKey",t.builderPublicKey),r.searchParams.set("userId",t.userId),e.includeGlobalScopeDesignSystems&&r.searchParams.set("includeGlobalScopeDesignSystems","true"),e.includeDocumentCount&&r.searchParams.set("includeDocumentCount","true");let n=await Fe(r,{headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`}});if(!n.ok)return[];let i=await n.json()??[];return e.onlyEditAccess?i.filter(s=>s.spaceId===t.builderPublicKey):i}var hH,MDe,mH,CH,sm,HB,xx,IH,jmt,Ymt,qmt,EH,PDe,Ss,Ko,$mt,LDe,_De,UDe,BH,GDe,JA=L(()=>{"use strict";h();bi();Zh();hH=z(require("@sentry/node"),1);Bt();kr();yr();hr();xi();rr();MDe=require("node:path"),mH=ve("RepoIndexing"),CH="AGENTS.md",sm="icons.mdx",HB="tokens.mdx",xx="installation.md",IH="repo-indexing",jmt=[{value:"space",label:"Space",hint:"Available to all applications in your current space"}],Ymt=[{value:"organization",label:"Organization",hint:"Available to all applications in your organization"}],qmt=[{value:"global",label:"Global",hint:"Available to all applications in the Builder platform"}],EH=async(t,e,r)=>{if(!t.userId)throw new Error("User ID is required");let i=e?.isAdminInOrganization,s=e?.email?.includes("@builder.io"),o=[...jmt];if((i||s)&&o.push(...Ymt),s&&o.push(...qmt),o.length===1)return o[0].value;if(r){if(!o.some(c=>c.value===r))throw new Error(`You don't have permission to use the scope "${r}"`);return r}let a=await wi({message:"What is your design system scope?",options:o});if(!je(a))return a},PDe=async(t,e)=>{try{let r=t.getAppRootDir(),n=await zo(t,r);if(!n)return{name:void 0,version:void 0};let i=e??n.name,s;if(e){let o=n.dependencies?.[e]||n.devDependencies?.[e];s=o?.replace(/^[\^~>=<]+/,"")||o}else s=n.version;return{name:i,version:s}}catch(r){return mH.error("Error parsing design system",r,{loggerOptions:{debug:!0}}),{name:void 0,version:void 0}}},Ss=async(t,e,r)=>{try{let n=new URL("/mappings/store-component-docs",Ne);n.searchParams.set("apiKey",t.builderPublicKey),n.searchParams.set("userId",t.userId);let i=await Fe(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`},body:JSON.stringify(e)});if(!i.ok){let s=await i.text();throw mH.error("API request failed:",i.status,s,{loggerOptions:{debug:!0}}),new Error(`Failed to store component group: ${i.status} ${s}`)}return await i.json()}catch(n){throw n}},Ko=async(t,e,r,n,i,s,o,a={},A)=>{let{maxTokens:c,retriesAllowed:u=0,expectFile:l="tool",include:d,exclude:g,instructions:p,privacyMode:f}=a,m=null,C=l==="tool"?{...t,writeFile:async(B,E)=>(m=typeof E=="string"?E:E.toString(),Promise.resolve())}:t,y={accessControl:$mt(d,g),workingDirectory:t.cwd(),...o&&{workspace:o}};s&&!(0,MDe.isAbsolute)(s)&&y.accessControl?.entries?.push({action:"allow",resource:`**/node_modules/${s}/**/*`,permissions:["list","read"]},{action:"allow",resource:`!**/node_modules/${s}/node_modules/**/*`,permissions:["list"]},{action:"deny",resource:`**/node_modules/${s}/node_modules`,permissions:["list","read","write"]});try{let B=new ka({maxTokens:c,sys:C,credentials:e,position:"repo-indexing",sessionOrCompletionId:r,...s&&!s.startsWith("/")&&{workingDirectory:`node_modules/${s}`},fusionConfig:y,privacyMode:f,builtInCustomInstructions:p?[{id:"repo-indexing-instructions",name:"repo-indexing-instructions",type:"always",content:p}]:void 0,enabledTools:["Read","Write","Glob","Bash","Grep","Skill","TaskCreate","TaskUpdate","TaskList"],...A&&{metadata:A}});i&&B.setDebug(i),await B.initializeSession({skipSessionLoading:!0});let E=B.connectToEventLoop(!1,async Q=>{Q.type==="error"&&mH.error(Q.message,{loggerOptions:{debug:!0}})});try{await B.sendMessage(n),await B.waitUntilIdle()}finally{E(),await B.close()}if(l!=="tool"){let Q=t.join(t.cwd(),l);if(await t.exists(Q)){m=await t.readFile(Q);try{await t.unlink(Q)}catch(D){hH.captureException(D,{extra:{expectedFile:l,expectedFilePath:Q}})}}}if(!m){let Q=hH.captureException(new dt("Repo indexing failed: No essential files were written"),{tags:{...a?.tags,sessionId:r}});throw new dt(`Sorry, we ran into a problem when indexing your components.
|
|
4490
4490
|
Session ID: ${r}.
|
|
4491
|
-
Please try again. If the issue persists, please contact support@builder.io. and provide the error ID: ${Q}`)}return m}catch(B){if(u===0)throw B;return Ko(t,e,r,n,i,s,o,{...a,retriesAllowed:u-1},A)}},$mt=(t,e)=>{let r=t?(Array.isArray(t)?t:[t]).map(o=>o.trim()).filter(o=>o.length>0):[],n=e?(Array.isArray(e)?e:[e]).map(o=>o.trim()).filter(o=>o.length>0):[],i=[];i.push({action:"deny",resource:"*.mapper.tsx",description:"Do not index mapper files.",permissions:["read","write","list"]});for(let o of n)i.push({action:"deny",resource:o,description:"Excluded by --exclude flag.",permissions:["read","write","list"]});if(r.length>0){i.push({action:"allow",resource:".",permissions:["read","list"]});for(let o of r)i.push({action:"allow",resource:o,description:"Included by --include flag.",permissions:["read","list"]})}else i.push({action:"allow",resource:".",permissions:["read","list"]}),i.push({action:"allow",resource:"**/*",permissions:["read","list"]});i.push({action:"allow",resource:
|
|
4491
|
+
Please try again. If the issue persists, please contact support@builder.io. and provide the error ID: ${Q}`)}return m}catch(B){if(u===0)throw B;return Ko(t,e,r,n,i,s,o,{...a,retriesAllowed:u-1},A)}},$mt=(t,e)=>{let r=t?(Array.isArray(t)?t:[t]).map(o=>o.trim()).filter(o=>o.length>0):[],n=e?(Array.isArray(e)?e:[e]).map(o=>o.trim()).filter(o=>o.length>0):[],i=[];i.push({action:"deny",resource:"*.mapper.tsx",description:"Do not index mapper files.",permissions:["read","write","list"]});for(let o of n)i.push({action:"deny",resource:o,description:"Excluded by --exclude flag.",permissions:["read","write","list"]});if(r.length>0){i.push({action:"allow",resource:".",permissions:["read","list"]});for(let o of r)i.push({action:"allow",resource:o,description:"Included by --include flag.",permissions:["read","list"]})}else i.push({action:"allow",resource:".",permissions:["read","list"]}),i.push({action:"allow",resource:"**/*",permissions:["read","list"]});i.push({action:"allow",resource:CH,permissions:["write"]},{action:"allow",resource:"**/repo-indexing/*.mdx",permissions:["write"]},{action:"allow",resource:"component-groups.json",permissions:["write"]},{action:"allow",resource:".icon_discovery_staging/**/*",permissions:["write"]},{action:"allow",resource:".token_discovery_staging/**/*",permissions:["write"]},{action:"allow",resource:"installation.json",permissions:["write"]});let s="You can read all files, but you can only write AGENTS.md, component-groups.json, icons.json, installation.json, .icon_discovery_staging/**/* and repo-indexing/*.mdx.";return r.length>0&&(s=`You can only read files matching these patterns: ${r.join(", ")}. You can only write AGENTS.md, component-groups.json, icons.json, installation.json, .icon_discovery_staging/**/* and repo-indexing/*.mdx.`),n.length>0&&(s+=` Excluded patterns: ${n.join(", ")}.`),{denyDescription:s,entries:i}};LDe=(t,e)=>e.find(r=>r.designSystemName===t)||null,_De=(t,e,r,n)=>n&&n.find(i=>i.designSystemName===e&&i.scope===r)||null,UDe=async(t,e)=>{let r=new URL("/design-systems/v1",Ne);r.searchParams.set("apiKey",t.builderPublicKey),r.searchParams.set("userId",t.userId);let n=await Fe(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`},body:JSON.stringify(e)});if(!n.ok){let o=(await n.json()).message||"Failed to add design system";throw new Error(o)}return(await n.json()).id},BH=async(t,e)=>{let r=new URL(`/design-systems/v1/${e.id}`,Ne);r.searchParams.set("apiKey",t.builderPublicKey),r.searchParams.set("userId",t.userId);let n=await Fe(r,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`},body:JSON.stringify(e)});if(!n.ok)throw new Error("Failed to update design system");return await n.json()},GDe=async t=>{let e=t.join(t.getAppRootDir(),IH);try{return await t.exists(e)?(await t.readdir(e)).filter(s=>s.endsWith(".mdx")||s.endsWith(".md")).length>0:!1}catch{return!1}}});async function Vmt(t,e){let r="please, enter your own prompt",n=t.getCurrentState(),i=t.getLastApplyResultsTurn();switch(n){case"initial-with-url":{let s='e.g., "add a new contact page", "update the card component", "add a header to the layout of the app"',o=await lr({message:`Describe how the design integrates into your codebase: ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:s,validate(a){if(a.length===0||a===s)return"please, enter a detailed instruction";if(a.length<10)return"a more detailed instruction is needed"}});return je(o)?{command:"exit",userPrompt:void 0,feedback:void 0}:{command:void 0,userPrompt:o??"integrate design into the app, might be a new page/component/layout depending on the design",feedback:void 0}}case"initial-without-url":{let s='e.g., "add a new page", "add a new component", "update the button component"',o=await lr({message:`What do you want to do? ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:s,validate(a){if(a.length===0||a===s)return r}});return je(o)?{command:"exit",userPrompt:void 0,feedback:void 0}:{command:void 0,userPrompt:o??"integrate design into the app, might be a new page/component/layout depending on the design",feedback:void 0}}case"abort":{let s='e.g., "make sure to keep X, while removing Y"',o=await lr({message:`Okey! what do you want to do? ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:s,validate(a){if(a.length===0||a===s)return r}});return je(o)?(await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0}):{command:void 0,userPrompt:o??"integrate design into the app, might be a new page/component/layout depending on the design",feedback:void 0}}case"error":{let s="Press Enter to retry or prompt how to proceed",o=await lr({message:`Mmmh! something went wrong, let's try again: ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:s,validate:void 0});if(je(o))return await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0};let a=o?.trim();return!a||a.length===0||a===s?{command:void 0,userPrompt:"Retry the last failed instruction/command and continue if successful",feedback:void 0}:{command:void 0,userPrompt:a,feedback:void 0}}case"success":{let s='e.g., "Plan, search, build"';if(!i?.applyResults.length){if(e.accept)return await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0};let a=await lr({message:">",placeholder:s,validate(A){if(A.length===0||A===s)return r}});return je(a)?(await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0}):{command:void 0,userPrompt:a??"integrate design into the app, might be a new page/component/layout depending on the design",feedback:void 0}}let o=t.lastTurnHasChanges()?e.accept?"good":await wi({message:`What do you want to do next? ${(0,ot.dim)("or Ctrl+C to exit")}`,options:[{value:"good",label:"\u{1F44D} Accept and Continue",hint:"you will be able to keep prompting for more changes"},{value:"bad",label:"\u{1F44E} Refine",hint:"something went wrong, but I wanna refine instead of a complete undo"},{value:"undo",label:"\u23EE\uFE0F Undo last changes",hint:"want to revert the last changes"}]}):"continue";if(je(o))return await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0};if(o==="continue"){let a='e.g., "implement the new page"',A=await lr({message:`What else can I do for you? ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:a,validate(c){if(!c||c===a)return"Ctrl+C to exit"}});return je(A)?(await t.acceptCode(),{feedback:void 0,command:"exit",userPrompt:void 0}):{command:void 0,userPrompt:A,feedback:void 0}}if(o==="good"){if(t.sendFeedback({feedbackSentiment:"positive"}),e.accept)return await t.acceptCode(),{feedback:"positive",command:"exit",userPrompt:void 0};let a='e.g., "Make it mobile-friendly", "Add form validation", "add docs"',A=await lr({message:`Describe any additional improvements: ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:a,validate(c){if(!c||c===a)return"Ctrl+C to exit"}});return je(A)?(await t.acceptCode(),{feedback:"positive",command:"exit",userPrompt:void 0}):{userPrompt:A,feedback:"positive",command:void 0}}if(o==="bad"){t.sendFeedback({feedbackSentiment:"negative"});let a=`e.g., "code seems to be broken", "i can't see the page"`,A=await lr({message:`What went wrong? Please be more detailed this time ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:a,validate(c){if(!c||c===a)return"Ctrl+C to exit"}});return je(A)?(await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0}):(t.sendFeedback({feedbackSentiment:"negative",feedbackText:A}),{feedback:"negative",userPrompt:`Last changes were not good, here's my feedback:
|
|
4492
4492
|
${A}
|
|
4493
4493
|
Notice that previously changes were already applied, any patch goes on top the previous changes.`,command:void 0})}if(o==="undo"){t.sendFeedback({feedbackSentiment:"undo"});let{undone:a}=await t.undoLastUserMessage();a&&a.length>0&&$.warn(`Restored files to previous state:
|
|
4494
4494
|
|
|
4495
4495
|
${a.map(u=>(0,ot.dim)(u)).join(`
|
|
4496
4496
|
`)}
|
|
4497
|
-
`);let A='e.g., "do X and Y, but make sure to do Z"',c=await lr({message:`Let's try again, please be more detailed this time ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:A,validate(u){if(u=u.trim(),!u||u===A)return"Ctrl+C to exit"}});return je(c)?(await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0}):{feedback:"negative",command:void 0,userPrompt:c}}}default:throw new Error(`Unknown state: ${n}`)}}function KDe(t){return t.replace(JDe,"").length}function
|
|
4497
|
+
`);let A='e.g., "do X and Y, but make sure to do Z"',c=await lr({message:`Let's try again, please be more detailed this time ${(0,ot.dim)("or Ctrl+C to exit")}`,placeholder:A,validate(u){if(u=u.trim(),!u||u===A)return"Ctrl+C to exit"}});return je(c)?(await t.acceptCode(),{command:"exit",userPrompt:void 0,feedback:void 0}):{feedback:"negative",command:void 0,userPrompt:c}}}default:throw new Error(`Unknown state: ${n}`)}}function KDe(t){return t.replace(JDe,"").length}function yH(t,e,r,n){let i=process.stdout.columns||80,s=Math.min(Math.floor(i*.8),120),o=s-4,a=t.split(`
|
|
4498
4498
|
`),A=!1,c=!1;if(n!==void 0){let p=Math.abs(n);a.length>p&&(n>0?(a=a.slice(0,p),A=!0):(a=a.slice(-p),c=!0))}a=a.map(p=>{if(KDe(p)>o){let f=0,m=0;for(;m<o-3&&f<p.length;)p.substring(f).match(JDe)?.[0]?.startsWith(p[f])||m++,f++;return p.slice(0,f)+"..."}return p});let u="\u2500".repeat(Math.max(0,s-2)),l=e(`${r}\u250C${u}\u2510`),d=e(`${r}\u2514${u}\u2518`),g=a.map(p=>{let f=" ".repeat(Math.max(0,o-KDe(p)));return`${r}${e("\u2502")} ${(0,ot.dim)(p)}${f} ${e("\u2502")}`});if(c){let p="... continues above ...",f=" ".repeat(Math.max(0,o-p.length));g.unshift(`${r}${e("\u2502")} ${e(p)}${f} ${e("\u2502")}`)}if(A){let p="... continues below ...",f=" ".repeat(Math.max(0,o-p.length));g.push(`${r}${e("\u2502")} ${e(p)}${f} ${e("\u2502")}`)}return`${l}
|
|
4499
4499
|
${g.join(`
|
|
4500
4500
|
`)}
|
|
@@ -4509,14 +4509,14 @@ ${d}`}function Wmt(t,e){let r="https://docs.google.com/forms/d/e/1FAIpQLSdHUIxeN
|
|
|
4509
4509
|
${a}${A}`}function eCt(t){return t.length===0?(0,ot.green)("Changes are applied"):`${(0,ot.green)("Changes applied, please review the changes:")}
|
|
4510
4510
|
|
|
4511
4511
|
${t.map(e=>{let r=e.addedLines>0?(0,ot.green)("\u25A0".repeat(Math.min(e.addedLines,5))):"",n=e.removedLines>0?(0,ot.red)("\u25A0".repeat(Math.min(e.removedLines,5))):"";return`${(0,ot.dim)(e.filePath)} ${(0,ot.green)(`+${e.addedLines}`)} ${(0,ot.red)(`-${e.removedLines}`)} ${r}${n}`}).join(`
|
|
4512
|
-
`)}`}async function
|
|
4513
|
-
If you are using Windows Git Bash, try a different terminal or wrap the command with winpty.`),await Me(1);return}await Pt("figma code started",{}),e.workspace||await
|
|
4512
|
+
`)}`}async function DH(t,e){let r=t.getCwdDir();$.info(`Opening project: ${(0,ot.dim)(r)}`);let n=await cl({basePath:r,globPattern:"**/{package.json,tsconfig.json}",sys:t}),i=n.filter(c=>c.endsWith("/package.json")),s=await zo(t,r),o=(await t.readdir(r)).some(c=>c.endsWith(".xcodeproj")||c.endsWith(".xcworkspace")||c==="Podfile"),a=(await t.readdir(r)).some(c=>c.startsWith("build.gradle")||c.startsWith("settings.gradle"));if(!(s||a||o)&&($.warn("Looks like you are running this command outside a JS, iOS or Android project, this project runs better when executed at the root of a JS, iOS or Android project."),await Pt("cli code outside project",{}),e&&await wr({message:"Do you want to continue anyway?",active:"Yes",inactive:"No",initialValue:!1})!==!0)){await Me(1);return}let A=n.filter(c=>c.endsWith("/tsconfig.json"));t.Sentry?.setExtra("nonRootPackageJsons",i),t.Sentry?.setExtra("nonRootTsConfigs",A),t.Sentry?.setExtra("packageJson",s),t.Sentry?.setExtra("cwdDir",r)}async function jDe(t){let e=await t.getRepoInfo(),r={client:"@builder.io/dev-tools",clientVersion:t.version,nodeVersion:process.version,frameworks:t.getFrameworks().map(n=>n.name),systemPlatform:process.platform,systemEOL:Fx.default.EOL,systemArch:Fx.default.arch(),inGitRepo:e.hasGit};try{let n=Fx.default.userInfo();r.systemShell=n.shell??void 0}catch{}return r}function tCt(){return process.stdout.isTTY||process.env.FORCE_TTY==="1"}function rCt(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var ot,Fx,QH,HDe,kx,ODe,JDe,Rx=L(()=>{"use strict";h();ot=z(Ir(),1);Cp();rr();kr();Ls();GB();bi();Fx=z(require("node:os"),1);zr();Hs();Zh();Tx();Ic();Ml();QH=z(require("node:readline"),1);Ns();TB();NB();JA();HDe=async(t,e,r)=>{r.prototype?await YDe(t,r):e==="generate"||e==="gen"||e==="g"?await kx(t,r):e==="gen"?Zc("code"):await kx(t,r)},kx=async(t,e)=>{if(console.log(""),sr((0,ot.bgCyan)((0,ot.bold)((0,ot.white)(" code ")))+" "+(0,ot.dim)(ht)),!tCt()&&!e.prompt){await Pt("tty error",{}),$.error(`This command requires a TTY-enabled terminal.
|
|
4513
|
+
If you are using Windows Git Bash, try a different terminal or wrap the command with winpty.`),await Me(1);return}await Pt("figma code started",{}),e.workspace||await DH(t,!e.prompt);let r=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0}),n,i;if(e.workspace){let I=await $De(t,e.workspace);n=I.workspace,i=I.workingDirectory}let s=await Fl(t,e),o=await om(r,{includeGlobalScopeDesignSystems:!0,includeDocumentCount:!0});if(s.repoIndexingConfig?.designSystems){let I=new Set(o.map(E=>E.designSystemName)),B=s.repoIndexingConfig.designSystems.filter(E=>!I.has(E));B.length>0&&$.warn(`\u26A0\uFE0F The following design systems in your configuration no longer exist or you don't have access:
|
|
4514
4514
|
`+B.map(E=>` \u2022 ${E}`).join(`
|
|
4515
|
-
`))}if(!s.repoIndexingConfig){let I=o.filter(y=>y.scope==="space"||y.scope==="organization");if(I.length>0){let y=[];if(I.length===1){let B=I[0],E=await wr({message:`Use the ${B.designSystemName} design system (${B.docCount} document${B.docCount===1?"":"s"})${B.scope==="organization"?" (Organization)":""} with code generation?`});if(je(E))return Ke("Aborted"),await Me(1);E&&y.push(I[0].designSystemName)}else{let B=await nd({message:"You have available design systems. Select the ones you want to use:",options:I.map(E=>({value:E.designSystemName,label:`${E.scope==="organization"?"(Organization) ":""}${E.designSystemName} (${E.docCount} document${E.docCount===1?"":"s"})`})),required:!1});if(je(B))return Ke("Aborted"),await Me(1);y.push(...B)}if(y&&y.length>0){s.repoIndexingConfig={designSystems:y};let B=await wr({message:`Save selection${y.length>1?"s":""} for this working directory to your builder.config.json?`,active:"Yes",inactive:"No"});if(je(B))return Ke("Aborted"),await Me(1);B&&await
|
|
4515
|
+
`))}if(!s.repoIndexingConfig){let I=o.filter(y=>y.scope==="space"||y.scope==="organization");if(I.length>0){let y=[];if(I.length===1){let B=I[0],E=await wr({message:`Use the ${B.designSystemName} design system (${B.docCount} document${B.docCount===1?"":"s"})${B.scope==="organization"?" (Organization)":""} with code generation?`});if(je(E))return Ke("Aborted"),await Me(1);E&&y.push(I[0].designSystemName)}else{let B=await nd({message:"You have available design systems. Select the ones you want to use:",options:I.map(E=>({value:E.designSystemName,label:`${E.scope==="organization"?"(Organization) ":""}${E.designSystemName} (${E.docCount} document${E.docCount===1?"":"s"})`})),required:!1});if(je(B))return Ke("Aborted"),await Me(1);y.push(...B)}if(y&&y.length>0){s.repoIndexingConfig={designSystems:y};let B=await wr({message:`Save selection${y.length>1?"s":""} for this working directory to your builder.config.json?`,active:"Yes",inactive:"No"});if(je(B))return Ke("Aborted"),await Me(1);B&&await _4(t,s,e)}}}let a=new ka({sys:t,credentials:r,position:"cli",initialUrl:e.url,mcpServers:!e.disableMcp,autoImportLocalMCPs:!e.disableMcp,privacyMode:s?.privacyMode,skipFileDiff:!1,fusionConfig:{...s,workingDirectory:i,workspace:n}}),A=e.prompt,c=(I,y)=>{(y.ctrl&&y.name==="c"||y.name==="escape")&&a.abort()},u,l=()=>{u&&d(),u=QH.default.createInterface({input:process.stdin,output:process.stdout}),process.stdin.isTTY&&process.stdin.setRawMode(!0),QH.default.emitKeypressEvents(process.stdin,u),process.stdin.on("keypress",c)},d=()=>{u&&(process.stdin.removeListener("keypress",c),process.stdin.isTTY&&process.stdin.setRawMode(!1),u.close(),u=void 0)},g,p;await a.initializeSession(),zmt(a);let f="",m="";A&&(await a.sendMessage({userPrompt:A,user:{source:"builder.io",userId:r.userId,role:"user"}}),e.prototype&&(A=void 0));let C=a.connectToEventLoop(!1,async I=>{switch(I.type){case"start":{if(f="",m=I.title,I.name==="tool"&&["view_path","Read"].includes(I.filePath))break;g&&(g.stop(),g=void 0),p&&(p[1](`
|
|
4516
4516
|
`),p[2](),p=void 0),I.name==="text"?(p=qDe(),pu.message(p[0],{symbol:(0,ot.magenta)("~")})):(g=Bi(),g.start(I.title),g.extra(ODe));break}case"delta":{f+=I.delta,I.name==="tool"||(p?p[1](I.delta):g&&g.extra(`
|
|
4517
4517
|
|
|
4518
4518
|
`+(m?" "+(0,ot.bgMagenta)(` ${m} `)+`
|
|
4519
|
-
`:"")+
|
|
4519
|
+
`:"")+yH(f,ot.magenta," ",-15)+`
|
|
4520
4520
|
`+ODe));break}case"tool":{g&&(g.stop(`${I.name}`),g=void 0);break}case"file":case"diff":{g&&(g.stop(`${I.title}: ${(0,ot.dim)(I.filePath)}`),g=void 0);break}case"text":{p&&(p[1](`
|
|
4521
4521
|
`),p[2](),p=void 0);break}case"user-abort":{g&&(g.stop(),g=void 0),p&&(p[1](`
|
|
4522
4522
|
`),p[2](),p=void 0),$.error("Generation aborted");break}case"wait-for-input":{if(A)await a.stopEventLoop();else{await new Promise(B=>setTimeout(B,100)),d();let y=await Vmt(a,e);y.command==="exit"?await a.stopEventLoop():y.userPrompt&&(l(),await a.sendMessage({userPrompt:y.userPrompt,user:{source:"builder.io",userId:r.userId,role:"user"}}))}break}case"user-input":{p&&(p[1](`
|
|
@@ -4525,13 +4525,13 @@ If you are using Windows Git Bash, try a different terminal or wrap the command
|
|
|
4525
4525
|
`+I.files.map(y=>` ${(0,ot.dim)(y.filePath)} (${rCt(y.size)})`).join(`
|
|
4526
4526
|
`));break}case"tool_result":{I.result.tool_name==="bash"&&g&&(g.stop(),g=void 0),I.result.is_error?$.error(`${I.result.title?I.result.title:`Tool failed: ${I.result.tool_name}`}
|
|
4527
4527
|
|
|
4528
|
-
${
|
|
4528
|
+
${yH(QL(I.result.content).trim(),ot.red,"")}`):$.info(`${I.result.title?I.result.title:`Tool: ${I.result.tool_name}`}
|
|
4529
4529
|
|
|
4530
|
-
${
|
|
4530
|
+
${yH(QL(I.result.content).trim(),ot.green,"",15)}`);break}case"error":{if(I.stopReason==="limit"){await Pt("code generation",{spaceId:r.builderPublicKey,cli:!0,error:"rate limit reached"});let y=I.message??"The request was cancelled because it reached the account limits. Please upgrade your plan.";$.error((0,ot.red)("\u{1F6A8} "+y));let B=new URL("https://builder.io/account/subscription");B.searchParams.set("space_id",r.builderPublicKey),await wr({message:(0,ot.dim)(B.href),active:"Open subscription page",inactive:"Exit"})&&await xl(B.href),await Me(1)}else if(I.code==="ask-to-continue")if(g&&(g.stop(),g=void 0),await wr({message:I.message||"The agent has been working for a while. Do you want to continue?",active:"Yes, continue",inactive:"No, stop here"}))await a.sendMessage({userPrompt:"",displayPrompt:"Continue!",isManualContinue:!0,user:{source:"agent",role:"agent"},queue:!0});else{$.info("Code generation stopped by user.");break}else await Pt("code generation",{spaceId:r.builderPublicKey,cli:!0,error:I.message}),$.error(I.message),await Me(1);break}case"done":{p&&(p[1](`
|
|
4531
4531
|
`),p[2](),p=void 0),g&&(g.stop(),g=void 0),I.usage&&I.usage.total/I.usage.limits.aiGeneration>.5&&$.info(Zmt(I.usage.total,I.usage.limits.aiGeneration)),I.applyResults.length>0&&$.success(eCt(I.applyResults));break}case"continue":{g&&(g.stop("All changes applied"),g=void 0);break}default:if(g){if(I.type==="stdio")break;g.stop(),g=void 0}}});await a.waitForEventLoop(),C(),d(),await Xmt(a),await Me(0)};ODe=`
|
|
4532
|
-
`+(0,ot.dim)("ESC to interrupt"),JDe=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g});function nCt(t){let e=t.match(/\/app\/projects\/([^/]+)\/([^/]+)/);return e?{projectId:e[1],branchName:e[2]}:null}function eu(t){if(!t.includes("://")&&!t.startsWith("http"))return null;let e;try{e=new URL(t)}catch{return null}if(!e.hostname.endsWith("builder.io"))return null;let r=nCt(e.pathname);if(!r)throw new Error(`Malformed Builder URL: "${t}". Expected format: https://builder.io/app/projects/<projectId>/<branchName>`);return r}var JB=L(()=>{"use strict";h()});function aCt(t){let e=t.split("/");for(let i of e)if(iCt.has(i))return!1;let r=e[e.length-1];if(sCt.has(r))return!1;let n=r.includes(".")?"."+r.split(".").pop():"";return oCt.has(n.toLowerCase())}async function YB(t){let{projectId:e,branchName:r,apiKey:n,authHeaders:i,userId:s}=t,o=await Fe(new URL(`${Ne}/projects/branch/chat-history?apiKey=${n}&userId=${s??""}`),{method:"POST",headers:i,body:JSON.stringify({projectId:e,branchName:r})});return o.ok?(await o.json()).conversation:[]}async function qB(t){let{projectId:e,branchName:r,apiKey:n,authHeaders:i,userId:s,showLogs:o=!0}=t,a=r.replace(/[/\\]/g,"-"),A=Dn(Ma.default.join(
|
|
4532
|
+
`+(0,ot.dim)("ESC to interrupt"),JDe=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g});function nCt(t){let e=t.match(/\/app\/projects\/([^/]+)\/([^/]+)/);return e?{projectId:e[1],branchName:e[2]}:null}function eu(t){if(!t.includes("://")&&!t.startsWith("http"))return null;let e;try{e=new URL(t)}catch{return null}if(!e.hostname.endsWith("builder.io"))return null;let r=nCt(e.pathname);if(!r)throw new Error(`Malformed Builder URL: "${t}". Expected format: https://builder.io/app/projects/<projectId>/<branchName>`);return r}var JB=L(()=>{"use strict";h()});function aCt(t){let e=t.split("/");for(let i of e)if(iCt.has(i))return!1;let r=e[e.length-1];if(sCt.has(r))return!1;let n=r.includes(".")?"."+r.split(".").pop():"";return oCt.has(n.toLowerCase())}async function YB(t){let{projectId:e,branchName:r,apiKey:n,authHeaders:i,userId:s}=t,o=await Fe(new URL(`${Ne}/projects/branch/chat-history?apiKey=${n}&userId=${s??""}`),{method:"POST",headers:i,body:JSON.stringify({projectId:e,branchName:r})});return o.ok?(await o.json()).conversation:[]}async function qB(t){let{projectId:e,branchName:r,apiKey:n,authHeaders:i,userId:s,showLogs:o=!0}=t,a=r.replace(/[/\\]/g,"-"),A=Dn(Ma.default.join(wH.default.homedir(),".builder","prototypes")),c=Dn(Ma.default.join(A,`${e}__${a}`)),u=Dn(Ma.default.join(c,"code")),l;o&&(l=is()),o&&l.start("Fetching bundle...");let[d,g]=await Promise.all([Fe(new URL(`${Ne}/projects/branch/bundle-download-url?apiKey=${n}&userId=${s??""}`),{method:"POST",headers:i,body:JSON.stringify({projectId:e,branchName:r})}),Fe(new URL(`${Ne}/projects/branches?apiKey=${n}&projectId=${e}&branchName=${encodeURIComponent(r)}`),{method:"GET",headers:i})]);if(!d.ok){let x=await d.text().catch(()=>d.statusText);Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"bundle-download-url"},extra:{projectId:e,branchName:r,status:d.status,errorBody:x}}),o&&(l.stop("Failed to get bundle URL"),$.error(x));return}if(!g.ok){let x=await g.text().catch(()=>g.statusText);Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"resolve-branch"},extra:{projectId:e,branchName:r,status:g.status,errorBody:x}}),o&&(l.stop("Failed to resolve branch"),$.error(x));return}let{signedUrl:p,partial:f}=await d.json(),C=(await g.json()).branch,I=C.gitAiBranch??C.backup?.gitBranchName??Object.values(C.backups??{})[0]?.gitBranchName,y;try{y=await Fe(p)}catch(x){Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"bundle-download"},extra:{projectId:e,branchName:r,partial:f,error:x instanceof Error?x.message:String(x)}}),o&&(l.stop("Failed to download bundle"),$.error(`Bundle download failed: ${x instanceof Error?x.message:String(x)}`));return}if(!y.ok){Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"bundle-download"},extra:{projectId:e,branchName:r,partial:f,status:y.status,statusText:y.statusText}}),o&&(l.stop("Failed to download bundle"),$.error(`Bundle download failed: ${y.statusText}`));return}let B=tu.default.mkdtempSync(Ma.default.join(wH.default.tmpdir(),"builder-prototype-")),E=Ma.default.join(B,"repo.bundle"),Q=Ma.default.join(B,"repo"),v=await y.arrayBuffer(),D=Buffer.from(v.slice(0,20)).toString("utf8");if(!D.startsWith("# v")){Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"validate-bundle"},extra:{projectId:e,branchName:r,partial:f,bundleSize:v.byteLength,headerPreview:JSON.stringify(D.slice(0,40))}}),o&&(l.stop("Invalid bundle"),$.error("Downloaded file is not a git bundle. The backup may not exist yet for this branch."));return}tu.default.writeFileSync(E,new Uint8Array(v));let S=I??"main";try{if(f){await jB("git",["init",Q],{cwd:B});let{stdout:x}=await jB("git",["-C",Q,"bundle","unbundle",E],{cwd:B}),P=x.trim().split(/\s+/)[0];if(P)await jB("git",["-C",Q,"checkout",P],{cwd:B});else throw new Error("Bundle produced no refs \u2014 it may be empty or corrupt")}else await jB("git",["clone","--branch",S,E,Q],{cwd:B})}catch(x){Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"git-extract"},extra:{projectId:e,branchName:r,partial:f,checkoutBranch:S,error:x instanceof Error?x.message:String(x)}}),o&&(l.stop("Failed to extract bundle"),$.error(`Could not extract git bundle: ${x}`)),tu.default.rmSync(B,{recursive:!0,force:!0});return}let{stdout:b}=await jB("git",["ls-files"],{cwd:Q});tu.default.mkdirSync(u,{recursive:!0});for(let x of b.trim().split(`
|
|
4533
4533
|
`).filter(Boolean))if(aCt(x))try{let P=Ma.default.join(Q,x),O=Ma.default.join(u,x);tu.default.mkdirSync(Ma.default.dirname(O),{recursive:!0}),tu.default.copyFileSync(P,O)}catch{}return o&&l.stop(`Files saved to ${u}`),tu.default.rmSync(B,{recursive:!0,force:!0}),{projectDir:u,prototypesRoot:A,apiKey:n}}async function YDe(t,e){let r=e.prototype;if(!r){$.error("Please provide a prototype URL: --prototype https://builder.io/app/projects/<projectId>/<branchName>");return}let n=eu(r);if(!n){$.error(`Invalid prototype URL: ${r}
|
|
4534
|
-
Expected format: https://builder.io/app/projects/<projectId>/<branchName>`);return}console.log(""),sr((0,Pl.bgCyan)((0,Pl.bold)((0,Pl.white)(" prototype ")))+" "+(0,Pl.dim)(ht));let{projectId:i,branchName:s}=n,o=await Wt(t,e,{builderPrivateKey:!0,builderPublicKey:!0});if(!o.builderPublicKey){$.error("No space ID found. Run 'builder login' first.");return}let a=o.builderPublicKey,A={"Content-Type":"application/json",Authorization:`Bearer ${o.builderPrivateKey}`},[c,u]=await Promise.all([qB({projectId:i,branchName:s,apiKey:a,authHeaders:A,userId:o.userId}),YB({projectId:i,branchName:s,apiKey:a,authHeaders:A,userId:o.userId}).catch(()=>[])]);if(!c)return;let l=e.prompt?.trim()||await cCt();if(!l)return;let d=Ma.default.relative(process.cwd(),c.projectDir);e.prompt=ACt(d,u,l),e.spaceId=a;let g=()=>tu.default.rmSync(c.prototypesRoot,{recursive:!0,force:!0});process.on("exit",g),process.on("SIGINT",g),process.on("SIGTERM",g),process.on("uncaughtException",g),process.on("unhandledRejection",g),await kx(t,e)}function
|
|
4534
|
+
Expected format: https://builder.io/app/projects/<projectId>/<branchName>`);return}console.log(""),sr((0,Pl.bgCyan)((0,Pl.bold)((0,Pl.white)(" prototype ")))+" "+(0,Pl.dim)(ht));let{projectId:i,branchName:s}=n,o=await Wt(t,e,{builderPrivateKey:!0,builderPublicKey:!0});if(!o.builderPublicKey){$.error("No space ID found. Run 'builder login' first.");return}let a=o.builderPublicKey,A={"Content-Type":"application/json",Authorization:`Bearer ${o.builderPrivateKey}`},[c,u]=await Promise.all([qB({projectId:i,branchName:s,apiKey:a,authHeaders:A,userId:o.userId}),YB({projectId:i,branchName:s,apiKey:a,authHeaders:A,userId:o.userId}).catch(()=>[])]);if(!c)return;let l=e.prompt?.trim()||await cCt();if(!l)return;let d=Ma.default.relative(process.cwd(),c.projectDir);e.prompt=ACt(d,u,l),e.spaceId=a;let g=()=>tu.default.rmSync(c.prototypesRoot,{recursive:!0,force:!0});process.on("exit",g),process.on("SIGINT",g),process.on("SIGTERM",g),process.on("uncaughtException",g),process.on("unhandledRejection",g),await kx(t,e)}function bH(t){return t.length===0?"No conversation history available.":t.map((e,r)=>`### ${e.title?`**${e.title}**`:`Message ${r+1}`}
|
|
4535
4535
|
${e.userPrompt}`).join(`
|
|
4536
4536
|
|
|
4537
4537
|
`)}function ACt(t,e,r){return`## Step 1 \u2014 Read the prototype code (do this first, before anything else)
|
|
@@ -4541,7 +4541,7 @@ Read all files in ${t} to fully understand what was built: the components, pages
|
|
|
4541
4541
|
After reading the prototype files, review the conversation history below to understand the intent and goals behind what was built.
|
|
4542
4542
|
|
|
4543
4543
|
## Conversation History
|
|
4544
|
-
${
|
|
4544
|
+
${bH(e)}
|
|
4545
4545
|
|
|
4546
4546
|
## Step 3 \u2014 Handle the user request
|
|
4547
4547
|
Only after completing steps 1 and 2, respond to the request below.
|
|
@@ -4550,7 +4550,7 @@ Rules:
|
|
|
4550
4550
|
- Never write into the prototype folder ${t}
|
|
4551
4551
|
|
|
4552
4552
|
## User request
|
|
4553
|
-
${r}`}async function cCt(){let t=await lr({message:"What would you like to do with this prototype?",placeholder:"e.g. implement the login page, add a dark mode toggle..."});if(je(t)){Ke("Cancelled");return}return t}var VDe,tu,
|
|
4553
|
+
${r}`}async function cCt(){let t=await lr({message:"What would you like to do with this prototype?",placeholder:"e.g. implement the login page, add a dark mode toggle..."});if(je(t)){Ke("Cancelled");return}return t}var VDe,tu,wH,Ma,WDe,Pl,Lp,jB,iCt,sCt,oCt,Tx=L(()=>{"use strict";h();VDe=require("node:child_process"),tu=z(require("node:fs"),1),wH=z(require("node:os"),1),Ma=z(require("node:path"),1),WDe=require("node:util");rr();Pl=z(Ir(),1),Lp=z(require("@sentry/node"),1);yr();kr();hr();xv();zr();Rx();JB();jB=(0,WDe.promisify)(VDe.execFile),iCt=new Set(["node_modules","dist","build",".git",".next",".nuxt",".svelte-kit",".output","__pycache__",".turbo",".cache","coverage",".vite","storybook-static"]),sCt=new Set(["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","package.json","tsconfig.json","tsconfig.node.json","eslint.config.js",".eslintrc.js",".eslintrc.json",".prettierrc",".gitignore",".npmrc",".nvmrc"]),oCt=new Set([".ts",".tsx",".js",".jsx",".vue",".svelte",".css",".scss",".less",".html",".astro"])});function zDe(t){let e=t.tokenCategories??uCt,r=t.componentSlugs??[];return`# Design System: ${t.designSystemName}
|
|
4554
4554
|
|
|
4555
4555
|
This document describes the CSS design system produced by Builder.io's DSI flow. Use it as a reference when generating code that consumes the design system's tokens or components.
|
|
4556
4556
|
|
|
@@ -4731,7 +4731,7 @@ ${c.question}`}).join(`
|
|
|
4731
4731
|
`),o=t.user,a=`BRANCH AGENT: The branch is waiting for user input, but the user is not in the chat. If the user who initiated this branch is reachable via a private channel (DM or their origin channel), please send them a brief private nudge. Do NOT post to any public Slack channel. If no private channel is available, discard this notification \u2014 the branch will proceed with its best judgment.
|
|
4732
4732
|
${s}
|
|
4733
4733
|
|
|
4734
|
-
${nIt(o,r,n)}`;if((await t.session.sendMessageToOrgAgent({content:a,channelId:t.user.channelId,senderDisplayName:`Branch Agent (${t.projectId}/${t.branchName})`,senderType:"sub-agent",agentProjectId:t.projectId,agentBranchName:t.branchName,userSource:t.user})).status==="success")return{isError:!1,toolResult:"The user is not available right now. The question has been forwarded to the org agent who will try to reach the right person. Proceed with your best judgment for now."}}return{isError:!0,toolResult:"The user is currently not present in the chat and the org agent could not be reached. Try to proceed with your best judgment or wait and try again later."}}}async function TCt(t,e){let{session:r,signal:n,credentials:i}=t,s=e.input,o=await r.waitForDevServer(n);if(!o.shouldProceed)return{isError:!0,toolResult:o.message,title:"Get Screenshot Error"};let a,A=r.getProxyConfig();if(s.href)try{a=new URL(s.href,A.proxyDefaultOrigin)}catch(f){Pa.captureException(f)}let c=new vx;A.proxyOrigin&&A.proxyDestination&&c.setMapping(A.proxyOrigin,A.proxyDestination);let u=a?c.mapUrl(a):void 0;if(!s.href||!s.href.startsWith("https://")&&!s.href.startsWith("http://")||a?.origin===A.proxyDefaultOrigin||a&&CA(a.hostname)||u&&CA(u.hostname))try{let f=Qn([t.signal,AbortSignal.timeout(15e3)]);return await t.passThrough(e,{signal:f})}catch{}if(!u)return{isError:!0,toolResult:"The href can not be resolved a fully qualified URL.",title:"Get Screenshot Error"};let d=new URL(`${Ne}/codegen/tools/GetScreenshot`);i.builderPublicKey&&d.searchParams.set("apiKey",i.builderPublicKey),i.userId&&d.searchParams.set("userId",i.userId);let g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.builderPrivateKey}`},body:JSON.stringify({...s,href:u.href}),signal:n});return g.ok?await g.json():{isError:!0,toolResult:`Failed to capture screenshot: ${g.statusText}`,title:"Get Screenshot Error"}}async function RB(t){let e=process.platform==="win32"?"rg.exe":"rg";try{if(process.pkg){let r=xs.dirname(process.execPath),n=xs.join(r,"bin",e);if(t.existsSync(n))return n}}catch{}try{let r=xs.dirname(process.execPath),n=xs.join(r,e);if(t.existsSync(n))return n}catch{}try{let r=process.platform==="win32"?"win32-x64":`${process.platform}-${process.arch}`,n=xs.join(__dirname,"..","vendors",r,e);if(t.existsSync(n))return n}catch{}return"rg"}async function PCt(t,e){let{signal:r,bashWorkingDirectory:n,sys:i,filterText:s,fusionConfig:o,user:a}=t,A=await RB(i),c=["--path-separator","/","-A","1","-B","1","--max-columns","500","--max-count","100","--max-filesize","3M","--json","--multiline","--multiline-dotall","--hidden","--line-number",...e.case_sensitive?[]:["-i"]],u=n,l=`Grepping codebase with "${e.query}"`,d="";e.include_glob&&(d+=` (including: ${e.include_glob})`),e.exclude_glob&&(d+=` (excluding: ${e.exclude_glob})`,c.push("--glob",`!${e.exclude_glob}`)),NCt.forEach(p=>{c.push("--glob",p)}),l+=d,MCt(e.query)&&c.push("--fixed-strings"),c.push("--",e.query);let g=await LCt(A,c,u,r,e.query,d,l);if(!g.isError&&g.toolResult)try{let p=await doe(g.toolResult,o?.accessControl,a.principals,e.include_glob??void 0);if(p)return{...g,toolResult:Ia(s(p),200,300)};if(e.include_glob){let f=await nwe(t,{pattern:e.include_glob});if(f.isError){let m=e.include_glob.startsWith("**/")?"Try a wider Grep without include_glob.":`Try a wider Grep with **/${e.include_glob}`;return{isError:!0,toolResult:`Zero files read, include_glob: "${e.include_glob}" is too restrictive. ${m}`,title:f.title}}else return{isError:!0,toolResult:`No matches found for pattern: "${e.query}" ${d||""}`,title:f.title}}return{isError:!0,toolResult:`No matches found for pattern: "${e.query}" ${d||""}`,title:g.title}}catch(p){return{isError:!0,toolResult:`Error processing search results: ${p instanceof Error?p.message:String(p)}`,title:g.title}}return g}async function LCt(t,e,r,n,i,s,o){return new Promise(a=>{let A=new Ni(1e4),c=Cc({command:t,args:e,options:{env:process.env,cwd:r,stdio:["ignore","pipe","pipe"],signal:n}});c.on("spawn",()=>{c.pid&&
|
|
4734
|
+
${nIt(o,r,n)}`;if((await t.session.sendMessageToOrgAgent({content:a,channelId:t.user.channelId,senderDisplayName:`Branch Agent (${t.projectId}/${t.branchName})`,senderType:"sub-agent",agentProjectId:t.projectId,agentBranchName:t.branchName,userSource:t.user})).status==="success")return{isError:!1,toolResult:"The user is not available right now. The question has been forwarded to the org agent who will try to reach the right person. Proceed with your best judgment for now."}}return{isError:!0,toolResult:"The user is currently not present in the chat and the org agent could not be reached. Try to proceed with your best judgment or wait and try again later."}}}async function TCt(t,e){let{session:r,signal:n,credentials:i}=t,s=e.input,o=await r.waitForDevServer(n);if(!o.shouldProceed)return{isError:!0,toolResult:o.message,title:"Get Screenshot Error"};let a,A=r.getProxyConfig();if(s.href)try{a=new URL(s.href,A.proxyDefaultOrigin)}catch(f){Pa.captureException(f)}let c=new vx;A.proxyOrigin&&A.proxyDestination&&c.setMapping(A.proxyOrigin,A.proxyDestination);let u=a?c.mapUrl(a):void 0;if(!s.href||!s.href.startsWith("https://")&&!s.href.startsWith("http://")||a?.origin===A.proxyDefaultOrigin||a&&CA(a.hostname)||u&&CA(u.hostname))try{let f=Qn([t.signal,AbortSignal.timeout(15e3)]);return await t.passThrough(e,{signal:f})}catch{}if(!u)return{isError:!0,toolResult:"The href can not be resolved a fully qualified URL.",title:"Get Screenshot Error"};let d=new URL(`${Ne}/codegen/tools/GetScreenshot`);i.builderPublicKey&&d.searchParams.set("apiKey",i.builderPublicKey),i.userId&&d.searchParams.set("userId",i.userId);let g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.builderPrivateKey}`},body:JSON.stringify({...s,href:u.href}),signal:n});return g.ok?await g.json():{isError:!0,toolResult:`Failed to capture screenshot: ${g.statusText}`,title:"Get Screenshot Error"}}async function RB(t){let e=process.platform==="win32"?"rg.exe":"rg";try{if(process.pkg){let r=xs.dirname(process.execPath),n=xs.join(r,"bin",e);if(t.existsSync(n))return n}}catch{}try{let r=xs.dirname(process.execPath),n=xs.join(r,e);if(t.existsSync(n))return n}catch{}try{let r=process.platform==="win32"?"win32-x64":`${process.platform}-${process.arch}`,n=xs.join(__dirname,"..","vendors",r,e);if(t.existsSync(n))return n}catch{}return"rg"}async function PCt(t,e){let{signal:r,bashWorkingDirectory:n,sys:i,filterText:s,fusionConfig:o,user:a}=t,A=await RB(i),c=["--path-separator","/","-A","1","-B","1","--max-columns","500","--max-count","100","--max-filesize","3M","--json","--multiline","--multiline-dotall","--hidden","--line-number",...e.case_sensitive?[]:["-i"]],u=n,l=`Grepping codebase with "${e.query}"`,d="";e.include_glob&&(d+=` (including: ${e.include_glob})`),e.exclude_glob&&(d+=` (excluding: ${e.exclude_glob})`,c.push("--glob",`!${e.exclude_glob}`)),NCt.forEach(p=>{c.push("--glob",p)}),l+=d,MCt(e.query)&&c.push("--fixed-strings"),c.push("--",e.query);let g=await LCt(A,c,u,r,e.query,d,l);if(!g.isError&&g.toolResult)try{let p=await doe(g.toolResult,o?.accessControl,a.principals,e.include_glob??void 0);if(p)return{...g,toolResult:Ia(s(p),200,300)};if(e.include_glob){let f=await nwe(t,{pattern:e.include_glob});if(f.isError){let m=e.include_glob.startsWith("**/")?"Try a wider Grep without include_glob.":`Try a wider Grep with **/${e.include_glob}`;return{isError:!0,toolResult:`Zero files read, include_glob: "${e.include_glob}" is too restrictive. ${m}`,title:f.title}}else return{isError:!0,toolResult:`No matches found for pattern: "${e.query}" ${d||""}`,title:f.title}}return{isError:!0,toolResult:`No matches found for pattern: "${e.query}" ${d||""}`,title:g.title}}catch(p){return{isError:!0,toolResult:`Error processing search results: ${p instanceof Error?p.message:String(p)}`,title:g.title}}return g}async function LCt(t,e,r,n,i,s,o){return new Promise(a=>{let A=new Ni(1e4),c=Cc({command:t,args:e,options:{env:process.env,cwd:r,stdio:["ignore","pipe","pipe"],signal:n}});c.on("spawn",()=>{c.pid&&lH(c.pid,10)}),c.stdout.on("data",u=>{A.write(u.toString())}),c.stderr.on("data",u=>{A.write(u.toString())}),c.on("error",u=>{a({isError:!0,toolResult:`Failed to start ripgrep process: ${u.message}`,title:o})}),c.on("close",u=>{let l=A.getContent();u==null?a({isError:!0,toolResult:`The process was aborted while grepping for pattern: "${i}" ${s||""}`,title:o}):u===0?a({isError:!1,toolResult:l,title:o}):u===1?a({isError:!0,toolResult:`No matches found for pattern: "${i}" ${s||""}`,title:o}):(Pa.captureException(new dt("Fatal ripgrep error",{cause:new dt(l)}),{contexts:{ripgrep:{exitCode:u,cwd:r,rgPath:t,args:e}}}),a({isError:!0,toolResult:`There was a fatal error when grepping for pattern: "${i}"
|
|
4735
4735
|
|
|
4736
4736
|
${l}
|
|
4737
4737
|
(remember it needs to be a string encoded regex)`,title:o}))})})}function _Ct(t){return t.includes("npm i")||t==="yarn"||t.includes("pnpm i")}function UCt(t){return fI(t).some(r=>r.startsWith("git ")||r.startsWith("gh "))}async function iwe(t,e,r,n,i){let{sys:s,signal:o,allowedCommands:a,bashWorkingDirectory:A,emitter:c,devServerOrchestrator:u,filterText:l,enabledTools:d}=t,g=i==="bash"?"Bash":"PowerShell";if(e&&u&&u.devCommand&&(d.includes("DevServerRestart")||d.includes("DevServerControl"))&&e.includes(u.devCommand))return{isError:!0,toolResult:`Seems like you tried to execute "${u.devCommand}", however "${g}" tool is not the right tool to use, use "DevServerRestart" tool instead.`,title:`${g} command "${e}"`};if(!(t.fusionConfig?.skipCommandSecurity===!0)){let B=a0(),E=hI(e,B);if(E)return{isError:!0,toolResult:`ACL policy: Security policy violation (${E.policy}): ${E.message}.
|
|
@@ -4739,7 +4739,7 @@ Stop and communicate to the user that the command is not allowed. Do not create
|
|
|
4739
4739
|
|
|
4740
4740
|
Stdout so far:
|
|
4741
4741
|
|
|
4742
|
-
${l(O)}`),B({isError:!0,toolResult:P,title:`${g} command "${e}"`})};D.on("spawn",()=>{D.pid&&
|
|
4742
|
+
${l(O)}`),B({isError:!0,toolResult:P,title:`${g} command "${e}"`})};D.on("spawn",()=>{D.pid&&lH(D.pid,10),C.aborted?b():C.addEventListener("abort",b,{once:!0})}),D.on("error",x=>{B({isError:!0,toolResult:l(S.getContent().slice(0,5e3))+`
|
|
4743
4743
|
`+String(x),title:`${g} command "${e}"`})}),D.on("exit",x=>{let P=l(S.getContent().slice(0,5e3)),O=x!==0;O&&(P+=`
|
|
4744
4744
|
exited with code ${x}`,f&&(f.state==="install-failed"||f.state==="install-aborted"||f.state==="not-installed")&&(P+=`
|
|
4745
4745
|
|
|
@@ -4832,36 +4832,36 @@ And here's some extra context about the branch at hand:
|
|
|
4832
4832
|
|
|
4833
4833
|
The ReadBranch tool can be used to get more context about the branch.
|
|
4834
4834
|
Make sure you put humans in context when forwarding information.
|
|
4835
|
-
`}async function iIt(t){let{sys:e,bashWorkingDirectory:r}=t,n=r;try{let i=xs.join(n,".builder","sources","figma","manifest.json"),s="Design System";try{let d=await e.readFile(i);if(d){let g=JSON.parse(d);g.figmaName&&(s=g.figmaName)}}catch{}let o=xs.join(n,".builder","output","_index","tokens-report.json"),a=[],A=["colors","typography","spacing","elevation","brand"];try{let d=await e.readFile(o);if(!d)throw new Error("empty");let g=JSON.parse(d);for(let p of A)g.filesWritten?.some(f=>f.endsWith(`tokens/${p}.css`))&&a.push(p)}catch{}let c=[];try{let d=xs.join(n,".builder","output","tokens","components"),g=await e.readdir(d);for(let p of g)if(p.endsWith(".css")){let f=xs.basename(p,".css");f!=="components"&&c.push(f)}c.sort()}catch{}let u=zDe({designSystemName:s,tokenCategories:a.length>0?a:void 0,componentSlugs:c}),l=xs.join(n,".builder","output","AGENTS.md");return await e.writeFile(l,u),{isError:!1,title:"Generated AGENTS.md",toolResult:`Wrote \`.builder/output/AGENTS.md\` (${s}). Token categories: ${a.length>0?a.join(", "):"none"}. Components: ${c.length>0?c.join(", "):"none"}.`}}catch(i){return{isError:!0,title:"GenerateDesignSystemAgentMd failed",toolResult:`Failed to generate AGENTS.md: ${i?.message??String(i)}`}}}var xs,Pa,ewe,twe,NCt,MCt,
|
|
4836
|
-
`);I=Q.pop()||"";for(let v of Q){let D=v.trim();if(D.length>0&&(C.push(D),A!==void 0&&C.length>=A)){B=!0,m.kill("SIGTERM");return}}}),m.stderr.on("data",E=>{y+=E.toString()}),m.on("error",E=>{o?.Sentry?.captureException(E,{tags:{errorType:"ripgrep_spawn_error",component:"getAllProjectFilesRipgrep"},extra:{basePath:t,patterns:l,errorMessage:E.message}}),f(E)}),m.on("close",E=>{if(I.trim().length>0&&!B&&(A===void 0||C.length<A)&&C.push(I.trim()),B){p(C);return}if(E!==null&&E>1){o?.Sentry?.captureException(new Error(`ripgrep exited with code ${E}`),{tags:{errorType:"ripgrep_error",component:"getAllProjectFilesRipgrep"},extra:{basePath:t,patterns:l,stderr:y,exitCode:E}}),f(new Error(`ripgrep failed: ${y}`));return}if(!a){let Q=new Set;for(let D of C){let S=D.split("/");for(let b=1;b<S.length;b++)Q.add(S.slice(0,b).join("/")+"/")}let v=[...C,...Q].sort();p(v);return}p(C)})})}async function aIt(t,e,r){let n=await qw("**/*",{cwd:t,ignoreFiles:Am,ignore:VB}),i=[];for(let s of n){let o=(0,Gi.resolve)(t,s);try{let a=(0,es.readFileSync)(o,"utf-8");if(a.includes("This code was generated by Builder.io")){let A=Awe(a);if(e&&r&&(A.contentId!==e||A.sessionKey!==r))continue;i.push({path:s,code:Nx(a),name:s.split("/").pop()||"",timestamp:(0,es.statSync)(o).mtime.getTime(),snippetId:A.snippetId})}}catch(a){am.error(`Error reading file ${o}:`,a)}}return i}function AIt(t,e){let r=Awe(t);return r.contentId===e.contentId&&r.sessionKey===e.sessionKey}function iye(t){return t.filter(e=>(e=e.toLowerCase(),!e.endsWith(".png")&&!e.endsWith(".jpg")&&!e.endsWith(".jpeg")&&!e.endsWith(".gif")&&!e.endsWith(".ico")&&!e.endsWith(".webp")&&!e.includes(".mapper.")))}function kH(t){let e=(0,v4.default)().add(VB);function r(n){try{let i=(0,Gi.resolve)(t,n);if((0,es.existsSync)(i)){let s=(0,es.readFileSync)(i,"utf8");e.add(s)}}catch(i){am.debug(`No ${n} found or error reading it:`,i)}}for(let n of Am)r(n);return n=>{let i=n.split(Gi.sep).join("/");return e.ignores(i)}}async function jv(t,e){let r=(0,v4.default)().add(VB);async function n(i){try{let s=e.resolve(t,i);if(await e.exists(s)){let o=await e.readFile(s);o&&r.add(o)}}catch(s){am.debug(`No ${i} found or error reading it:`,s)}}for(let i of Am)await n(i);return i=>{let s=i.split(Gi.sep).join("/");return r.ignores(s)}}function swe(t,e,r){let n=kH(t),i=awe.default.watch(t,{ignored:n,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:600},ignorePermissionErrors:!0,followSymlinks:!1,atomic:600}),s=async a=>{let A=(0,Gi.relative)(t,a);try{let c=(0,es.readFileSync)(a,"utf-8");if(AIt(c,e.snippet)){let u=e.writtenFiles.find(l=>l.path===A);u?(u.code=Nx(c),u.timestamp=Date.now()):e.writtenFiles.push({path:A,code:Nx(c),timestamp:Date.now(),name:A.split("/").pop()||""}),e.timeStamp=Date.now(),r(e)}}catch(c){am.debug(`Error reading file ${a}:`,c)}};i.on("add",async a=>{$.info(`File added: ${a}`),await s(a)}).on("change",async a=>{$.info(`File changed: ${a}`),await s(a)}).on("unlink",a=>{$.info(`File deleted: ${a}`);let A=(0,Gi.relative)(t,a);e.writtenFiles=e.writtenFiles.filter(c=>c.path!==A),e.timeStamp=Date.now(),r(e)}).on("unlinkDir",a=>{$.info(`Folder deleted: ${a}`);let A=(0,Gi.relative)(t,a);e.writtenFiles=e.writtenFiles.filter(c=>!c.path.startsWith(A)),e.timeStamp=Date.now(),r(e)}).on("ready",()=>{am.debug("Initial scan complete. Ready for changes.")}).on("error",a=>{am.error(`Watcher error: ${a}`)}),i.on("raw",async(a,A,c)=>{if(a==="rename"){$.info(`File renamed: ${c?.oldPath} -> ${A}`);let u=c?.oldPath?(0,Gi.relative)(t,c.oldPath):void 0,l=A?(0,Gi.relative)(t,A):void 0;if(u&&l){let d=e.writtenFiles.find(g=>g.path===u);d&&(d.path=l,e.timeStamp=Date.now(),r(e))}}});let o=async()=>{await i.close()};return process.on("SIGINT",o),process.on("SIGTERM",o),o}async function cwe(t,e){console.log(""),sr((0,Ll.bgMagenta)((0,Ll.bold)((0,Ll.white)(" sync server ")))+" "+(0,Ll.dim)(ht)),t.debug("builder sync server init");let r=await Ed(t),n=e,i=()=>Promise.resolve();n&&setTimeout(()=>{i=swe(t.getAppRootDir(),n,s=>{n=s})},1e3),await pL({...r,ensureFigmaImportPage:()=>Promise.reject("Not supported"),getPastSyncInfo:({sessionKey:s,since:o})=>!n||s!==n.snippet.sessionKey?null:{...n,hasChanged:n.timeStamp>o},resyncSnippet:async s=>{await i();let o=await S4({path:n?.pathInput,snippet:s.snippet,cwd:t.getAppRootDir()});return o&&(n=o,i=swe(t.getAppRootDir(),n,a=>{n=a})),n},getClientId:()=>"builder-sync-cli",closeAppServer:async()=>{await i()},restartAppServer:async()=>{t.debug("restart server")},enableAppWatch:async s=>s,...t})}async function S4(t){let e=t.snippetId,r=t.snippet||null;if(!r&&e&&(r=await fL(e)),!r)return Ke(`No snippet found for id ${e}`),await Me(1);let n=process.cwd(),i=UC(n)??n,s=await aIt(i,r.contentId,r.sessionKey),o=s.filter(l=>l.snippetId===r.id);if($.info(`Found ${o.length} matching files for snippet ${r.id} in existing files ${s.length}`),o.length>0){let l=Math.max(...o.map(d=>d.timestamp||0));return{snippet:r,writtenFiles:o,pathInput:owe(o.map(d=>d.path)),timeStamp:l}}let a=hL(i,r.framework||"react"),A=t.path||owe(s.map(l=>l.path))||await lr({message:"Where should we copy the files?",initialValue:a,validate(l){if(l.length===0)return"File path is required!";if(l[0]!==".")return"Please enter a relative path."}});je(A)&&(Ke("Cancelled sync"),process.exit(0));for(let l of s){let d=(0,Gi.resolve)(i,l.path);try{(0,es.unlinkSync)(d),$.info(`Deleted old file: ${d}`);let g=(0,Gi.dirname)(d);(0,es.readdirSync)(g).length===0&&((0,es.rmdirSync)(g),$.info(`Deleted empty folder: ${g}`))}catch(g){$.error(`Error cleaning up file ${d}: ${g}`)}}let c=await Vw(i,r,r.files,A,!0);$.success("All files have been written successfully.");let u=Math.max(...c.map(l=>l.timestamp||0));return{snippet:r,writtenFiles:c.map(l=>({...l,code:Nx(l.code)})),pathInput:A,timeStamp:u||Date.now()}}function Nx(t){if(!t)return t;let e=/<!--\s*This code was generated by Builder\.io\s*-->\s*(?:<!--\s*https:\/\/builder\.io\/content\/[a-f0-9]+\?codeSession=[a-f0-9]+&sid=[a-f0-9]+\s*-->\s*)?/,r=/\/\*\*\s*\n\s*\* This code was generated by Builder\.io\s*\n\s*\* https:\/\/builder\.io\/content\/[a-f0-9]+\?codeSession=[a-f0-9]+&sid=[a-f0-9]+\s*\n\s*\*\/\s*/,n=t.replace(e,"").replace(r,"");return n=n.replace(/^\n+/,""),n}function owe(t){if(t.length===0)return"";if(t.length===1)return`./${t[0].slice(0,t[0].lastIndexOf("/")+1)}`;let e=t.map(i=>i.split("/")),r=Math.min(...e.map(i=>i.length)),n=[];for(let i=0;i<r;i++){let s=e[0][i];if(e.every(o=>o[i]===s))n.push(s);else break}return`./${n.join("/")}`}var Gi,es,Ll,awe,v4,am,sIt,Am,VB,Cp=L(()=>{"use strict";h();Gi=require("node:path");Bt();es=require("node:fs"),Ll=z(Ir(),1);one();pQ();dL();mL();rr();awe=z(require("chokidar"),1),v4=z(require("ignore"),1);Ns();GC();zr();da();FH();am=ve("Sync");sIt=!1;Am=[".gitignore",".ignore",".builderignore"],VB=["**/*.snap","**/*.liquid","**/.git","**/dist","**/*.pyc","**/.DS_Store","**/.vscode","**/__pycache__","**/coverage","**/.next","**/coverage","**/example","**/__snapshots__","**/.gradle","**/xcuserdata","**/.build","**/*.zip","**/*.pem","**/*.key","**/*.p12","**/*.pfx","**/*.cer","**/*.crt","**/*.der","**/*.p7b","**/*.p7c","**/*.jks","**/*.keystore","**/id_rsa","**/id_rsa.*","**/id_dsa","**/id_dsa.*","**/id_ecdsa","**/id_ecdsa.*","**/id_ed25519","**/id_ed25519.*","**/.ssh/**","**/known_hosts","**/authorized_keys","**/.aws/**","**/credentials","**/.gcp/**","**/.azure/**","**/gcloud/**","**/google-credentials.json","**/gcp-key.json","**/service-account*.json","**/.pypirc","**/.dockercfg","**/.docker/config.json","**/token.json","**/tokens.json","**/secrets.json","**/secret.json","**/api-keys.json","**/apikeys.json","**/*.sql","**/*.sqlite","**/*.sqlite3","**/*.db","**/*.dump","**/*.bak","**/passwd","**/.htpasswd","**/shadow","**/.git-credentials","**/.gitconfig","**/.netrc","**/kubeconfig","**/.kube/**","**/k8s-secrets.yaml","**/k8s-secrets.yml","**/*.tfstate","**/*.tfstate.*","**/.terraform/**","**/.history","**/.bash_history","**/.zsh_history","**/wallet.dat","**/.gnupg/**","**/private.xml","**/signing.properties","**/*.ovpn","**/wp-config.php","**/config.inc.php","**/local_settings.py","**/database.yml","**/secrets.yml","**/.tox/**","**/firebase-adminsdk*.json","**/firebaseConfig.json","**/google-services.json","**/GoogleService-Info.plist"]});async function Px(t,e,r,n="",i,s){let o=[];try{if(!await t.exists(e))return o;let a=await t.readdir(e);for(let A of a){let c=t.join(e,A);if(i&&s){let l=t.relative(s,c);if(!l.startsWith("..")&&!l.startsWith("/")&&i(l))continue}let u=await t.stat(c).catch(()=>null);if(u)if(u.isDirectory()){let l=n?`${n}/${A}`:A,d=await Px(t,c,r,l,i,s);o.push(...d)}else o.push(c)}}catch{}return o}async function Mx(t,e,r){try{if(!(await t.stat(e).catch(()=>null))?.isFile())return null;let i=await t.readFile(e);if(!i)return null;let s=t.relative(r,e);return vZ(i,s)}catch(n){return t.Sentry?.captureException(n),null}}async function RH({sys:t,projectDir:e,currentDir:r,rootDir:n,allowedCommands:i,skipCommandSecurity:s,homeDir:o}){let a=[],A=[".cursor/rules",".builder/rules",".agents/rules"],c=[".claude/skills",".builder/skills",".cursor/skills",".agents/skills"],u=[".cursorrules",".builderrules",".windsurfrules",".github/copilot-instructions.md"],l=await jv(e,t),d=C=>{let I=t.basename(C);return I.toLowerCase().endsWith(".mdc")||I.toUpperCase()==="RULE.MD"},g=C=>t.basename(C).toUpperCase()==="SKILL.MD",p=o??(0,lwe.homedir)();if(p)try{for(let C of cIt){let I=t.resolve(p,C);if(await t.exists(I)){let y=await Px(t,I,I);for(let B of y.filter(g)){let E=await Mx(t,B,e);E&&a.push({...E,isSkill:!0,scope:"user"})}}}}catch(C){uwe.debug("Error reading user-level skills/rules:",C)}let f=new Set;for(let C of Array.isArray(r)?r:[r]){let I=C,y;do{try{for(let B of A){let E=t.resolve(I,B);if(!f.has(E)&&(f.add(E),await t.exists(E))){let v=(await Px(t,E,E,"",l,e)).filter(d);for(let D of v){let S=await Mx(t,D,e);S&&a.push({...S,scope:"project"})}}}for(let B of c){let E=t.resolve(I,B);if(!f.has(E)&&(f.add(E),await t.exists(E))){let v=(await Px(t,E,E,"",l,e)).filter(g);for(let D of v){let S=await Mx(t,D,e);S&&a.push({...S,isSkill:!0,scope:"project"})}}}for(let B of u){let E=t.resolve(I,B);if(f.has(E))continue;f.add(E);let Q=t.relative(e,E);if(!Q.startsWith("..")&&!Q.startsWith("/")&&l(Q))continue;let v=await Mx(t,E,e);v&&a.push({...v,scope:"project"})}}catch(B){uwe.debug(`Error reading ${I}:`,B)}if(y=I,I=t.dirname(I),I===y)break}while(y!==n)}let m=process.env;return a.map(C=>C.isSkill?{...C,content:Qv(C.content,{cwd:e,env:m,allowedCommands:i,skipCommandSecurity:s})}:C)}var lwe,uwe,cIt,TH=L(()=>{"use strict";h();lwe=require("node:os");SZ();Cp();TO();Bt();uwe=ve("RulesDiscovery");cIt=[".builder/skills",".agents/skills"]});function SB(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return Array.from(r.values())}function FB(t){for(let e=t.turns.length-1;e>=0;e--){let r=t.turns[e];if(r.state==="done"&&r.nextUrl)return r}}function NH(t){for(let e=t.turns.length-1;e>=0;e--){let r=t.turns[e];if(r.user.role==="user"&&r.completionId)return r}}function oye(t){return FB(t)??NH(t)}function aye(t,e){if(!e)return;let r=t.turns.indexOf(e),n=r===-1?t.turns.length-1:r;for(let i=n;i>=0;i--){let s=t.turns[i];if(s.state==="done"&&s.user.role==="user"&&s.completionId)return s}}function Aye(t){for(let e=t.turns.length-1;e>=0;e--){let r=t.turns[e];if(r.nextUrl&&(r.applyResults.length>0||r.user.role==="user"))return r}}function Fa(t){return t[t.length-1]}function cye(t){for(let e=t.length-1;e>=0;e--)t[e].state!=="done"&&t.splice(e,1)}async function uye(t,e,r,n){let i=new URL(`${Ne}/codegen/restore-consumed-credit`);e.builderPublicKey&&i.searchParams.set("apiKey",e.builderPublicKey),e.userId&&i.searchParams.set("userId",e.userId);let s={"Content-Type":"application/json"};e.builderPrivateKey&&(s.Authorization=`Bearer ${e.builderPrivateKey}`);try{await Fe(i,{method:"POST",body:JSON.stringify({sessionId:r,restoreCredits:n}),headers:s,signal:AbortSignal.timeout(3e4)})}catch(o){let a=o&&o.name==="AbortError"||typeof o?.code=="string"&&o.code==="ABORT_ERR"||typeof o?.timeout=="boolean"&&o.timeout||/timeout|abort/i.test(o?.message??"");t.Sentry?.captureException(o,{level:"warning",tags:{operation:"restore-consumed-credit",timeout:a}})}}function gwe(t,e){let r={totalSize:e.length,totalSizeMB:(e.length/1048576).toFixed(2)};if(t.attachments?.length){let i=t.attachments.map(o=>JSON.stringify(o).length),s={};t.attachments.forEach((o,a)=>{let A=o.type||"unknown",c=i[a];s[A]||(s[A]={count:0,totalSize:0}),s[A].count++,s[A].totalSize+=c}),r.attachments={count:t.attachments.length,totalSize:i.reduce((o,a)=>o+a,0),totalSizeMB:(i.reduce((o,a)=>o+a,0)/(1024*1024)).toFixed(2),byType:Object.entries(s).map(([o,a])=>({type:o,count:a.count,sizeMB:(a.totalSize/(1024*1024)).toFixed(2)})),largestAttachments:t.attachments.map((o,a)=>({type:o.type,size:i[a],sizeMB:(i[a]/(1024*1024)).toFixed(2)})).sort((o,a)=>a.size-o.size).slice(0,5)}}if(t.files?.length){let i={},s=0,o=0,a=0;t.files.forEach(c=>{let u=c.filePath?.split(".").pop()||"no-ext";i[u]||(i[u]={count:0,withContent:0,totalContentSize:0}),i[u].count++,c.content?(i[u].withContent++,i[u].totalContentSize+=c.content.length,s++,a+=c.content.length):o++});let A=Object.entries(i).sort((c,u)=>u[1].totalContentSize-c[1].totalContentSize).slice(0,10).map(([c,u])=>({ext:c,count:u.count,withContent:u.withContent,contentSizeMB:(u.totalContentSize/(1024*1024)).toFixed(2)}));r.files={totalCount:t.files.length,withContent:s,withoutContent:o,totalContentSize:a,totalContentSizeMB:(a/(1024*1024)).toFixed(2),topExtensionsBySize:A}}let n={};if(t.userPrompt&&(n.userPrompt={size:t.userPrompt.length,sizeMB:(t.userPrompt.length/(1024*1024)).toFixed(2),hasGitDiff:t.userPrompt.includes("<modified-files-context>")},n.userPrompt.hasGitDiff)){let i=t.userPrompt.match(/<modified-files-context>([\s\S]*?)<\/modified-files-context>/);i&&(n.gitDiffInPrompt={size:i[1].length,sizeMB:(i[1].length/(1024*1024)).toFixed(2)})}if(t.uiContextPrompt&&(n.uiContextPrompt={size:t.uiContextPrompt.length,sizeMB:(t.uiContextPrompt.length/(1024*1024)).toFixed(2)}),Object.keys(n).length>0&&(r.prompts=n),t.toolResults?.length){let i=JSON.stringify(t.toolResults).length;r.toolResults={count:t.toolResults.length,totalSize:i,totalSizeMB:(i/(1024*1024)).toFixed(2)}}return r}async function*lye(t,e,r,n,i){if(!e.builderPrivateKey)throw new Error("Missing builder public key during completion stream");let s=new AbortController,o=JSON.stringify(r),a=new URL(`${Ne}/codegen/completion`);e.builderPublicKey&&a.searchParams.set("apiKey",e.builderPublicKey),e.userId&&a.searchParams.set("userId",e.userId);let A=performance.now(),c=A,u,l=!1,d=0,g=[];try{let p=await Fe(a,{method:"POST",body:o,keepalive:!0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.builderPrivateKey}`},signal:Qn([n,s.signal])},i);if(!p.ok){let m=await p.text(),C=`Bad Status: ${p.status}: ${m}`;if(p.status===413){let y=gwe(r,o),B=[];y.attachments?.totalSizeMB&&B.push(`Attachments: ${y.attachments.totalSizeMB}MB (${y.attachments.count} files)`),y.files?.totalContentSizeMB&&B.push(`File content: ${y.files.totalContentSizeMB}MB (${y.files.withContent} files)`),y.prompts?.gitDiffInPrompt?.sizeMB&&B.push(`Git diff: ${y.prompts.gitDiffInPrompt.sizeMB}MB`),y.prompts?.uiContextPrompt?.sizeMB&&B.push(`UI context: ${y.prompts.uiContextPrompt.sizeMB}MB`),y.toolResults?.totalSizeMB&&B.push(`Tool results: ${y.toolResults.totalSizeMB}MB`),B.length>0&&(C+=`
|
|
4835
|
+
`}async function iIt(t){let{sys:e,bashWorkingDirectory:r}=t,n=r;try{let i=xs.join(n,".builder","sources","figma","manifest.json"),s="Design System";try{let d=await e.readFile(i);if(d){let g=JSON.parse(d);g.figmaName&&(s=g.figmaName)}}catch{}let o=xs.join(n,".builder","output","_index","tokens-report.json"),a=[],A=["colors","typography","spacing","elevation","brand"];try{let d=await e.readFile(o);if(!d)throw new Error("empty");let g=JSON.parse(d);for(let p of A)g.filesWritten?.some(f=>f.endsWith(`tokens/${p}.css`))&&a.push(p)}catch{}let c=[];try{let d=xs.join(n,".builder","output","tokens","components"),g=await e.readdir(d);for(let p of g)if(p.endsWith(".css")){let f=xs.basename(p,".css");f!=="components"&&c.push(f)}c.sort()}catch{}let u=zDe({designSystemName:s,tokenCategories:a.length>0?a:void 0,componentSlugs:c}),l=xs.join(n,".builder","output","AGENTS.md");return await e.writeFile(l,u),{isError:!1,title:"Generated AGENTS.md",toolResult:`Wrote \`.builder/output/AGENTS.md\` (${s}). Token categories: ${a.length>0?a.join(", "):"none"}. Components: ${c.length>0?c.join(", "):"none"}.`}}catch(i){return{isError:!0,title:"GenerateDesignSystemAgentMd failed",toolResult:`Failed to generate AGENTS.md: ${i?.message??String(i)}`}}}var xs,Pa,ewe,twe,NCt,MCt,F4=L(()=>{"use strict";h();Hs();pI();PL();mI();z_();mI();HI();foe();O0();da();xs=z(require("node:path"),1);Tu();K0();kB();Zh();Pa=z(require("@sentry/node"),1);JI();xi();FDe();yr();RDe();NDe();Tx();XDe();JB();NO();aU();ewe=5e4;twe=new Set(["mcp__chrome__click","mcp__chrome__hover","mcp__chrome__fill","mcp__chrome__type","mcp__chrome__select_option","mcp__chrome__press_key"]);NCt=["!**/.git/**","!**/.hg/**","!**/.svn/**","!**/.DS_Store","!**/.idea/**","!**/.vscode/**","!**/.cache/**","!**/coverage/**","!**/node_modules/**","!**/dist/**","!**/*.tsbuildinfo","!**/package-lock.json","!**/yarn.lock","!**/pnpm-lock.yaml","!**/*.min.js","!**/*.min.css","!**/*.bundle.js","!**/*.chunk.js","!**/builder-registry.*","!**/*.bundle.css","!**/*.map","!**/vendor/**","!**/target/**","!**/__pycache__/**","!**/*.pyc","!**/*.pyo","!**/*.class","!**/*.jar","!**/build/**/*.gradle","!**/*.lock","!**/*.log","!**/*.o","!**/*.a","!**/*.so","!**/*.dylib","!**/*.dll","!**/*.exe","!**/*.zip","!**/*.tar","!**/*.tar.gz","!**/*.tgz","!**/*.7z","!**/*.rar","!**/*.png","!**/*.jpg","!**/*.jpeg","!**/*.gif","!**/*.svg","!**/*.ico","!**/*.webp","!**/*.mp4","!**/*.mp3"],MCt=t=>{let e=["{","(","["],r=["}",")","]"],n=[],i=[],s=new Map([["{","}"],["(",")"],["[","]"]]);for(let o=0;o<=t.length-1;o++){let a=t[o];t[o-1]==="\\"&&t[o-2]!=="\\"||(e.includes(a)?n.push({location:o,value:a}):r.includes(a)&&i.push({location:o,value:a}))}for(let o of n){let{location:a,value:A}=o,c=i.findIndex(u=>u.location>a&&u.value===s.get(A));if(c>-1)i.splice(c,1);else return!0}return i.length>0}});function Awe(t){let e=t.match(/builder\.io\/content\/([^?]+)\?codeSession=([^&]+)&sid=([^\s]+)/);return e?{contentId:e[1],sessionKey:e[2],snippetId:e[3]}:{}}async function cl(t){let e={...t,globPattern:t.globPattern??"**/*",deep:t.deep??12,onlyFiles:t.onlyFiles??!0,gitignore:t.gitignore??!0};if(t.sys&&sIt)try{return await oIt(e)}catch(p){t.sys?.Sentry?.captureException(p)}let{basePath:r,globPattern:n,extraIgnorePatterns:i,dot:s,deep:o,gitignore:a,sys:A,onlyFiles:c,maxFiles:u}=e,l=Array.isArray(n)?[...n]:[n],d=[...VB,...i||[]],g=l.findIndex(p=>p.includes("node_modules"));g>-1?l.splice(g,0,"!**/node_modules"):d.push("**/node_modules");try{if(!c){let m=(await qw(l,{cwd:r,ignoreFiles:Am,ignore:d,absolute:!1,onlyFiles:c,dot:s,gitignore:a,suppressErrors:!0,deep:o,objectMode:!0})).map(C=>C.dirent?.isDirectory()?`${C.path}/`:C.path);return u!==void 0&&m.length>u?m.slice(0,u):m}let p=await qw(l,{cwd:r,ignoreFiles:Am,ignore:d,absolute:!1,onlyFiles:c,dot:s,gitignore:a,suppressErrors:!0,deep:o});return u!==void 0&&p.length>u?p.slice(0,u):p}catch(p){throw A?.Sentry?.captureException(p,{tags:{errorType:"filesystem_permission",component:"getAllProjectFiles"},extra:{basePath:r,patterns:l,errorCode:p.code}}),p}}async function oIt({basePath:t,globPattern:e,extraIgnorePatterns:r,dot:n,deep:i,gitignore:s,sys:o,onlyFiles:a,maxFiles:A}){if(!o)throw new Error("sys is required");let c=await RB(o),u=["--files","--path-separator","/"];n&&u.push("--hidden"),s||u.push("--no-ignore"),i!==void 0&&u.push("--max-depth",String(i));let l=e?Array.isArray(e)?e:[e]:[],d=l.findIndex(p=>p.includes("node_modules"));for(let p of l)p.startsWith("!")||p!=="**/*"&&u.push("--glob",p);let g=[...VB,...r||[]];d===-1&&g.push("**/node_modules/**");for(let p of g)u.push("--glob",`!${p}`);for(let p of Am){let f=(0,Gi.resolve)(t,p);(0,es.existsSync)(f)&&u.push("--ignore-file",p)}return new Promise((p,f)=>{let m=Cc({command:c,args:u,options:{env:process.env,cwd:t,stdio:["ignore","pipe","pipe"]}}),C=[],I="",y="",B=!1;m.stdout.on("data",E=>{if(B)return;I+=E.toString();let Q=I.split(`
|
|
4836
|
+
`);I=Q.pop()||"";for(let v of Q){let D=v.trim();if(D.length>0&&(C.push(D),A!==void 0&&C.length>=A)){B=!0,m.kill("SIGTERM");return}}}),m.stderr.on("data",E=>{y+=E.toString()}),m.on("error",E=>{o?.Sentry?.captureException(E,{tags:{errorType:"ripgrep_spawn_error",component:"getAllProjectFilesRipgrep"},extra:{basePath:t,patterns:l,errorMessage:E.message}}),f(E)}),m.on("close",E=>{if(I.trim().length>0&&!B&&(A===void 0||C.length<A)&&C.push(I.trim()),B){p(C);return}if(E!==null&&E>1){o?.Sentry?.captureException(new Error(`ripgrep exited with code ${E}`),{tags:{errorType:"ripgrep_error",component:"getAllProjectFilesRipgrep"},extra:{basePath:t,patterns:l,stderr:y,exitCode:E}}),f(new Error(`ripgrep failed: ${y}`));return}if(!a){let Q=new Set;for(let D of C){let S=D.split("/");for(let b=1;b<S.length;b++)Q.add(S.slice(0,b).join("/")+"/")}let v=[...C,...Q].sort();p(v);return}p(C)})})}async function aIt(t,e,r){let n=await qw("**/*",{cwd:t,ignoreFiles:Am,ignore:VB}),i=[];for(let s of n){let o=(0,Gi.resolve)(t,s);try{let a=(0,es.readFileSync)(o,"utf-8");if(a.includes("This code was generated by Builder.io")){let A=Awe(a);if(e&&r&&(A.contentId!==e||A.sessionKey!==r))continue;i.push({path:s,code:Nx(a),name:s.split("/").pop()||"",timestamp:(0,es.statSync)(o).mtime.getTime(),snippetId:A.snippetId})}}catch(a){am.error(`Error reading file ${o}:`,a)}}return i}function AIt(t,e){let r=Awe(t);return r.contentId===e.contentId&&r.sessionKey===e.sessionKey}function iye(t){return t.filter(e=>(e=e.toLowerCase(),!e.endsWith(".png")&&!e.endsWith(".jpg")&&!e.endsWith(".jpeg")&&!e.endsWith(".gif")&&!e.endsWith(".ico")&&!e.endsWith(".webp")&&!e.includes(".mapper.")))}function k4(t){let e=(0,vH.default)().add(VB);function r(n){try{let i=(0,Gi.resolve)(t,n);if((0,es.existsSync)(i)){let s=(0,es.readFileSync)(i,"utf8");e.add(s)}}catch(i){am.debug(`No ${n} found or error reading it:`,i)}}for(let n of Am)r(n);return n=>{let i=n.split(Gi.sep).join("/");return e.ignores(i)}}async function jv(t,e){let r=(0,vH.default)().add(VB);async function n(i){try{let s=e.resolve(t,i);if(await e.exists(s)){let o=await e.readFile(s);o&&r.add(o)}}catch(s){am.debug(`No ${i} found or error reading it:`,s)}}for(let i of Am)await n(i);return i=>{let s=i.split(Gi.sep).join("/");return r.ignores(s)}}function swe(t,e,r){let n=k4(t),i=awe.default.watch(t,{ignored:n,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:600},ignorePermissionErrors:!0,followSymlinks:!1,atomic:600}),s=async a=>{let A=(0,Gi.relative)(t,a);try{let c=(0,es.readFileSync)(a,"utf-8");if(AIt(c,e.snippet)){let u=e.writtenFiles.find(l=>l.path===A);u?(u.code=Nx(c),u.timestamp=Date.now()):e.writtenFiles.push({path:A,code:Nx(c),timestamp:Date.now(),name:A.split("/").pop()||""}),e.timeStamp=Date.now(),r(e)}}catch(c){am.debug(`Error reading file ${a}:`,c)}};i.on("add",async a=>{$.info(`File added: ${a}`),await s(a)}).on("change",async a=>{$.info(`File changed: ${a}`),await s(a)}).on("unlink",a=>{$.info(`File deleted: ${a}`);let A=(0,Gi.relative)(t,a);e.writtenFiles=e.writtenFiles.filter(c=>c.path!==A),e.timeStamp=Date.now(),r(e)}).on("unlinkDir",a=>{$.info(`Folder deleted: ${a}`);let A=(0,Gi.relative)(t,a);e.writtenFiles=e.writtenFiles.filter(c=>!c.path.startsWith(A)),e.timeStamp=Date.now(),r(e)}).on("ready",()=>{am.debug("Initial scan complete. Ready for changes.")}).on("error",a=>{am.error(`Watcher error: ${a}`)}),i.on("raw",async(a,A,c)=>{if(a==="rename"){$.info(`File renamed: ${c?.oldPath} -> ${A}`);let u=c?.oldPath?(0,Gi.relative)(t,c.oldPath):void 0,l=A?(0,Gi.relative)(t,A):void 0;if(u&&l){let d=e.writtenFiles.find(g=>g.path===u);d&&(d.path=l,e.timeStamp=Date.now(),r(e))}}});let o=async()=>{await i.close()};return process.on("SIGINT",o),process.on("SIGTERM",o),o}async function cwe(t,e){console.log(""),sr((0,Ll.bgMagenta)((0,Ll.bold)((0,Ll.white)(" sync server ")))+" "+(0,Ll.dim)(ht)),t.debug("builder sync server init");let r=await Ed(t),n=e,i=()=>Promise.resolve();n&&setTimeout(()=>{i=swe(t.getAppRootDir(),n,s=>{n=s})},1e3),await pL({...r,ensureFigmaImportPage:()=>Promise.reject("Not supported"),getPastSyncInfo:({sessionKey:s,since:o})=>!n||s!==n.snippet.sessionKey?null:{...n,hasChanged:n.timeStamp>o},resyncSnippet:async s=>{await i();let o=await SH({path:n?.pathInput,snippet:s.snippet,cwd:t.getAppRootDir()});return o&&(n=o,i=swe(t.getAppRootDir(),n,a=>{n=a})),n},getClientId:()=>"builder-sync-cli",closeAppServer:async()=>{await i()},restartAppServer:async()=>{t.debug("restart server")},enableAppWatch:async s=>s,...t})}async function SH(t){let e=t.snippetId,r=t.snippet||null;if(!r&&e&&(r=await fL(e)),!r)return Ke(`No snippet found for id ${e}`),await Me(1);let n=process.cwd(),i=UC(n)??n,s=await aIt(i,r.contentId,r.sessionKey),o=s.filter(l=>l.snippetId===r.id);if($.info(`Found ${o.length} matching files for snippet ${r.id} in existing files ${s.length}`),o.length>0){let l=Math.max(...o.map(d=>d.timestamp||0));return{snippet:r,writtenFiles:o,pathInput:owe(o.map(d=>d.path)),timeStamp:l}}let a=hL(i,r.framework||"react"),A=t.path||owe(s.map(l=>l.path))||await lr({message:"Where should we copy the files?",initialValue:a,validate(l){if(l.length===0)return"File path is required!";if(l[0]!==".")return"Please enter a relative path."}});je(A)&&(Ke("Cancelled sync"),process.exit(0));for(let l of s){let d=(0,Gi.resolve)(i,l.path);try{(0,es.unlinkSync)(d),$.info(`Deleted old file: ${d}`);let g=(0,Gi.dirname)(d);(0,es.readdirSync)(g).length===0&&((0,es.rmdirSync)(g),$.info(`Deleted empty folder: ${g}`))}catch(g){$.error(`Error cleaning up file ${d}: ${g}`)}}let c=await Vw(i,r,r.files,A,!0);$.success("All files have been written successfully.");let u=Math.max(...c.map(l=>l.timestamp||0));return{snippet:r,writtenFiles:c.map(l=>({...l,code:Nx(l.code)})),pathInput:A,timeStamp:u||Date.now()}}function Nx(t){if(!t)return t;let e=/<!--\s*This code was generated by Builder\.io\s*-->\s*(?:<!--\s*https:\/\/builder\.io\/content\/[a-f0-9]+\?codeSession=[a-f0-9]+&sid=[a-f0-9]+\s*-->\s*)?/,r=/\/\*\*\s*\n\s*\* This code was generated by Builder\.io\s*\n\s*\* https:\/\/builder\.io\/content\/[a-f0-9]+\?codeSession=[a-f0-9]+&sid=[a-f0-9]+\s*\n\s*\*\/\s*/,n=t.replace(e,"").replace(r,"");return n=n.replace(/^\n+/,""),n}function owe(t){if(t.length===0)return"";if(t.length===1)return`./${t[0].slice(0,t[0].lastIndexOf("/")+1)}`;let e=t.map(i=>i.split("/")),r=Math.min(...e.map(i=>i.length)),n=[];for(let i=0;i<r;i++){let s=e[0][i];if(e.every(o=>o[i]===s))n.push(s);else break}return`./${n.join("/")}`}var Gi,es,Ll,awe,vH,am,sIt,Am,VB,Cp=L(()=>{"use strict";h();Gi=require("node:path");Bt();es=require("node:fs"),Ll=z(Ir(),1);one();pQ();dL();mL();rr();awe=z(require("chokidar"),1),vH=z(require("ignore"),1);Ns();GC();zr();da();F4();am=ve("Sync");sIt=!1;Am=[".gitignore",".ignore",".builderignore"],VB=["**/*.snap","**/*.liquid","**/.git","**/dist","**/*.pyc","**/.DS_Store","**/.vscode","**/__pycache__","**/coverage","**/.next","**/coverage","**/example","**/__snapshots__","**/.gradle","**/xcuserdata","**/.build","**/*.zip","**/*.pem","**/*.key","**/*.p12","**/*.pfx","**/*.cer","**/*.crt","**/*.der","**/*.p7b","**/*.p7c","**/*.jks","**/*.keystore","**/id_rsa","**/id_rsa.*","**/id_dsa","**/id_dsa.*","**/id_ecdsa","**/id_ecdsa.*","**/id_ed25519","**/id_ed25519.*","**/.ssh/**","**/known_hosts","**/authorized_keys","**/.aws/**","**/credentials","**/.gcp/**","**/.azure/**","**/gcloud/**","**/google-credentials.json","**/gcp-key.json","**/service-account*.json","**/.pypirc","**/.dockercfg","**/.docker/config.json","**/token.json","**/tokens.json","**/secrets.json","**/secret.json","**/api-keys.json","**/apikeys.json","**/*.sql","**/*.sqlite","**/*.sqlite3","**/*.db","**/*.dump","**/*.bak","**/passwd","**/.htpasswd","**/shadow","**/.git-credentials","**/.gitconfig","**/.netrc","**/kubeconfig","**/.kube/**","**/k8s-secrets.yaml","**/k8s-secrets.yml","**/*.tfstate","**/*.tfstate.*","**/.terraform/**","**/.history","**/.bash_history","**/.zsh_history","**/wallet.dat","**/.gnupg/**","**/private.xml","**/signing.properties","**/*.ovpn","**/wp-config.php","**/config.inc.php","**/local_settings.py","**/database.yml","**/secrets.yml","**/.tox/**","**/firebase-adminsdk*.json","**/firebaseConfig.json","**/google-services.json","**/GoogleService-Info.plist"]});async function Px(t,e,r,n="",i,s){let o=[];try{if(!await t.exists(e))return o;let a=await t.readdir(e);for(let A of a){let c=t.join(e,A);if(i&&s){let l=t.relative(s,c);if(!l.startsWith("..")&&!l.startsWith("/")&&i(l))continue}let u=await t.stat(c).catch(()=>null);if(u)if(u.isDirectory()){let l=n?`${n}/${A}`:A,d=await Px(t,c,r,l,i,s);o.push(...d)}else o.push(c)}}catch{}return o}async function Mx(t,e,r){try{if(!(await t.stat(e).catch(()=>null))?.isFile())return null;let i=await t.readFile(e);if(!i)return null;let s=t.relative(r,e);return vZ(i,s)}catch(n){return t.Sentry?.captureException(n),null}}async function R4({sys:t,projectDir:e,currentDir:r,rootDir:n,allowedCommands:i,skipCommandSecurity:s,homeDir:o}){let a=[],A=[".cursor/rules",".builder/rules",".agents/rules"],c=[".claude/skills",".builder/skills",".cursor/skills",".agents/skills"],u=[".cursorrules",".builderrules",".windsurfrules",".github/copilot-instructions.md"],l=await jv(e,t),d=C=>{let I=t.basename(C);return I.toLowerCase().endsWith(".mdc")||I.toUpperCase()==="RULE.MD"},g=C=>t.basename(C).toUpperCase()==="SKILL.MD",p=o??(0,lwe.homedir)();if(p)try{for(let C of cIt){let I=t.resolve(p,C);if(await t.exists(I)){let y=await Px(t,I,I);for(let B of y.filter(g)){let E=await Mx(t,B,e);E&&a.push({...E,isSkill:!0,scope:"user"})}}}}catch(C){uwe.debug("Error reading user-level skills/rules:",C)}let f=new Set;for(let C of Array.isArray(r)?r:[r]){let I=C,y;do{try{for(let B of A){let E=t.resolve(I,B);if(!f.has(E)&&(f.add(E),await t.exists(E))){let v=(await Px(t,E,E,"",l,e)).filter(d);for(let D of v){let S=await Mx(t,D,e);S&&a.push({...S,scope:"project"})}}}for(let B of c){let E=t.resolve(I,B);if(!f.has(E)&&(f.add(E),await t.exists(E))){let v=(await Px(t,E,E,"",l,e)).filter(g);for(let D of v){let S=await Mx(t,D,e);S&&a.push({...S,isSkill:!0,scope:"project"})}}}for(let B of u){let E=t.resolve(I,B);if(f.has(E))continue;f.add(E);let Q=t.relative(e,E);if(!Q.startsWith("..")&&!Q.startsWith("/")&&l(Q))continue;let v=await Mx(t,E,e);v&&a.push({...v,scope:"project"})}}catch(B){uwe.debug(`Error reading ${I}:`,B)}if(y=I,I=t.dirname(I),I===y)break}while(y!==n)}let m=process.env;return a.map(C=>C.isSkill?{...C,content:Qv(C.content,{cwd:e,env:m,allowedCommands:i,skipCommandSecurity:s})}:C)}var lwe,uwe,cIt,T4=L(()=>{"use strict";h();lwe=require("node:os");SZ();Cp();TO();Bt();uwe=ve("RulesDiscovery");cIt=[".builder/skills",".agents/skills"]});function SB(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return Array.from(r.values())}function FB(t){for(let e=t.turns.length-1;e>=0;e--){let r=t.turns[e];if(r.state==="done"&&r.nextUrl)return r}}function N4(t){for(let e=t.turns.length-1;e>=0;e--){let r=t.turns[e];if(r.user.role==="user"&&r.completionId)return r}}function oye(t){return FB(t)??N4(t)}function aye(t,e){if(!e)return;let r=t.turns.indexOf(e),n=r===-1?t.turns.length-1:r;for(let i=n;i>=0;i--){let s=t.turns[i];if(s.state==="done"&&s.user.role==="user"&&s.completionId)return s}}function Aye(t){for(let e=t.turns.length-1;e>=0;e--){let r=t.turns[e];if(r.nextUrl&&(r.applyResults.length>0||r.user.role==="user"))return r}}function Fa(t){return t[t.length-1]}function cye(t){for(let e=t.length-1;e>=0;e--)t[e].state!=="done"&&t.splice(e,1)}async function uye(t,e,r,n){let i=new URL(`${Ne}/codegen/restore-consumed-credit`);e.builderPublicKey&&i.searchParams.set("apiKey",e.builderPublicKey),e.userId&&i.searchParams.set("userId",e.userId);let s={"Content-Type":"application/json"};e.builderPrivateKey&&(s.Authorization=`Bearer ${e.builderPrivateKey}`);try{await Fe(i,{method:"POST",body:JSON.stringify({sessionId:r,restoreCredits:n}),headers:s,signal:AbortSignal.timeout(3e4)})}catch(o){let a=o&&o.name==="AbortError"||typeof o?.code=="string"&&o.code==="ABORT_ERR"||typeof o?.timeout=="boolean"&&o.timeout||/timeout|abort/i.test(o?.message??"");t.Sentry?.captureException(o,{level:"warning",tags:{operation:"restore-consumed-credit",timeout:a}})}}function gwe(t,e){let r={totalSize:e.length,totalSizeMB:(e.length/1048576).toFixed(2)};if(t.attachments?.length){let i=t.attachments.map(o=>JSON.stringify(o).length),s={};t.attachments.forEach((o,a)=>{let A=o.type||"unknown",c=i[a];s[A]||(s[A]={count:0,totalSize:0}),s[A].count++,s[A].totalSize+=c}),r.attachments={count:t.attachments.length,totalSize:i.reduce((o,a)=>o+a,0),totalSizeMB:(i.reduce((o,a)=>o+a,0)/(1024*1024)).toFixed(2),byType:Object.entries(s).map(([o,a])=>({type:o,count:a.count,sizeMB:(a.totalSize/(1024*1024)).toFixed(2)})),largestAttachments:t.attachments.map((o,a)=>({type:o.type,size:i[a],sizeMB:(i[a]/(1024*1024)).toFixed(2)})).sort((o,a)=>a.size-o.size).slice(0,5)}}if(t.files?.length){let i={},s=0,o=0,a=0;t.files.forEach(c=>{let u=c.filePath?.split(".").pop()||"no-ext";i[u]||(i[u]={count:0,withContent:0,totalContentSize:0}),i[u].count++,c.content?(i[u].withContent++,i[u].totalContentSize+=c.content.length,s++,a+=c.content.length):o++});let A=Object.entries(i).sort((c,u)=>u[1].totalContentSize-c[1].totalContentSize).slice(0,10).map(([c,u])=>({ext:c,count:u.count,withContent:u.withContent,contentSizeMB:(u.totalContentSize/(1024*1024)).toFixed(2)}));r.files={totalCount:t.files.length,withContent:s,withoutContent:o,totalContentSize:a,totalContentSizeMB:(a/(1024*1024)).toFixed(2),topExtensionsBySize:A}}let n={};if(t.userPrompt&&(n.userPrompt={size:t.userPrompt.length,sizeMB:(t.userPrompt.length/(1024*1024)).toFixed(2),hasGitDiff:t.userPrompt.includes("<modified-files-context>")},n.userPrompt.hasGitDiff)){let i=t.userPrompt.match(/<modified-files-context>([\s\S]*?)<\/modified-files-context>/);i&&(n.gitDiffInPrompt={size:i[1].length,sizeMB:(i[1].length/(1024*1024)).toFixed(2)})}if(t.uiContextPrompt&&(n.uiContextPrompt={size:t.uiContextPrompt.length,sizeMB:(t.uiContextPrompt.length/(1024*1024)).toFixed(2)}),Object.keys(n).length>0&&(r.prompts=n),t.toolResults?.length){let i=JSON.stringify(t.toolResults).length;r.toolResults={count:t.toolResults.length,totalSize:i,totalSizeMB:(i/(1024*1024)).toFixed(2)}}return r}async function*lye(t,e,r,n,i){if(!e.builderPrivateKey)throw new Error("Missing builder public key during completion stream");let s=new AbortController,o=JSON.stringify(r),a=new URL(`${Ne}/codegen/completion`);e.builderPublicKey&&a.searchParams.set("apiKey",e.builderPublicKey),e.userId&&a.searchParams.set("userId",e.userId);let A=performance.now(),c=A,u,l=!1,d=0,g=[];try{let p=await Fe(a,{method:"POST",body:o,keepalive:!0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.builderPrivateKey}`},signal:Qn([n,s.signal])},i);if(!p.ok){let m=await p.text(),C=`Bad Status: ${p.status}: ${m}`;if(p.status===413){let y=gwe(r,o),B=[];y.attachments?.totalSizeMB&&B.push(`Attachments: ${y.attachments.totalSizeMB}MB (${y.attachments.count} files)`),y.files?.totalContentSizeMB&&B.push(`File content: ${y.files.totalContentSizeMB}MB (${y.files.withContent} files)`),y.prompts?.gitDiffInPrompt?.sizeMB&&B.push(`Git diff: ${y.prompts.gitDiffInPrompt.sizeMB}MB`),y.prompts?.uiContextPrompt?.sizeMB&&B.push(`UI context: ${y.prompts.uiContextPrompt.sizeMB}MB`),y.toolResults?.totalSizeMB&&B.push(`Tool results: ${y.toolResults.totalSizeMB}MB`),B.length>0&&(C+=`
|
|
4837
4837
|
|
|
4838
4838
|
Payload size: ${y.totalSizeMB}MB. Top contributors:
|
|
4839
4839
|
${B.join(`
|
|
4840
|
-
`)}`)}let I=new Error(C);throw I.name=`BadStatus${p.status}`,I}let f=of(p.body);for await(let m of f)if(c=performance.now(),d+=m.length,m.length!==0){g.push(m),g=g.slice(-10);try{let C=JSON.parse(m);C.type==="ping"&&(u=performance.now()),l=!0,yield C}catch(C){t.Sentry?.captureException(C,{extra:{value:m,valueLength:m.length},tags:{operation:"codegen-stream"}})}}}catch(p){let f=performance.now();if(p instanceof Error&&p.name==="AbortError"||p instanceof Error&&p.name==="HTTPStreamBroke"||p instanceof Error&&p.name==="BadStatus403"||p instanceof oi){if(p instanceof Error&&p.name==="HTTPStreamBroke"){n.aborted||s.abort(p);let y=new Blob([o]).size,B=u!==void 0?f-u:void 0;t.Sentry?.setContext("brokenStreamInfo",{timeSinceLastPing:B,lastMessageElapsed:f-c,totalElapsed:f-A,responseSize:d,requestSize:y,didStream:l,lastEvents:g});let E=20*1024*1024,Q=y>E;t.Sentry?.getCurrentScope().addAttachment({filename:Q?"truncated-body.json":"body.json",data:Q?o.slice(0,2e5):o})}throw p}if(p instanceof qe)throw p;let m=p instanceof Error?p.name:"UnknownError",C=new dt(`codegen/completion endpoint: ${m}`,{cause:p}),I=gwe(r,o);throw t.Sentry?.captureException(C,{tags:{operation:"codegen-stream"},extra:{bodySize:o.length,responseSize:d,attachments:r.attachments?.length??0,files:r.files?.length??0,toolResults:r.toolResults?.length??0,didStream:l,lastMessageElapsed:f-c,totalElapsed:f-A,lastEvents:g,payloadBreakdown:I}}),C}}async function xB(t,e,r,n,i){let s,a=JSON.stringify(n);for(let A=0;A<3;A++){try{let c=new URL(`${Ne}${r}`);e.builderPublicKey&&c.searchParams.set("apiKey",e.builderPublicKey),e.userId&&c.searchParams.set("userId",e.userId);let u={"Content-Type":"application/json"};e.builderPrivateKey&&(u.Authorization=`Bearer ${e.builderPrivateKey}`);let l=AbortSignal.timeout(3e4),d=await Fe(c,{method:"POST",body:a,keepalive:!0,headers:u,signal:l},i);if(d.ok)return!0;throw new Error(`Bad Status: ${d.status}`)}catch(c){c instanceof qe&&Zr(c),s=c}A<2&&await Rg(A)}return s&&t.Sentry?.captureException(s),!1}async function KA(t,e,r,n){try{if(n?.signal?.aborted)return;let i=new URL(`${Ne}${e}`);t.builderPublicKey&&i.searchParams.set("apiKey",t.builderPublicKey),t.userId&&i.searchParams.set("userId",t.userId);let s={"Content-Type":"application/json"};t.builderPrivateKey&&(s.Authorization=`Bearer ${t.builderPrivateKey}`);let o=n?.timeoutMs??3e4,a=AbortSignal.timeout(o),A=n?.signal?Qn([n.signal,a]):a,c=await Fe(i,{method:"POST",body:JSON.stringify(r),keepalive:!0,headers:s,signal:A},n?.debug??!1);return c.ok?await c.json():void 0}catch{return}}async function ax(t,e,r,n){let i,o=JSON.stringify(r);for(let a=0;a<2;a++){try{let A=new URL(`${Ne}/codegen/sessions/set-last-completion`);e.builderPublicKey&&A.searchParams.set("apiKey",e.builderPublicKey),e.userId&&A.searchParams.set("userId",e.userId);let c={"Content-Type":"application/json"};e.builderPrivateKey&&(c.Authorization=`Bearer ${e.builderPrivateKey}`);let u=await Fe(A,{method:"POST",body:o,keepalive:!0,headers:c,signal:AbortSignal.timeout(3e4)},n);if(u.ok)return!0;throw new Error(`Bad Status: ${u.status}`)}catch(A){A instanceof qe&&Zr(A),i=A}a<1&&await Rg(a)}return i&&t.Sentry?.captureException(i),!1}async function Ax(t,e,r,n,i,s,o){try{let a=new URL(`${Ne}/codegen/sessions/${r}/turns`);e.builderPublicKey&&a.searchParams.set("apiKey",e.builderPublicKey),e.userId&&a.searchParams.set("userId",e.userId),a.searchParams.set("linear",String(n)),s&&a.searchParams.set("completionIdCursor",s);let A={"Content-Type":"application/json"};return e.builderPrivateKey&&(A.Authorization=`Bearer ${e.builderPrivateKey}`),await(await Fe(a,{method:"GET",headers:A,keepalive:!0,signal:Qn([o,AbortSignal.timeout(1e4)])},i)).json()}catch(a){return a instanceof qe&&Zr(a),t.Sentry?.captureException(a),{turns:[],sessionId:r,initialUrl:void 0,beforeCommit:void 0,title:void 0,createdUnixTime:void 0,updatedUnixTime:void 0,allIds:[],lastCompletionId:void 0,canLoadMore:!1}}}async function pye(t,e){let r=await t.getRepoInfo(e),n={client:"@builder.io/dev-tools",clientVersion:t.version,nodeVersion:process.version,frameworks:t.getFrameworks().map(i=>i.name),systemPlatform:process.platform,systemEOL:Lx.default.EOL,systemArch:Lx.default.arch(),inGitRepo:!!r.remoteUrl};try{let i=Lx.default.userInfo();n.systemShell=i.shell??void 0}catch{}return n}function qDe(){let t=!1,e=[],r,n;i();function i(){n=new Promise(A=>r=A)}async function*s(){await n;let A=e.shift();A&&(yield A),t||(yield*s())}function o(A){e.push(A),r(),i()}function a(){t=!0,r()}return[s(),o,a]}function dwe(t,e){return t.split(e).length-1}function
|
|
4840
|
+
`)}`)}let I=new Error(C);throw I.name=`BadStatus${p.status}`,I}let f=of(p.body);for await(let m of f)if(c=performance.now(),d+=m.length,m.length!==0){g.push(m),g=g.slice(-10);try{let C=JSON.parse(m);C.type==="ping"&&(u=performance.now()),l=!0,yield C}catch(C){t.Sentry?.captureException(C,{extra:{value:m,valueLength:m.length},tags:{operation:"codegen-stream"}})}}}catch(p){let f=performance.now();if(p instanceof Error&&p.name==="AbortError"||p instanceof Error&&p.name==="HTTPStreamBroke"||p instanceof Error&&p.name==="BadStatus403"||p instanceof oi){if(p instanceof Error&&p.name==="HTTPStreamBroke"){n.aborted||s.abort(p);let y=new Blob([o]).size,B=u!==void 0?f-u:void 0;t.Sentry?.setContext("brokenStreamInfo",{timeSinceLastPing:B,lastMessageElapsed:f-c,totalElapsed:f-A,responseSize:d,requestSize:y,didStream:l,lastEvents:g});let E=20*1024*1024,Q=y>E;t.Sentry?.getCurrentScope().addAttachment({filename:Q?"truncated-body.json":"body.json",data:Q?o.slice(0,2e5):o})}throw p}if(p instanceof qe)throw p;let m=p instanceof Error?p.name:"UnknownError",C=new dt(`codegen/completion endpoint: ${m}`,{cause:p}),I=gwe(r,o);throw t.Sentry?.captureException(C,{tags:{operation:"codegen-stream"},extra:{bodySize:o.length,responseSize:d,attachments:r.attachments?.length??0,files:r.files?.length??0,toolResults:r.toolResults?.length??0,didStream:l,lastMessageElapsed:f-c,totalElapsed:f-A,lastEvents:g,payloadBreakdown:I}}),C}}async function xB(t,e,r,n,i){let s,a=JSON.stringify(n);for(let A=0;A<3;A++){try{let c=new URL(`${Ne}${r}`);e.builderPublicKey&&c.searchParams.set("apiKey",e.builderPublicKey),e.userId&&c.searchParams.set("userId",e.userId);let u={"Content-Type":"application/json"};e.builderPrivateKey&&(u.Authorization=`Bearer ${e.builderPrivateKey}`);let l=AbortSignal.timeout(3e4),d=await Fe(c,{method:"POST",body:a,keepalive:!0,headers:u,signal:l},i);if(d.ok)return!0;throw new Error(`Bad Status: ${d.status}`)}catch(c){c instanceof qe&&Zr(c),s=c}A<2&&await Rg(A)}return s&&t.Sentry?.captureException(s),!1}async function KA(t,e,r,n){try{if(n?.signal?.aborted)return;let i=new URL(`${Ne}${e}`);t.builderPublicKey&&i.searchParams.set("apiKey",t.builderPublicKey),t.userId&&i.searchParams.set("userId",t.userId);let s={"Content-Type":"application/json"};t.builderPrivateKey&&(s.Authorization=`Bearer ${t.builderPrivateKey}`);let o=n?.timeoutMs??3e4,a=AbortSignal.timeout(o),A=n?.signal?Qn([n.signal,a]):a,c=await Fe(i,{method:"POST",body:JSON.stringify(r),keepalive:!0,headers:s,signal:A},n?.debug??!1);return c.ok?await c.json():void 0}catch{return}}async function ax(t,e,r,n){let i,o=JSON.stringify(r);for(let a=0;a<2;a++){try{let A=new URL(`${Ne}/codegen/sessions/set-last-completion`);e.builderPublicKey&&A.searchParams.set("apiKey",e.builderPublicKey),e.userId&&A.searchParams.set("userId",e.userId);let c={"Content-Type":"application/json"};e.builderPrivateKey&&(c.Authorization=`Bearer ${e.builderPrivateKey}`);let u=await Fe(A,{method:"POST",body:o,keepalive:!0,headers:c,signal:AbortSignal.timeout(3e4)},n);if(u.ok)return!0;throw new Error(`Bad Status: ${u.status}`)}catch(A){A instanceof qe&&Zr(A),i=A}a<1&&await Rg(a)}return i&&t.Sentry?.captureException(i),!1}async function Ax(t,e,r,n,i,s,o){try{let a=new URL(`${Ne}/codegen/sessions/${r}/turns`);e.builderPublicKey&&a.searchParams.set("apiKey",e.builderPublicKey),e.userId&&a.searchParams.set("userId",e.userId),a.searchParams.set("linear",String(n)),s&&a.searchParams.set("completionIdCursor",s);let A={"Content-Type":"application/json"};return e.builderPrivateKey&&(A.Authorization=`Bearer ${e.builderPrivateKey}`),await(await Fe(a,{method:"GET",headers:A,keepalive:!0,signal:Qn([o,AbortSignal.timeout(1e4)])},i)).json()}catch(a){return a instanceof qe&&Zr(a),t.Sentry?.captureException(a),{turns:[],sessionId:r,initialUrl:void 0,beforeCommit:void 0,title:void 0,createdUnixTime:void 0,updatedUnixTime:void 0,allIds:[],lastCompletionId:void 0,canLoadMore:!1}}}async function pye(t,e){let r=await t.getRepoInfo(e),n={client:"@builder.io/dev-tools",clientVersion:t.version,nodeVersion:process.version,frameworks:t.getFrameworks().map(i=>i.name),systemPlatform:process.platform,systemEOL:Lx.default.EOL,systemArch:Lx.default.arch(),inGitRepo:!!r.remoteUrl};try{let i=Lx.default.userInfo();n.systemShell=i.shell??void 0}catch{}return n}function qDe(){let t=!1,e=[],r,n;i();function i(){n=new Promise(A=>r=A)}async function*s(){await n;let A=e.shift();A&&(yield A),t||(yield*s())}function o(A){e.push(A),r(),i()}function a(){t=!0,r()}return[s(),o,a]}function dwe(t,e){return t.split(e).length-1}function M4(t){return t=t.toLowerCase(),t.endsWith("claude.md")||t.endsWith("agent.md")||t.endsWith("agents.md")}function dye(t,e){if(!t.startsWith(e))return!1;t=t.slice(e.length);let n=dwe(t,"/");return n<2&&t.endsWith("package.json")||t.endsWith("Podfile")||t.endsWith("Cartfile")||n<2&&t.endsWith("global.css")||n<2&&t.endsWith("tailwind.config.ts")||n<2&&t.endsWith("tailwind.config.js")||t.endsWith("libraries.toml")}function fye(t,e){return M4(t)?(t.startsWith(e)&&(t=t.slice(e.length)),dwe(t,"/")===0):!1}function hye(t){return t?[/ERROR[ ]in\b/i,/Module not found: Can't resolve\b/i,/(\b|^)failed to compile\b/i,/(\b|^)Internal server error\b/i,/(\b|^)Error when evaluating SSR module virtual\b/i,/(\b|^)ReferenceError: \w* is not defined\b/i,/(\b|^)Found \d+ errors?\./i,/(\b|^)error TS\d+\b/i,/(\b|^)SyntaxError: Unexpected token\b/i,/(\b|^)Error processing file\b.*SyntaxError\b/i,/(\b|^)Module build failed\b/i,/(\b|^)Build failed\b/i,/(\b|^)\[Error:.*\]/i,/(\b|^)uncaughtException: /i].some(r=>r.test(t)):!1}async function $De(t,e){try{let r=t.resolve(t.cwd(),e);if(!await t.exists(r))throw new Error(`Workspace file not found: ${e}`);let n=await t.readFile(r);if(!n)throw new Error(`Failed to read workspace file: ${e}`);let i=JSON.parse(n);if(!i.folders||!Array.isArray(i.folders))throw new Error('Invalid workspace configuration: missing "folders" array');let s=t.dirname(r);return{workspace:i,workingDirectory:s}}catch(r){throw uIt.error(`Error loading workspace: ${r instanceof Error?r.message:String(r)}`),r}}function b4(t){let e=t[0];for(let r=1;r<t.length;r++)e=P4(e,t[r]);return e}function P4(t,e){let r=`${t.displayPrompt??t.userPrompt}
|
|
4841
4841
|
|
|
4842
4842
|
${e.displayPrompt??e.userPrompt}`;return{...e,displayPrompt:r,softContextWindow:e.softContextWindow??t.softContextWindow,idempotencyKey:t.idempotencyKey??e.idempotencyKey,syncChanges:e.syncChanges??t.syncChanges,autoPush:e.autoPush??t.autoPush,runValidateCommand:!!(e.runValidateCommand||t.runValidateCommand),maxCompletions:t.maxCompletions||e.maxCompletions?Math.max(t.maxCompletions??ux,e.maxCompletions??ux):void 0,userPrompt:t.userPrompt+`
|
|
4843
4843
|
|
|
4844
|
-
`+e.userPrompt,files:Array.from(new Set([...t.files??[],...e.files??[]])),includeBaseFiles:t.includeBaseFiles}}function mye(){let t=setInterval(()=>{},1073741824);return()=>clearInterval(t)}function
|
|
4844
|
+
`+e.userPrompt,files:Array.from(new Set([...t.files??[],...e.files??[]])),includeBaseFiles:t.includeBaseFiles}}function mye(){let t=setInterval(()=>{},1073741824);return()=>clearInterval(t)}function v4(t){let e=t.trim().split(/\s+/).filter(Boolean),r=Number.parseInt(e[0]??"",10),n=Number.parseInt(e[1]??"",10);return{ahead:Number.isFinite(r)?r:0,behind:Number.isFinite(n)?n:0}}function Cye(t,e){let r=[];function n(i){let s=r.findIndex(o=>o.key===i.key);s>=0?r[s]=i:r.push(i)}for(let i of t)n(i);for(let i of e)n(i);return r}function Iye(t){return typeof t=="boolean"?{pullFirst:t}:t}function Rp(t){if(t instanceof Error){let e=`${t.message}`;return t.cause instanceof Error&&(e+=`
|
|
4845
4845
|
=======
|
|
4846
|
-
`,e+=Rp(t.cause)),e}return String(t)}function Sl(){return new Promise(t=>setImmediate(t))}function Wc(t,e){return!t||!e?t:new Promise((r,n)=>{let i=()=>{n(rn(e?.reason))};if(e.addEventListener("abort",i),e.aborted){e.removeEventListener("abort",i),n(rn(e.reason));return}t.then(s=>{e.removeEventListener("abort",i),r(s)},s=>{e.removeEventListener("abort",i),n(s)})})}function Eye(t,e){return Promise.race([t.then(()=>!1,()=>!1),new Promise(r=>setTimeout(()=>r(!0),e))])}function rn(t){if(t instanceof Error){let e=new Error(t.message,{cause:t});return e.name="AbortError",t}else{let e=new Error(t?String(t):"AbortError");return e.name="AbortError",e}}function
|
|
4847
|
-
`)}var Lx,pwe,uIt,ux,sye,gye,Go,Tp,Ic=L(()=>{"use strict";h();kr();yr();hr();Lx=z(require("node:os"),1),pwe=require("node:path/posix");yZ();uw();Bt();xi();lw();
|
|
4846
|
+
`,e+=Rp(t.cause)),e}return String(t)}function Sl(){return new Promise(t=>setImmediate(t))}function Wc(t,e){return!t||!e?t:new Promise((r,n)=>{let i=()=>{n(rn(e?.reason))};if(e.addEventListener("abort",i),e.aborted){e.removeEventListener("abort",i),n(rn(e.reason));return}t.then(s=>{e.removeEventListener("abort",i),r(s)},s=>{e.removeEventListener("abort",i),n(s)})})}function Eye(t,e){return Promise.race([t.then(()=>!1,()=>!1),new Promise(r=>setTimeout(()=>r(!0),e))])}function rn(t){if(t instanceof Error){let e=new Error(t.message,{cause:t});return e.name="AbortError",t}else{let e=new Error(t?String(t):"AbortError");return e.name="AbortError",e}}function S4(t,e){return{type:"dev-server",devServerState:t.devState,setupState:t.setupState,httpServerState:t.httpServerState.state,devCommand:t.devCommand,setupCommand:t.setupCommand,proxyServer:t.proxyTarget,proxyServerSelection:t.proxyServerSelection,remoteAddress:t.httpServerState.remoteAddress,remotePort:t.httpServerState.remotePort,proxyServerReachable:!!e?.isLocal,validateState:t.validateCommandState}}function Bye(t,e,r){return e<0||e>=t.length||(r>=t.length&&(r=t.length-1),r<0&&(r=0),t.splice(r,0,t.splice(e,1)[0])),t}function lIt(t){return t?.folders?.length===1||!t?.folders?.length}function yye(t){let e=t?.folders.find(i=>i.enableGit);if(!e?.name)return"";let r=lIt(t)?"":`${e.name}/`,n=e.recommendedRoot;return n?uP((0,pwe.join)(r,uP(n))):r}function lx(t){return`GH_TOKEN_${t.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`}function gIt(t){if(!t)return"unknown";let e=t.toLowerCase();return e.includes("github.com")||e.includes("github:")?"github":e.includes("gitlab.com")||e.includes("gitlab")?"gitlab":e.includes("dev.azure.com")||e.includes("visualstudio.com")?"azure":e.includes("bitbucket.org")||e.includes("bitbucket")?"bitbucket":e.includes("github")?"selfHostedGithub":"unknown"}function pIt(t){return t==="gitlab"?{full:"Merge Request",short:"MR"}:{full:"Pull Request",short:"PR"}}function Qye(t,e,r){let n=[],{trigger:i,syncedBranches:s,pushedToRemote:o}=r,a=e.find(p=>p.name===t.folderName||p.path===t.folderName),A=a?.repoUrl,c=a?.repoName,u=gIt(A),l=pIt(u),d=t.folderName?` [${t.folderName}]`:"",g=c?` (${c})`:"";switch(i){case"session-start":n.push(`Git Status${d}${g} at Session Start:`);break;case"sync-success":n.push(`Git Sync${d}${g} Completed Successfully:`),s?.length&&n.push(` - Synced with: ${s.join(", ")}`);break;case"push-success":n.push(`Git Push${d}${g} Completed Successfully:`),o&&n.push(` - Changes pushed to remote branch: ${t.remoteBranch}`);break;case"pull-success":n.push(`Git Pull${d}${g} Completed Successfully:`);break}if(c&&n.push(` - Repository: ${c}`),u!=="unknown")if((u==="github"||u==="selfHostedGithub")&&process.env.GH_TOKEN){n.push(" - Provider: GitHub ( gh cli is available using the Bash tool )");let p=Object.keys(process.env).filter(f=>f.startsWith("GH_TOKEN_")).sort();p.length>0&&(n.push(` - GitHub token env vars: GH_TOKEN (primary repo default), ${p.join(", ")}`),n.push(" - Use the repo-specific GH_TOKEN_<REPO> when targeting a specific linked repo; fall back to GH_TOKEN for the primary repo"))}else n.push(` - Provider: ${u}`);if(n.push(` - Current branch: ${t.currentBranch}`),n.push(` - Remote branch exists: ${t.remoteBranchExists?"yes":"no"}`),t.currentCommit&&n.push(` - Current commit: ${t.currentCommit.slice(0,7)}`),t.ahead>0||t.behind>0?t.ahead>0&&t.behind>0?n.push(` - Branch is ${t.ahead} commit(s) ahead and ${t.behind} commit(s) behind remote`):t.ahead>0?n.push(` - Branch is ${t.ahead} commit(s) ahead of remote`):n.push(` - Branch is ${t.behind} commit(s) behind remote`):t.remoteBranchExists&&n.push(" - Branch is up to date with remote"),t.canSync&&n.push(" - Sync available (can pull and/or push changes)"),t.canPush&&!t.canSync&&n.push(" - Push available"),t.canPull&&!t.canSync&&n.push(" - Pull available (remote has new changes)"),t.hasMergeConflict&&n.push(" - \u26A0\uFE0F MERGE CONFLICT DETECTED - must be resolved before continuing"),t.commitMode==="prs"||t.commitMode==="draft-prs"){let p=t.commitMode==="draft-prs";n.push(` - Commit mode: ${t.commitMode} (creates ${p?"draft ":""}${l.full}s)`)}else n.push(` - Commit mode: ${t.commitMode}`);return n.join(`
|
|
4847
|
+
`)}var Lx,pwe,uIt,ux,sye,gye,Go,Tp,Ic=L(()=>{"use strict";h();kr();yr();hr();Lx=z(require("node:os"),1),pwe=require("node:path/posix");yZ();uw();Bt();xi();lw();T4();JI();Tu();Tu();uIt=ve("CodegenUtils"),ux=100,sye=200;gye=t=>{if(!t)return{id:void 0,isInitial:!0};let e=new URL(t);return e.protocol==="cgen:"?{isInitial:!1,id:e.pathname.slice(1)}:{isInitial:!0,id:void 0}};Go=class extends Error{code;stdout;stderr;command;constructor(e,r,n,i,s){super(`${e} failed with code ${r}
|
|
4848
4848
|
|
|
4849
4849
|
${n}
|
|
4850
|
-
${i}`,s),this.name="BashError",this.command=e,this.code=r,this.stdout=n,this.stderr=i}},Tp=class extends Error{branchName;constructor(e,r){super(`Base branch "${e}" not found`,r),this.name="ParentBranchNotFoundError",this.branchName=e}}});function dIt(t){return t.replace(/(https?:\/\/)([^@\s]+@)?([^\/\s]+)/g,(e,r,n,i)=>n?`${r}***@${i}`:e)}async function Ws(t,e,r){let n=Math.max(r.retry??0,0)+1,i;for(let s=0;s<n;s++)try{return await fIt(t,e,r)}catch(o){i=o,s<n-1&&await Rg(s)}throw i}function Uo(){let t=fwe;return fwe++,t.toString()}function fIt(t,e,r){let n=`${t} ${e.join(" ")}`,i=performance.now(),s=Uo();r.skipLogging||
|
|
4850
|
+
${i}`,s),this.name="BashError",this.command=e,this.code=r,this.stdout=n,this.stderr=i}},Tp=class extends Error{branchName;constructor(e,r){super(`Base branch "${e}" not found`,r),this.name="ParentBranchNotFoundError",this.branchName=e}}});function dIt(t){return t.replace(/(https?:\/\/)([^@\s]+@)?([^\/\s]+)/g,(e,r,n,i)=>n?`${r}***@${i}`:e)}async function Ws(t,e,r){let n=Math.max(r.retry??0,0)+1,i;for(let s=0;s<n;s++)try{return await fIt(t,e,r)}catch(o){i=o,s<n-1&&await Rg(s)}throw i}function Uo(){let t=fwe;return fwe++,t.toString()}function fIt(t,e,r){let n=`${t} ${e.join(" ")}`,i=performance.now(),s=Uo();r.skipLogging||xH.debug(`(id=${s}): starting (cwd: ${r.cwd||"NOT SET"}): ${dIt(n)}`);let o=new Promise((a,A)=>{let c="",u="",l=(0,hwe.spawn)(t,e,{cwd:r.cwd,stdio:[r.stdin?"pipe":"ignore","pipe","pipe"],shell:!1});r.stdin&&(l.stdin.write(r.stdin),l.stdin.end());let d=r.timeout?setTimeout(()=>{Os(r.sys,l).then(()=>{A(new Go(n,void 0,c,u,{cause:new Error(`${t} command timed out`)}))})},r.timeout):void 0;l.on("error",g=>{clearTimeout(d),A(new Go(n,void 0,c,u,{cause:g}))}),l.stdout?.on("data",g=>{let p=g.toString();c+=p}),l.stderr?.on("data",g=>{let p=g.toString();u+=p}),l.on("close",g=>{if(clearTimeout(d),g===0)a(u&&!c?u:c);else{if(g===128&&hIt(c,u)&&r.sys.Sentry?.captureException(new Error("Git repo is corrupted"),{tags:{operation:"codegen-git"},extra:{stdout:c,stderr:u,command:n,exitCode:g}}),g===128&&mIt(c,u)){r.sys.Sentry?.captureException(new Error("Git repo not found or inaccessible"),{tags:{operation:"codegen-git"},extra:{stdout:c,stderr:u,command:n,exitCode:g}}),A(new Error("Your connected Git repository is no longer accessible. Please verify the repo exists and you have permission to access it.",{cause:new Go(n,g,c,u)}));return}A(new Go(n,g??void 0,c,u))}})});return r.skipLogging?o:o.then(a=>{let A=Math.round(performance.now()-i);return xH.debug(`(id=${s}): success (code: 0) [${A}ms] ${a.replaceAll(`
|
|
4851
4851
|
`," ").trim()}`),a}).catch(a=>{let A=a instanceof Go?a:a?.cause instanceof Go?a.cause:null;if(A){let c=Math.round(performance.now()-i),u=`${A.stdout.trim()} ${A.stderr.trim()}`.replaceAll(`
|
|
4852
|
-
`," ").trim();
|
|
4852
|
+
`," ").trim();xH.debug(`[GIT](id=${s}): error (code: ${A.code}) [${c}ms] ${u}`)}throw a})}async function Gc(t,e){try{return(await Ws("git",["status","--porcelain=v1","-z","--ignore-submodules=dirty"],{cwd:t,sys:e})).trim().length===0}catch{return!1}}function _l(t){return t&&typeof t=="object"&&"stderr"in t&&t.stderr?String(t.stderr):t instanceof Error?t.message:String(t)}async function hh(t,e,r){try{let n=new URL(`${Ne}/projects/git-configs`);n.searchParams.set("projectId",e),t.builderPublicKey&&n.searchParams.set("apiKey",t.builderPublicKey),t.userId&&n.searchParams.set("userId",t.userId);let i=await Fe(n,{keepalive:!0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`},signal:AbortSignal.timeout(1e4)},r);if(i.status===404)return{success:!1,error:new Error("Failed to fetch git configs",{cause:new Error("Project not found")})};if(!i.ok){let o,a=`Failed to fetch git configs. HTTP ${i.status}: ${i.statusText}`;try{let A=await i.json();A.message&&(a=A.message),A.gitDiagnostics&&(o=A.gitDiagnostics)}catch{}return{success:!1,error:new Error(a),gitDiagnostics:o}}return{success:!0,gitConfigs:(await i.json()).gitConfigs}}catch(n){return{success:!1,error:new Error("Failed to fetch git configs",{cause:n instanceof Error?n:new Error(String(n))})}}}var hwe,xH,fwe,hIt,mIt,xo=L(()=>{"use strict";h();Ic();da();hwe=require("node:child_process");yr();hr();uw();Bt();xH=ve("Git");fwe=0;hIt=(t,e)=>{let r=[/fatal:\s*bad\s+object/i,/fatal:\s*loose\s+object.*is\s+corrupt/i,/fatal:\s*index\s+file.*is\s+corrupt/i,/fatal:\s*corrupt\s+loose\s+object/i,/fatal:\s*object\s+file.*is\s+corrupt/i,/fatal:\s*packfile.*is\s+truncated/i,/corrupted\s+pack/i,/invalid\s+pack\s+checksum/i,/error:\s*inflate:\s+data\s+stream\s+error/i,/error:\s*missing\s+blob/i,/error:\s*missing\s+commit/i,/error:\s*broken\s+link/i,/unable\s+to\s+read\s+.*object/i,/repository\s+corruption/i,/index.*is\s+corrupt/i],n=`${t}
|
|
4853
4853
|
${e}`.toLowerCase();return r.some(i=>i.test(n))},mIt=(t,e)=>{let r=[/remote:\s*repository\s+not\s+found/i,/fatal:\s*repository\s+'[^']*'\s+not\s+found/i,/error:\s*repository\s+not\s+found/i,/the\s+requested\s+repository\s+does\s+not\s+exist/i,/access\s+denied\s+or\s+repository\s+not\s+found/i],n=`${t}
|
|
4854
|
-
${e}`;return r.some(i=>i.test(n))}});function Ewe(){if(Ul!==void 0)return Ul;if(jA.default.platform!=="darwin")return Ul=null,null;try{let t=(0,_x.execSync)("scutil --nwi | grep 'Network interfaces:' | awk '{print $3}'",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();if(!t)return Ul=null,null;let e=(0,_x.execSync)("networksetup -listnetworkserviceorder",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=s=>{try{let o=(0,_x.execSync)(`networksetup -getautoproxyurl "${s}"`,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),a=o.match(/Enabled: (Yes|No)/i),A=a&&a[1].toLowerCase()==="yes",c=o.match(/URL: (.*)/),u=c?c[1].trim():null;if(A){if(!u||u==="(null)")return null}else return null;let l=A&&u&&u!=="(null)"?u:null;return l&&
|
|
4855
|
-
\u274C Not a Figma URL - hostname check failed`),null;let n=r.searchParams.get("node-id")?.replaceAll("-",":"),i=r.pathname.split("/")[2];return n&&i?{fileID:i,nodeId:n}:null}catch{return null}},yIt="https://api.figma.com/v1/",ru=async(t,e,r,{auth:n,params:i})=>{let s=new URL(`${yIt}${r}`),o={};if(n.oauth?o.Authorization=`Bearer ${n.access_token}`:o["X-FIGMA-TOKEN"]=n.access_token,i)for(let A in i)i[A]!=null&&s.searchParams.set(A,i[A].toString());let a=await Fe(s,{headers:o});if(!a.ok){if(a.status===401){$.error("Seems like figma auth is expired or it's invalid, let's try to");let A=await Wt(t,e,{force:!0,requireFigmaAuth:"always"});return ru(t,e,r,{auth:A.figmaAuth,params:i})}throw new Error(`Figma REST ${a.statusText}: ${await a.text()}`)}return a.json()},QIt=async(t,e,r,n,i,s)=>(await ru(t,e,`files/${n}/nodes`,{auth:r,params:{ids:i,depth:s}})).nodes;DIt=async(t,e,r,n)=>{if(!r)return{};let i=new Map,s={};return n.forEach(o=>{let a=
|
|
4854
|
+
${e}`;return r.some(i=>i.test(n))}});function Ewe(){if(Ul!==void 0)return Ul;if(jA.default.platform!=="darwin")return Ul=null,null;try{let t=(0,_x.execSync)("scutil --nwi | grep 'Network interfaces:' | awk '{print $3}'",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();if(!t)return Ul=null,null;let e=(0,_x.execSync)("networksetup -listnetworkserviceorder",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),r=s=>{try{let o=(0,_x.execSync)(`networksetup -getautoproxyurl "${s}"`,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),a=o.match(/Enabled: (Yes|No)/i),A=a&&a[1].toLowerCase()==="yes",c=o.match(/URL: (.*)/),u=c?c[1].trim():null;if(A){if(!u||u==="(null)")return null}else return null;let l=A&&u&&u!=="(null)"?u:null;return l&&RH.info(`Detected PAC URL from service "${s}": ${l}`),l}catch{return null}},n=new RegExp(`\\(Hardware Port: (.*), Device: ${t}\\)`,"i"),i=e.match(n);if(i&&i[1]){let s=i[1],o=r(s);if(o)return Ul=o,o}else if(t.match(/^(utun|ipsec|ppp|gif|stf|lo)\d*/)){let s=["Wi-Fi","Ethernet","Thunderbolt Ethernet"];for(let o of s)if(e.includes(o)){let a=r(o);if(a)return Ul=a,a}}}catch(t){let e=t instanceof Error?t.message:String(t);RH.warn(`Error detecting PAC URL: ${e}`),Ul=null}return Ul=null,null}async function CIt(t){if(um===void 0){let e=Ewe();if(!e){um=null;return}try{let r=jA.default.env.FUSION_REJECT_UNAUTHORIZED!=="0",n=new YA.Agent({connect:{rejectUnauthorized:r}}),s=await(await(0,YA.fetch)(e,{dispatcher:n})).text(),o=await(0,Cwe.getQuickJS)();um=await(0,mwe.createPacResolver)(o,s)}catch{um=null;return}}if(um!==null)try{let e=await um(t);if(!e||e==="DIRECT")return;let r=e.match(/PROXY\s+([^\s;]+)/i);if(r){let n=r[1];return n.startsWith("http")?n:`http://${n}`}}catch(e){RH.info(`PAC resolution failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}async function IIt(t){let e=jA.default.env.FUSION_REJECT_UNAUTHORIZED!=="0",r=jA.default.env.HTTPS_PROXY||jA.default.env.https_proxy||jA.default.env.HTTP_PROXY||jA.default.env.http_proxy;if(r)return cm||(cm=new YA.ProxyAgent({uri:r,connect:{rejectUnauthorized:e},requestTls:{rejectUnauthorized:e}})),cm;if(t){let n=await CIt(t);if(n)return new YA.ProxyAgent({uri:n,connect:{rejectUnauthorized:e},requestTls:{rejectUnauthorized:e}})}return cm||Ewe()||(cm=new YA.Agent({connect:{rejectUnauthorized:e}})),cm||new YA.Agent({connect:{rejectUnauthorized:e}})}function EIt(){let e={darwin:"Macintosh",win32:"Windows NT",linux:"Linux",android:"Android",ios:"iPhone"}[jA.default.platform]||"Unknown",r=jA.default.platform==="win32"?"10.0":"";return{"User-Agent":`Mozilla/5.0 (${e}${r?"; "+r:""}) builder-cli/${mZ}`,"Sec-Ch-Ua-Platform":e}}async function EDe(t=1e3){let r=new URL("/codegen/health",Ne);for(let n=1;n<=3;n++)try{let i=await Fe(r);return i.ok?void 0:new qe({type:"server_error",statusCode:i.status,hostname:r.hostname,cause:new Error(`Builder.io API is not healthy (HTTP ${i.status})`),message:`Builder.io API is not healthy (HTTP ${i.status})`,suggestions:["Try again in a few minutes - this may be a temporary issue","Contact support if the problem persists"]})}catch(i){if(n===3)return i instanceof qe?i:new qe({type:"connection_refused",cause:i instanceof Error?i:new Error(String(i)),message:"Failed to connect to Builder.io API after 3 attempts",suggestions:["Check your internet connection",`Verify that ${r.hostname} is accessible from your network`,"Try again in a few minutes"],hostname:r.hostname});await new Promise(s=>setTimeout(s,t))}}var YA,mwe,Cwe,_x,jA,Iwe,RH,FH,cm,Ul,um,kH,Fe,hr=L(()=>{"use strict";h();YA=require("undici"),mwe=z(qX(),1),Cwe=z(eP(),1),_x=require("node:child_process");hZ();jA=z(require("node:process"),1),Iwe=z(require("@sentry/node"),1);xi();Bt();Tu();yr();xo();RH=ve("Proxy"),FH=ve("Fetch");Fe=async(t,e,r)=>{let n=new URL(t),i=n.hostname,s=n.port?parseInt(n.port):void 0,o=Uo(),a=performance.now(),A="";try{let c=Iwe.getTraceData(),u=await IIt(n.toString());r&&FH.info(`(${o}): ${n.href}`);let l=n.hostname==="api.builder.io",d=await(0,YA.fetch)(n,{...e,dispatcher:u,headers:{...e?.headers,...EIt(),...c,...kH&&l?{Cookie:kH.join("; ")}:{}}});if(l&&(kH=d.headers.getSetCookie()),A=`status: ${d.status}`,!d.ok){if(d.status===402){let g=await d.json(),p=g.code??"credits-limit-daily",f=g.message??"You've reached the DAY AI credits limit for your current plan.";throw new oi(f,p)}else if(d.status===429){let g=await d.json(),p=g.code??"credits-limit-other",f=g.message??"Rate limit exceeded. Please try again later.";throw new oi(f,p)}if(d.status>=500){let g;try{let p=await d.text();if(p)try{let f=JSON.parse(p);g=f.message||f.error||p}catch{g=p}}catch{}throw new qe({type:"server_error",cause:g?new Error(g):void 0,message:`Server error from ${i} (HTTP ${d.status}). The server encountered an internal error.`,suggestions:["Try again in a few minutes - this may be a temporary issue","Contact support if the problem persists"],hostname:i,statusCode:d.status})}}return d}catch(c){if(A=A||"fetch error",c instanceof qe||c instanceof oi||c instanceof Error&&c.name==="AbortError")throw c;if(c instanceof Error){if(c.name==="TypeError"&&c.cause instanceof Error){let g=c.cause;if(g.code)throw xN(g,i,s)}if(c.code)throw xN(c,i,s);if(c.message?.includes("SSL")||c.message?.includes("TLS")||c.message?.includes("certificate")||c.message?.includes("CERT"))throw new qe({type:"ssl_certificate_invalid",cause:c,message:`SSL/TLS error connecting to ${i}. The connection could not be secured.`,suggestions:["If behind a corporate proxy with custom CA certificates:"," \u2192 Try: export NODE_USE_SYSTEM_CA=1 (recommended if CA is in system trust store)"," \u2192 Or: export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem"," \u2192 Or use the --acceptSelfSigned CLI flag","For Node.js 22+, you can also use --use-system-ca flag","Contact your IT department to get the corporate root CA certificate","Try again in a few minutes","Contact support@builder.io if the issue persists"],hostname:i})}let u=e?.method||"GET",l=c instanceof Error?c.message:String(c);throw new qe({type:"unknown",cause:c instanceof Error?c:new Error(String(c)),message:`Network error for ${u} ${n.toString()}: ${l}`,suggestions:["Check your internet connection","Try again in a few minutes","Contact support if the issue persists"],hostname:i,port:s})}finally{let c=Math.round(performance.now()-a);A==="fetch error"||/^status: [45]/.test(A)?FH.warn(`(${o}): ${e?.method??"GET"} ${n.pathname} ${A} [${c}ms]`):r&&FH.info(`(${o}): ${A} [${c}ms]`)}}});async function Bwe(t,e,r,n,i){if(i.length>0){let s=await DIt(t,e,r,i);for(let o of n)if(o.figmaUrl&&!o.figmaKey){let a=s[o.figmaUrl];a&&(o.figmaKey=a)}}}var BIt,TH,yIt,ru,QIt,DIt,NH=L(()=>{"use strict";h();rr();hr();Ns();BIt=z(require("@sentry/node"),1);yr();kr();kf();TH=t=>{try{let e=t.replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\=/g,"=").replace(/\\\?/g,"?").replace(/\\\&/g,"&"),r=new URL(e);if(!r.hostname.includes("figma.com"))return console.log(`
|
|
4855
|
+
\u274C Not a Figma URL - hostname check failed`),null;let n=r.searchParams.get("node-id")?.replaceAll("-",":"),i=r.pathname.split("/")[2];return n&&i?{fileID:i,nodeId:n}:null}catch{return null}},yIt="https://api.figma.com/v1/",ru=async(t,e,r,{auth:n,params:i})=>{let s=new URL(`${yIt}${r}`),o={};if(n.oauth?o.Authorization=`Bearer ${n.access_token}`:o["X-FIGMA-TOKEN"]=n.access_token,i)for(let A in i)i[A]!=null&&s.searchParams.set(A,i[A].toString());let a=await Fe(s,{headers:o});if(!a.ok){if(a.status===401){$.error("Seems like figma auth is expired or it's invalid, let's try to");let A=await Wt(t,e,{force:!0,requireFigmaAuth:"always"});return ru(t,e,r,{auth:A.figmaAuth,params:i})}throw new Error(`Figma REST ${a.statusText}: ${await a.text()}`)}return a.json()},QIt=async(t,e,r,n,i,s)=>(await ru(t,e,`files/${n}/nodes`,{auth:r,params:{ids:i,depth:s}})).nodes;DIt=async(t,e,r,n)=>{if(!r)return{};let i=new Map,s={};return n.forEach(o=>{let a=TH(o);if(!a){t.Sentry?.captureException(new Error("Invalid Figma URL, use Cmd+L while selecting a figma component to get a link to selection"),{extra:{figmaUrl:o},level:"warning"});return}let A=i.get(a.fileID);A||(A=[],i.set(a.fileID,A)),A.includes(a.nodeId)||A.push(a.nodeId),s[o]=`${a.fileID}/${a.nodeId}`}),await Promise.all(Array.from(i.entries()).map(async([o,a])=>{let A=await QIt(t,e,r,o,a.join(","),0);for(let c of a){let u=A[c],l=u.components[c]?.key??u.componentSets[c]?.key;l||t.Sentry?.withScope(g=>{g.addAttachment({data:JSON.stringify(A,null,2),filename:`${o}.json`}),t.Sentry?.captureException(new Error("Cannot resolve figma component key for NodeID"),{extra:{nodeId:c,fileID:o},level:"warning"})});let d=`${o}/${c}`;for(let g of n)s[g]===d&&(s[g]=l)}})),s}});function MH(t){return!(t.category!==Ho.DiagnosticCategory.Error||!t.file||t.code===6133||t.code===6138||t.code===6305||t.code===6196||t.code===6192||t.code===6198||t.code===6199||t.code===6205||t.code===1449||t.code===2578||t.code===7006||t.code===5074||t.code===7026||t.code===2503||t.code===2695||t.code===2322)}var Ho,ywe=L(()=>{"use strict";h();Ho=z(require("typescript"),1)});async function wIt(t,e,r){let n=[],i=[e],s=t.relative(t.getAppRootDir(),e.fileName);for(;i.length>0;){let o=i.shift();if(FIt(o,e)){let a=vIt(t,o,e,r),{line:A,character:c}=e.getLineAndCharacterOfPosition(o.getStart());a&&(a.loc=`${s}:${A+1}:${c+1}`,n.push(a))}i.push(...o.getChildren(e))}return n}function vIt(t,e,r,n){let[i]=e.arguments;if(!i)throw new Error("Invalid figmaMapping call, no arguments found");if(!yt.default.isObjectLiteralExpression(i))throw new Error("Invalid figmaMapping call, argument is not an object literal");let s=i.properties;if(!s)throw new Error("Invalid figmaMapping call, argument has no properties");let o="",a,A,c,u="-",l=t.basename(r.fileName).replace(/\.mapper\.[tsxjm]+$/,""),d,g,p,f,m;if(e.typeArguments&&e.typeArguments.length>0){let v=Qwe(e.typeArguments[0].getText(r));v&&(l=v)}for(let v of s){let D=v.name?.getText(r);if(!D)throw new Error("Invalid figmaMapping call, property has no name");switch(D){case"componentName":{if(!("initializer"in v))throw new Error("Invalid figmaMapping call, componentName has no initializer");let S=v.initializer;if(!yt.default.isStringLiteral(S))throw new Error("Invalid figmaMapping call, componentName is not a string literal");a=S.text;break}case"url":{if(!("initializer"in v))throw new Error("Invalid figmaMapping call, url has no initializer");let S=v.initializer;if(!yt.default.isStringLiteral(S))throw new Error("Invalid figmaMapping call, url is not a string literal");f=S.text;break}case"componentKey":{if(!("initializer"in v))throw new Error("Invalid figmaMapping call, componentKey has no initializer");let S=v.initializer;if(!yt.default.isStringLiteral(S))throw new Error("Invalid figmaMapping call, componentKey is not a string literal");o=S.text;break}case"meta":{if(!("initializer"in v))throw new Error("Invalid figmaMapping call, meta has no initializer");let S=v.initializer;if(yt.default.isObjectLiteralExpression(S)){m={imports:[]};for(let b of S.properties)yt.default.isPropertyAssignment(b)&&yt.default.isIdentifier(b.name)&&b.name.text==="imports"&&yt.default.isArrayLiteralExpression(b.initializer)&&(m.imports=b.initializer.elements.map(P=>{if(yt.default.isStringLiteral(P))return P.text;if(yt.default.isObjectLiteralExpression(P)){let O={};for(let J of P.properties)if(yt.default.isPropertyAssignment(J)&&yt.default.isIdentifier(J.name)){let _=J.name.text;yt.default.isStringLiteral(J.initializer)&&(O[_]=J.initializer.text)}return O}return null}).filter(Boolean))}break}case"mapper":if(yt.default.isMethodDeclaration(v)){let S=function(x){let O=n.getSymbolAtLocation(x)?.getDeclarations()?.[0];if(O){let J=xIt(O);if(J?.importClause){let _=J.importClause.name?.getText(r);return _===u?(d="default",g=_):J.importClause.namedBindings&&yt.default.isNamedImports(J.importClause.namedBindings)&&(d="named",J.importClause.namedBindings.elements.forEach(K=>{K.name.getText(r)===u&&(g=K.name.getText(r))})),g&&yt.default.isStringLiteral(J.moduleSpecifier)&&(p=J.moduleSpecifier.text),!0}}return!1},b=function(x){if((yt.default.isJsxOpeningElement(x)||yt.default.isJsxSelfClosingElement(x))&&yt.default.isIdentifier(x.tagName)){u=x.tagName.getText(r),S(x.tagName);return}else if(yt.default.isTaggedTemplateExpression(x)&&yt.default.isIdentifier(x.tag)&&(x.tag.escapedText==="html"||x.tag.escapedText==="tmpl")){if(yt.default.isTemplateExpression(x.template)){let O=x.template.templateSpans.find(J=>yt.default.isIdentifier(J.expression)&&SIt(J.expression.text)&&S(J.expression));if(O&&yt.default.isIdentifier(O.expression)){u=O.expression.text;return}}let P=x.template.getText(r).match(/^`\s*<([^\s]+)/);if(P){u=P[1];return}if(P=x.template.getText(r).match(/^`\s*([^\s]+)/),P){u=P[1];return}}else yt.default.forEachChild(x,b)};var E=S,Q=b;if(v.parameters&&v.parameters.length>0&&v.parameters[0]&&v.parameters[0].type){let x=v.parameters[0].type.getText(r),P=Qwe(x);P&&(l=P)}yt.default.forEachChild(v,b),c=v.getText(r).replace(/^mapper/,"function Mapper"),A=PH(c);break}case"designTokenMapper":if(yt.default.isMethodDeclaration(v)){c=v.getText(r).replace(/^designTokenMapper/,"function Mapper"),A=PH(c),o="design-tokens";break}case"genericMapper":if(yt.default.isMethodDeclaration(v)){c=v.getText(r).replace(/^genericMapper/,"function Mapper"),A=PH(c),o="*";break}}}if(!o&&!f)throw new Error("Invalid figmaMapping call, no componentKey or url found");if(!o&&!A)throw new Error("Invalid figmaMapping call, no mapper found");if(!o&&!c)throw new Error("Invalid figmaMapping call, no original mapper found");let C=MIt(r),I=m?.imports??[],y=[],B=[];y.push(...C);for(let v of I)typeof v=="string"?B.push(v):y.push(v);return{builderName:u,figmaName:a??l,figmaKey:o,figmaUrl:f,inputMapper:A,exportType:d,importName:g,importPath:p,originalInputMapper:c,imports:y,importStrings:B.length>0?B:void 0,source:"cli"}}function SIt(t){return t.charAt(0)===t.charAt(0).toUpperCase()}function PH(t){return yt.default.transpile(t,{target:yt.default.ScriptTarget.Latest,allowNonTsExtensions:!0,moduleResolution:yt.default.ModuleResolutionKind.NodeJs,module:yt.default.ModuleKind.CommonJS,noImplicitAny:!1,esModuleInterop:!0,noUnusedLocals:!1,noUnusedParameters:!1,jsx:yt.default.JsxEmit.React,jsxFactory:"React.createElement",jsxFragmentFactory:"React.Fragment",allowJs:!0,checkJs:!0,strict:!0,suppressImplicitAnyIndexErrors:!0,typeRoots:["node_modules/@types"],inlineSources:!0,inlineSourceMap:!0})}function xIt(t){let e=t;for(;e;){if(yt.default.isImportDeclaration(e))return e;e=e.parent}}function FIt(t,e){return yt.default.isCallExpression(t)&&t.expression.getText(e)===bIt}async function AI(t){let e=["node_modules","dist","build","public"];return(await t.readdirRecursive(t.getAppRootDir(),e)).filter(n=>eo(n))}function Qwe(t){let e=t.match(/^Figma(\w+)Props$/);if(e&&typeof e[1]=="string")return e[1]}async function LH(t,e,r,n=!1){try{return r||(r=await Ed(t)),(await r.setPublicApiKey({publicApiKey:e})).modifiedType==="permission-error"?{success:!1,error:"permission-error"}:(n&&await r.ensureFigmaImportPage(),{success:!0})}catch(i){let s="unknown-error";return i instanceof Error?s=i.message:typeof i=="string"&&(s=i),{success:!1,error:s}}}function TIt(t){return yt.default.formatDiagnosticsWithColorAndContext(t,RIt)}async function gL({sys:t,mappingFiles:e,typeCheck:r}){if(t.Sentry?.setContext("findMappings",{mappingFiles:e}),!e.length)return{mapperFiles:[],figmaBuilderLinks:[],figmaLinksToResolve:[],diagnostics:[]};let n=[],i=[],s=[],o=await vn(t,e),a=o.getTypeChecker(),A=o.getSyntacticDiagnostics().filter(MH).filter(l=>l.file?.fileName?e.includes(l.file.fileName):!1);if(A.length>0)return $.error(`At least one of the mappings contain syntactic errors:
|
|
4856
4856
|
|
|
4857
|
-
${TIt(A)}`),Me(1);let c=[...r?o.getSemanticDiagnostics():[]].filter(
|
|
4857
|
+
${TIt(A)}`),Me(1);let c=[...r?o.getSemanticDiagnostics():[]].filter(MH);for(let l of e)try{let d=o.getSourceFile(l);if(!d){t.Sentry?.captureException(new Error("Could not find source file"),{extra:{file:l,sourceFiles:o.getSourceFiles().map(f=>f.fileName)},level:"warning"});continue}let g=d?.fileName;if(i.push({filePath:l,content:d.getText()}),g){let f=c.filter(m=>m.file?.fileName===g);f.length>0&&s.push(...f)}let p=await wIt(t,d,a);n.push(...p)}catch(d){return t.Sentry?.captureException(d),await Me(1)}let u=n.filter(l=>l.figmaUrl&&!l.figmaKey).map(l=>l.figmaUrl);return{mapperFiles:i,figmaBuilderLinks:n,figmaLinksToResolve:u,diagnostics:s}}function NIt(t){let e=new Set,r=[],n=[];for(let i of t){let s=!1;if(!i.figmaKey){n.push([i,"no-key"]);continue}i.figmaKey?(s||=e.has(i.figmaKey),e.add(i.figmaKey)):i.figmaUrl&&(s||=e.has(i.figmaUrl),e.add(i.figmaUrl)),s?n.push([i,"duplicate"]):r.push(i)}if(r.length>0){let i=`Found ${r.length} mappings:
|
|
4858
4858
|
`+r.map(s=>{let o=!1;s.figmaKey?(o||=e.has(s.figmaKey),e.add(s.figmaKey)):s.figmaUrl&&(o||=e.has(s.figmaUrl),e.add(s.figmaUrl));let a="";switch(s.figmaKey){case"design-tokens":a=" "+(0,mt.cyan)("\u2747\uFE0E Design tokens mapper");break;case"*":a=" "+(0,mt.yellow)("\u25CF Generic mapper");break;default:a=` ${(0,mt.magenta)("\u2756 "+Co(s.figmaName))} ${(0,mt.dim)("\u2192")} ${s.builderName==="-"?"-":"<"+s.builderName+">"}`;break}return s.loc&&(a=`${a} in ${(0,mt.dim)(s.loc)}`),a}).join(`
|
|
4859
4859
|
`);$.info(i)}if(n.length>0){let i=n.map(([s,o])=>{let a="";switch(s.figmaKey){case"design-tokens":a+=(0,mt.cyan)("\u2747\uFE0E Design tokens mapper");break;case"*":a+=(0,mt.yellow)("\u25CF Generic mapper");break;default:a+=`${(0,mt.magenta)("\u2756 "+Co(s.figmaName))}`;break}switch(a=(s.loc?(0,mt.bgRed)(`${a} in ${s.loc}`):a)+`
|
|
4860
4860
|
`,o){case"duplicate":a+=(0,mt.bold)("Component mapping is duplicateds");break;case"no-key":a+=`Could not resolve the "url" to a figma component key.
|
|
4861
4861
|
${(0,mt.dim)(s.figmaUrl)} is not a COMPONENT or COMPONENT_SET`;break}return a}).join(`
|
|
4862
|
-
`);$.error(i)}return{filteredLinks:r,skippedLinks:n}}function MIt(t){let e=[];for(let r of t.statements){if(!yt.default.isImportDeclaration(r)||!r.importClause||r.importClause.isTypeOnly||!yt.default.isStringLiteral(r.moduleSpecifier))continue;let n=r.moduleSpecifier.text;if(n.startsWith("@builder.io"))continue;r.importClause.name&&e.push({importType:"default",importName:r.importClause.name.text,importPath:n});let i=r.importClause.namedBindings;if(i&&yt.default.isNamedImports(i))for(let s of i.elements)s.isTypeOnly||e.push({importType:"named",importName:s.name.text,importPath:n})}return e}var yt,mt,Dwe,bIt,kIt,RIt,cI=L(()=>{"use strict";h();yt=z(require("typescript"),1);kr();rr();mt=z(Ir(),1);ro();pQ();yV();Ns();yr();xt();Ls();hr();zr();kf();
|
|
4862
|
+
`);$.error(i)}return{filteredLinks:r,skippedLinks:n}}function MIt(t){let e=[];for(let r of t.statements){if(!yt.default.isImportDeclaration(r)||!r.importClause||r.importClause.isTypeOnly||!yt.default.isStringLiteral(r.moduleSpecifier))continue;let n=r.moduleSpecifier.text;if(n.startsWith("@builder.io"))continue;r.importClause.name&&e.push({importType:"default",importName:r.importClause.name.text,importPath:n});let i=r.importClause.namedBindings;if(i&&yt.default.isNamedImports(i))for(let s of i.elements)s.isTypeOnly||e.push({importType:"named",importName:s.name.text,importPath:n})}return e}var yt,mt,Dwe,bIt,kIt,RIt,cI=L(()=>{"use strict";h();yt=z(require("typescript"),1);kr();rr();mt=z(Ir(),1);ro();pQ();yV();Ns();yr();xt();Ls();hr();zr();kf();NH();Rx();ywe();Dwe=async(t,e)=>{let r=await jDe(t);t.Sentry?.setContext("userContext",r),await Pt("figma publish started",{});let n=!e.yes||!e.skipInstallation;if(n&&!process.stdout.isTTY&&process.env.FORCE_TTY!=="1")return await Pt("tty error",{}),Ke(`This command requires a TTY-enabled terminal.
|
|
4863
4863
|
see docs for more information on how to run non-interactive.
|
|
4864
|
-
If you are using Windows Git Bash, try a different terminal or wrap the command with winpty.`),await Me(1);let i=Ux(e);console.log(""),sr((0,mt.bgCyan)((0,mt.bold)((0,mt.white)(" figma publish ")))+" "+(0,mt.dim)(ht)),await
|
|
4864
|
+
If you are using Windows Git Bash, try a different terminal or wrap the command with winpty.`),await Me(1);let i=Ux(e);console.log(""),sr((0,mt.bgCyan)((0,mt.bold)((0,mt.white)(" figma publish ")))+" "+(0,mt.dim)(ht)),await DH(t,n);let s,o,a,A,c,u;if(e.clearMappings)s=[],o=[],a=[],A=[],c=[],u=[];else{s=await AI(t);let D=await gL({mappingFiles:s,sys:t});o=D.figmaBuilderLinks,a=D.figmaLinksToResolve,A=D.mapperFiles;let{filteredLinks:S,skippedLinks:b}=NIt(o);c=S,u=b}let{builderPrivateKey:l,builderPublicKey:d,userId:g,spaceName:p,figmaAuth:f}=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0,requireFigmaAuth:a.length>0?"if-unset":void 0});if(f&&a.length>0&&await Bwe(t,e,f,o,a),u.length>0){if(await Pt("figma publish user error",{mappingFiles:s.length,filteredLinks:c.length,skippedLinks:u.length}),e.force!==!0)return $.message(""),Ke(`Found some errors in the mapping files. Please fix the issues and try again, or use the ${(0,mt.bold)("--force")} flag to publish regardless.`),await Me(1);$.warn("Local mappings contain some type errors, but --force flag was used, skipping.")}let m;try{m=await Ed(t)}catch(D){t.Sentry?.captureException(D,{level:"warning"})}let C=p?`${(0,mt.bold)(p)} ${(0,mt.dim)("("+d+")")}`:`space id "${(0,mt.bold)(d)}"`;if(c.length===0){let D=e.clearMappings?`Clear mappings flag is set. All existing mappings will be removed from space: ${C}.`:`No mappings found. Publishing will remove all existing mapping in space: ${C}.`;$.warning(D);let S=i||e.yes||await wr({message:"Do you want to continue?",active:"Publish",inactive:"Cancel"});if(je(S)||!S)return Ke("Publish cancelled."),await Me(1)}else{let D=!1;for(let b of c)if(b.imports&&b.imports.length>0){let x=b.imports.filter(P=>P.importPath?.startsWith("."));x.length>0&&(D=!0,$.warn(`${(0,mt.dim)(`Found relative imports in ${b.loc}:`)}
|
|
4865
4865
|
${x.map(P=>P.importPath).join("/n")}`))}D&&$.warn(`${(0,mt.yellow)(`Relative imports may break when code is generated in different projects.
|
|
4866
4866
|
Instead, use one of these approaches:`)}
|
|
4867
4867
|
${(0,mt.dim)("\u2022")} Package imports ${(0,mt.dim)('(e.g. import { Button } from "@your-org/components")')}
|
|
@@ -4869,11 +4869,11 @@ ${(0,mt.dim)("\u2022")} TypeScript path aliases ${(0,mt.dim)('(e.g. import { Inp
|
|
|
4869
4869
|
|
|
4870
4870
|
These imports will be preserved exactly as written when generating code.
|
|
4871
4871
|
See: https://www.builder.io/c/docs/component-mapping-publishing
|
|
4872
|
-
`);let S=i||e.yes||await wi({message:`Do you want to publish the found mappings to ${C}?`,options:[{label:"Publish",hint:"Existing mappings will be overwritten",value:!0},{label:"Cancel",value:!1}]});if(je(S)||!S)return Ke("Publish cancelled.\nYou can use `npx builder.io@latest auth` to re-authenticate in a different space"),await Me(1)}let I=is(),y=await t.getRepoInfo(),B;if(e.dryrun||(I.start("Publishing Figma Mappings"),B=await kIt(t,d,l,g,{figmaBuilderLinks:c,remoteUrl:y?.remoteUrl,defaultBranch:y?.defaultBranch,currentBranch:y?.currentBranch,commit:y?.commit,userContext:r,mapperFiles:A}),I.stop(c.length>0?`${c.length} mappings uploaded`:"All mappings removed from the Builder space")),e.verbose||e.dryrun){let D=CT(BQ);$.info(D.highlight("json",JSON.stringify(c,null,2)).value)}let{success:E,error:Q}=await
|
|
4872
|
+
`);let S=i||e.yes||await wi({message:`Do you want to publish the found mappings to ${C}?`,options:[{label:"Publish",hint:"Existing mappings will be overwritten",value:!0},{label:"Cancel",value:!1}]});if(je(S)||!S)return Ke("Publish cancelled.\nYou can use `npx builder.io@latest auth` to re-authenticate in a different space"),await Me(1)}let I=is(),y=await t.getRepoInfo(),B;if(e.dryrun||(I.start("Publishing Figma Mappings"),B=await kIt(t,d,l,g,{figmaBuilderLinks:c,remoteUrl:y?.remoteUrl,defaultBranch:y?.defaultBranch,currentBranch:y?.currentBranch,commit:y?.commit,userContext:r,mapperFiles:A}),I.stop(c.length>0?`${c.length} mappings uploaded`:"All mappings removed from the Builder space")),e.verbose||e.dryrun){let D=CT(BQ);$.info(D.highlight("json",JSON.stringify(c,null,2)).value)}let{success:E,error:Q}=await LH(t,d,m,!0);E||(Q==="permission-error"?$.error("Failed to set public api key. Please ensure you have write access in the current directory. You can use chmod to change the permissions of this directory."):$.error("Error setting public api key: "+Q)),$.success(`${(0,mt.bgGreen)((0,mt.bold)((0,mt.white)(" Done! \u{1F389} ")))} ${B?(0,mt.dim)("id "+B):""}`);let v={react:"npm run start",angular:"npm run start",vue:"npm run dev",svelte:"npm run dev",next:"npm run dev",remix:"npm run dev"}[m?.framework??"react"]??"npm run start";Cn((0,mt.dim)(`You can now start the dev server:
|
|
4873
4873
|
|
|
4874
4874
|
`)+(0,mt.bgBlack)((0,mt.white)((0,mt.bold)(` ${v} `)))+`
|
|
4875
4875
|
|
|
4876
|
-
`+(0,mt.dim)("Then, go back to Figma and generate code again to see your mapped components.")),await Pt("figma publish success",{spaceId:d,mappingFiles:s.length,figmaBuilderLinks:c.length})};bIt="figmaMapping";kIt=async(t,e,r,n,i)=>{let s=new URL(`${Ne}/mappings/publish`);s.searchParams.set("apiKey",e),s.searchParams.set("userId",n);let a=await(await Fe(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(i)})).json();if(typeof a=="object"&&typeof a.id=="string")return a.id;throw new Error("Figma Publish Response is not valid")},RIt={getCanonicalFileName:t=>t,getCurrentDirectory:()=>yt.default.sys.getCurrentDirectory(),getNewLine:()=>yt.default.sys.newLine}});function
|
|
4876
|
+
`+(0,mt.dim)("Then, go back to Figma and generate code again to see your mapped components.")),await Pt("figma publish success",{spaceId:d,mappingFiles:s.length,figmaBuilderLinks:c.length})};bIt="figmaMapping";kIt=async(t,e,r,n,i)=>{let s=new URL(`${Ne}/mappings/publish`);s.searchParams.set("apiKey",e),s.searchParams.set("userId",n);let a=await(await Fe(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(i)})).json();if(typeof a=="object"&&typeof a.id=="string")return a.id;throw new Error("Figma Publish Response is not valid")},RIt={getCanonicalFileName:t=>t,getCurrentDirectory:()=>yt.default.sys.getCurrentDirectory(),getNewLine:()=>yt.default.sys.newLine}});function UH(){return(0,hn.join)((0,Gx.homedir)(),".builder","config","data.json")}async function UIt(t,e){let r=(0,bwe.randomUUID)();return xwe({sys:t,name:"Figma",initialPort:PIt,requestListener:async(n,i,s,o,a)=>{let A=new URL(i.url||"",`http://localhost:${n}`);if(A.pathname==="/figma-connect"){let c=A.searchParams.get("code"),u=A.searchParams.get("state"),l="nrGCqw6TLl95QJhVDi097A",d=_It,p=`Basic ${Buffer.from(`${l}:${d}`).toString("base64")}`;if(c&&r===u){let m=await(await Fe("https://api.figma.com/v1/oauth/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:p},body:new URLSearchParams({redirect_uri:`http://localhost:${n}/figma-connect`,code:c,grant_type:"authorization_code"}).toString()})).json();s.end(`<!doctype html>
|
|
4877
4877
|
<html lang="en" dir="ltr">
|
|
4878
4878
|
<head>
|
|
4879
4879
|
<meta charset="utf-8" />
|
|
@@ -5091,15 +5091,15 @@ See: https://www.builder.io/c/docs/component-mapping-publishing
|
|
|
5091
5091
|
<!--SCRIPT_PLACEHOLDER-->
|
|
5092
5092
|
</body>
|
|
5093
5093
|
</html>
|
|
5094
|
-
`.replace("{{MESSAGE}}","The CLI has authenticated correctly with Builder.io"),()=>{a({privateKey:A.searchParams.get("p-key")||"",spaceId:A.searchParams.get("api-key")||"",spaceName:A.searchParams.get("org-name")||"",userId:A.searchParams.get("user-id")||""})})},onListen:i=>{let s=process.env.BUILDER_WEB_HOST||"https://builder.io",o=new URL("/cli-auth",s);o.searchParams.set("client_id","builder-dev-tools-cli"),o.searchParams.set("host",n),o.searchParams.set("response_type","code"),o.searchParams.set("cli","true"),e&&o.searchParams.set("space_id",e);let a=new URL(Xl,`http://localhost:${i}`);a.searchParams.set(vy,(0,Gx.platform)()),a.searchParams.set(Sy,process.versions.node);let A=t.getFrameworks();return A.length>0&&(o.searchParams.set(Zp,A[0].name),a.searchParams.set(Zp,A[0].name)),o.searchParams.set("redirect_url",a.href),o.href},silent:r?.silent,onAuthStatus:r?.onAuthStatus})}function bx(t,e,r="user"){let n=vwe(t,r);if(e=Object.assign(n,e),r==="user"){let s=
|
|
5094
|
+
`.replace("{{MESSAGE}}","The CLI has authenticated correctly with Builder.io"),()=>{a({privateKey:A.searchParams.get("p-key")||"",spaceId:A.searchParams.get("api-key")||"",spaceName:A.searchParams.get("org-name")||"",userId:A.searchParams.get("user-id")||""})})},onListen:i=>{let s=process.env.BUILDER_WEB_HOST||"https://builder.io",o=new URL("/cli-auth",s);o.searchParams.set("client_id","builder-dev-tools-cli"),o.searchParams.set("host",n),o.searchParams.set("response_type","code"),o.searchParams.set("cli","true"),e&&o.searchParams.set("space_id",e);let a=new URL(Xl,`http://localhost:${i}`);a.searchParams.set(vy,(0,Gx.platform)()),a.searchParams.set(Sy,process.versions.node);let A=t.getFrameworks();return A.length>0&&(o.searchParams.set(Zp,A[0].name),a.searchParams.set(Zp,A[0].name)),o.searchParams.set("redirect_url",a.href),o.href},silent:r?.silent,onAuthStatus:r?.onAuthStatus})}function bx(t,e,r="user"){let n=vwe(t,r);if(e=Object.assign(n,e),r==="user"){let s=UH();try{(0,ts.mkdirSync)((0,hn.dirname)(s),{recursive:!0}),(0,ts.writeFileSync)(s,JSON.stringify({credentials:e},null,2));return}catch(o){throw t.Sentry?.captureException(new Error("Failed to write credentials",{cause:o}),{level:"warning",extra:{filepath:s}}),new Error("Failed to store credentials in user home directory")}}let i=[{path:(0,hn.join)(t.getAppRootDir(),"node_modules",".builder","data.json"),shouldTry:()=>(0,ts.existsSync)((0,hn.join)(t.getAppRootDir(),"node_modules")),ensureGitignore:!1},{path:(0,hn.join)(t.getAppRootDir(),".builder","config","data.json"),shouldTry:()=>!0,ensureGitignore:!0},{path:(0,hn.join)(t.getAppRootDir(),".config","builderio","data.json"),shouldTry:()=>!0,ensureGitignore:!0}];for(let s of i)if(s.shouldTry())try{(0,ts.mkdirSync)((0,hn.dirname)(s.path),{recursive:!0}),(0,ts.writeFileSync)(s.path,JSON.stringify({credentials:e},null,2)),s.ensureGitignore&&OIt(t,s.path);return}catch(o){t.Sentry?.captureException(new Error("Failed to write credentials",{cause:o}),{level:"warning",extra:{filepath:s.path}});continue}throw new Error("Failed to store credentials in any location")}function OIt(t,e){let r=(0,hn.join)(t.getAppRootDir(),".gitignore"),n=(0,hn.relative)(t.getAppRootDir(),e).replace(/\\/g,"/");try{let i="";if((0,ts.existsSync)(r)&&(i=(0,ts.readFileSync)(r,"utf8")),!i.split(`
|
|
5095
5095
|
`).some(a=>{let A=a.trim();return A===n||A===(0,hn.dirname)(n)+"/"})){let a=n;(0,ts.writeFileSync)(r,i+`
|
|
5096
5096
|
`+a+`
|
|
5097
|
-
`)}}catch(i){t.Sentry?.captureException(i,{level:"info"})}}function vwe(t,e="user"){let r=e==="user"?[
|
|
5098
|
-
OPEN: ${(0,Gl.dim)(d)}`),n=Bi(),n.start(`Waiting for ${t.name} authentication`));try{await xl(d)}catch{t.silent||$.warn("Could not open browser automatically. Please open the URL above manually.")}let g=await i;return t.silent?t.onAuthStatus?.({type:"auth-success",name:t.name}):n&&n.stop(`Authenticated with ${t.name} successfully`),g}catch(l){throw t.silent?t.onAuthStatus?.({type:"auth-error",name:t.name,message:String(l)}):n&&(n.stop(`Failed to authenticate with ${t.name}.`,-1),Zc("auth")),t.sys.Sentry?.captureException(l),l}finally{A()}}var wwe,Gx,hn,ts,Gl,bwe,PIt,LIt,
|
|
5097
|
+
`)}}catch(i){t.Sentry?.captureException(i,{level:"info"})}}function vwe(t,e="user"){let r=e==="user"?[UH()]:[(0,hn.join)(t.getAppRootDir(),"node_modules",".builder","data.json"),(0,hn.join)(t.getAppRootDir(),".builder","config","data.json"),(0,hn.join)(t.getAppRootDir(),".config","builderio","data.json"),(0,hn.join)(t.getRepoRootDir(),".git",".builder.json")];for(let n of r)if((0,ts.existsSync)(n)){let i;try{i=(0,ts.readFileSync)(n,"utf8")}catch(s){t.Sentry?.captureException(new Error("Failed to read credentials file",{cause:s}),{level:"warning",extra:{filepath:n}});continue}try{return JSON.parse(i).credentials}catch(s){t.Sentry?.captureException(new Error("Failed to parse credentials JSON",{cause:s}),{level:"warning",extra:{filepath:n,fileSize:i.length}})}}return{}}function Swe(t,e="user"){let r=e==="user"?[UH()]:[(0,hn.join)(t.getAppRootDir(),"node_modules",".builder","data.json"),(0,hn.join)(t.getAppRootDir(),".builder","config","data.json"),(0,hn.join)(t.getAppRootDir(),".config","builderio","data.json"),(0,hn.join)(t.getRepoRootDir(),".git",".builder.json")],n=!1;for(let i of r)if((0,ts.existsSync)(i))try{t.unlinkSync(i),n=!0}catch(s){t.Sentry?.captureException(s,{level:"warning"})}return n}async function xwe(t){let e,r,n,i=new Promise((l,d)=>{e=l,r=d}),s=t.initialPort,o=0,a=(0,wwe.createServer)((l,d)=>t.requestListener(s,l,d,e,r)),A=()=>{c(),a&&("closeAllConnections"in a&&a.closeAllConnections(),a.close(l=>{l&&t.sys.Sentry?.captureException(l)}))};process.on("uncaughtExceptionMonitor",A),process.on("unhandledRejection",A),process.on("SIGINT",A),process.on("SIGTERM",A),process.on("exit",A);let c=()=>{process.removeListener("uncaughtExceptionMonitor",A),process.removeListener("unhandledRejection",A),process.removeListener("SIGINT",A),process.removeListener("SIGTERM",A),process.removeListener("exit",A)},u=()=>new Promise((l,d)=>{let g=p=>{a.removeListener("error",g),p.code==="EADDRINUSE"&&o<_H?(t.silent||$.warning(`Port ${s} is already in use, trying next port`),s++,o++,l(0)):d(p)};a.once("error",g),a.listen(s,()=>{a.removeListener("error",g);let p=a.address();l(p.port)})});try{let l=0;for(;l===0&&o<_H;)l=await u();if(l===0)throw new Error(`Failed to find an available port after ${_H} attempts`);let d=t.onListen(l);t.silent?(t.onAuthStatus?.({type:"auth-url",url:d,name:t.name}),t.onAuthStatus?.({type:"auth-waiting",name:t.name})):($.warn(`Required authenticating with ${t.name}
|
|
5098
|
+
OPEN: ${(0,Gl.dim)(d)}`),n=Bi(),n.start(`Waiting for ${t.name} authentication`));try{await xl(d)}catch{t.silent||$.warn("Could not open browser automatically. Please open the URL above manually.")}let g=await i;return t.silent?t.onAuthStatus?.({type:"auth-success",name:t.name}):n&&n.stop(`Authenticated with ${t.name} successfully`),g}catch(l){throw t.silent?t.onAuthStatus?.({type:"auth-error",name:t.name,message:String(l)}):n&&(n.stop(`Failed to authenticate with ${t.name}.`,-1),Zc("auth")),t.sys.Sentry?.captureException(l),l}finally{A()}}var wwe,Gx,hn,ts,Gl,bwe,PIt,LIt,_H,Ux,Jo,Wt,_It,kr=L(()=>{"use strict";h();wwe=require("node:http");ed();Gx=require("node:os"),hn=require("node:path"),ts=require("node:fs");rr();Gl=z(Ir(),1);cI();Ls();bwe=require("node:crypto");hr();Ml();GB();bi();TB();Ns();PIt=5294,LIt=5284,_H=4,Ux=t=>!!(process.env.CI||t.ci);Jo=(t,e,r="user")=>{let n=Ux(e)?{}:vwe(t,r),i=n.spaceName,s=e.builderUserId??process.env.BUILDER_USER_ID??n.userId,o=e.builderPublicKey??process.env.BUILDER_PUBLIC_KEY??n.builderPublicKey,a=e.builderPrivateKey??process.env.BUILDER_PRIVATE_KEY??n.builderPrivateKey,A=process.env.FIGMA_PERSONAL_TOKEN??e.figmaToken,c;return A?c={access_token:A,oauth:!1}:c=n.figmaAuth,{spaceName:i,userId:s,builderPublicKey:o,builderPrivateKey:a,figmaAuth:c,timestamp:n.timestamp}},Wt=async(t,e,r)=>{let n=r.scope??"user",{spaceName:i,userId:s,builderPublicKey:o,builderPrivateKey:a,figmaAuth:A,timestamp:c}=Jo(t,e,n);if(r.forceSpaceId&&!e.yes&&o&&o!==r.forceSpaceId)if(r.silent)o=r.forceSpaceId,a=void 0,i=void 0,s=void 0;else if($.warning(`You are currently authenticated for space ${(0,Gl.yellow)(o)} (${i||"unnamed"}), but this command requires space ${(0,Gl.green)(r.forceSpaceId)}.`),await wi({message:"You must switch to the correct space to continue with this code generation command.",options:[{value:"switch",label:"Switch to required space",hint:"Authenticate with the correct space and continue"},{value:"exit",label:"Exit code generation",hint:"Cancel the command and stay in current space"}]})==="switch")o=r.forceSpaceId,a=void 0,i=void 0,s=void 0;else return $.info("Code generation cancelled. You can run the command again when you're ready to switch spaces."),await Me(1);if(Ux(e)){if(!A&&r.requireFigmaAuth==="if-unset")throw new Error(`No Figma personal token found.
|
|
5099
5099
|
Please set the FIGMA_PERSONAL_TOKEN environment variable.`);if(!a&&r.builderPrivateKey)throw new Error(`No Builder private key found.
|
|
5100
5100
|
Please set the BUILDER_PRIVATE_KEY environment variable.`);if(!o&&r.builderPublicKey)throw new Error(`No Builder public key found.
|
|
5101
|
-
Please set the BUILDER_PUBLIC_KEY environment variable.`);return{figmaAuth:A,builderPublicKey:o,builderPrivateKey:a,userId:s,spaceName:i}}if((r.requireFigmaAuth==="always"||!A&&r.requireFigmaAuth==="if-unset")&&(A=await UIt(t,r.silent?{silent:!0,onAuthStatus:r.onAuthStatus}:void 0),bx(t,{figmaAuth:A},n)),r.force||!a&&r.builderPrivateKey||!o&&r.builderPublicKey){let{privateKey:u,spaceId:l,spaceName:d,userId:g}=await GIt(t,r.forceSpaceId,r.silent?{silent:!0,onAuthStatus:r.onAuthStatus}:void 0);if(r.forceSpaceId&&l!==r.forceSpaceId)throw new Error(`OAuth flow returned space ${(0,Gl.yellow)(l)}, however the command specified --spaceId=${(0,Gl.green)(r.forceSpaceId)}`);o=l,a=u,i=d,s=g,await wz(s),await zo(t,t.getAppRootDir())&&!await
|
|
5102
|
-
`),this.dy++}write(e,r=!1){this.linewrap===!0&&r===!1?this.stream.write(e.substr(0,this.getWidth())):this.stream.write(e)}lineWrapping(e){this.stream.isTTY&&(this.linewrap=e,e?this.stream.write("\x1B[?7h"):this.stream.write("\x1B[?7l"))}isTTY(){return this.stream.isTTY===!0}getWidth(){return this.stream.columns||(this.stream.isTTY?80:200)}};Gwe.exports=K4});var Kwe=N((Dfr,J4)=>{"use strict";h();var Owe=t=>Number.isNaN(t)?!1:t>=4352&&(t<=4447||t===9001||t===9002||11904<=t&&t<=12871&&t!==12351||12880<=t&&t<=19903||19968<=t&&t<=42182||43360<=t&&t<=43388||44032<=t&&t<=55203||63744<=t&&t<=64255||65040<=t&&t<=65049||65072<=t&&t<=65131||65281<=t&&t<=65376||65504<=t&&t<=65510||110592<=t&&t<=110593||127488<=t&&t<=127569||131072<=t&&t<=262141);J4.exports=Owe;J4.exports.default=Owe});var Jwe=N((bfr,Hwe)=>{"use strict";h();Hwe.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var Ywe=N((Sfr,j4)=>{"use strict";h();var uEt=sU(),lEt=Kwe(),gEt=Jwe(),jwe=t=>{if(typeof t!="string"||t.length===0||(t=uEt(t),t.length===0))return 0;t=t.replace(gEt()," ");let e=0;for(let r=0;r<t.length;r++){let n=t.codePointAt(r);n<=31||n>=127&&n<=159||n>=768&&n<=879||(n>65535&&r++,e+=lEt(n)?2:1)}return e};j4.exports=jwe;j4.exports.default=jwe});var Y4=N((Ffr,qwe)=>{h();qwe.exports=function(e,r,n){if(r.autopadding!==!0)return e;function i(s,o){return(r.autopaddingChar+s).slice(-o)}return n==="percentage"?i(e,3):e}});var q4=N((Rfr,$we)=>{h();$we.exports=function(e,r){let n=Math.round(e*r.barsize),i=r.barsize-n;return r.barCompleteString.substr(0,n)+r.barGlue+r.barIncompleteString.substr(0,i)}});var $4=N((Nfr,Vwe)=>{h();Vwe.exports=function(e,r,n){function i(o){return n?n*Math.round(o/n):o}function s(o){return(r.autopaddingChar+o).slice(-2)}return e>3600?s(Math.floor(e/3600))+"h"+s(i(e%3600/60))+"m":e>60?s(Math.floor(e/60))+"m"+s(i(e%60))+"s":e>10?s(i(e))+"s":s(e)+"s"}});var V4=N((Pfr,Wwe)=>{h();var pEt=Ywe(),dEt=Y4(),fEt=q4(),hEt=$4();Wwe.exports=function(e,r,n){let i=e.format,s=e.formatTime||hEt,o=e.formatValue||dEt,a=e.formatBar||fEt,A=Math.floor(r.progress*100)+"",c=r.stopTime||Date.now(),u=Math.round((c-r.startTime)/1e3),l=Object.assign({},n,{bar:a(r.progress,e),percentage:o(A,e,"percentage"),total:o(r.total,e,"total"),value:o(r.value,e,"value"),eta:o(r.eta,e,"eta"),eta_formatted:s(r.eta,e,5),duration:o(u,e,"duration"),duration_formatted:s(u,e,1)});i=i.replace(/\{(\w+)\}/g,function(p,f){return typeof l[f]<"u"?l[f]:p});let d=Math.max(0,r.maxWidth-pEt(i)-2),g=Math.floor(d/2);switch(e.align){case"right":i=d>0?" ".repeat(d)+i:i;break;case"center":i=g>0?" ".repeat(g)+i:i;break;default:break}return i}});var Kx=N((_fr,zwe)=>{h();function Cr(t,e){return typeof t>"u"||t===null?e:t}zwe.exports={parse:function(e,r){let n={},i=Object.assign({},r,e);return n.throttleTime=1e3/Cr(i.fps,10),n.stream=Cr(i.stream,process.stderr),n.terminal=Cr(i.terminal,null),n.clearOnComplete=Cr(i.clearOnComplete,!1),n.stopOnComplete=Cr(i.stopOnComplete,!1),n.barsize=Cr(i.barsize,40),n.align=Cr(i.align,"left"),n.hideCursor=Cr(i.hideCursor,!1),n.linewrap=Cr(i.linewrap,!1),n.barGlue=Cr(i.barGlue,""),n.barCompleteChar=Cr(i.barCompleteChar,"="),n.barIncompleteChar=Cr(i.barIncompleteChar,"-"),n.format=Cr(i.format,"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}"),n.formatTime=Cr(i.formatTime,null),n.formatValue=Cr(i.formatValue,null),n.formatBar=Cr(i.formatBar,null),n.etaBufferLength=Cr(i.etaBuffer,10),n.etaAsynchronousUpdate=Cr(i.etaAsynchronousUpdate,!1),n.progressCalculationRelative=Cr(i.progressCalculationRelative,!1),n.synchronousUpdate=Cr(i.synchronousUpdate,!0),n.noTTYOutput=Cr(i.noTTYOutput,!1),n.notTTYSchedule=Cr(i.notTTYSchedule,2e3),n.emptyOnZero=Cr(i.emptyOnZero,!1),n.forceRedraw=Cr(i.forceRedraw,!1),n.autopadding=Cr(i.autopadding,!1),n.gracefulExit=Cr(i.gracefulExit,!1),n},assignDerivedOptions:function(e){return e.barCompleteString=e.barCompleteChar.repeat(e.barsize+1),e.barIncompleteString=e.barIncompleteChar.repeat(e.barsize+1),e.autopaddingChar=e.autopadding?Cr(e.autopaddingChar," "):"",e}}});var W4=N((Ofr,Zwe)=>{h();var Xwe=Uwe(),mEt=H4(),CEt=V4(),IEt=Kx(),EEt=require("events");Zwe.exports=class extends EEt{constructor(e){super(),this.options=IEt.assignDerivedOptions(e),this.terminal=this.options.terminal?this.options.terminal:new mEt(this.options.stream),this.value=0,this.startValue=0,this.total=100,this.lastDrawnString=null,this.startTime=null,this.stopTime=null,this.lastRedraw=Date.now(),this.eta=new Xwe(this.options.etaBufferLength,0,0),this.payload={},this.isActive=!1,this.formatter=typeof this.options.format=="function"?this.options.format:CEt}render(e=!1){let r={progress:this.getProgress(),eta:this.eta.getTime(),startTime:this.startTime,stopTime:this.stopTime,total:this.total,value:this.value,maxWidth:this.terminal.getWidth()};this.options.etaAsynchronousUpdate&&this.updateETA();let n=this.formatter(this.options,r,this.payload);(e||this.options.forceRedraw||this.options.noTTYOutput&&!this.terminal.isTTY()||this.lastDrawnString!=n)&&(this.emit("redraw-pre"),this.terminal.cursorTo(0,null),this.terminal.write(n),this.terminal.clearRight(),this.lastDrawnString=n,this.lastRedraw=Date.now(),this.emit("redraw-post"))}start(e,r,n){this.value=r||0,this.total=typeof e<"u"&&e>=0?e:100,this.startValue=r||0,this.payload=n||{},this.startTime=Date.now(),this.stopTime=null,this.lastDrawnString="",this.eta=new Xwe(this.options.etaBufferLength,this.startTime,this.value),this.isActive=!0,this.emit("start",e,r)}stop(){this.isActive=!1,this.stopTime=Date.now(),this.emit("stop",this.total,this.value)}update(e,r={}){typeof e=="number"&&(this.value=e,this.eta.update(Date.now(),e,this.total));let n=(typeof e=="object"?e:r)||{};this.emit("update",this.total,this.value);for(let i in n)this.payload[i]=n[i];this.value>=this.getTotal()&&this.options.stopOnComplete&&this.stop()}getProgress(){let e=this.value/this.total;return this.options.progressCalculationRelative&&(e=(this.value-this.startValue)/(this.total-this.startValue)),isNaN(e)&&(e=this.options&&this.options.emptyOnZero?0:1),e=Math.min(Math.max(e,0),1),e}increment(e=1,r={}){typeof e=="object"?this.update(this.value+1,e):this.update(this.value+e,r)}getTotal(){return this.total}setTotal(e){typeof e<"u"&&e>=0&&(this.total=e)}updateETA(){this.eta.update(Date.now(),this.value,this.total)}}});var t0e=N((Jfr,e0e)=>{h();var BEt=W4(),yEt=Kx();e0e.exports=class extends BEt{constructor(e,r){super(yEt.parse(e,r)),this.timer=null,this.options.noTTYOutput&&this.terminal.isTTY()===!1&&(this.options.synchronousUpdate=!1),this.schedulingRate=this.terminal.isTTY()?this.options.throttleTime:this.options.notTTYSchedule,this.sigintCallback=null}render(){this.timer&&(clearTimeout(this.timer),this.timer=null),super.render(),this.options.noTTYOutput&&this.terminal.isTTY()===!1&&this.terminal.newline(),this.timer=setTimeout(this.render.bind(this),this.schedulingRate)}update(e,r){this.timer&&(super.update(e,r),this.options.synchronousUpdate&&this.lastRedraw+this.options.throttleTime*2<Date.now()&&this.render())}start(e,r,n){this.options.noTTYOutput===!1&&this.terminal.isTTY()===!1||(this.sigintCallback===null&&this.options.gracefulExit&&(this.sigintCallback=this.stop.bind(this),process.once("SIGINT",this.sigintCallback),process.once("SIGTERM",this.sigintCallback)),this.terminal.cursorSave(),this.options.hideCursor===!0&&this.terminal.cursor(!1),this.options.linewrap===!1&&this.terminal.lineWrapping(!1),super.start(e,r,n),this.render())}stop(){this.timer&&(this.sigintCallback&&(process.removeListener("SIGINT",this.sigintCallback),process.removeListener("SIGTERM",this.sigintCallback),this.sigintCallback=null),this.render(),super.stop(),clearTimeout(this.timer),this.timer=null,this.options.hideCursor===!0&&this.terminal.cursor(!0),this.options.linewrap===!1&&this.terminal.lineWrapping(!0),this.terminal.cursorRestore(),this.options.clearOnComplete?(this.terminal.cursorTo(0,null),this.terminal.clearLine()):this.terminal.newline())}}});var n0e=N((qfr,r0e)=>{h();var QEt=H4(),DEt=W4(),wEt=Kx(),bEt=require("events");r0e.exports=class extends bEt{constructor(e,r){super(),this.bars=[],this.options=wEt.parse(e,r),this.options.synchronousUpdate=!1,this.terminal=this.options.terminal?this.options.terminal:new QEt(this.options.stream),this.timer=null,this.isActive=!1,this.schedulingRate=this.terminal.isTTY()?this.options.throttleTime:this.options.notTTYSchedule,this.loggingBuffer=[],this.sigintCallback=null}create(e,r,n,i={}){let s=new DEt(Object.assign({},this.options,{terminal:this.terminal},i));return this.bars.push(s),this.options.noTTYOutput===!1&&this.terminal.isTTY()===!1||(this.sigintCallback===null&&this.options.gracefulExit&&(this.sigintCallback=this.stop.bind(this),process.once("SIGINT",this.sigintCallback),process.once("SIGTERM",this.sigintCallback)),this.isActive||(this.options.hideCursor===!0&&this.terminal.cursor(!1),this.options.linewrap===!1&&this.terminal.lineWrapping(!1),this.timer=setTimeout(this.update.bind(this),this.schedulingRate)),this.isActive=!0,s.start(e,r,n),this.emit("start")),s}remove(e){let r=this.bars.indexOf(e);return r<0?!1:(this.bars.splice(r,1),this.update(),this.terminal.newline(),this.terminal.clearBottom(),!0)}update(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this.emit("update-pre"),this.terminal.cursorRelativeReset(),this.emit("redraw-pre"),this.loggingBuffer.length>0)for(this.terminal.clearLine();this.loggingBuffer.length>0;)this.terminal.write(this.loggingBuffer.shift(),!0);for(let e=0;e<this.bars.length;e++)e>0&&this.terminal.newline(),this.bars[e].render();this.emit("redraw-post"),this.options.noTTYOutput&&this.terminal.isTTY()===!1&&(this.terminal.newline(),this.terminal.newline()),this.timer=setTimeout(this.update.bind(this),this.schedulingRate),this.emit("update-post"),this.options.stopOnComplete&&!this.bars.find(e=>e.isActive)&&this.stop()}stop(){if(clearTimeout(this.timer),this.timer=null,this.sigintCallback&&(process.removeListener("SIGINT",this.sigintCallback),process.removeListener("SIGTERM",this.sigintCallback),this.sigintCallback=null),this.isActive=!1,this.options.hideCursor===!0&&this.terminal.cursor(!0),this.options.linewrap===!1&&this.terminal.lineWrapping(!0),this.terminal.cursorRelativeReset(),this.emit("stop-pre-clear"),this.options.clearOnComplete)this.terminal.clearBottom();else{for(let e=0;e<this.bars.length;e++)e>0&&this.terminal.newline(),this.bars[e].render(),this.bars[e].stop();this.terminal.newline()}this.emit("stop")}log(e){this.loggingBuffer.push(e)}}});var s0e=N((Vfr,i0e)=>{h();i0e.exports={format:"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"=",barIncompleteChar:"-"}});var a0e=N((zfr,o0e)=>{h();o0e.exports={format:" {bar} {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var c0e=N((Zfr,A0e)=>{h();A0e.exports={format:" \x1B[90m{bar}\x1B[0m {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var l0e=N((thr,u0e)=>{h();u0e.exports={format:" {bar}\u25A0 {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u25A0",barIncompleteChar:" "}});var p0e=N((nhr,g0e)=>{h();var vEt=s0e(),SEt=a0e(),xEt=c0e(),FEt=l0e();g0e.exports={legacy:vEt,shades_classic:SEt,shades_grey:xEt,rect:FEt}});var h0e=N((shr,f0e)=>{h();var d0e=t0e(),kEt=n0e(),REt=p0e(),TEt=V4(),NEt=Y4(),MEt=q4(),PEt=$4();f0e.exports={Bar:d0e,SingleBar:d0e,MultiBar:kEt,Presets:REt,Format:{Formatter:TEt,BarFormat:MEt,ValueFormat:NEt,TimeFormat:PEt}}});var Q0e=N((Shr,y0e)=>{h();y0e.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var jbt={};wy(jbt,{default:()=>Jbt});module.exports=Wr(jbt);h();h();(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="1058b737-24de-4d5f-82e2-8f119dd3d19e",t._sentryDebugIdIdentifier="sentry-dbid-1058b737-24de-4d5f-82e2-8f119dd3d19e")}catch{}})();h();Bt();var eRe=require("../core/index.cjs"),tRe=require("../node/index.cjs"),rRe=require("../server/index.cjs"),nRe=z(cY(),1);h();h();var Ox=require("fs/promises");xk();kr();cI();rr();var Kr=z(Ir(),1),lm=require("node:path");Ns();Ls();hr();zr();kf();var KIt="https://cdn.builder.io",kwe=async(t,e)=>{console.log(""),sr((0,Kr.bgCyan)((0,Kr.bold)((0,Kr.white)(" figma migrate ")))+" "+(0,Kr.dim)(ht));let{builderPrivateKey:r,builderPublicKey:n}=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0});await Pt("figma publish started",{spaceId:n});let i=await AI(t);if(i.length>0){await Pt("figma migrate with existing files",{spaceId:n}),$.warning(`${(0,Kr.yellow)("This repo already has figma mappings in:")}
|
|
5101
|
+
Please set the BUILDER_PUBLIC_KEY environment variable.`);return{figmaAuth:A,builderPublicKey:o,builderPrivateKey:a,userId:s,spaceName:i}}if((r.requireFigmaAuth==="always"||!A&&r.requireFigmaAuth==="if-unset")&&(A=await UIt(t,r.silent?{silent:!0,onAuthStatus:r.onAuthStatus}:void 0),bx(t,{figmaAuth:A},n)),r.force||!a&&r.builderPrivateKey||!o&&r.builderPublicKey){let{privateKey:u,spaceId:l,spaceName:d,userId:g}=await GIt(t,r.forceSpaceId,r.silent?{silent:!0,onAuthStatus:r.onAuthStatus}:void 0);if(r.forceSpaceId&&l!==r.forceSpaceId)throw new Error(`OAuth flow returned space ${(0,Gl.yellow)(l)}, however the command specified --spaceId=${(0,Gl.green)(r.forceSpaceId)}`);o=l,a=u,i=d,s=g,await wz(s),await zo(t,t.getAppRootDir())&&!await LH(t,l,void 0,!1)&&!r.silent&&$.warn("Unable to set public api key in an existing .env file or create a new one. Please ensure you have write access in the current directory."),bx(t,{builderPublicKey:o,builderPrivateKey:a,spaceName:i,userId:s,timestamp:new Date().toISOString()},n)}return s?t.Sentry?.setUser({id:s,username:process.env.USER||process.env.USERNAME||"unknown"}):o&&t.Sentry?.setUser({id:o,username:process.env.USER||process.env.USERNAME||"unknown"}),(i||o)&&t.Sentry?.setContext("builder",{spaceId:o,spaceName:i,userId:s}),{figmaAuth:A,builderPublicKey:o,builderPrivateKey:a,spaceName:i,userId:s,timestamp:c}},_It="RHr2ed743waC2g2ZHMEJSn6O0NQ08L"});var Uwe=N((Efr,_we)=>{h();var OH=class{constructor(e,r,n){this.etaBufferLength=e||100,this.valueBuffer=[n],this.timeBuffer=[r],this.eta="0"}update(e,r,n){this.valueBuffer.push(r),this.timeBuffer.push(e),this.calculate(n-r)}getTime(){return this.eta}calculate(e){let r=this.valueBuffer.length,n=Math.min(this.etaBufferLength,r),i=this.valueBuffer[r-1]-this.valueBuffer[r-n],s=this.timeBuffer[r-1]-this.timeBuffer[r-n],o=i/s;this.valueBuffer=this.valueBuffer.slice(-this.etaBufferLength),this.timeBuffer=this.timeBuffer.slice(-this.etaBufferLength);let a=Math.ceil(e/o/1e3);isNaN(a)?this.eta="NULL":isFinite(a)?a>1e7?this.eta="INF":a<0?this.eta=0:this.eta=a:this.eta="INF"}};_we.exports=OH});var HH=N((yfr,Gwe)=>{h();var _p=require("readline"),KH=class{constructor(e){this.stream=e,this.linewrap=!0,this.dy=0}cursorSave(){this.stream.isTTY&&this.stream.write("\x1B7")}cursorRestore(){this.stream.isTTY&&this.stream.write("\x1B8")}cursor(e){this.stream.isTTY&&(e?this.stream.write("\x1B[?25h"):this.stream.write("\x1B[?25l"))}cursorTo(e=null,r=null){this.stream.isTTY&&_p.cursorTo(this.stream,e,r)}cursorRelative(e=null,r=null){this.stream.isTTY&&(this.dy=this.dy+r,_p.moveCursor(this.stream,e,r))}cursorRelativeReset(){this.stream.isTTY&&(_p.moveCursor(this.stream,0,-this.dy),_p.cursorTo(this.stream,0,null),this.dy=0)}clearRight(){this.stream.isTTY&&_p.clearLine(this.stream,1)}clearLine(){this.stream.isTTY&&_p.clearLine(this.stream,0)}clearBottom(){this.stream.isTTY&&_p.clearScreenDown(this.stream)}newline(){this.stream.write(`
|
|
5102
|
+
`),this.dy++}write(e,r=!1){this.linewrap===!0&&r===!1?this.stream.write(e.substr(0,this.getWidth())):this.stream.write(e)}lineWrapping(e){this.stream.isTTY&&(this.linewrap=e,e?this.stream.write("\x1B[?7h"):this.stream.write("\x1B[?7l"))}isTTY(){return this.stream.isTTY===!0}getWidth(){return this.stream.columns||(this.stream.isTTY?80:200)}};Gwe.exports=KH});var Kwe=N((Dfr,JH)=>{"use strict";h();var Owe=t=>Number.isNaN(t)?!1:t>=4352&&(t<=4447||t===9001||t===9002||11904<=t&&t<=12871&&t!==12351||12880<=t&&t<=19903||19968<=t&&t<=42182||43360<=t&&t<=43388||44032<=t&&t<=55203||63744<=t&&t<=64255||65040<=t&&t<=65049||65072<=t&&t<=65131||65281<=t&&t<=65376||65504<=t&&t<=65510||110592<=t&&t<=110593||127488<=t&&t<=127569||131072<=t&&t<=262141);JH.exports=Owe;JH.exports.default=Owe});var Jwe=N((bfr,Hwe)=>{"use strict";h();Hwe.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var Ywe=N((Sfr,jH)=>{"use strict";h();var uEt=sU(),lEt=Kwe(),gEt=Jwe(),jwe=t=>{if(typeof t!="string"||t.length===0||(t=uEt(t),t.length===0))return 0;t=t.replace(gEt()," ");let e=0;for(let r=0;r<t.length;r++){let n=t.codePointAt(r);n<=31||n>=127&&n<=159||n>=768&&n<=879||(n>65535&&r++,e+=lEt(n)?2:1)}return e};jH.exports=jwe;jH.exports.default=jwe});var YH=N((Ffr,qwe)=>{h();qwe.exports=function(e,r,n){if(r.autopadding!==!0)return e;function i(s,o){return(r.autopaddingChar+s).slice(-o)}return n==="percentage"?i(e,3):e}});var qH=N((Rfr,$we)=>{h();$we.exports=function(e,r){let n=Math.round(e*r.barsize),i=r.barsize-n;return r.barCompleteString.substr(0,n)+r.barGlue+r.barIncompleteString.substr(0,i)}});var $H=N((Nfr,Vwe)=>{h();Vwe.exports=function(e,r,n){function i(o){return n?n*Math.round(o/n):o}function s(o){return(r.autopaddingChar+o).slice(-2)}return e>3600?s(Math.floor(e/3600))+"h"+s(i(e%3600/60))+"m":e>60?s(Math.floor(e/60))+"m"+s(i(e%60))+"s":e>10?s(i(e))+"s":s(e)+"s"}});var VH=N((Pfr,Wwe)=>{h();var pEt=Ywe(),dEt=YH(),fEt=qH(),hEt=$H();Wwe.exports=function(e,r,n){let i=e.format,s=e.formatTime||hEt,o=e.formatValue||dEt,a=e.formatBar||fEt,A=Math.floor(r.progress*100)+"",c=r.stopTime||Date.now(),u=Math.round((c-r.startTime)/1e3),l=Object.assign({},n,{bar:a(r.progress,e),percentage:o(A,e,"percentage"),total:o(r.total,e,"total"),value:o(r.value,e,"value"),eta:o(r.eta,e,"eta"),eta_formatted:s(r.eta,e,5),duration:o(u,e,"duration"),duration_formatted:s(u,e,1)});i=i.replace(/\{(\w+)\}/g,function(p,f){return typeof l[f]<"u"?l[f]:p});let d=Math.max(0,r.maxWidth-pEt(i)-2),g=Math.floor(d/2);switch(e.align){case"right":i=d>0?" ".repeat(d)+i:i;break;case"center":i=g>0?" ".repeat(g)+i:i;break;default:break}return i}});var Kx=N((_fr,zwe)=>{h();function Cr(t,e){return typeof t>"u"||t===null?e:t}zwe.exports={parse:function(e,r){let n={},i=Object.assign({},r,e);return n.throttleTime=1e3/Cr(i.fps,10),n.stream=Cr(i.stream,process.stderr),n.terminal=Cr(i.terminal,null),n.clearOnComplete=Cr(i.clearOnComplete,!1),n.stopOnComplete=Cr(i.stopOnComplete,!1),n.barsize=Cr(i.barsize,40),n.align=Cr(i.align,"left"),n.hideCursor=Cr(i.hideCursor,!1),n.linewrap=Cr(i.linewrap,!1),n.barGlue=Cr(i.barGlue,""),n.barCompleteChar=Cr(i.barCompleteChar,"="),n.barIncompleteChar=Cr(i.barIncompleteChar,"-"),n.format=Cr(i.format,"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}"),n.formatTime=Cr(i.formatTime,null),n.formatValue=Cr(i.formatValue,null),n.formatBar=Cr(i.formatBar,null),n.etaBufferLength=Cr(i.etaBuffer,10),n.etaAsynchronousUpdate=Cr(i.etaAsynchronousUpdate,!1),n.progressCalculationRelative=Cr(i.progressCalculationRelative,!1),n.synchronousUpdate=Cr(i.synchronousUpdate,!0),n.noTTYOutput=Cr(i.noTTYOutput,!1),n.notTTYSchedule=Cr(i.notTTYSchedule,2e3),n.emptyOnZero=Cr(i.emptyOnZero,!1),n.forceRedraw=Cr(i.forceRedraw,!1),n.autopadding=Cr(i.autopadding,!1),n.gracefulExit=Cr(i.gracefulExit,!1),n},assignDerivedOptions:function(e){return e.barCompleteString=e.barCompleteChar.repeat(e.barsize+1),e.barIncompleteString=e.barIncompleteChar.repeat(e.barsize+1),e.autopaddingChar=e.autopadding?Cr(e.autopaddingChar," "):"",e}}});var WH=N((Ofr,Zwe)=>{h();var Xwe=Uwe(),mEt=HH(),CEt=VH(),IEt=Kx(),EEt=require("events");Zwe.exports=class extends EEt{constructor(e){super(),this.options=IEt.assignDerivedOptions(e),this.terminal=this.options.terminal?this.options.terminal:new mEt(this.options.stream),this.value=0,this.startValue=0,this.total=100,this.lastDrawnString=null,this.startTime=null,this.stopTime=null,this.lastRedraw=Date.now(),this.eta=new Xwe(this.options.etaBufferLength,0,0),this.payload={},this.isActive=!1,this.formatter=typeof this.options.format=="function"?this.options.format:CEt}render(e=!1){let r={progress:this.getProgress(),eta:this.eta.getTime(),startTime:this.startTime,stopTime:this.stopTime,total:this.total,value:this.value,maxWidth:this.terminal.getWidth()};this.options.etaAsynchronousUpdate&&this.updateETA();let n=this.formatter(this.options,r,this.payload);(e||this.options.forceRedraw||this.options.noTTYOutput&&!this.terminal.isTTY()||this.lastDrawnString!=n)&&(this.emit("redraw-pre"),this.terminal.cursorTo(0,null),this.terminal.write(n),this.terminal.clearRight(),this.lastDrawnString=n,this.lastRedraw=Date.now(),this.emit("redraw-post"))}start(e,r,n){this.value=r||0,this.total=typeof e<"u"&&e>=0?e:100,this.startValue=r||0,this.payload=n||{},this.startTime=Date.now(),this.stopTime=null,this.lastDrawnString="",this.eta=new Xwe(this.options.etaBufferLength,this.startTime,this.value),this.isActive=!0,this.emit("start",e,r)}stop(){this.isActive=!1,this.stopTime=Date.now(),this.emit("stop",this.total,this.value)}update(e,r={}){typeof e=="number"&&(this.value=e,this.eta.update(Date.now(),e,this.total));let n=(typeof e=="object"?e:r)||{};this.emit("update",this.total,this.value);for(let i in n)this.payload[i]=n[i];this.value>=this.getTotal()&&this.options.stopOnComplete&&this.stop()}getProgress(){let e=this.value/this.total;return this.options.progressCalculationRelative&&(e=(this.value-this.startValue)/(this.total-this.startValue)),isNaN(e)&&(e=this.options&&this.options.emptyOnZero?0:1),e=Math.min(Math.max(e,0),1),e}increment(e=1,r={}){typeof e=="object"?this.update(this.value+1,e):this.update(this.value+e,r)}getTotal(){return this.total}setTotal(e){typeof e<"u"&&e>=0&&(this.total=e)}updateETA(){this.eta.update(Date.now(),this.value,this.total)}}});var t0e=N((Jfr,e0e)=>{h();var BEt=WH(),yEt=Kx();e0e.exports=class extends BEt{constructor(e,r){super(yEt.parse(e,r)),this.timer=null,this.options.noTTYOutput&&this.terminal.isTTY()===!1&&(this.options.synchronousUpdate=!1),this.schedulingRate=this.terminal.isTTY()?this.options.throttleTime:this.options.notTTYSchedule,this.sigintCallback=null}render(){this.timer&&(clearTimeout(this.timer),this.timer=null),super.render(),this.options.noTTYOutput&&this.terminal.isTTY()===!1&&this.terminal.newline(),this.timer=setTimeout(this.render.bind(this),this.schedulingRate)}update(e,r){this.timer&&(super.update(e,r),this.options.synchronousUpdate&&this.lastRedraw+this.options.throttleTime*2<Date.now()&&this.render())}start(e,r,n){this.options.noTTYOutput===!1&&this.terminal.isTTY()===!1||(this.sigintCallback===null&&this.options.gracefulExit&&(this.sigintCallback=this.stop.bind(this),process.once("SIGINT",this.sigintCallback),process.once("SIGTERM",this.sigintCallback)),this.terminal.cursorSave(),this.options.hideCursor===!0&&this.terminal.cursor(!1),this.options.linewrap===!1&&this.terminal.lineWrapping(!1),super.start(e,r,n),this.render())}stop(){this.timer&&(this.sigintCallback&&(process.removeListener("SIGINT",this.sigintCallback),process.removeListener("SIGTERM",this.sigintCallback),this.sigintCallback=null),this.render(),super.stop(),clearTimeout(this.timer),this.timer=null,this.options.hideCursor===!0&&this.terminal.cursor(!0),this.options.linewrap===!1&&this.terminal.lineWrapping(!0),this.terminal.cursorRestore(),this.options.clearOnComplete?(this.terminal.cursorTo(0,null),this.terminal.clearLine()):this.terminal.newline())}}});var n0e=N((qfr,r0e)=>{h();var QEt=HH(),DEt=WH(),wEt=Kx(),bEt=require("events");r0e.exports=class extends bEt{constructor(e,r){super(),this.bars=[],this.options=wEt.parse(e,r),this.options.synchronousUpdate=!1,this.terminal=this.options.terminal?this.options.terminal:new QEt(this.options.stream),this.timer=null,this.isActive=!1,this.schedulingRate=this.terminal.isTTY()?this.options.throttleTime:this.options.notTTYSchedule,this.loggingBuffer=[],this.sigintCallback=null}create(e,r,n,i={}){let s=new DEt(Object.assign({},this.options,{terminal:this.terminal},i));return this.bars.push(s),this.options.noTTYOutput===!1&&this.terminal.isTTY()===!1||(this.sigintCallback===null&&this.options.gracefulExit&&(this.sigintCallback=this.stop.bind(this),process.once("SIGINT",this.sigintCallback),process.once("SIGTERM",this.sigintCallback)),this.isActive||(this.options.hideCursor===!0&&this.terminal.cursor(!1),this.options.linewrap===!1&&this.terminal.lineWrapping(!1),this.timer=setTimeout(this.update.bind(this),this.schedulingRate)),this.isActive=!0,s.start(e,r,n),this.emit("start")),s}remove(e){let r=this.bars.indexOf(e);return r<0?!1:(this.bars.splice(r,1),this.update(),this.terminal.newline(),this.terminal.clearBottom(),!0)}update(){if(this.timer&&(clearTimeout(this.timer),this.timer=null),this.emit("update-pre"),this.terminal.cursorRelativeReset(),this.emit("redraw-pre"),this.loggingBuffer.length>0)for(this.terminal.clearLine();this.loggingBuffer.length>0;)this.terminal.write(this.loggingBuffer.shift(),!0);for(let e=0;e<this.bars.length;e++)e>0&&this.terminal.newline(),this.bars[e].render();this.emit("redraw-post"),this.options.noTTYOutput&&this.terminal.isTTY()===!1&&(this.terminal.newline(),this.terminal.newline()),this.timer=setTimeout(this.update.bind(this),this.schedulingRate),this.emit("update-post"),this.options.stopOnComplete&&!this.bars.find(e=>e.isActive)&&this.stop()}stop(){if(clearTimeout(this.timer),this.timer=null,this.sigintCallback&&(process.removeListener("SIGINT",this.sigintCallback),process.removeListener("SIGTERM",this.sigintCallback),this.sigintCallback=null),this.isActive=!1,this.options.hideCursor===!0&&this.terminal.cursor(!0),this.options.linewrap===!1&&this.terminal.lineWrapping(!0),this.terminal.cursorRelativeReset(),this.emit("stop-pre-clear"),this.options.clearOnComplete)this.terminal.clearBottom();else{for(let e=0;e<this.bars.length;e++)e>0&&this.terminal.newline(),this.bars[e].render(),this.bars[e].stop();this.terminal.newline()}this.emit("stop")}log(e){this.loggingBuffer.push(e)}}});var s0e=N((Vfr,i0e)=>{h();i0e.exports={format:"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"=",barIncompleteChar:"-"}});var a0e=N((zfr,o0e)=>{h();o0e.exports={format:" {bar} {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var c0e=N((Zfr,A0e)=>{h();A0e.exports={format:" \x1B[90m{bar}\x1B[0m {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var l0e=N((thr,u0e)=>{h();u0e.exports={format:" {bar}\u25A0 {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u25A0",barIncompleteChar:" "}});var p0e=N((nhr,g0e)=>{h();var vEt=s0e(),SEt=a0e(),xEt=c0e(),FEt=l0e();g0e.exports={legacy:vEt,shades_classic:SEt,shades_grey:xEt,rect:FEt}});var h0e=N((shr,f0e)=>{h();var d0e=t0e(),kEt=n0e(),REt=p0e(),TEt=VH(),NEt=YH(),MEt=qH(),PEt=$H();f0e.exports={Bar:d0e,SingleBar:d0e,MultiBar:kEt,Presets:REt,Format:{Formatter:TEt,BarFormat:MEt,ValueFormat:NEt,TimeFormat:PEt}}});var Q0e=N((Shr,y0e)=>{h();y0e.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var jbt={};wy(jbt,{default:()=>Jbt});module.exports=Wr(jbt);h();h();(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="d846de74-8420-4c8d-a250-fd7e5dd5feb6",t._sentryDebugIdIdentifier="sentry-dbid-d846de74-8420-4c8d-a250-fd7e5dd5feb6")}catch{}})();h();Bt();var eRe=require("../core/index.cjs"),tRe=require("../node/index.cjs"),rRe=require("../server/index.cjs"),nRe=z(cY(),1);h();h();var Ox=require("fs/promises");xk();kr();cI();rr();var Kr=z(Ir(),1),lm=require("node:path");Ns();Ls();hr();zr();kf();var KIt="https://cdn.builder.io",kwe=async(t,e)=>{console.log(""),sr((0,Kr.bgCyan)((0,Kr.bold)((0,Kr.white)(" figma migrate ")))+" "+(0,Kr.dim)(ht));let{builderPrivateKey:r,builderPublicKey:n}=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0});await Pt("figma publish started",{spaceId:n});let i=await AI(t);if(i.length>0){await Pt("figma migrate with existing files",{spaceId:n}),$.warning(`${(0,Kr.yellow)("This repo already has figma mappings in:")}
|
|
5103
5103
|
|
|
5104
5104
|
${i.map(c=>` - ${(0,lm.relative)(t.getAppRootDir(),c)}`).join(`
|
|
5105
5105
|
`)}
|
|
@@ -5117,7 +5117,7 @@ Migration is going to create new files, possibly duplicates.`);let A=await wr({m
|
|
|
5117
5117
|
`):Fwe(e);return ZA(t.getAppRootDir(),`import { figmaMapping } from '@builder.io/dev-tools/figma';
|
|
5118
5118
|
${o}
|
|
5119
5119
|
|
|
5120
|
-
${s}`,"typescript",void 0)}function Fwe(t){let{importName:e,importPath:r}=t,n="importType"in t?t.importType:t.exportType;if(e&&r){let i=JSON.stringify(r);return n==="named"?`import { ${e} } from ${i};`:`import ${e} from ${i};`}return""}cI();kr();GB();var jo=z(Ir(),1);rr();rr();Ns();bi();Ls();zr();h();kf();kr();
|
|
5120
|
+
${s}`,"typescript",void 0)}function Fwe(t){let{importName:e,importPath:r}=t,n="importType"in t?t.importType:t.exportType;if(e&&r){let i=JSON.stringify(r);return n==="named"?`import { ${e} } from ${i};`:`import ${e} from ${i};`}return""}cI();kr();GB();var jo=z(Ir(),1);rr();rr();Ns();bi();Ls();zr();h();kf();kr();NH();var ns=z(require("fs/promises"),1),rs=z(require("node:path"),1);var Rwe=`# Creating mappings for Vue
|
|
5121
5121
|
|
|
5122
5122
|
Component mappings in Vue involve creating \`.mapper.ts\` files that connect Figma components to your Vue code components. These mappings define how Figma component properties translate to Vue component props.
|
|
5123
5123
|
|
|
@@ -6740,7 +6740,7 @@ The \`figma\` variable allows to access the state of the figma components:
|
|
|
6740
6740
|
...
|
|
6741
6741
|
|
|
6742
6742
|
Check out the API reference for more in \`./figma-api-reference.md\`.
|
|
6743
|
-
`;rr();zr();var Ol=z(Ir(),1);Ml();xt();function VIt(t){let e=t.match(/team\/(\d+)/),r=
|
|
6743
|
+
`;rr();zr();var Ol=z(Ir(),1);Ml();xt();function VIt(t){let e=t.match(/team\/(\d+)/),r=TH(t);if(r)return{teamId:void 0,fileKey:r.fileID,nodeId:r.nodeId};let n=t.match(/(?:file|design)\/([a-zA-Z0-9]+)/);return{teamId:e?.[1],fileKey:n?.[1],nodeId:void 0}}async function WIt(t,e,r){let{sys:n,args:i,figmaAuth:s,debug:o}=t,a=[],A=!0,c;for($.info(`Extracting components and component sets for team ${e}`);A;){let u={page_size:100};c&&(u.after=c),o({url:`teams/${e}/components`,params:u}),r();let l=await ru(n,i,`teams/${e}/components`,{auth:s,params:u}),{meta:{components:d,cursor:g}}=l;d.push(...d),g?c=g.after:A=!1}return a}async function zIt(t,e,r){let{sys:n,args:i,figmaAuth:s,debug:o}=t,a=[],A=!0,c;for($.info(`Extracting component sets for team ${e}`);A;){let u={page_size:100};c&&(u.after=c),o({url:`teams/${e}/component_sets`,params:u}),r();let l=await ru(n,i,`teams/${e}/component_sets`,{auth:s,params:u}),{meta:{component_sets:d,cursor:g}}=l;a.push(...d),g?c=g.after:A=!1}return a}async function XIt(t,e,r){let{sys:n,args:i,figmaAuth:s,debug:o}=t,a,A;if(r){A=`files/${e}/nodes`;let b=await ru(n,i,A,{auth:s,params:{ids:r}});a=Object.assign({name:b.name,thumbnailUrl:b.thumbnailUrl,role:b.role,lastModified:b.lastModified},b.nodes[r])}else A=`files/${e}`,a=await ru(n,i,A,{auth:s});let{components:c,componentSets:u}=a,l=new Map;for(let[b,x]of Object.entries(c))l.set(x,b);for(let[b,x]of Object.entries(u))l.set(x,b);let d=0,g=0,p=new Set;for(let[b,x]of Object.entries(a.componentSets))p.add(b),x.remote&&g++;let f=[],m=new Map;for(let[b,x]of Object.entries(a.components))x.componentSetId?p.has(x.componentSetId)&&m.set(x.key,x.componentSetId):(f.push(x),x.remote&&d++);$.info(`Name: ${a.name}${r?`
|
|
6744
6744
|
Selection: ${r}`:""}
|
|
6745
6745
|
Last Modified: ${a.lastModified}
|
|
6746
6746
|
Role: ${a.role}
|
|
@@ -6801,7 +6801,7 @@ Processed ${d.length} components${m>0?`
|
|
|
6801
6801
|
Skipped ${m} components
|
|
6802
6802
|
- ${g.length} empty (no inputs and no JSX)
|
|
6803
6803
|
- ${p.length} hidden (name starts with _ or .)`:""}`)};function AEt(t){return t.name.startsWith("_")||t.name.startsWith(".")}function cEt(t){return t?t.inputs.length===0&&t.jsx==="":!0}var Lwe=async(t,e,r)=>{if(e==="migrate")await kwe(t,r);else if(e==="publish"||e==="p")await Dwe(t,r);else{if(e==="add"||e==="generate"||e==="gen"||e==="g")return Ke(`The 'figma generate' command has been removed. You can create mapper files manually.
|
|
6804
|
-
See: https://www.builder.io/c/docs/mapping-functions`),await Me(1);if(e==="report")await Pwe(t,r);else if(e==="auth"){console.log(""),sr((0,jo.bgCyan)((0,jo.bold)((0,jo.white)(" figma auth ")))+" "+(0,jo.dim)(ht));let{builderPublicKey:n}=await Wt(t,r,{requireFigmaAuth:"always",builderPrivateKey:!0,builderPublicKey:!0,force:!0});await Pt("figma auth",{spaceId:n}),Cn((0,jo.bgGreen)((0,jo.bold)((0,jo.white)(" Done! \u{1F389} "))))}else e==="help"&&Zc(r._[2]||"figma")}};rr();xi();xt();mL();h();function
|
|
6804
|
+
See: https://www.builder.io/c/docs/mapping-functions`),await Me(1);if(e==="report")await Pwe(t,r);else if(e==="auth"){console.log(""),sr((0,jo.bgCyan)((0,jo.bold)((0,jo.white)(" figma auth ")))+" "+(0,jo.dim)(ht));let{builderPublicKey:n}=await Wt(t,r,{requireFigmaAuth:"always",builderPrivateKey:!0,builderPublicKey:!0,force:!0});await Pt("figma auth",{spaceId:n}),Cn((0,jo.bgGreen)((0,jo.bold)((0,jo.white)(" Done! \u{1F389} "))))}else e==="help"&&Zc(r._[2]||"figma")}};rr();xi();xt();mL();h();function GH(t,e){return{cwd:t,command:e[0],snippetId:e[1],path:e[2]}}Cp();Ns();Ls();GB();Rx();nH();var Wl=z(Ir(),1);zr();kr();h();var Op=z(require("@sentry/node"),1);Bt();var La=z(Ir(),1);rr();kr();yr();var Xx=z(require("node:crypto"),1);hr();zr();Hs();Hs();var sJ=z(h0e(),1);h();h();h();h();function zH({onlyFirst:t=!1}={}){let i="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(i,t?void 0:"g")}var LEt=zH();function WB(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return!t.includes("\x1B")&&!t.includes("\x9B")?t:t.replace(LEt,"")}h();h();h();var Hx=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Jx=[12288,12288,65281,65376,65504,65510],XH=[8361,8361,65377,65470,65474,65479,65482,65487,65490,65495,65498,65500,65512,65518],ZH=[32,126,162,163,165,166,172,172,175,175,10214,10221,10629,10630],zB=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];h();var jx=(t,e)=>{let r=0,n=Math.floor(t.length/2)-1;for(;r<=n;){let i=Math.floor((r+n)/2),s=i*2;if(e<t[s])n=i-1;else if(e>t[s+1])r=i+1;else return!0}return!1};var _Et=Hx[0],UEt=Hx.at(-1),GEt=Jx[0],OEt=Jx.at(-1),Chr=XH[0],Ihr=XH.at(-1),Ehr=ZH[0],Bhr=ZH.at(-1),KEt=zB[0],HEt=zB.at(-1),m0e=19968,[JEt,jEt]=YEt(zB);function YEt(t){let e=t[0],r=t[1];for(let n=0;n<t.length;n+=2){let i=t[n],s=t[n+1];if(m0e>=i&&m0e<=s)return[i,s];s-i>r-e&&(e=i,r=s)}return[e,r]}var C0e=t=>t<_Et||t>UEt?!1:jx(Hx,t),I0e=t=>t<GEt||t>OEt?!1:jx(Jx,t);var E0e=t=>t>=JEt&&t<=jEt?!0:t<KEt||t>HEt?!1:jx(zB,t);function qEt(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function B0e(t,{ambiguousAsWide:e=!1}={}){return qEt(t),I0e(t)||E0e(t)||e&&C0e(t)?2:1}var D0e=z(Q0e(),1),$Et=new Intl.Segmenter,VEt=/^\p{Default_Ignorable_Code_Point}$/u;function Up(t,e={}){if(typeof t!="string"||t.length===0)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:n=!1}=e;if(n||(t=WB(t)),t.length===0)return 0;let i=0,s={ambiguousAsWide:!r};for(let{segment:o}of $Et.segment(t)){let a=o.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!VEt.test(o)){if((0,D0e.default)().test(o)){i+=2;continue}i+=B0e(a,s)}}return i}h();var w0e=(t=0)=>e=>`\x1B[${e+t}m`,b0e=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,v0e=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`,Hr={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Nhr=Object.keys(Hr.modifier),WEt=Object.keys(Hr.color),zEt=Object.keys(Hr.bgColor),Mhr=[...WEt,...zEt];function XEt(){let t=new Map;for(let[e,r]of Object.entries(Hr)){for(let[n,i]of Object.entries(r))Hr[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Hr[n],t.set(i[0],i[1]);Object.defineProperty(Hr,e,{value:r,enumerable:!1})}return Object.defineProperty(Hr,"codes",{value:t,enumerable:!1}),Hr.color.close="\x1B[39m",Hr.bgColor.close="\x1B[49m",Hr.color.ansi=w0e(),Hr.color.ansi256=b0e(),Hr.color.ansi16m=v0e(),Hr.bgColor.ansi=w0e(10),Hr.bgColor.ansi256=b0e(10),Hr.bgColor.ansi16m=v0e(10),Object.defineProperties(Hr,{rgbToAnsi256:{value(e,r,n){return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[n]=r;n.length===3&&(n=[...n].map(s=>s+s).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:e=>Hr.rgbToAnsi256(...Hr.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,n,i;if(e>=232)r=((e-232)*10+8)/255,n=r,i=r;else{e-=16;let a=e%36;r=Math.floor(e/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let s=Math.max(r,n,i)*2;if(s===0)return 30;let o=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(r));return s===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,r,n)=>Hr.ansi256ToAnsi(Hr.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>Hr.ansi256ToAnsi(Hr.hexToAnsi256(e)),enumerable:!1}}),Hr}var ZEt=XEt(),S0e=ZEt;var qx=new Set(["\x1B","\x9B"]),eBt=39,tJ="\x07",k0e="[",tBt="]",R0e="m",Yx=`${tBt}8;;`,x0e=t=>`${qx.values().next().value}${k0e}${t}${R0e}`,F0e=t=>`${qx.values().next().value}${Yx}${t}${tJ}`,rBt=t=>t.split(" ").map(e=>Up(e)),eJ=(t,e,r)=>{let n=[...e],i=!1,s=!1,o=Up(WB(t.at(-1)));for(let[a,A]of n.entries()){let c=Up(A);if(o+c<=r?t[t.length-1]+=A:(t.push(A),o=0),qx.has(A)&&(i=!0,s=n.slice(a+1,a+1+Yx.length).join("")===Yx),i){s?A===tJ&&(i=!1,s=!1):A===R0e&&(i=!1);continue}o+=c,o===r&&a<n.length-1&&(t.push(""),o=0)}!o&&t.at(-1).length>0&&t.length>1&&(t[t.length-2]+=t.pop())},nBt=t=>{let e=t.split(" "),r=e.length;for(;r>0&&!(Up(e[r-1])>0);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},iBt=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",i,s,o=rBt(t),a=[""];for(let[l,d]of t.split(" ").entries()){r.trim!==!1&&(a[a.length-1]=a.at(-1).trimStart());let g=Up(a.at(-1));if(l!==0&&(g>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),g=0),(g>0||r.trim===!1)&&(a[a.length-1]+=" ",g++)),r.hard&&o[l]>e){let p=e-g,f=1+Math.floor((o[l]-p-1)/e);Math.floor((o[l]-1)/e)<f&&a.push(""),eJ(a,d,e);continue}if(g+o[l]>e&&g>0&&o[l]>0){if(r.wordWrap===!1&&g<e){eJ(a,d,e);continue}a.push("")}if(g+o[l]>e&&r.wordWrap===!1){eJ(a,d,e);continue}a[a.length-1]+=d}r.trim!==!1&&(a=a.map(l=>nBt(l)));let A=a.join(`
|
|
6805
6805
|
`),c=[...A],u=0;for(let[l,d]of c.entries()){if(n+=d,qx.has(d)){let{groups:p}=new RegExp(`(?:\\${k0e}(?<code>\\d+)m|\\${Yx}(?<uri>.*)${tJ})`).exec(A.slice(u))||{groups:{}};if(p.code!==void 0){let f=Number.parseFloat(p.code);i=f===eBt?void 0:f}else p.uri!==void 0&&(s=p.uri.length===0?void 0:p.uri)}let g=S0e.codes.get(Number(i));c[l+1]===`
|
|
6806
6806
|
`?(s&&(n+=F0e("")),i&&g&&(n+=x0e(g))):d===`
|
|
6807
6807
|
`&&(i&&g&&(n+=x0e(i)),s&&(n+=F0e(s))),u+=d.length}return n};function XB(t,e,r){return String(t).normalize().replaceAll(`\r
|
|
@@ -7249,7 +7249,7 @@ This design system provides an icon library. A list of icons available as well a
|
|
|
7249
7249
|
## Design Tokens
|
|
7250
7250
|
|
|
7251
7251
|
This design system provides design tokens. A list of tokens available as well as token usage examples can be found in \`design-system-docs/*-${HB}\`.
|
|
7252
|
-
`,c=$0e.replaceAll("{{COMPONENTS}}",o).replaceAll("{{ICONS}}",n.hasIcons?a:"").replaceAll("{{TOKENS}}",n.hasDesignTokens?A:"");try{let u={type:"agent",name:
|
|
7252
|
+
`,c=$0e.replaceAll("{{COMPONENTS}}",o).replaceAll("{{ICONS}}",n.hasIcons?a:"").replaceAll("{{TOKENS}}",n.hasDesignTokens?A:"");try{let u={type:"agent",name:CH,description:"Repository agent documentation",content:c,designSystemId:n.designSystemId,rawComponents:s.map(l=>({name:l.name,description:l.description})),rawTokenGroups:n.discoveredTokenGroups};await Ss(e,u,i)}catch(u){throw new dt("Failed to store agent docs",{cause:u})}},z0e=async(t,e,r)=>{let n=new Set(e.map(s=>s.name)),i=r.filter(s=>!n.has(s.name));i.length>0&&await dBt(t,i.map(s=>s.id))},dBt=async(t,e)=>{let r=new URL("/mappings/deprecate-component-docs",Ne);r.searchParams.set("apiKey",t.builderPublicKey),r.searchParams.set("userId",t.userId);let n=await Fe(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`},body:JSON.stringify(e)});if(!n.ok){let i=await n.text();throw pBt.error("API request failed:",n.status,i),new Error(`Failed to mark component as deprecated: ${n.status} ${i}`)}};JA();var sbe=require("node:path");xi();Ls();h();var Z0e=require("node:child_process"),ebe=require("util"),tbe=require("node:path"),X0e=(0,ebe.promisify)(Z0e.exec);async function gm(t){let e=t.cwd(),r;try{let{stdout:a}=await X0e("git rev-parse --show-toplevel",{cwd:e});r=a.trim()}catch{return}let n=(0,tbe.relative)(r,e),i=n?`./${n}`:"./",s;try{let{stdout:a}=await X0e("git remote get-url origin",{cwd:e});s=a.trim()}catch{return}let o=fBt(s);return{gitRoot:r,recommendedRoot:i==="./"?void 0:i,originUrl:s,...o}}function fBt(t){let e=t.startsWith("git@")||t.startsWith("ssh://")?"ssh":"https",r="custom",n="",i="",s="",o=!0,a=t.replace(/^git@/,"").replace(/^https?:\/\//,"").replace(/^ssh:\/\//,"").replace(/\.git$/,"");if(a.includes("github.com")){r="github";let c=a.match(/github\.com[:/]([^/]+)\/(.+)/);c&&(i=c[1],s=c[2].replace(/\.git$/,""),n=`${i}/${s}`)}else if(a.includes("gitlab.com")){r="gitlab";let c=a.match(/gitlab\.com[:/]([^/]+)\/(.+)/);c&&(i=c[1],s=c[2].replace(/\.git$/,""),n=`${i}/${s}`)}else if(a.includes("bitbucket.org")){r="bitbucket";let c=a.match(/bitbucket\.org[:/]([^/]+)\/(.+)/);c&&(i=c[1],s=c[2].replace(/\.git$/,""),n=`${i}/${s}`)}else if(a.includes("dev.azure.com")||a.includes("visualstudio.com")){r="azure";let c=a.match(/dev\.azure\.com[:/]([^/]+)\/([^/]+)\/_git\/(.+)/);c&&(i=c[1],s=c[3].replace(/\.git$/,""),n=`${c[1]}/${c[2]}/${s}`)}else{r="custom";let c=a.split(/[:/]/);c.length>=2&&(i=c[c.length-2],s=c[c.length-1].replace(/\.git$/,""),n=`${i}/${s}`)}let A=s.replace(/[^a-zA-Z0-9-_]/g,"-");return{repoProvider:r,repoProtocol:e,repoFullName:n,repoOwner:i,repoName:s,isPrivate:o,projectName:A}}function rbe(t){let e=[];return e.push(`Repository root: ${t.gitRoot}`),t.recommendedRoot&&t.recommendedRoot!=="./"&&e.push(`Current path: ${t.recommendedRoot} (monorepo detected)`),e.push(`Git origin: ${t.originUrl}`),e.push(`Provider: ${t.repoProvider.charAt(0).toUpperCase()+t.repoProvider.slice(1)}`),e.push(`Repository: ${t.repoFullName}`),e.push(`Status: ${t.isPrivate?"Private":"Public"} repository`),e}gw();NB();var nu=ve("RepoIndexing"),ZB=8,Wx="Done \u2713";async function nbe(t,e,r){let n=is();n.start("Creating fusion example project..."),await Pt("fusion example project creation started",{designSystemName:e,userId:t.userId,spaceId:t.builderPublicKey});try{let i=`${e} Example`,s={name:i,repoFullName:yf,repoProvider:"github",repoUrl:`https://github.com/${yf}`,repoPrivate:!1,isExample:!0,settings:{installCommand:"npm install",devServerCommand:"npm run dev",devServerUrl:"http://localhost:8080",designSystems:[e]}},o="main",a={name:o,friendlyName:o,createdBy:t.userId,isDefault:!0,isPublic:!1},A=new URL("/projects",Ne);A.searchParams.set("apiKey",t.builderPublicKey),A.searchParams.set("userId",t.userId);let c=await Fe(A,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`},body:JSON.stringify({...s,branchData:a})});if(!c.ok){let I=await c.text();throw new Error(`Failed to create project: ${I}`)}let l=(await c.json()).project.id;n.stop(),$.success(`\u2713 Fusion project created: ${i}`),n.start("Spawning background agent to install design system...");let d=`Install the design system "${e}" in this project.
|
|
7253
7253
|
|
|
7254
7254
|
The design system is already attached to this project. Use the installation.md document from the attached design system to follow the installation instructions.
|
|
7255
7255
|
|
|
@@ -7276,11 +7276,11 @@ ${u.join(", ")}
|
|
|
7276
7276
|
Re-run your command and try again. If this problem persists, please contact us at support@builder.io.`,$.warn(E);return}$.info(`Add "${s}" to your "builder.config.json" file to use your design system with code generation.
|
|
7277
7277
|
|
|
7278
7278
|
Learn more at https://www.builder.io/c/docs/component-indexing#generating-code.
|
|
7279
|
-
`)},oJ=async(t,e)=>{let{designSystemPackage:r,skipDetailedGrouping:n,force:i,skipHeader:s,listIndexedRepos:o,components:a,include:A,exclude:c,instructions:u,uploadCustomDocs:l}=e,{designSystemName:d}=e,g=J=>!t.existsSync(J)||!t.statSync(J).isDirectory()?($.error(`Directory ${J} does not exist. Please provide a valid directory.`),!1):!0,p=Date.now();Op.getCurrentScope().setTag("operation","repo-indexing"),Op.getCurrentScope().setTag("designSystemPackage",r||"none"),s||(console.log(),sr((0,La.bgCyan)((0,La.bold)((0,La.white)(" repository indexing ")))+" "+(0,La.dim)(ht)));let f=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0}),m=await Fl(t,e),C=await T0e(f);if(o){let J=await om(f);if(J.length===0){console.log("No indexed repositories found");return}console.log("Indexed repositories:"),J.forEach((_,K)=>{console.log(`${K+1}. ${_.designSystemName}`)});return}if(e.testFusionExample){let J=d;if(!J){let _=await om(f);if(_.length===0){$.error("No indexed design systems found. Please index a design system first.");return}let K=await wi({message:"Select a design system to test fusion example project creation:",options:_.map(j=>({value:j.designSystemName,label:j.designSystemName}))});if(je(K)){Ke("Test cancelled");return}J=K}await nbe(f,J,e);return}let I=Xx.default.randomUUID().slice(0,8);Op.getCurrentScope().setTag("sessionId",I);try{let J=await BBt(f,e.debug);J.isAllowed||($.error(`Error: ${J.reason||"Access denied for repository indexing"}`),process.exit(1))}catch(J){if(J instanceof qe){Zr(J);return}$.error("Error: We were unable to determine if your subscription is an enterprise subscription. Contact support@builder.io for more information."),process.exit(1)}let y={folders:[{path:t.getCwdDir()}]};e.includeDirectories&&e.includeDirectories.split(",").forEach(_=>{let K=_.trim();K.length>0&&(g(K)||process.exit(1),y.folders.push({path:K}))}),e.addDirectory&&(Array.isArray(e.addDirectory)?e.addDirectory:[e.addDirectory]).forEach(_=>{let K=_.trim();K.length>0&&(g(K)||process.exit(1),y.folders.push({path:K}))});let B=await PDe(t,r),E=B.version,Q=B.name,v=await om(f,{onlyEditAccess:!0}),D,S;try{if(d===void 0){let J=[...v.map(K=>({value:K.id,label:K.designSystemName+" ("+K.scope+")"+(e.debug?` - ${K.id}`:"")}))],_="new";if(J.length>0&&(_=await wi({message:"Which design system would you like to index? You can bypass this by re-running this command with the --designSystemName flag.",options:[...J,{value:"new",label:"Create a new design system"}]}),je(_)))return;if(_==="new"){let K=await
|
|
7279
|
+
`)},oJ=async(t,e)=>{let{designSystemPackage:r,skipDetailedGrouping:n,force:i,skipHeader:s,listIndexedRepos:o,components:a,include:A,exclude:c,instructions:u,uploadCustomDocs:l}=e,{designSystemName:d}=e,g=J=>!t.existsSync(J)||!t.statSync(J).isDirectory()?($.error(`Directory ${J} does not exist. Please provide a valid directory.`),!1):!0,p=Date.now();Op.getCurrentScope().setTag("operation","repo-indexing"),Op.getCurrentScope().setTag("designSystemPackage",r||"none"),s||(console.log(),sr((0,La.bgCyan)((0,La.bold)((0,La.white)(" repository indexing ")))+" "+(0,La.dim)(ht)));let f=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0}),m=await Fl(t,e),C=await T0e(f);if(o){let J=await om(f);if(J.length===0){console.log("No indexed repositories found");return}console.log("Indexed repositories:"),J.forEach((_,K)=>{console.log(`${K+1}. ${_.designSystemName}`)});return}if(e.testFusionExample){let J=d;if(!J){let _=await om(f);if(_.length===0){$.error("No indexed design systems found. Please index a design system first.");return}let K=await wi({message:"Select a design system to test fusion example project creation:",options:_.map(j=>({value:j.designSystemName,label:j.designSystemName}))});if(je(K)){Ke("Test cancelled");return}J=K}await nbe(f,J,e);return}let I=Xx.default.randomUUID().slice(0,8);Op.getCurrentScope().setTag("sessionId",I);try{let J=await BBt(f,e.debug);J.isAllowed||($.error(`Error: ${J.reason||"Access denied for repository indexing"}`),process.exit(1))}catch(J){if(J instanceof qe){Zr(J);return}$.error("Error: We were unable to determine if your subscription is an enterprise subscription. Contact support@builder.io for more information."),process.exit(1)}let y={folders:[{path:t.getCwdDir()}]};e.includeDirectories&&e.includeDirectories.split(",").forEach(_=>{let K=_.trim();K.length>0&&(g(K)||process.exit(1),y.folders.push({path:K}))}),e.addDirectory&&(Array.isArray(e.addDirectory)?e.addDirectory:[e.addDirectory]).forEach(_=>{let K=_.trim();K.length>0&&(g(K)||process.exit(1),y.folders.push({path:K}))});let B=await PDe(t,r),E=B.version,Q=B.name,v=await om(f,{onlyEditAccess:!0}),D,S;try{if(d===void 0){let J=[...v.map(K=>({value:K.id,label:K.designSystemName+" ("+K.scope+")"+(e.debug?` - ${K.id}`:"")}))],_="new";if(J.length>0&&(_=await wi({message:"Which design system would you like to index? You can bypass this by re-running this command with the --designSystemName flag.",options:[...J,{value:"new",label:"Create a new design system"}]}),je(_)))return;if(_==="new"){let K=await EH(f,C);if(!K)return;S=K;let j=await lr({message:"What is your design system name?",initialValue:Q,validate(ee){if(ee.trim().length===0)return"A design system name is required"}});if(je(j))return;if(d=j,D=_De(f,d,S,v),D){if(S==="organization"&&D.spaceId!==f.builderPublicKey){$.warn("A design system with this name already exists within your organization, but you do not have permission to re-index it.");return}if(!e.yes){let ee=await wr({message:`A design system with the name "${d}" already exists in your ${S}. Would you like to proceed with this design system?`});if(je(ee)||!ee)return}}}else{if(D=v.find(K=>K.id===_),S=D.scope,S==="organization"&&(D.spaceId!==f.builderPublicKey||!C?.isAdminInOrganization)){$.warn("A design system with this name already exists within your organization, but you do not have permission to re-index it.");return}d=D.designSystemName}}else if(D=LDe(d,v),D){if(S=D.scope,S==="organization"&&(D.spaceId!==f.builderPublicKey||!C?.isAdminInOrganization)){$.warn("A design system with this name already exists within your organization, but you do not have permission to re-index it.");return}}else{if(!e.yes){let _=await wr({message:`No indexed design system named "${d}" exists. Would you like to proceed with creating a new design system index?`});if(je(_)||!_)return}let J=await EH(f,C,e.scope);if(!J)return;S=J}}catch(J){let _=new dt("Failed to select a design system",{cause:J});Op.captureException(_,{tags:{operation:"repo-indexing",sessionId:I,designSystemPackage:r||"none"}}),console.log("Sorry, we encountered a problem when selecting a design system to index. Please try again. If the issue persists, contact support@builder.io.");return}let b=is();if(r)if((0,sbe.isAbsolute)(r))g(r)||process.exit(1),y.folders.push({path:r});else{let J=t.join(t.getAppRootDir(),`node_modules/${r}`);await t.exists(J)||($.error(`Design system package ${r} is not installed. Please install it first.`),process.exit(1))}nu.debug("Workspace config",y);let x=D?.id||"",P=!D&&d;if(P){let J=await gm(t);x=await UDe(f,{designSystemName:d,designSystemVersion:E,designSystemPackage:r,status:"in-progress",scope:S,gitOriginUrl:J?.originUrl,gitRelativePath:J?.recommendedRoot,cliArgs:process.argv.slice(2)})}let O=null;try{if(l){b.start("Processing custom documentation"),await t.exists(l)||($.error(`${l} does not exist`),process.exit(1));let{validDocs:J,invalidFiles:_}=await IBt(t,l);if(J.length===0&&($.error(`No valid files found in ${l}`),process.exit(1)),!P){$.warn("This design system already exists");let X=await wr({message:"Are you sure you want to fully replace the existing files?"});(je(X)||!X)&&($.info("Aborting..."),process.exit(1))}await Pt("repo indexing started",{sessionId:I,commandString:process.argv.slice(2).join(" "),forceBoolean:e.force||!1,currentDirectory:t.getCwdDir(),designSystemPackage:r||"none",designSystemPackageName:Q||"none",designSystemVersion:E||"none",designSystemId:x||"none",userId:f.userId,spaceId:f.builderPublicKey,source:"custom"}),b.message("Uploading custom documentation files");let K=[],j=[],ee=[],U=[],Y=[],H=[],Z=0;for(let X of J)if(Ug(X.document))K.push({name:X.document.name,description:X.document.description,relatedComponents:X.document.relatedComponents,relevantFiles:X.document.relevantFiles,hash:X.document.hash,type:"component"});else if(Ku(X.document)){let we={name:X.document.name,type:"token",relevantFiles:X.document.relevantFiles,tokens:X.document.rawTokens||[],hash:X.document.hash};U.push(we)}for(let X of J)try{if(await EBt(t,f,X,{designSystemId:x,designSystemPackage:r,designSystemVersion:E,sessionId:`${I}-custom-doc-${X.document.name}`,debug:e.debug}),Ug(X.document))j.push({name:X.document.name,description:X.document.description,relatedComponents:X.document.relatedComponents,relevantFiles:X.document.relevantFiles,hash:X.document.hash,type:"component"});else if(Qf(X.document))Z++;else if(Ku(X.document)){let we={name:X.document.name,type:"token",relevantFiles:X.document.relevantFiles,tokens:X.document.rawTokens||[],hash:X.document.hash};Y.push(we)}}catch(we){Ug(X.document)?ee.push(X.document.name):Ku(X.document)?H.push(X.document.name):ee.push(X.document.name),nu.error(`Failed to process ${X.document.name}:`,we,{loggerOptions:{debug:!0}})}if(j.length>0||U.length>0||Z>0){b.message("Creating agent documentation");try{await iJ(t,f,j,{designSystemId:x,debug:e.debug,hasIcons:Z>0,hasDesignTokens:U.length>0,discoveredTokenGroups:U.map(X=>X.name)})}catch(X){$.warn(`Failed to create agent documentation: ${X instanceof Error?X.message:String(X)}`)}}let ue=await ibe(f,x,e.debug),ge=j.map(X=>({name:X.name,type:"component",description:X.description,relevantFiles:X.relevantFiles,relatedComponents:X.relatedComponents,hash:X.hash}));J.forEach(X=>{Qf(X.document)?ge.push({name:X.document.name,type:"icon"}):Ku(X.document)?ge.push({name:X.document.name,type:"token",relevantFiles:X.document.relevantFiles,tokens:X.document.rawTokens||[],hash:X.document.hash}):n0(X.document)&&ge.push({name:X.document.name,type:"installation",relevantFiles:[],hash:X.document.hash})}),b.stop("Custom documentation collected"),await Pt("repo indexing completed",{sessionId:I,commandString:process.argv.slice(2).join(" "),forceBoolean:e.force,designSystemPackage:r||"none",designSystemId:x||"none",userId:f.userId,spaceId:f.builderPublicKey,source:"custom"});let he=[..._,...ee];O={componentsToCheck:ge,storedComponentDocs:ue,source:"custom",summaryData:{indexedComponents:j,discoveredComponents:K,failedComponents:he,failedTokens:H,numIconsIndexed:Z,discoveredTokenGroups:U,tokenGroupsToIndex:Y}}}else{if(await GDe(t)){if($.warn(XB(`\u26A0\uFE0F Warning: Existing ${IH} folder found.
|
|
7280
7280
|
|
|
7281
7281
|
For best results, please delete the repo-indexing folder in your project before running this command. Indexed component documentation can be viewed at https://builder.io/app/design-system-intelligence after completion.`,(process.stdout.columns||80)-4)),!e.yes){let Ce=await wr({message:"Continue with existing files?"});if(typeof Ce=="symbol"||!Ce){$.info("Repository indexing canceled.");return}}b=is()}b.start("Indexing repository");let _={sessionId:I,commandString:process.argv.slice(2).join(" "),forceBoolean:e.force||!1,currentDirectory:t.getCwdDir(),skipDetailedGroupingBoolean:e.skipDetailedGrouping,designSystemPackage:r||"none",designSystemPackageName:Q||"none",designSystemVersion:E||"none",designSystemId:x||"none",workspaceConfig:y,includeDirectories:e.includeDirectories||"none",addDirectory:e.addDirectory,debugBoolean:e.debug||!1,listIndexedReposBoolean:o||!1,userId:f.userId,spaceId:f.builderPublicKey,instructions:u};await Pt("repo indexing started",_),b.message("Looking for components");let K=await ibe(f,x,e.debug),j=K.find(Ce=>Qf(Ce)),ee=K.filter(Ce=>Ku(Ce)),U=K.filter(Ce=>Ug(Ce)),Y=hBt(a),H=Y.length>0,[Z,ue,ge,he]=await Promise.all([L0e(t,f,`${I}-component-discovery`,U,{designSystemPackage:r,designSystemVersion:E,workspaceConfig:y,debug:e.debug,force:i,specificComponents:Y,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode}),Y0e(t,f,`${I}-installation-discovery`,{designSystemId:x,designSystemPackage:r,designSystemVersion:E,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode}),!H&&G0e(t,f,`${I}-icon-discovery`,{designSystemPackage:r,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode})||void 0,!H&&H0e(t,f,`${I}-token-discovery`,ee,{designSystemPackage:r,workspaceConfig:y,debug:e.debug,force:i,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode})]),{numComponentsFound:X,componentsToIndex:we,discoveredComponents:Je}=Z,{tokenGroupsToIndex:le,discoveredTokenGroups:be}=he||{tokenGroupsToIndex:[],discoveredTokenGroups:[]};if(Y.length>0&&we.length===0){$.info("No changes detected for the specified components. Use --force to reindex anyway.");return}let de=!H&&(i||!j||j.hash!==ge?.hash),ke=!H&&le.length>0;if(X===0&&!de&&!ke&&($.warn(XB("We were unable to index your repository because no components were found. If your components are a dependency of your project be sure to specify the package name using --designSystemPackage when re-running this command.",(process.stdout.columns||80)-4)),process.exit(1)),we.length===0&&!de&&!ke){$.info(XB("Component index is up to date!",(process.stdout.columns||80)-4));return}if(n)return;let Qe=K.find(Ce=>RL(Ce));if(i){let Ce=U.length;if(b.stop(`${X} new and ${Ce} existing component docs found`),Ce>0){let V=await wr({message:"Using --force will remove existing component documents. Continue?"});if(typeof V=="symbol"||!V){b.stop("Canceled");return}}b.start("")}let rt=0,nt=[];b.stop("Started indexing component docs:");let Ut=new sJ.default.MultiBar({clearOnComplete:!1,hideCursor:!0},sJ.default.Presets.shades_grey);Ut.log(""),Ut.log(`Indexing in progress with ${ZB} workers...`);let $r=Ut.create(we.length+le.length,rt,{name:"Total"},{format:`${(0,La.cyan)("{bar}")} | {name} | {percentage}% | (Step {value}/{total})`}),Ht={};for(let Ce=0;Ce<ZB;Ce++)Ht[Ce]={statusBar:Ut.create(1,0,{name:"Starting..."},{format:"{name}"}),name:"Starting..."};let Ge=(Ce,V)=>{V?Ht[Ce].name=`Indexing: ${V}`:Ht[Ce].name=Wx,$r.update(rt)},nn=async(Ce,V)=>{let te=[],oe=[],me=[...Ce],Re=async et=>{for(;me.length>0;){let wt=me.shift();if(!wt)break;switch(Ge(et,wt.name),wt.type){case"token":try{await J0e(t,f,`${I}-${wt.name}-doc`,wt,{designSystemId:x,designSystemPackage:r,designSystemVersion:E,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode}),rt++}catch{oe.push(wt.name)}break;case"component":try{await W0e(t,f,`${I}-${wt.name}-doc`,wt,{designSystemId:x,designSystemPackage:r,designSystemVersion:E,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode}),b.message(`Component docs stored for ${wt.name}`),nt.push(wt),rt++}catch{te.push(wt.name)}break}}Ge(et,"")},_e=Array.from({length:V},(et,wt)=>Re(wt)),gt=0,tr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Rt=setInterval(()=>{for(let et=0;et<ZB;et++)Ht[et].name!==Wx?Ht[et].statusBar.update(0,{name:`${Ht[et].name} ${tr[gt]}`}):Ht[et].statusBar.update(0,{name:Wx});gt=(gt+1)%tr.length},100);await Promise.all(_e),clearInterval(Rt);for(let et=0;et<ZB;et++)Ht[et].statusBar.update(0,{name:Wx});return Ut.stop(),{failedComponents:te,failedTokens:oe}},At=Je.some(Ce=>!U.find(V=>V.name===Ce.name)),[Et,cr,ze]=await Promise.all([(async()=>!Qe||i||At||de||ke?(b.message("Summarizing component library"),await iJ(t,f,Je,{designSystemId:x,debug:e.debug,hasIcons:!H&&(ge?.icons.length||0)>0,hasDesignTokens:!H&&be.length>0,discoveredTokenGroups:be.map(Ce=>Ce.name)}),b.message("Agent docs stored"),{success:!0}):{success:!0})(),ge&&O0e(f,ge,{designSystemId:x,debug:e.debug,sessionId:`${I}-icon-discovery`,previousHash:j?.hash,force:i}),nn(H?we:[...we,...le],ZB)]),{failedComponents:qt,failedTokens:Oe}=ze,Be=[...Je,...H?[]:be];(ge?.icons.length||0)>0&&Be.push({name:sm,type:"icon"}),ue?.hash&&Be.push({name:xx,type:"installation",hash:ue.hash,relevantFiles:ue.relevantFiles}),O={componentsToCheck:Be,storedComponentDocs:K,source:"auto",specificComponentNames:Y,summaryData:{indexedComponents:nt,discoveredComponents:Je,failedComponents:qt,failedTokens:Oe,numIconsIndexed:H?0:cr&&ge?.icons.length||0,discoveredTokenGroups:be,tokenGroupsToIndex:le}},await Pt("repo indexing completed",{sessionId:I,commandString:process.argv.slice(2).join(" "),forceBoolean:e.force,skipDetailedGroupingBoolean:e.skipDetailedGrouping,designSystemPackage:r||"none",designSystemId:x||"none",userId:f.userId,spaceId:f.builderPublicKey}),e.createFusionExample&&await nbe(f,d,e)}}catch(J){throw $.error(J instanceof Error?J.message:String(J)),Op.captureException(J,{tags:{operation:"repo-indexing",sessionId:I,designSystemPackage:r||"none",source:l?"custom":"auto"},extra:{skipDetailedGrouping:n,force:i,uploadCustomDocs:l}}),nu.error(`
|
|
7282
|
-
Stack trace:`,J instanceof Error?J.stack:"",{loggerOptions:{debug:!0}}),x&&await
|
|
7283
|
-
`))),{validDocs:A,invalidFiles:a}},EBt=async(t,e,r,n)=>{let{document:i,body:s}=r,{designSystemId:o,designSystemPackage:a,designSystemVersion:A,sessionId:c,debug:u}=n,l;if(Ug(i)||Ku(i)){let d=i.relevantFiles||[];d.length>0?l=await Gp(t,d):l=Xx.default.createHash("sha256").update(s).digest("hex")}else(Qf(i)||n0(i))&&(l=Xx.default.createHash("sha256").update(s).digest("hex"));try{if(Ug(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}else if(Ku(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}else if(Qf(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}else if(n0(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}}catch(d){throw new dt(`Failed to process custom doc: ${i.name}`,{cause:d})}},BBt=async(t,e)=>{let r=new URL("/allow-feature",Ne);r.searchParams.set("feature","repo-indexing"),r.searchParams.set("apiKey",t.builderPublicKey),r.searchParams.set("userId",t.userId);let n=await Fe(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`}});if(!n.ok){let s=await n.text();return nu.error("API request failed:",n.status,s,{loggerOptions:{debug:!0}}),{isAllowed:!1,reason:s||"Unable to verify permissions"}}let i=await n.json();return{isAllowed:i.isAllowed,reason:i.reason}};
|
|
7282
|
+
Stack trace:`,J instanceof Error?J.stack:"",{loggerOptions:{debug:!0}}),x&&await BH(f,{id:x,designSystemName:d,designSystemPackage:r,designSystemVersion:E,status:"failed",scope:S,source:l?"custom":"auto"}),J}if(O&&O.summaryData){let J=O.storedComponentDocs.filter(_=>RL(_)?!1:O.specificComponentNames&&O.specificComponentNames.length>0?O.specificComponentNames.includes(_.name):!0);await z0e(f,O.componentsToCheck,J),mBt(O.summaryData.discoveredComponents,O.summaryData.indexedComponents,p,O.summaryData.failedComponents,i,d,x,O.summaryData.numIconsIndexed,O.summaryData.discoveredTokenGroups,O.summaryData.tokenGroupsToIndex,O.summaryData.failedTokens),x&&await BH(f,{id:x,designSystemName:d,designSystemPackage:r,designSystemVersion:E,status:"completed",scope:S,source:O.source})}},ibe=async(t,e,r)=>{let n=new URL(`/design-systems/v1/${e}/docs`,Ne);n.searchParams.set("apiKey",t.builderPublicKey),n.searchParams.set("userId",t.userId);let i=await Fe(n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`}});if(!i.ok){let s=await i.text();return nu.error("API request failed:",i.status,s,{loggerOptions:{debug:!0}}),[]}return await i.json()},zx=t=>{if(Array.isArray(t))return t.map(n=>String(n).trim()).filter(n=>n.length>0);if(typeof t!="string")return[];let e=t.trim();if(e===""||e==="[]")return[];let r=e;return r=r.replace(/^\[|\]$/g,""),r=r.replace(/['"]/g,""),r.split(",").map(n=>n.trim()).filter(n=>n.length>0)},CBt=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[r,n]of Object.entries(t))typeof r=="string"&&typeof n=="string"&&(e[r]=n);return Object.keys(e).length>0?e:void 0},IBt=async(t,e)=>{(await t.stat(e)).isDirectory()||($.error(`${e} is not a valid directory`),process.exit(1));let i=(await t.readdir(e)).filter(u=>u.endsWith(".md")||u.endsWith(".mdx"));i.length===0&&($.error(`No .md or .mdx files found in ${e}`),process.exit(1));let s=["name","description","type"],o=["token","icon","component","installation"],a=[],A=[],c=new Set;for(let u of i){let l=t.join(e,u),d=await t.readFile(l),g;try{g=af(d||"")}catch{a.push(u);continue}let{frontmatter:p,body:f}=g;if(!p||typeof p!="object"||!s.every(y=>!!p[y])){a.push(u);continue}if(typeof p.type!="string"||!o.includes(p.type)){a.push(u);continue}let m=p.name.toLowerCase();if(c.has(m)){a.push(u);continue}if(c.add(m),!f||f.trim()===""){a.push(u);continue}let C={name:p.name,description:p.description,content:f,designSystemId:""},I;switch(p.type){case"component":{I={...C,type:"component",relatedComponents:zx(p.relatedComponents),relevantFiles:zx(p.relevantFiles),hash:""};break}case"token":{I={...C,type:"token",relevantFiles:zx(p.relevantFiles),rawTokens:zx(p.rawTokens),tokenValues:CBt(p.tokenValues),hash:""};break}case"icon":{I={...C,type:"icon",hash:""};break}case"installation":{I={...C,type:"installation",hash:""};break}default:a.push(u);continue}A.push({document:I,filePath:l,frontmatter:p,body:f||""})}return $.info(`Found ${A.length} valid files`),a.length>0&&($.warn(`Files: [${a.join(", ")}] will be excluded because they have invalid or duplicate frontmatter`),$.warn(["---","name: example","description: example text","type: token | icon | component | installation","(optional) relevantFiles: [file1, file2]","(optional) relatedComponents: [component1, component2]","---"].join(`
|
|
7283
|
+
`))),{validDocs:A,invalidFiles:a}},EBt=async(t,e,r,n)=>{let{document:i,body:s}=r,{designSystemId:o,designSystemPackage:a,designSystemVersion:A,sessionId:c,debug:u}=n,l;if(Ug(i)||Ku(i)){let d=i.relevantFiles||[];d.length>0?l=await Gp(t,d):l=Xx.default.createHash("sha256").update(s).digest("hex")}else(Qf(i)||n0(i))&&(l=Xx.default.createHash("sha256").update(s).digest("hex"));try{if(Ug(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}else if(Ku(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}else if(Qf(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}else if(n0(i)){let d={...i,sessionId:c,hash:l||i.hash,designSystemId:o,...A&&{designSystemVersion:A},...a&&{designSystemPackage:a}};await Ss(e,d,u)}}catch(d){throw new dt(`Failed to process custom doc: ${i.name}`,{cause:d})}},BBt=async(t,e)=>{let r=new URL("/allow-feature",Ne);r.searchParams.set("feature","repo-indexing"),r.searchParams.set("apiKey",t.builderPublicKey),r.searchParams.set("userId",t.userId);let n=await Fe(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.builderPrivateKey}`}});if(!n.ok){let s=await n.text();return nu.error("API request failed:",n.status,s,{loggerOptions:{debug:!0}}),{isAllowed:!1,reason:s||"Unable to verify permissions"}}let i=await n.json();return{isAllowed:i.isAllowed,reason:i.reason}};K4();h();h();kr();var Zx=z(Ir(),1);rr();xi();var obe=(t,e)=>{try{let{builderPublicKey:r,userId:n,spaceName:i}=Jo(t,e);if(r===void 0){$.message((0,Zx.red)("\u2717 Not Authenticated to Builder.io")),$.message('Re-run this with the "auth" command to authenticate with Builder.io.');return}$.message((0,Zx.green)("\u2713 Authenticated to Builder.io")),i!==void 0&&$.message(`Space Name: ${i}`),r!==void 0&&$.message(`Space ID: ${r}`),n!==void 0&&$.message(`User ID: ${n}`)}catch(r){let n=t.Sentry?.captureException(new dt("Failed to read credentials",{cause:r}));$.error(`Sorry, we ran into a problem while checking authentication. Please try again. If this issue persists, contact support@builder.io, and provide the error ID: ${n}`)}};kr();rr();var _n=z(Ir(),1);zr();Ls();var abe=async(t,e,r)=>{if(e==="status"){obe(t,r);return}if(r.reset){console.log(""),sr((0,_n.bgCyan)((0,_n.bold)((0,_n.white)(" auth reset ")))+" "+(0,_n.dim)(ht)),Swe(t)?($.success("Credentials have been cleared successfully"),await Pt("auth reset",{})):$.info("No credentials found to clear"),Cn((0,_n.bgGreen)((0,_n.bold)((0,_n.white)(" Done! \u{1F389} "))));return}console.log(""),sr((0,_n.bgCyan)((0,_n.bold)((0,_n.white)(" auth ")))+" "+(0,_n.dim)(ht));let n=!1,{builderPublicKey:i}=await Wt(t,r,{builderPrivateKey:!0,builderPublicKey:!0,force:!0,requireFigmaAuth:n?"always":void 0});await Pt("auth",{spaceId:i}),Cn((0,_n.bgGreen)((0,_n.bold)((0,_n.white)(" Done! \u{1F389} "))))};h();rr();var Un=z(Ir(),1);zr();Ml();kr();hr();yr();TB();var bbe=require("node:child_process"),vbe=require("util");h();var Abe=require("node:child_process"),cbe=require("util"),pm=(0,cbe.promisify)(Abe.exec);async function ube(){let t={};try{let{stdout:e}=await pm("node --version");t.node=e.trim().replace(/^v/,"")}catch{}try{let{stdout:e}=await pm("npm --version");t.npm=e.trim()}catch{}try{let{stdout:e}=await pm("pnpm --version");t.pnpm=e.trim()}catch{}try{let{stdout:e}=await pm("yarn --version");t.yarn=e.trim()}catch{}try{let{stdout:e}=await pm("bun --version");t.bun=e.trim()}catch{}try{let{stdout:e}=await pm("deno --version"),r=e.match(/deno (\d+\.\d+\.\d+)/);r&&(t.deno=r[1])}catch{}return t}function lbe(t){let e=[];return t.node&&e.push({key:"node",type:"mise",tool:"node",version:t.node}),t.npm&&e.push({key:"npm",type:"mise",tool:"npm",version:t.npm}),t.pnpm&&e.push({key:"pnpm",type:"mise",tool:"pnpm",version:t.pnpm}),t.yarn&&e.push({key:"yarn",type:"mise",tool:"yarn",version:t.yarn}),t.bun&&e.push({key:"bun",type:"mise",tool:"bun",version:t.bun}),t.deno&&e.push({key:"deno",type:"mise",tool:"deno",version:t.deno}),e}function gbe(t){let e=[];return t.node&&e.push(`node v${t.node}`),t.npm&&e.push(`npm ${t.npm}`),t.pnpm&&e.push(`pnpm ${t.pnpm}`),t.yarn&&e.push(`yarn ${t.yarn}`),t.bun&&e.push(`bun ${t.bun}`),t.deno&&e.push(`deno ${t.deno}`),e.join(", ")}h();rr();var hbe=z(a4(),1),mbe=require("node:path"),Cbe=require("node:fs"),yBt=new Set(["PATH","HOME","SHELL","USER","LOGNAME","TMPDIR","TEMP","TMP","PWD","OLDPWD","TERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","TERM_SESSION_ID","LANG","LC_ALL","LC_CTYPE","LC_COLLATE","LC_TIME","LC_NUMERIC","LC_MONETARY","LC_MESSAGES","SHLVL","_","DISPLAY","COLORTERM","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_CACHE_HOME","XDG_RUNTIME_DIR","SSH_AUTH_SOCK","SSH_AGENT_PID","MANPATH","INFOPATH","HOMEBREW_PREFIX","HOMEBREW_CELLAR","HOMEBREW_REPOSITORY","COMMAND_MODE","__CFBundleIdentifier","__CF_USER_TEXT_ENCODING","Apple_PubSub_Socket_Render","SUDO_COMMAND","SUDO_USER","SUDO_UID","SUDO_GID","ORIGINAL_XDG_CURRENT_DESKTOP","EDITOR","VISUAL","PAGER","LESS","LESSOPEN","NODE","NODE_PATH","NODE_OPTIONS","CLAUDE_CODE_SSE_PORT","COLOR","CURSOR_TRACE_ID","ENABLE_IDE_INTEGRATION","GIT_ASKPASS","VSCODE_GIT_ASKPASS_EXTRA_ARGS","VSCODE_GIT_ASKPASS_MAIN","VSCODE_GIT_ASKPASS_NODE","VSCODE_GIT_IPC_HANDLE","VSCODE_INJECTION","VSCODE_INSPECTOR_OPTIONS","INIT_CWD","MallocNanoZone","OSLogRateLimit","XPC_FLAGS","XPC_SERVICE_NAME","PNPM_HOME"]),QBt=[/^npm_config_/,/^npm_command$/,/^npm_execpath$/,/^npm_lifecycle_/,/^npm_node_execpath$/,/^npm_package_/];function pbe(t){return yBt.has(t)?!0:QBt.some(e=>e.test(t))}var dbe={"Build & Development":[/^NODE_ENV$/,/^CI$/,/^NODE_OPTIONS$/,/^DEBUG$/,/^PORT$/,/^HOST$/,/^ENVIRONMENT$/,/^ENV$/,/^BUILD_/,/^DEV_/],"NPM & Package Managers":[/^NPM_/,/^YARN_/,/^PNPM_/,/^BUN_/],"Framework Specific":[/^NEXT_/,/^REACT_/,/^VITE_/,/^NUXT_/,/^VUE_/,/^ANGULAR_/,/^SVELTE_/,/^GATSBY_/,/^REMIX_/],"Public Variables":[/^PUBLIC_/,/^NEXT_PUBLIC_/,/^REACT_APP_/,/^VITE_/],"API & Services":[/^API_/,/^DATABASE_/,/^DB_/,/^REDIS_/,/^AWS_/,/^GCP_/,/^AZURE_/,/^STRIPE_/,/^SENTRY_/,/^VERCEL_/,/^NETLIFY_/],Custom:[]},fbe=[/TOKEN/i,/KEY/i,/SECRET/i,/PASSWORD/i,/PASS/i,/AUTH/i,/PRIVATE/i,/CREDENTIAL/i],DBt=new Set(["NODE_ENV","CI","PORT","HOST","ENVIRONMENT"]);async function wBt(t,e){let r=[".env",".env.local",".env.development",".env.development.local"],n={};for(let i of r){let s=(0,mbe.join)(e,i);if((0,Cbe.existsSync)(s))try{let o=(0,hbe.config)({path:s});o.parsed&&Object.assign(n,o.parsed)}catch{}}return n}function bBt(t){let e=[];if(t)for(let[n,i]of Object.entries(t)){if(!i||pbe(n))continue;let s="Custom";for(let[a,A]of Object.entries(dbe))if(A.some(c=>c.test(n))){s=a;break}let o=fbe.some(a=>a.test(n));e.push({key:n,value:i,category:s==="Custom"?".env Variables":s,isSecret:o,shouldPreselect:!0,fromDotEnv:!0})}let r=new Set(t?Object.keys(t):[]);for(let[n,i]of Object.entries(process.env)){if(r.has(n)||pbe(n)||i===void 0)continue;let s="Custom";for(let[A,c]of Object.entries(dbe))if(c.some(u=>u.test(n))){s=A;break}let o=fbe.some(A=>A.test(n)),a=DBt.has(n)||n.startsWith("NEXT_PUBLIC_")||n.startsWith("REACT_APP_")||n.startsWith("VITE_")||n.startsWith("PUBLIC_")||n==="NODE_ENV"||n==="CI";e.push({key:n,value:i,category:s,isSecret:o,shouldPreselect:a})}return e.sort((n,i)=>n.category!==i.category?n.category.localeCompare(i.category):n.key.localeCompare(i.key)),e}async function Ibe(t,e){let r=await wBt(t,e),n=bBt(r);if(n.length===0)return[];let i=new Map;for(let p of n)i.has(p.category)||i.set(p.category,[]),i.get(p.category).push(p);let s=[];for(let[p,f]of i){s.push({value:`__category_${p}__`,label:`
|
|
7284
7284
|
${p} (${f.length})`,hint:""});for(let m of f){let C=m.isSecret?"***":m.value.length>50?`${m.value.substring(0,47)}...`:m.value;s.push({value:m.key,label:` ${m.key}`,hint:C})}}let o=n.filter(p=>p.shouldPreselect).map(p=>p.key),a=o.length,A=n.length,c=n.filter(p=>p.fromDotEnv).length,u=c>0?`Select environment variables (${c} from .env, ${a} pre-selected)`:`Select environment variables (${a} of ${A} pre-selected)`,l=await nd({message:u,options:s.filter(p=>!p.value.startsWith("__category_")),initialValues:o,required:!1});if(je(l))return null;let d=new Set(l),g=[];for(let p of n)d.has(p.key)&&g.push({key:p.key,value:p.value,isSecret:p.isSecret});return g}function Ebe(t){let e=t.filter(n=>n.isSecret).length,r=t.length-e;return{total:t.length,secrets:e,public:r}}h();var aJ=require("node:path"),Bbe=require("node:os");rr();async function ybe(t,e){let r={},n=(0,aJ.join)(e,".npmrc");try{let o=await t.readFile(n);o&&(r.projectNpmrc={path:n,content:o})}catch{}let i=(0,aJ.join)((0,Bbe.homedir)(),".npmrc");try{let o=await t.readFile(i);o&&(r.userNpmrc={path:i,content:o})}catch{}let s="/etc/hosts";try{let o=await t.readFile(s);o&&(r.etcHosts={path:s,content:o})}catch{}return r}async function Qbe(t){let e=[];if(t.projectNpmrc&&e.push({key:"projectNpmrc",displayName:".npmrc (project)",path:"./.npmrc",content:t.projectNpmrc.content,hint:"NPM configuration for project"}),t.userNpmrc&&e.push({key:"userNpmrc",displayName:".npmrc (user)",path:"~/.npmrc",content:t.userNpmrc.content,hint:"Your user NPM configuration"}),t.etcHosts&&e.push({key:"etcHosts",displayName:"/etc/hosts",path:"/etc/hosts",content:t.etcHosts.content,hint:"System hosts file"}),e.length===0)return[];let r=e.map(a=>({value:a.key,label:a.displayName,hint:a.hint})),n=e.map(a=>a.key),i=await nd({message:`Select configuration files to include (${e.length} found)`,options:r,initialValues:n,required:!1});if(je(i))return null;let s=new Set(i),o=[];for(let a of e)s.has(a.key)&&o.push({path:a.path,content:a.content});return o}h();var Dbe=require("node:child_process");rr();var Kp=z(Ir(),1);async function wbe(t,e){let n=0,i=e;for(;n<3;){if(n++,i)$.info(`Working directory: ${t}`);else{$.info(`Working directory: ${t}`);let o=await lr({message:"Enter install command",placeholder:"npm install",defaultValue:"npm install",validate:a=>{if(!a||a.trim().length===0)return"Command cannot be empty"}});if(je(o))return{success:!1,command:"",skipped:!0};i=o}let s=await vBt(i,t);if(s.success)return $.success((0,Kp.green)("\u2713 Install completed successfully!")),{success:!0,command:i,exitCode:0,skipped:!1};if($.error((0,Kp.red)(`\u2717 Install failed with exit code ${s.exitCode}`)),n<3){let o=await wi({message:"Try again with a different command?",options:[{value:"retry",label:"Yes, try again"},{value:"skip",label:"No, skip and continue anyway"}]});if(je(o)||o==="skip")return $.warn((0,Kp.yellow)("\u26A0 Skipping install step")),{success:!1,command:i,exitCode:s.exitCode,skipped:!0};i=void 0}else{$.warn((0,Kp.yellow)("\u26A0 Maximum retry attempts reached"));let o=await wi({message:"Continue without successful install?",options:[{value:"yes",label:"Yes, continue anyway"},{value:"no",label:"No, exit"}]});return je(o)||o==="no"?{success:!1,command:i,exitCode:s.exitCode,skipped:!1}:{success:!1,command:i,exitCode:s.exitCode,skipped:!0}}}return{success:!1,command:i||"",skipped:!0}}function vBt(t,e){return new Promise(r=>{let n=t.trim().split(/\s+/),i=n[0],s=n.slice(1),o=(0,Dbe.spawn)(i,s,{cwd:e,stdio:"inherit",shell:!0});o.on("error",a=>{$.error(`Failed to execute command: ${a.message}`),r({success:!1,exitCode:1})}),o.on("exit",a=>{let A=a??1;r({success:A===0,exitCode:A})})})}var SBt=(0,vbe.promisify)(bbe.exec);function xBt(t){let e=t.replace(/\.git$/,"");return e.startsWith("git@")&&(e=e.replace(/^git@/,"https://").replace(/:([^/])/,"/$1")),!e.startsWith("http://")&&!e.startsWith("https://")&&(e=`https://${e}`),e}async function Sbe(t,e){console.log(""),sr((0,Un.bgCyan)((0,Un.bold)((0,Un.white)(" connect-repo ")))+" "+(0,Un.dim)(ht));try{$.step("Detecting git repository...");let r=await gm(t);if(!r){Ke("No git repository detected. Please run this command from within a git repository.");return}let n=rbe(r);tg(n.join(`
|
|
7285
7285
|
`),"Repository Detected");let i=await lr({message:"Project name",initialValue:r.projectName,validate:p=>{if(!p||p.trim().length===0)return"Project name cannot be empty"}});if(je(i)){Ke("Project creation cancelled");return}let s=i.trim(),o=await wbe(r.gitRoot,e.installCommand);if(!o.success&&!o.skipped){Ke("Installation failed. Cannot continue.");return}$.step("Collecting environment variables...");let a=await Ibe(t,r.gitRoot);if(a===null){Ke("Environment variable selection cancelled");return}let A=Ebe(a);$.info(`\u2713 Selected ${A.total} variables (${A.secrets} secret, ${A.public} public)`),$.step("Collecting configuration files...");let c=await ybe(t,r.gitRoot),u=await Qbe(c);if(u===null){Ke("Configuration file selection cancelled");return}u.length>0?$.info(`\u2713 Selected ${u.length} configuration file(s)`):$.info("\u25CB No configuration files selected"),$.step("Detecting tool versions...");let l=Bi();l.start("Checking installed tools");let d=await ube(),g=lbe(d);l.stop(),$.info(`\u2713 Detected: ${gbe(d)}`),await FBt(t,e,r,s,o.command,g,a,u)}catch(r){throw t.Sentry?.captureException(r),$.error(r instanceof Error?r.message:String(r)),Ke("Command failed"),r}}async function FBt(t,e,r,n,i,s,o,a){$.step("Creating Fusion project...");let A=[`Project: ${(0,Un.bold)(n)}`,`Provider: ${r.repoProvider} (${r.isPrivate?"private":"public"})`];r.recommendedRoot&&A.push(`Recommended root: ${r.recommendedRoot}`),A.push(`Environment: ${o.length} variables`,`Config files: ${a.length} files`,`Tools: ${s.length} dependencies`),tg(A.join(`
|
|
7286
7286
|
`),"Summary");let c=Bi();c.start("Authenticating");let u=await Wt(t,e,{builderPublicKey:!0,builderPrivateKey:!0});c.stop(),$.success(`\u2713 Authenticated as ${u.userId} (Space: ${u.spaceName||u.builderPublicKey})`);let l=await wi({message:`Create project "${(0,Un.bold)(n)}" in space "${(0,Un.bold)(u.spaceName||u.builderPublicKey)}"?`,options:[{value:"confirm",label:"Confirm",hint:"Create the project"},{value:"changeSpace",label:"Choose Different Space",hint:"Switch to another space"},{value:"cancel",label:"Cancel",hint:"Cancel project creation"}]});if(je(l)){Ke("Project creation cancelled");return}if(l==="cancel"){Ke("Project creation cancelled");return}l==="changeSpace"&&(u=await Wt(t,e,{builderPublicKey:!0,builderPrivateKey:!0,force:!0}));let d;try{let{stdout:I}=await SBt("git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || git remote show origin | grep 'HEAD branch' | cut -d' ' -f5",{cwd:r.gitRoot});d=I.trim().replace("refs/remotes/origin/","")}catch{$.warning("Could not determine main branch name")}let g=xBt(r.originUrl),p={name:n,repoFullName:r.repoFullName,repoProvider:r.repoProvider,repoProtocol:r.repoProvider==="github"||r.repoProvider==="selfHostedGithub"?void 0:"https",repoUrl:g,repoPrivate:r.isPrivate,needSetup:!0,settings:{installCommand:i,setupDependencies:s,recommendedRoot:r.recommendedRoot,environmentVariables:o,fileOverrides:a,mainBranchName:d}},f="happy-cli",m={name:f,createdBy:u.userId,friendlyName:f,isDefault:!0,isPublic:!1,lockedFusionEnvironment:"cloud"},C={...p,branchData:m};if(e.dryrun){c.stop(),$.info("Dry run mode - project will not be created"),tg(`API Endpoint: POST ${Ne}/projects?apiKey=${u.builderPublicKey}&userId=${u.userId}
|
|
@@ -7293,7 +7293,7 @@ ${JSON.stringify(C,void 0,2)}`,"Dry Run Configuration"),Cn((0,Un.green)("Dry run
|
|
|
7293
7293
|
It must be "${e}.stdout", "${e}.stderr", "${e}.all", "${e}.ipc", or "${e}.fd3", "${e}.fd4" (and so on).`);if(n>=r.length)throw new TypeError(`"${e}.${t}" is invalid: that file descriptor does not exist.
|
|
7294
7294
|
Please set the "stdio" option to ensure that file descriptor exists.`);return n==="all"?[1,2]:[n]},pJ=t=>{if(t==="all")return t;if(Yo.includes(t))return Yo.indexOf(t);let e=YBt.exec(t);if(e!==null)return Number(e[1])},YBt=/^fd(\d+)$/,qBt=(t,e)=>t.map(r=>r===void 0?VBt[e]:r),$Bt=(0,Kbe.debuglog)("execa").enabled?"full":"none",VBt={lines:!1,buffer:!0,maxBuffer:1e3*1e3*100,verbose:$Bt,stripFinalNewline:!0},dJ=["lines","buffer","maxBuffer","verbose","stripFinalNewline"],su=(t,e)=>e==="ipc"?t.at(-1):t[e];var fm=({verbose:t},e)=>fJ(t,e)!=="none",hm=({verbose:t},e)=>!["none","short"].includes(fJ(t,e)),Jbe=({verbose:t},e)=>{let r=fJ(t,e);return AF(r)?r:void 0},fJ=(t,e)=>e===void 0?WBt(t):su(t,e),WBt=t=>t.find(e=>AF(e))??cF.findLast(e=>t.includes(e)),AF=t=>typeof t=="function",cF=["none","short","full"];h();var sve=require("node:util");h();var jbe=require("node:process"),Ybe=require("node:util"),qbe=(t,e)=>{let r=[t,...e],n=r.join(" "),i=r.map(s=>ryt($be(s))).join(" ");return{command:n,escapedCommand:i}},ty=t=>(0,Ybe.stripVTControlCharacters)(t).split(`
|
|
7295
7295
|
`).map(e=>$be(e)).join(`
|
|
7296
|
-
`),$be=t=>t.replaceAll(ZBt,e=>zBt(e)),zBt=t=>{let e=eyt[t];if(e!==void 0)return e;let r=t.codePointAt(0),n=r.toString(16);return r<=tyt?`\\u${n.padStart(4,"0")}`:`\\U${n}`},XBt=()=>{try{return new RegExp("\\p{Separator}|\\p{Other}","gu")}catch{return/[\s\u0000-\u001F\u007F-\u009F\u00AD]/g}},ZBt=XBt(),eyt={" ":" ","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},tyt=65535,ryt=t=>nyt.test(t)?t:jbe.platform==="win32"?`"${t.replaceAll('"','""')}"`:`'${t.replaceAll("'","'\\''")}'`,nyt=/^[\w./-]+$/;h();h();
|
|
7296
|
+
`),$be=t=>t.replaceAll(ZBt,e=>zBt(e)),zBt=t=>{let e=eyt[t];if(e!==void 0)return e;let r=t.codePointAt(0),n=r.toString(16);return r<=tyt?`\\u${n.padStart(4,"0")}`:`\\U${n}`},XBt=()=>{try{return new RegExp("\\p{Separator}|\\p{Other}","gu")}catch{return/[\s\u0000-\u001F\u007F-\u009F\u00AD]/g}},ZBt=XBt(),eyt={" ":" ","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},tyt=65535,ryt=t=>nyt.test(t)?t:jbe.platform==="win32"?`"${t.replaceAll('"','""')}"`:`'${t.replaceAll("'","'\\''")}'`,nyt=/^[\w./-]+$/;h();h();pH();var Vbe={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Wbe={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},iyt={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},syt={...Vbe,...Wbe},oyt={...Vbe,...iyt},ayt=OB(),Ayt=ayt?syt:oyt,uF=Ayt,bIr=Object.entries(Wbe);h();var zbe=z(require("node:tty"),1),cyt=zbe.default?.WriteStream?.prototype?.hasColors?.()??!1,Dt=(t,e)=>{if(!cyt)return i=>i;let r=`\x1B[${t}m`,n=`\x1B[${e}m`;return i=>{let s=i+"",o=s.indexOf(n);if(o===-1)return r+s+n;let a=r,A=0,u=(e===22?n:"")+r;for(;o!==-1;)a+=s.slice(A,o)+u,A=o+n.length,o=s.indexOf(n,A);return a+=s.slice(A)+n,a}},xIr=Dt(0,0),Xbe=Dt(1,22),FIr=Dt(2,22),kIr=Dt(3,23),RIr=Dt(4,24),TIr=Dt(53,55),NIr=Dt(7,27),MIr=Dt(8,28),PIr=Dt(9,29),LIr=Dt(30,39),_Ir=Dt(31,39),UIr=Dt(32,39),GIr=Dt(33,39),OIr=Dt(34,39),KIr=Dt(35,39),HIr=Dt(36,39),JIr=Dt(37,39),lF=Dt(90,39),jIr=Dt(40,49),YIr=Dt(41,49),qIr=Dt(42,49),$Ir=Dt(43,49),VIr=Dt(44,49),WIr=Dt(45,49),zIr=Dt(46,49),XIr=Dt(47,49),ZIr=Dt(100,49),Zbe=Dt(91,39),eEr=Dt(92,39),eve=Dt(93,39),tEr=Dt(94,39),rEr=Dt(95,39),nEr=Dt(96,39),iEr=Dt(97,39),sEr=Dt(101,49),oEr=Dt(102,49),aEr=Dt(103,49),AEr=Dt(104,49),cEr=Dt(105,49),uEr=Dt(106,49),lEr=Dt(107,49);var nve=({type:t,message:e,timestamp:r,piped:n,commandId:i,result:{failed:s=!1}={},options:{reject:o=!0}})=>{let a=uyt(r),A=lyt[t]({failed:s,reject:o,piped:n}),c=gyt[t]({reject:o});return`${lF(`[${a}]`)} ${lF(`[${i}]`)} ${c(A)} ${c(e)}`},uyt=t=>`${gF(t.getHours(),2)}:${gF(t.getMinutes(),2)}:${gF(t.getSeconds(),2)}.${gF(t.getMilliseconds(),3)}`,gF=(t,e)=>String(t).padStart(e,"0"),tve=({failed:t,reject:e})=>t?e?uF.cross:uF.warning:uF.tick,lyt={command:({piped:t})=>t?"|":"$",output:()=>" ",ipc:()=>"*",error:tve,duration:tve},rve=t=>t,gyt={command:()=>Xbe,output:()=>rve,ipc:()=>rve,error:({reject:t})=>t?Zbe:eve,duration:()=>lF};h();var ive=(t,e,r)=>{let n=Jbe(e,r);return t.map(({verboseLine:i,verboseObject:s})=>pyt(i,s,n)).filter(i=>i!==void 0).map(i=>dyt(i)).join("")},pyt=(t,e,r)=>{if(r===void 0)return t;let n=r(t,e);if(typeof n=="string")return n},dyt=t=>t.endsWith(`
|
|
7297
7297
|
`)?t:`${t}
|
|
7298
7298
|
`;var qA=({type:t,verboseMessage:e,fdNumber:r,verboseInfo:n,result:i})=>{let s=fyt({type:t,result:i,verboseInfo:n}),o=hyt(e,s),a=ive(o,n,r);a!==""&&console.warn(a.slice(0,-1))},fyt=({type:t,result:e,verboseInfo:{escapedCommand:r,commandId:n,rawOptions:{piped:i=!1,...s}}})=>({type:t,escapedCommand:r,commandId:`${n}`,timestamp:new Date,piped:i,result:e,options:s}),hyt=(t,e)=>t.split(`
|
|
7299
7299
|
`).map(r=>myt({...e,message:r})),myt=t=>({verboseLine:nve(t),verboseObject:t}),pF=t=>{let e=typeof t=="string"?t:(0,sve.inspect)(t);return ty(e).replaceAll(" "," ".repeat(Cyt))},Cyt=2;var ove=(t,e)=>{fm(e)&&qA({type:"command",verboseMessage:t,verboseInfo:e})};h();var ave=(t,e,r)=>{Byt(t);let n=Iyt(t);return{verbose:t,escapedCommand:e,commandId:n,rawOptions:r}},Iyt=t=>fm({verbose:t})?Eyt++:void 0,Eyt=0n,Byt=t=>{for(let e of t){if(e===!1)throw new TypeError(`The "verbose: false" option was renamed to "verbose: 'none'".`);if(e===!0)throw new TypeError(`The "verbose: true" option was renamed to "verbose: 'short'".`);if(!cF.includes(e)&&!AF(e)){let r=cF.map(n=>`'${n}'`).join(", ");throw new TypeError(`The "verbose" option must not be ${e}. Allowed values are: ${r} or a function.`)}}};h();var hJ=require("node:process"),dF=()=>hJ.hrtime.bigint(),mJ=t=>Number(hJ.hrtime.bigint()-t)/1e6;var fF=(t,e,r)=>{let n=dF(),{command:i,escapedCommand:s}=qbe(t,e),o=gJ(r,"verbose"),a=ave(o,s,{...r});return ove(s,a),{command:i,escapedCommand:s,startTime:n,verboseInfo:a}};h();var FSe=z(require("node:path"),1),FJ=z(require("node:process"),1),kSe=z(JK(),1);h();var ry=z(require("node:process"),1),Kl=z(require("node:path"),1);h();function hF(t={}){let{env:e=process.env,platform:r=process.platform}=t;return r!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"}jw();var yyt=({cwd:t=ry.default.cwd(),path:e=ry.default.env[hF()],preferLocal:r=!0,execPath:n=ry.default.execPath,addExecPath:i=!0}={})=>{let s=Kl.default.resolve(mc(t)),o=[],a=e.split(Kl.default.delimiter);return r&&Qyt(o,a,s),i&&Dyt(o,a,n,s),e===""||e===Kl.default.delimiter?`${o.join(Kl.default.delimiter)}${e}`:[...o,e].join(Kl.default.delimiter)},Qyt=(t,e,r)=>{for(let n of Tre(r)){let i=Kl.default.join(n,"node_modules/.bin");e.includes(i)||t.push(i)}},Dyt=(t,e,r,n)=>{let i=Kl.default.resolve(n,mc(r),"..");e.includes(i)||t.push(i)},Ave=({env:t=ry.default.env,...e}={})=>{t={...t};let r=hF({env:t});return e.path=t[r],t[r]=yyt(e),t};h();var Dve=require("node:timers/promises");h();var cve=(t,e,r)=>{let n=r?iy:ny,i=t instanceof Ua?{}:{cause:t};return new n(e,i)},Ua=class extends Error{},uve=(t,e)=>{Object.defineProperty(t.prototype,"name",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,gve,{value:!0,writable:!1,enumerable:!1,configurable:!1})},lve=t=>mF(t)&&gve in t,gve=Symbol("isExecaError"),mF=t=>Object.prototype.toString.call(t)==="[object Error]",ny=class extends Error{};uve(ny,ny.name);var iy=class extends Error{};uve(iy,iy.name);h();var mm=require("node:os");h();var Cve=require("node:os");h();var pve=()=>{let t=fve-dve+1;return Array.from({length:t},wyt)},wyt=(t,e)=>({name:`SIGRT${e+1}`,number:dve+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),dve=34,fve=64;h();var mve=require("node:os");h();var hve=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];var CJ=()=>{let t=pve();return[...hve,...t].map(byt)},byt=({name:t,number:e,description:r,action:n,forced:i=!1,standard:s})=>{let{signals:{[t]:o}}=mve.constants,a=o!==void 0;return{name:t,number:a?o:e,description:r,supported:a,action:n,forced:i,standard:s}};var vyt=()=>{let t=CJ();return Object.fromEntries(t.map(Syt))},Syt=({name:t,number:e,description:r,supported:n,action:i,forced:s,standard:o})=>[t,{name:t,number:e,description:r,supported:n,action:i,forced:s,standard:o}],Ive=vyt(),xyt=()=>{let t=CJ(),e=65,r=Array.from({length:e},(n,i)=>Fyt(i,t));return Object.assign({},...r)},Fyt=(t,e)=>{let r=kyt(t,e);if(r===void 0)return{};let{name:n,description:i,supported:s,action:o,forced:a,standard:A}=r;return{[t]:{name:n,number:t,description:i,supported:s,action:o,forced:a,standard:A}}},kyt=(t,e)=>{let r=e.find(({name:n})=>Cve.constants.signals[n]===t);return r!==void 0?r:e.find(n=>n.number===t)},sBr=xyt();var Bve=t=>{let e="option `killSignal`";if(t===0)throw new TypeError(`Invalid ${e}: 0 cannot be used.`);return Qve(t,e)},yve=t=>t===0?t:Qve(t,"`subprocess.kill()`'s argument"),Qve=(t,e)=>{if(Number.isInteger(t))return Ryt(t,e);if(typeof t=="string")return Nyt(t,e);throw new TypeError(`Invalid ${e} ${String(t)}: it must be a string or an integer.
|
|
@@ -7394,7 +7394,7 @@ Smart Export URL: ${r.smartExportUrl}`);try{await c.initializeSession({skipSessi
|
|
|
7394
7394
|
Files changed:
|
|
7395
7395
|
${u.map(m=>` ${m.filePath} (+${m.addedLines} -${m.removedLines})`).join(`
|
|
7396
7396
|
`)}${p}`:`Implementation complete. No files were changed.${p}`}],isError:!1}}catch(n){return Vl.captureException(new Error("Builder MCP implementWithDesignSystem failed",{cause:n}),{tags:{operation:"dsi-mcp-implement"}}),{content:[{type:"text",text:`Error running implementation: ${n instanceof Error?n.message:String(n)}`}],isError:!0}}if(e==="pullPrototype")try{if(!Qi||!Fs)return{content:[{type:"text",text:"System and args must be initialized before calling pullPrototype"}],isError:!0};let{builderPublicKey:n,builderPrivateKey:i,userId:s}=Jo(Qi,Fs);if(!n||!s||!i)return{content:[{type:"text",text:`Missing required credentials. Please run \`npx ${it()} auth\` to authenticate.`}],isError:!0};if(!r||!r.prototypeUrl)return{content:[{type:"text",text:"Missing prototypeUrl"}],isError:!0};let o=eu(r.prototypeUrl);if(!o)return{content:[{type:"text",text:`Invalid prototype URL: ${r.prototypeUrl}
|
|
7397
|
-
Expected format: https://builder.io/app/projects/<projectId>/<branchName>`}],isError:!0};let a={"Content-Type":"application/json",Authorization:`Bearer ${i}`},[A,c]=await Promise.all([qB({projectId:o.projectId,branchName:o.branchName,apiKey:n,authHeaders:a,userId:s,showLogs:!1}),YB({projectId:o.projectId,branchName:o.branchName,apiKey:n,authHeaders:a,userId:s}).catch(()=>[])]);if(!A)return{content:[{type:"text",text:"Failed to pull prototype. The prototype may not exist or you may not have access."}],isError:!0};let u=A.projectDir,l=
|
|
7397
|
+
Expected format: https://builder.io/app/projects/<projectId>/<branchName>`}],isError:!0};let a={"Content-Type":"application/json",Authorization:`Bearer ${i}`},[A,c]=await Promise.all([qB({projectId:o.projectId,branchName:o.branchName,apiKey:n,authHeaders:a,userId:s,showLogs:!1}),YB({projectId:o.projectId,branchName:o.branchName,apiKey:n,authHeaders:a,userId:s}).catch(()=>[])]);if(!A)return{content:[{type:"text",text:"Failed to pull prototype. The prototype may not exist or you may not have access."}],isError:!0};let u=A.projectDir,l=bH(c);return{content:[{type:"text",text:`## Prototype Code
|
|
7398
7398
|
The prototype code has been downloaded to: ${u}
|
|
7399
7399
|
|
|
7400
7400
|
Read all files in that directory to understand the prototype implementation.
|
|
@@ -7414,7 +7414,7 @@ ${l}
|
|
|
7414
7414
|
`)}async function Gbt(t){let e=await Lbt("gh",["pr","diff",t]),r=_bt(e);Pbt(r);let n=Ubt(r.join(`
|
|
7415
7415
|
`))+`
|
|
7416
7416
|
`,i=(0,Zj.join)(process.cwd(),".builder","tmp");(0,wk.mkdirSync)(i,{recursive:!0});let s=(0,$ke.randomBytes)(4).toString("hex"),o=`pr-diff-${t}-${s}.diff`;(0,wk.writeFileSync)((0,Zj.join)(i,o),n,"utf-8"),process.stdout.write(`.builder/tmp/${o}
|
|
7417
|
-
`)}async function Vke(t,e,r){if(e==="diff"){let n=r._[2];if(!n)throw new Error("Usage: builderio agent diff <pr_number>");await Gbt(String(n))}else throw new Error(`Unknown agent subcommand: ${e??"(none)"}. Available: diff`)}h();kr();
|
|
7417
|
+
`)}async function Vke(t,e,r){if(e==="diff"){let n=r._[2];if(!n)throw new Error("Usage: builderio agent diff <pr_number>");await Gbt(String(n))}else throw new Error(`Unknown agent subcommand: ${e??"(none)"}. Available: diff`)}h();kr();W4();rr();async function Wke(t,e){let r=await Wt(t,e,{}),n=r.builderPublicKey;n||($.error("No space ID found. Please authenticate first with `npx @builder.io/dev-tools auth`."),process.exit(1));let i=t.cwd(),s=r.builderPrivateKey,o=!!e.continuous,a=2;s||($.error("No private key found. Please authenticate first with `npx @builder.io/dev-tools auth`."),process.exit(1));let A=async()=>{let c=is();c.start(`Syncing space ${n}...`);try{await Cx({sys:t,ownerId:n,privateKey:s,outputDir:i}),c.stop(`Synced space ${n}`)}catch(u){throw c.stop(`Sync failed: ${u instanceof Error?u.message:String(u)}`),u}};if(await A(),o){$.info(`Running in continuous mode, syncing every ${a} minutes. Press Ctrl+C to stop.`);let c=setInterval(async()=>{try{await A()}catch(u){$.error(`Sync error: ${u instanceof Error?u.message:String(u)}`)}},a*60*1e3);await new Promise(u=>{process.on("SIGINT",()=>{clearInterval(c),$.info("Stopped continuous sync."),u()})})}}h();kr();Ml();rr();var zke=z(require("prompts"),1),bk=z(Ir(),1);xo();Ns();xt();async function Wp(t,e){let n=[...t].sort((s,o)=>s.name.localeCompare(o.name,void 0,{sensitivity:"base"})).map(s=>({title:s.name,value:s.id})),{project:i}=await(0,zke.default)({type:"autocomplete",name:"project",message:e,choices:n,suggest:async(s,o)=>{if(!s)return o;let a=s.toLowerCase();return o.filter(A=>(A.title??"").toLowerCase().includes(a))}});return i||(Ke("Cancelled."),process.exit(0)),i}async function Xke(t,e){let{builderPublicKey:r,builderPrivateKey:n,userId:i,spaceName:s}=await Wt(t,e,{builderPrivateKey:!0,builderPublicKey:!0});if(!r||!n)throw new Error("Builder.io credentials are required. Run `npx builder.io auth` first.");let o=i??"",a;try{let{stdout:l}=await yi("git",["symbolic-ref","--short","HEAD"]);a=l.trim()}catch{throw new Error("Not inside a git repository, or HEAD is detached. Please run this command from a git branch.")}if(!await Gc(process.cwd(),t)){$.warn("You have uncommitted changes that will not be included in this push.");let l=await wr({message:"Continue anyway?"});(je(l)||!l)&&(Ke("Push cancelled."),process.exit(0))}if(e.dryrun){$.info(`Dry run: would push "${a}" and ensure a Builder branch exists.`);try{await yi("git",["push","--dry-run","origin",a])}catch(l){throw new Error(`git push --dry-run failed: ${_l(l)}`)}return}let c;try{c=await $l({projectId:e.projectId,builderPublicKey:r,builderPrivateKey:n,userId:o,spaceName:s,onMultipleRepoMatches:async l=>($.info("Multiple Builder.io projects are connected to this repository. Please select one:"),Wp(l,"Select a Builder.io project for this repository:")),onNoRepoMatch:async l=>Wp(l,"Select a Builder.io project:")})}catch(l){throw $.error("Could not resolve project."),l}let u=Bi();try{let l=await Ck({builderPublicKey:r,builderPrivateKey:n,userId:o},a,c,{onGitPushing:d=>u.start(`Pushing "${d}" to origin...`),onGitPushed:d=>u.stop(`Pushed "${d}" to origin.`),onBranchLookupStart:()=>u.start("Looking up Builder branch..."),onBranchFound:d=>u.stop("Builder branch found."),onBranchCreating:()=>{u.stop("No existing Builder branch found. Creating one..."),u.start("Creating Builder branch...")},onBranchCreated:d=>u.stop("Builder branch created."),onSyncDone:()=>$.info("Remote container synced."),onSyncWarning:d=>$.warn(`Could not notify remote container to sync: ${d}`)});$.success("Branch pushed successfully."),$.info(`View at: ${(0,bk.green)(l.branchUrl)}`)}catch(l){if(u.stop("Failed.",1),l instanceof $p){let d=s?`"${s}" (${l.builderPublicKey})`:l.builderPublicKey;$.error(`Project "${l.projectId}" was not found in space ${d}.
|
|
7418
7418
|
Make sure you are authenticated to the correct Builder.io space.
|
|
7419
7419
|
To switch spaces or re-authenticate, run:
|
|
7420
7420
|
|
|
@@ -7436,7 +7436,7 @@ Otherwise, make sure the branch exists and the Builder.io web app has pushed its
|
|
|
7436
7436
|
${(0,eY.cyan)("git stash")}`),new Error("git pull failed")}throw p}}$G();oY();async function Obt(t){let e=t.mainRef;if(!e)return process.stderr.write(JSON.stringify({success:!1,error:"mainRef is required"})+`
|
|
7437
7437
|
`),1;let r=t.branchRef;if(!r)return process.stderr.write(JSON.stringify({success:!1,error:"branchRef is required"})+`
|
|
7438
7438
|
`),1;let n=await av({cwd:process.cwd(),mainRef:e,branchRef:r}),i=JSON.stringify(n)+`
|
|
7439
|
-
`;return n.success?(process.stdout.write(i),0):(process.stderr.write(i),1)}async function Kbt(t,e){console.log(""),sr((0,Wl.bgMagenta)((0,Wl.bold)((0,Wl.white)(" dev-tools server ")))+" "+(0,Wl.dim)(ht)),t.debug("builder dev tools cli init");let r=await(0,eRe.createDevTools)(t,e.nativeApp);await(0,rRe.createDevToolsServer)({...r,getClientId:()=>"builder-dev-tools-cli",closeAppServer:async()=>{},restartAppServer:async()=>{t.debug("restart server")},enableAppWatch:async n=>n,...t})}Nye();async function Hbt(){let t=(0,nRe.default)(process.argv.slice(2),{string:["figmaToken","privateKey","spaceId","cwd","prompt","token","url","sessionId","command","c","serverUrl","builderPublicKey","builderPrivateKey","builderUserId","repoFullName","branchName","installCommand","projectId","configJson","configPath","workspace","enabledTools","disabledTools","designSystemPackage","includeDirectories","addDirectory","scope","components","include","exclude","instructions","uploadCustomDocs","name","mainRef","branchRef"],boolean:["help","ci","force","verbose","fusionInit","debug","dryrun","yes","skipInstallation","skipDetailedGrouping","noAuth","auth","dev","app","noOpen","open","silent","interactive","jsonOutput","local","clearMappings","index","listIndexedRepos","disableMcp","reset","privacyMode","nativeApp","runInPty","run-in-pty","acceptSelfSigned","chat","createFusionExample","testFusionExample","continuous","accept","remote","remote-only"],alias:{p:"port",c:"command",json:"jsonOutput",native:"nativeApp","run-in-pty":"runInPty",y:"yes",add:"addDirectory",i:"include",e:"exclude",project:"projectId","dry-run":"dryrun"},default:{interactive:!1,fusionInit:!1}});t.cwd&&process.chdir(t.cwd),t.debug&&(process.env.DEBUG="1"),t.acceptSelfSigned&&(process.env.FUSION_REJECT_UNAUTHORIZED="0");let e=await Dz(!!(t.verbose||t.debug));aY("process",Me),await e.withScope(async r=>{try{let n=await(0,tRe.createDevToolsNodeSys)({cwd:process.cwd(),ignoreMissingConfig:!0});n.Sentry?.setTag("cli-command",t._.join(" ")),n.Sentry?.setContext("flags-args",{...t});let i=t._[0];if(i==="resolve-schema-merge")return await Me(await Obt(t));let{builderPublicKey:s}=await Wt(n,t,{});if(n.Sentry?.setTag("spaceId",s),t.help)return Zc(t._[t._.length-1]),await Me(0);if(i==="figma"){let o=t._[1];try{return await Lwe(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="code"){let o=t._[1];try{t.index&&(t.skipDetailedGrouping=!0,t.skipHeader=!0,await oJ(n,t)),await HDe(n,o,t)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="index-repo"||i==="repo-index")try{return await oJ(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="launch"||i==="fusion")try{await mDe({sys:n,args:t})}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="add"){let o=
|
|
7439
|
+
`;return n.success?(process.stdout.write(i),0):(process.stderr.write(i),1)}async function Kbt(t,e){console.log(""),sr((0,Wl.bgMagenta)((0,Wl.bold)((0,Wl.white)(" dev-tools server ")))+" "+(0,Wl.dim)(ht)),t.debug("builder dev tools cli init");let r=await(0,eRe.createDevTools)(t,e.nativeApp);await(0,rRe.createDevToolsServer)({...r,getClientId:()=>"builder-dev-tools-cli",closeAppServer:async()=>{},restartAppServer:async()=>{t.debug("restart server")},enableAppWatch:async n=>n,...t})}Nye();async function Hbt(){let t=(0,nRe.default)(process.argv.slice(2),{string:["figmaToken","privateKey","spaceId","cwd","prompt","token","url","sessionId","command","c","serverUrl","builderPublicKey","builderPrivateKey","builderUserId","repoFullName","branchName","installCommand","projectId","configJson","configPath","workspace","enabledTools","disabledTools","designSystemPackage","includeDirectories","addDirectory","scope","components","include","exclude","instructions","uploadCustomDocs","name","mainRef","branchRef"],boolean:["help","ci","force","verbose","fusionInit","debug","dryrun","yes","skipInstallation","skipDetailedGrouping","noAuth","auth","dev","app","noOpen","open","silent","interactive","jsonOutput","local","clearMappings","index","listIndexedRepos","disableMcp","reset","privacyMode","nativeApp","runInPty","run-in-pty","acceptSelfSigned","chat","createFusionExample","testFusionExample","continuous","accept","remote","remote-only"],alias:{p:"port",c:"command",json:"jsonOutput",native:"nativeApp","run-in-pty":"runInPty",y:"yes",add:"addDirectory",i:"include",e:"exclude",project:"projectId","dry-run":"dryrun"},default:{interactive:!1,fusionInit:!1}});t.cwd&&process.chdir(t.cwd),t.debug&&(process.env.DEBUG="1"),t.acceptSelfSigned&&(process.env.FUSION_REJECT_UNAUTHORIZED="0");let e=await Dz(!!(t.verbose||t.debug));aY("process",Me),await e.withScope(async r=>{try{let n=await(0,tRe.createDevToolsNodeSys)({cwd:process.cwd(),ignoreMissingConfig:!0});n.Sentry?.setTag("cli-command",t._.join(" ")),n.Sentry?.setContext("flags-args",{...t});let i=t._[0];if(i==="resolve-schema-merge")return await Me(await Obt(t));let{builderPublicKey:s}=await Wt(n,t,{});if(n.Sentry?.setTag("spaceId",s),t.help)return Zc(t._[t._.length-1]),await Me(0);if(i==="figma"){let o=t._[1];try{return await Lwe(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="code"){let o=t._[1];try{t.index&&(t.skipDetailedGrouping=!0,t.skipHeader=!0,await oJ(n,t)),await HDe(n,o,t)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="index-repo"||i==="repo-index")try{return await oJ(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="launch"||i==="fusion")try{await mDe({sys:n,args:t})}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="add"){let o=GH(n.getAppRootDir(),process.argv.slice(2));return await Une(o),await Me(0)}else if(i==="sync"){let o=GH(n.getAppRootDir(),process.argv.slice(2)),a=await SH(o);await cwe(n,a).then(()=>{$.success("Builder dev tools is running")}).catch(A=>($.error("Cannot start builder dev tools"),n.Sentry?.captureException(A),Me(1)))}else if(i==="auth"){let o=t._[1];try{return await abe(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="doctor"){let o=t._[1];try{return await Uke(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="connect-repo"||i==="repo-connect")try{return await Sbe(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="agent"){let o=t._[1];try{return await Vke(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(Zr(a),Ke()),await Me(1)}}else if(i==="space-sync")try{return await Wke(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="push")try{return await Xke(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="pull")try{return await Zke(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else if(i==="dsi-mcp"||i==="mcp")try{await Yke(n,t)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(Zr(o),Ke()),await Me(1)}else{if(i==="help")return Zc(t._[1]),await Me(0);if(i==="publish"||i==="migrate"||i==="generate")return Ke("Command not found, do you mean `npx "+it()+" figma "+i+"`?"),await Me(1);Kbt(n,t).then(()=>{$.success("Builder dev tools is running")}).catch(o=>($.error("Cannot start builder dev tools"),e.captureException(o),Me(1)))}}catch(n){return e.captureException(n),n instanceof qe&&(Zr(n),Ke("Cannot start builder dev tools due to network error")),await Me(1)}})}Hbt().catch(t=>{process.stderr.write((t instanceof Error?t.stack??t.message:String(t))+`
|
|
7440
7440
|
`),process.exit(1)});var Jbt=void 0;
|
|
7441
7441
|
/*! Bundled license information:
|
|
7442
7442
|
|