@builder.io/dev-tools 1.64.2-beta.202606092106.da31a10 → 1.64.2-beta.202606100020.95cbe0b
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 +89 -89
- package/cli/index.cjs.map +2 -2
- 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/cli/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var aRe=Object.create;var Dy=Object.defineProperty;var ARe=Object.getOwnPropertyDescriptor;var cRe=Object.getOwnPropertyNames;var uRe=Object.getPrototypeOf,lRe=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 cRe(e))!lRe.call(t,i)&&i!==r&&Dy(t,i,{get:()=>e[i],enumerable:!(n=ARe(e,i))||n.enumerable});return t};var z=(t,e,r)=>(r=t!=null?aRe(uRe(t)):{},tY(e||!t||!t.__esModule?Dy(r,"default",{value:t,enumerable:!0}):r,t)),zr=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 aRe=Object.create;var Dy=Object.defineProperty;var ARe=Object.getOwnPropertyDescriptor;var cRe=Object.getOwnPropertyNames;var uRe=Object.getPrototypeOf,lRe=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 cRe(e))!lRe.call(t,i)&&i!==r&&Dy(t,i,{get:()=>e[i],enumerable:!(n=ARe(e,i))||n.enumerable});return t};var z=(t,e,r)=>(r=t!=null?aRe(uRe(t)):{},tY(e||!t||!t.__esModule?Dy(r,"default",{value:t,enumerable:!0}):r,t)),zr=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:"95cbe0b32de2f2c72efc7de36cfc4894d7a385fd"}}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 gRe(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:gRe(r,n),timestamp:new Date().toISOString()};r&&(i.context=r),t.write(JSON.stringify(i)+`
|
|
2
2
|
`)}function pRe(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 dRe(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()?pRe(rY(n??"info"),r,t):dRe(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((tvt,AY)=>{h();function vk(t){return t==null?[]:Array.isArray(t)?t:[t]}function fRe(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);fRe(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 hRe(){if(Nm!==void 0)return Nm;try{return Nm=require("prettier"),Nm}catch{return Nm=null,null}}function mRe(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 CRe(t){if(t)try{let r=(0,uY.createRequire)(t)("prettier");if(r)return r}catch{}return hRe()}async function ZA(t,e,r,n){try{let i=zl.default.resolve(t,n??"file.tsx"),s=CRe(i);if(!s)return e;if(n){let A=mRe(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((avt,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"},IRe={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ERe={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:IRe,erase:ERe,beep:"\x07"}});var Er=N((cvt,Nk)=>{h();var ky=process||{},dY=ky.argv||[],Fy=ky.env||{},BRe=!(Fy.NO_COLOR||dY.includes("--no-color"))&&(!!Fy.FORCE_COLOR||dY.includes("--color")||ky.platform==="win32"||(ky.stdout||{}).isTTY&&Fy.TERM!=="dumb"||!!Fy.CI),yRe=(t,e,r=t)=>n=>{let i=""+n,s=i.indexOf(e,t.length);return~s?t+QRe(i,e,r,s)+e:t+i+e},QRe=(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=BRe)=>{let e=t?yRe:()=>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 DRe({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(wRe,"")}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(xRe()," ");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(vRe.eastAsianWidth(i)){case"F":case"W":n+=2;break;case"A":n+=r;break;default:n+=1}}return n}function RRe(){let t=new Map;for(let[e,r]of Object.entries(Pr)){for(let[n,i]of Object.entries(r))Pr[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Pr[n],t.set(i[0],i[1]);Object.defineProperty(Pr,e,{value:r,enumerable:!1})}return Object.defineProperty(Pr,"codes",{value:t,enumerable:!1}),Pr.color.close="\x1B[39m",Pr.bgColor.close="\x1B[49m",Pr.color.ansi=hY(),Pr.color.ansi256=mY(),Pr.color.ansi16m=CY(),Pr.bgColor.ansi=hY(Mk),Pr.bgColor.ansi256=mY(Mk),Pr.bgColor.ansi16m=CY(Mk),Object.defineProperties(Pr,{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=>Pr.rgbToAnsi256(...Pr.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)=>Pr.ansi256ToAnsi(Pr.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>Pr.ansi256ToAnsi(Pr.hexToAnsi256(e)),enumerable:!1}}),Pr}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 Kn(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((wvt,KY)=>{"use strict";h();KY.exports=function(){if(process.env.npm_config_user_agent)return nTe(process.env.npm_config_user_agent)};function nTe(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 to(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=zo(e),r=zo(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=zo(t.normalize(i)),i.startsWith(".")||(i="./"+i),i}function zo(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 Br(t).replace(/ /g,"")}function ro(t,e){let r=t.extname(e),n=zo(t.basename(e,r)).split("/").pop();return Br(n==="index"?t.basename(t.dirname(e)):n)}function yr(t,e){let r=zo(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 Br(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 os(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 Ki(t){return typeof t=="string"}function sd(t){return typeof t=="string"?/^[A-Z][A-Za-z0-9]*$/.test(t):!1}function Ts(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 iTe(){return process.platform.startsWith("win")}function it(){return process.pkg?"@builder.io/agent":iTe()?'"@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 Hi(t){let e=t.join(t.getAppRootDir(),"tsconfig.json");return t.exists(e)}async function as(t,e){async function r(i,s){if(s>10)return;let o=await t.readdir(i);for(let a of o){if(sTe.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 Hi(t)?"ts":"js"}`;return t.join(e,s)}return n}async function Xo(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 sTe,vi=L(()=>{"use strict";h();sTe=["node_modules","dist","build","public"]});async function Sn(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 oTe(t,o,e,r)}catch(a){if(a instanceof Hy){await aTe(t,a.libName);continue}throw t.Sentry?.captureException(a),new Error(`createTsProgram() Could not create program for: ${e[0]}`,{cause:a})}}function oTe(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=Ts(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 Sn(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 aTe(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,no=L(()=>{"use strict";h();jr();xt();vi();Hy=class{libName;constructor(e){this.libName=e}};WY=new Map,Ky=new Map,Um=new Map,VY=new Map});var ATe,ht,Xr=L(()=>{"use strict";h();ATe="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 oTe(t,o,e,r)}catch(a){if(a instanceof Hy){await aTe(t,a.libName);continue}throw t.Sentry?.captureException(a),new Error(`createTsProgram() Could not create program for: ${e[0]}`,{cause:a})}}function oTe(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=Ts(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 Sn(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 aTe(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,no=L(()=>{"use strict";h();jr();xt();vi();Hy=class{libName;constructor(e){this.libName=e}};WY=new Map,Ky=new Map,Um=new Map,VY=new Map});var ATe,ht,Xr=L(()=>{"use strict";h();ATe="1.64.2-beta.202606100020.95cbe0b",ht=process.env.OVERRIDE_VERSION??ATe});async function ng(t){let e=[],r=await Xo(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 cTe)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,cTe,ig=L(()=>{"use strict";h();vi();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)}}]]),cTe=["@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 io(t){let e=e9(t),r=await t.readFile(e);return typeof r=="string"?JSON.parse(r):{}}async function so(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 uTe(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 uTe(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=lTe.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 q3e(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 $3e(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=$3e(t);return e?{frontmatter:q3e(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=V3e(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,V3e,lP,W3e,z3e,X3e,gP,Z3e,RZ,eKe,tKe,rKe,TZ,NZ,pP,MZ,nKe,pw,xZ,FZ,PZ=L(()=>{h();dw=require("node:events"),kZ=require("node:stream"),dP=require("node:stream/promises");V3e=(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{#r=new Set([]);#c=new Set([]);#s=new Set([]);#n;add(e){gP(e),!this.#r.has(e)&&(this.#r.add(e),this.#n??=W3e(this,this.#r),Z3e({passThroughStream:this,stream:e,streams:this.#r,ended:this.#c,aborted:this.#s,onFinished:this.#n}),e.pipe(this,{end:!1}))}remove(e){return gP(e),this.#r.has(e)?(e.unpipe(this),!0):!1}},W3e=async(t,e)=>{pw(t,xZ);let r=new AbortController;try{await Promise.race([z3e(t,r),X3e(t,e,r)])}finally{r.abort(),pw(t,-xZ)}},z3e=async(t,{signal:e})=>{await(0,dP.finished)(t,{signal:e,cleanup:!0})},X3e=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([eKe(s,e),tKe({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:o}),rKe({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",eKe=async(t,e)=>{try{await t,pP(e)}catch(r){RZ(r)?pP(e):MZ(e,r)}},tKe=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)}},rKe=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",nKe),t.destroy(e))},nKe=()=>{},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 iKe(t){return t.reduce((e,r)=>[].concat(e,r),[])}Af.flatten=iKe;function sKe(t,e){let r=[[]],n=0;for(let i of t)e(i)?(n++,r[n]=[]):r[n].push(i);return r}Af.splitWhen=sKe});var _Z=N(fw=>{"use strict";h();Object.defineProperty(fw,"__esModule",{value:!0});fw.isEnoentCodeError=void 0;function oKe(t){return t.code==="ENOENT"}fw.isEnoentCodeError=oKe});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 aKe(t,e){return new hP(t,e)}hw.createDirentFromStats=aKe});var HZ=N(Qn=>{"use strict";h();Object.defineProperty(Qn,"__esModule",{value:!0});Qn.convertPosixPathToPattern=Qn.convertWindowsPathToPattern=Qn.convertPathToPattern=Qn.escapePosixPath=Qn.escapeWindowsPath=Qn.escape=Qn.removeLeadingDotSegment=Qn.makeAbsolute=Qn.unixify=void 0;var AKe=require("os"),cKe=require("path"),GZ=AKe.platform()==="win32",uKe=2,lKe=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,gKe=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,pKe=/^\\\\([.?])/,dKe=/\\(?![!()+@[\]{}])/g;function fKe(t){return t.replace(/\\/g,"/")}Qn.unixify=fKe;function hKe(t,e){return cKe.resolve(t,e)}Qn.makeAbsolute=hKe;function mKe(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(uKe)}return t}Qn.removeLeadingDotSegment=mKe;Qn.escape=GZ?mP:CP;function mP(t){return t.replace(gKe,"\\$2")}Qn.escapeWindowsPath=mP;function CP(t){return t.replace(lKe,"\\$2")}Qn.escapePosixPath=CP;Qn.convertPathToPattern=GZ?OZ:KZ;function OZ(t){return mP(t).replace(pKe,"//$1").replace(dKe,"/")}Qn.convertWindowsPathToPattern=OZ;function KZ(t){return CP(t)}Qn.convertPosixPathToPattern=KZ});var jZ=N((NOt,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((POt,qZ)=>{h();var CKe=jZ(),YZ={"{":"}","(":")","[":"]"},IKe=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},EKe=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(CKe(e))return!0;var n=IKe;return r&&r.strict===!1&&(n=EKe),n(e)}});var WZ=N((_Ot,VZ)=>{"use strict";h();var BKe=$Z(),yKe=require("path").posix.dirname,QKe=require("os").platform()==="win32",IP="/",DKe=/\\/g,wKe=/[\{\[].*[\}\]]$/,bKe=/(^|[^\\])([\{\[]|\([^\)]+$)/,vKe=/\\([\!\*\?\|\[\]\(\)\{\}])/g;VZ.exports=function(e,r){var n=Object.assign({flipBackslashes:!0},r);n.flipBackslashes&&QKe&&e.indexOf(IP)<0&&(e=e.replace(DKe,IP)),wKe.test(e)&&(e+=IP),e+="a";do e=yKe(e);while(BKe(e)||bKe.test(e));return e.replace(vKe,"$1")}});var mw=N(po=>{"use strict";h();po.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;po.find=(t,e)=>t.nodes.find(r=>r.type===e);po.exceedsLimit=(t,e,r=1,n)=>n===!1||!po.isInteger(t)||!po.isInteger(e)?!1:(Number(e)-Number(t))/Number(r)>=n;po.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)};po.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;po.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;po.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;po.reduce=t=>t.reduce((e,r)=>(r.type==="text"&&e.push(r.value),r.type==="range"&&(r.type="text"),e),[]);po.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((KOt,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((JOt,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((YOt,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=SKe(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 SKe(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 xKe(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(RKe),s}function FKe(t,e,r){if(t===e)return{pattern:t,count:[],digits:0};let n=kKe(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+=TKe(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=xKe(t,e),s=[],o=t,a;for(let A=0;A<i.length;A++){let c=i[A],u=FKe(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=NKe(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 kKe(t,e){let r=[];for(let n=0;n<t.length;n++)r.push([t[n],e[n]]);return r}function RKe(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 TKe(t,e,r){return`[${t}${e-t===1?"":"-"}${e}]`}function aee(t){return/^-?(0+)\d/.test(t)}function NKe(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(($Ot,hee)=>{"use strict";h();var MKe=require("util"),lee=cee(),uee=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),PKe=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},LKe=(t,e,r)=>typeof t=="string"||typeof e=="string"?!0:r.stringify===!0,_Ke=(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},UKe=(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: "+MKe.inspect(...t)),fee=(t,e,r)=>{if(r.strictRanges===!0)throw dee([t,e]);return[]},GKe=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},OKe=(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&&LKe(t,e,n)===!1,g=n.transform||PKe(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(_Ke(g(i,C),l,d)),i=o?i-r:i+r,C++;return n.toRegex===!0?r>1?UKe(p,n,l):pee(m,null,{wrap:!1,...n}):m},KKe=(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)?OKe(t,e,r,i):KKe(t,e,Math.max(Math.abs(r),1),i):r!=null&&!uee(r)?GKe(r,i):Iw(t,e,1,r)};hee.exports=Iw});var Iee=N((WOt,Cee)=>{"use strict";h();var HKe=QP(),mee=mw(),JKe=(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=HKe(...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=JKe});var yee=N((XOt,Bee)=>{"use strict";h();var jKe=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)},YKe=(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=jKe(...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=YKe});var Dee=N((e8t,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((r8t,See)=>{"use strict";h();var qKe=Cw(),{MAX_LENGTH:wee,CHAR_BACKSLASH:DP,CHAR_BACKTICK:$Ke,CHAR_COMMA:VKe,CHAR_DOT:WKe,CHAR_LEFT_PARENTHESES:zKe,CHAR_RIGHT_PARENTHESES:XKe,CHAR_LEFT_CURLY_BRACE:ZKe,CHAR_RIGHT_CURLY_BRACE:e4e,CHAR_LEFT_SQUARE_BRACKET:bee,CHAR_RIGHT_SQUARE_BRACKET:vee,CHAR_DOUBLE_QUOTE:t4e,CHAR_SINGLE_QUOTE:r4e,CHAR_NO_BREAK_SPACE:n4e,CHAR_ZERO_WIDTH_NOBREAK_SPACE:i4e}=Dee(),s4e=(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===i4e||d===n4e)){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===zKe){o=p({type:"paren",nodes:[]}),s.push(o),p({type:"text",value:d});continue}if(d===XKe){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===t4e||d===r4e||d===$Ke){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===e4e){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===VKe&&l>0){if(o.ranges>0){o.ranges=0;let f=o.nodes.shift();o.nodes=[f,{type:"text",value:qKe(o)}]}p({type:"comma",value:d}),o.commas++;continue}if(d===WKe&&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=s4e});var Ree=N((i8t,kee)=>{"use strict";h();var Fee=Cw(),o4e=Iee(),a4e=yee(),A4e=xee(),Gs=(t,e={})=>{let r=[];if(Array.isArray(t))for(let n of t){let i=Gs.create(n,e);Array.isArray(i)?r.push(...i):r.push(i)}else r=[].concat(Gs.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(r=[...new Set(r)]),r};Gs.parse=(t,e={})=>A4e(t,e);Gs.stringify=(t,e={})=>Fee(typeof t=="string"?Gs.parse(t,e):t,e);Gs.compile=(t,e={})=>(typeof t=="string"&&(t=Gs.parse(t,e)),o4e(t,e));Gs.expand=(t,e={})=>{typeof t=="string"&&(t=Gs.parse(t,e));let r=a4e(t,e);return e.noempty===!0&&(r=r.filter(Boolean)),e.nodupes===!0&&(r=[...new Set(r)]),r};Gs.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Gs.compile(t,e):Gs.expand(t,e);kee.exports=Gs});var rI=N((o8t,Lee)=>{"use strict";h();var c4e=require("path"),pA="\\\\/",Tee=`[^${pA}]`,fc="\\.",u4e="\\+",l4e="\\?",Bw="\\/",g4e="(?=.)",Nee="[^/]",wP=`(?:${Bw}|$)`,Mee=`(?:^|${Bw})`,bP=`${fc}{1,2}${wP}`,p4e=`(?!${fc})`,d4e=`(?!${Mee}${bP})`,f4e=`(?!${fc}{0,1}${wP})`,h4e=`(?!${bP})`,m4e=`[^.${Bw}]`,C4e=`${Nee}*?`,Pee={DOT_LITERAL:fc,PLUS_LITERAL:u4e,QMARK_LITERAL:l4e,SLASH_LITERAL:Bw,ONE_CHAR:g4e,QMARK:Nee,END_ANCHOR:wP,DOTS_SLASH:bP,NO_DOT:p4e,NO_DOTS:d4e,NO_DOT_SLASH:f4e,NO_DOTS_SLASH:h4e,QMARK_NO_DOT:m4e,STAR:C4e,START_ANCHOR:Mee},I4e={...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}]|$)`},E4e={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:E4e,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:c4e.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?I4e:Pee}}});var nI=N(gs=>{"use strict";h();var B4e=require("path"),y4e=process.platform==="win32",{REGEX_BACKSLASH:Q4e,REGEX_REMOVE_BACKSLASH:D4e,REGEX_SPECIAL_CHARS:w4e,REGEX_SPECIAL_CHARS_GLOBAL:b4e}=rI();gs.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);gs.hasRegexChars=t=>w4e.test(t);gs.isRegexChar=t=>t.length===1&&gs.hasRegexChars(t);gs.escapeRegex=t=>t.replace(b4e,"\\$1");gs.toPosixSlashes=t=>t.replace(Q4e,"/");gs.removeBackslashes=t=>t.replace(D4e,e=>e==="\\"?"":e);gs.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};gs.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:y4e===!0||B4e.sep==="\\";gs.escapeLast=(t,e,r)=>{let n=t.lastIndexOf(e,r);return n===-1?t:t[n-1]==="\\"?gs.escapeLast(t,e,n-1):`${t.slice(0,n)}\\${t.slice(n)}`};gs.removePrefix=(t,e={})=>{let r=t;return r.startsWith("./")&&(r=r.slice(2),e.prefix="./"),r};gs.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((u8t,Jee)=>{"use strict";h();var _ee=nI(),{CHAR_ASTERISK:vP,CHAR_AT:v4e,CHAR_BACKWARD_SLASH:iI,CHAR_COMMA:S4e,CHAR_DOT:SP,CHAR_EXCLAMATION_MARK:xP,CHAR_FORWARD_SLASH:Hee,CHAR_LEFT_CURLY_BRACE:FP,CHAR_LEFT_PARENTHESES:kP,CHAR_LEFT_SQUARE_BRACKET:x4e,CHAR_PLUS:F4e,CHAR_QUESTION_MARK:Uee,CHAR_RIGHT_CURLY_BRACE:k4e,CHAR_RIGHT_PARENTHESES:Gee,CHAR_RIGHT_SQUARE_BRACKET:R4e}=rI(),Oee=t=>t===Hee||t===iI,Kee=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},T4e=(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},x=()=>c>=n,w=()=>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++;x()!==!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===S4e){if(d=S.isBrace=!0,p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===k4e&&(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===F4e||D===v4e||D===vP||D===Uee||D===xP)===!0&&w()===kP){if(p=S.isGlob=!0,f=S.isExtglob=!0,E=!0,D===xP&&c===u&&(B=!0),i===!0){for(;x()!==!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===x4e){for(;x()!==!0&&(j=P());){if(j===iI){I=S.backslashes=!0,P();continue}if(j===R4e){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(;x()!==!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 G=A,J="",_="";u>0&&(J=A.slice(0,u),A=A.slice(u),l-=u),G&&p===!0&&l>0?(G=A.slice(0,l),_=A.slice(l)):p===!0?(G="",_=A):G=A,G&&G!==""&&G!=="/"&&G!==A&&Oee(G.charCodeAt(G.length-1))&&(G=G.slice(0,-1)),r.unescape===!0&&(_&&(_=_ee.removeBackslashes(_)),G&&I===!0&&(G=_ee.removeBackslashes(G)));let K={prefix:J,input:t,start:u,base:G,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=T4e});var $ee=N((g8t,qee)=>{"use strict";h();var yw=rI(),Os=nI(),{MAX_LENGTH:Qw,POSIX_REGEX_SOURCE:N4e,REGEX_NON_SPECIAL_CHARS:M4e,REGEX_SPECIAL_CHARS_BACKREF:P4e,REPLACEMENTS:Yee}=yw,L4e=(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=>Os.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=Os.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,x=r.bash===!0?v(r):E;r.capture&&(x=`(${x})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let w={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=Os.removePrefix(t,w),i=t.length;let P=[],G=[],J=[],_=s,K,j=()=>w.index===i-1,ee=w.peek=(le=1)=>t[w.index+le],U=w.advance=()=>t[++w.index]||"",Y=()=>t.slice(w.index+1),H=(le="",be=0)=>{w.consumed+=le,w.index+=be},Z=le=>{w.output+=le.output!=null?le.output:le.value,H(le.value)},ue=()=>{let le=1;for(;ee()==="!"&&(ee(2)!=="("||ee(3)==="?");)U(),w.start++,le++;return le%2===0?!1:(w.negated=!0,w.start++,!0)},ge=le=>{w[le]++,J.push(le)},he=le=>{w[le]--,J.pop()},X=le=>{if(_.type==="globstar"){let be=w.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&&(w.output=w.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=x,w.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=w.parens,de.output=w.output;let ke=(r.capture?"(":"")+de.open;ge("parens"),X({type:le,value:be,output:w.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=x;if(le.inner&&le.inner.length>1&&le.inner.includes("/")&&(ke=v(r)),(ke!==x||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"&&(w.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(P4e,(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?x:""):x: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?(w.output=t,w):(w.output=Os.wrapOutput(be,w,e),w)}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,w.index+=Qe,Qe%2!==0&&(K+="\\")),r.unescape===!0?K=U():K+=U(),w.brackets===0){X({type:"text",value:K});continue}}if(w.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=N4e[rt];if(nt){_.value=Qe+nt,w.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(w.quotes===1&&K!=='"'){K=Os.escapeRegex(K),_.value+=K,Z({value:K});continue}if(K==='"'){w.quotes=w.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(w.parens===0&&r.strictBrackets===!0)throw new SyntaxError(uf("opening","("));let de=P[P.length-1];if(de&&w.parens===de.parens+1){Je(P.pop());continue}X({type:"paren",value:K,output:w.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(w.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||Os.hasRegexChars(de))continue;let ke=Os.escapeRegex(_.value);if(w.output=w.output.slice(0,-_.value.length),r.literalBrackets===!0){w.output+=ke,_.value=ke;continue}_.value=`(${a}${ke}|${_.value})`,w.output+=_.value;continue}if(K==="{"&&r.nobrace!==!0){ge("braces");let de={type:"brace",value:K,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};G.push(de),X(de);continue}if(K==="}"){let de=G[G.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=L4e(rt,r),w.backtrack=!0}if(de.comma!==!0&&de.dots!==!0){let Qe=w.output.slice(0,de.outputIndex),rt=w.tokens.slice(de.tokensIndex);de.value=de.output="\\{",K=ke="\\}",w.output=Qe;for(let nt of rt)w.output+=nt.output||nt.value}X({type:"brace",value:K,output:ke}),he("braces"),G.pop();continue}if(K==="|"){P.length>0&&P[P.length-1].conditions++,X({type:"text",value:K});continue}if(K===","){let de=K,ke=G[G.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"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),_=s;continue}X({type:"slash",value:K,output:g});continue}if(K==="."){if(w.braces>0&&_.type==="dot"){_.value==="."&&(_.output=l);let de=G[G.length-1];_.type="dots",_.output+=K,_.value+=K,de.dots=!0;continue}if(w.braces+w.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==="<"&&!Os.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&&w.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")||w.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=M4e.exec(Y());de&&(K+=de[0],w.index+=de[0].length),X({type:"text",value:K});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=K,_.output=x,w.backtrack=!0,w.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=w.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 Vr=t[w.index+4];if(Vr&&Vr!=="/")break;le=le.slice(3),H("/**",3)}if(de.type==="bos"&&j()){_.type="globstar",_.value+=K,_.output=v(r),w.output=_.output,w.globstar=!0,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&!rt&&j()){w.output=w.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=v(r)+(r.strictSlashes?")":"|$)"),_.value+=K,w.globstar=!0,w.output+=de.output+_.output,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&le[0]==="/"){let Vr=le[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=`${v(r)}${g}|${g}${Vr})`,_.value+=K,w.output+=de.output+_.output,w.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})`,w.output=_.output,w.globstar=!0,H(K+U()),X({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-_.output.length),_.type="globstar",_.output=v(r),_.value+=K,w.output+=_.output,w.globstar=!0,H(K);continue}let be={type:"star",value:K,output:x};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}(w.index===w.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(w.output+=C,_.output+=C):r.dot===!0?(w.output+=I,_.output+=I):(w.output+=D,_.output+=D),ee()!=="*"&&(w.output+=p,_.output+=p)),X(be)}for(;w.brackets>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","]"));w.output=Os.escapeLast(w.output,"["),he("brackets")}for(;w.parens>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing",")"));w.output=Os.escapeLast(w.output,"("),he("parens")}for(;w.braces>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","}"));w.output=Os.escapeLast(w.output,"{"),he("braces")}if(r.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${g}?`}),w.backtrack===!0){w.output="";for(let le of w.tokens)w.output+=le.output!=null?le.output:le.value,le.suffix&&(w.output+=le.suffix)}return w};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=Os.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 x=E(S[1]);return x?x+o+S[2]:void 0}}},Q=Os.removePrefix(t,I),v=E(Q);return v&&r.strictSlashes!==!0&&(v+=`${a}?`),v};qee.exports=RP});var Wee=N((d8t,Vee)=>{"use strict";h();var _4e=require("path"),U4e=jee(),TP=$ee(),NP=nI(),G4e=rI(),O4e=t=>t&&typeof t=="object"&&!Array.isArray(t),un=(t,e,r=!1)=>{if(Array.isArray(t)){let u=t.map(d=>un(d,e,r));return d=>{for(let g of u){let p=g(d);if(p)return p}return!1}}let n=O4e(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?un.compileRe(t,e):un.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=un(i.ignore,u,r)}let c=(u,l=!1)=>{let{isMatch:d,match:g,output:p}=un.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};un.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=un.matchBase(t,e,r,i):a=e.exec(A)),{isMatch:!!a,match:a,output:A}};un.matchBase=(t,e,r,n=NP.isWindows(r))=>(e instanceof RegExp?e:un.makeRe(e,r)).test(_4e.basename(t));un.isMatch=(t,e,r)=>un(e,r)(t);un.parse=(t,e)=>Array.isArray(t)?t.map(r=>un.parse(r,e)):TP(t,{...e,fastpaths:!1});un.scan=(t,e)=>U4e(t,e);un.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=un.toRegex(a,e);return n===!0&&(A.state=t),A};un.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)),un.compileRe(i,e,r,n)};un.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/$^/}};un.constants=G4e;Vee.exports=un});var Xee=N((h8t,zee)=>{"use strict";h();zee.exports=Wee()});var Dw=N((C8t,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},kr=(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};kr.match=kr;kr.matcher=(t,e)=>dA(t,e);kr.isMatch=(t,e,r)=>dA(e,r)(t);kr.any=kr.isMatch;kr.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(kr(t,e,{...r,onResult:s}));for(let a of i)o.has(a)||n.add(a);return[...n]};kr.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=>kr.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 kr.isMatch(t,e,{...r,contains:!0})};kr.matchKeys=(t,e,r)=>{if(!MP.isObject(t))throw new TypeError("Expected the first argument to be an object");let n=kr(Object.keys(t),e,r),i={};for(let s of n)i[s]=t[s];return i};kr.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};kr.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};kr.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))};kr.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)};kr.makeRe=(...t)=>dA.makeRe(...t);kr.scan=(...t)=>dA.scan(...t);kr.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};kr.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!rte(t)?[t]:tte(t,e)};kr.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return kr.braces(t,{...e,expand:!0})};kr.hasBraces=rte;nte.exports=kr});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"),K4e=WZ(),PP=Dw(),ste="**",H4e="\\",J4e=/[*?]|^!/,j4e=/\[[^[]*]/,Y4e=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,q4e=/[!*+?@]\([^(]*\)/,$4e=/,|\.\./,V4e=/(?!^)\/{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(H4e)||J4e.test(t)||j4e.test(t)||Y4e.test(t)||e.extglob!==!1&&q4e.test(t)||e.braceExpansion!==!1&&W4e(t))}tt.isDynamicPattern=ate;function W4e(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 $4e.test(n)}function z4e(t){return ww(t)?t.slice(1):t}tt.convertToPositivePattern=z4e;function X4e(t){return"!"+t}tt.convertToNegativePattern=X4e;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 eHe(t){return t.filter(Ate)}tt.getPositivePatterns=eHe;function tHe(t){return t.filter(e=>!LP(e))}tt.getPatternsInsideCurrentDirectory=tHe;function rHe(t){return t.filter(LP)}tt.getPatternsOutsideCurrentDirectory=rHe;function LP(t){return t.startsWith("..")||t.startsWith("./..")}tt.isPatternRelatedToParentDirectory=LP;function nHe(t){return K4e(t,{flipBackslashes:!1})}tt.getBaseDirectory=nHe;function iHe(t){return t.includes(ste)}tt.hasGlobStar=iHe;function cte(t){return t.endsWith("/"+ste)}tt.endsWithSlashGlobStar=cte;function sHe(t){let e=ite.basename(t);return cte(t)||ote(e)}tt.isAffectDepthOfReadingPattern=sHe;function oHe(t){return t.reduce((e,r)=>e.concat(ute(r)),[])}tt.expandPatternsWithBraceExpansion=oHe;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 aHe(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=aHe;function lte(t,e){return PP.makeRe(t,e)}tt.makeRe=lte;function AHe(t,e){return t.map(r=>lte(r,e))}tt.convertPatternsToRe=AHe;function cHe(t,e){return e.some(r=>r.test(t))}tt.matchAny=cHe;function uHe(t){return t.replace(V4e,"/")}tt.removeDuplicateSlashes=uHe;function lHe(t){let e=[],r=[];for(let n of t)gte(n)?e.push(n):r.push(n);return[e,r]}tt.partitionAbsoluteAndRelative=lHe;function gte(t){return ite.isAbsolute(t)}tt.isAbsolute=gte});var mte=N((y8t,hte)=>{"use strict";h();var gHe=require("stream"),dte=gHe.PassThrough,pHe=Array.prototype.slice;hte.exports=dHe;function dHe(){let t=[],e=pHe.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 fHe=mte();function hHe(t){let e=fHe(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=hHe;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 mHe(t){return typeof t=="string"}lf.isString=mHe;function CHe(t){return t===""}lf.isEmpty=CHe});var hc=N(Ti=>{"use strict";h();Object.defineProperty(Ti,"__esModule",{value:!0});Ti.string=Ti.stream=Ti.pattern=Ti.path=Ti.fs=Ti.errno=Ti.array=void 0;var IHe=LZ();Ti.array=IHe;var EHe=_Z();Ti.errno=EHe;var BHe=UZ();Ti.fs=BHe;var yHe=HZ();Ti.path=yHe;var QHe=pte();Ti.pattern=QHe;var DHe=Ite();Ti.stream=DHe;var wHe=Ete();Ti.string=wHe});var Dte=N(Ni=>{"use strict";h();Object.defineProperty(Ni,"__esModule",{value:!0});Ni.convertPatternGroupToTask=Ni.convertPatternGroupsToTasks=Ni.groupPatternsByBaseDirectory=Ni.getNegativePatternsAsPositive=Ni.getPositivePatterns=Ni.convertPatternsToTasks=Ni.generate=void 0;var ga=hc();function bHe(t,e){let r=Bte(t,e),n=Bte(e.ignore,e),i=yte(r),s=Qte(r,n),o=i.filter(u=>ga.pattern.isStaticPattern(u,e)),a=i.filter(u=>ga.pattern.isDynamicPattern(u,e)),A=_P(o,s,!1),c=_P(a,s,!0);return A.concat(c)}Ni.generate=bHe;function Bte(t,e){let r=t;return e.braceExpansion&&(r=ga.pattern.expandPatternsWithBraceExpansion(r)),e.baseNameMatch&&(r=r.map(n=>n.includes("/")?n:`**/${n}`)),r.map(n=>ga.pattern.removeDuplicateSlashes(n))}function _P(t,e,r){let n=[],i=ga.pattern.getPatternsOutsideCurrentDirectory(t),s=ga.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}Ni.convertPatternsToTasks=_P;function yte(t){return ga.pattern.getPositivePatterns(t)}Ni.getPositivePatterns=yte;function Qte(t,e){return ga.pattern.getNegativePatterns(t).concat(e).map(ga.pattern.convertToPositivePattern)}Ni.getNegativePatternsAsPositive=Qte;function UP(t){let e={};return t.reduce((r,n)=>{let i=ga.pattern.getBaseDirectory(n);return i in r?r[i].push(n):r[i]=[n],r},e)}Ni.groupPatternsByBaseDirectory=UP;function GP(t,e,r){return Object.keys(t).map(n=>OP(n,t[n],e,r))}Ni.convertPatternGroupsToTasks=GP;function OP(t,e,r,n){return{dynamic:n,positive:e,negative:r,base:t,patterns:[].concat(e,r.map(ga.pattern.convertToNegativePattern))}}Ni.convertPatternGroupToTask=OP});var bte=N(vw=>{"use strict";h();Object.defineProperty(vw,"__esModule",{value:!0});vw.read=void 0;function vHe(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=vHe;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 SHe(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=SHe});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 xHe(t){return t===void 0?Nu.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Nu.FILE_SYSTEM_ADAPTER),t)}Nu.createFileSystemAdapter=xHe});var xte=N(JP=>{"use strict";h();Object.defineProperty(JP,"__esModule",{value:!0});var FHe=Ste(),HP=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=FHe.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(),kHe=vte(),jP=xte();Mu.Settings=jP.default;function RHe(t,e,r){if(typeof e=="function"){Fte.read(t,YP(),e);return}Fte.read(t,YP(e),r)}Mu.stat=RHe;function THe(t,e){let r=YP(e);return kHe.read(t,r)}Mu.statSync=THe;function YP(t={}){return t instanceof jP.default?t:new jP.default(t)}});var Tte=N((K8t,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((J8t,Nte)=>{h();Nte.exports=MHe;var NHe=Tte();function MHe(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?NHe(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),PHe=Number.parseInt(Fw[1],10),Lte=10,LHe=10,_He=Pte>Lte,UHe=Pte===Lte&&PHe>=LHe;kw.IS_SUPPORT_READDIR_WITH_FILE_TYPES=_He||UHe});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 GHe(t,e){return new $P(t,e)}Rw.createDirentFromStats=GHe});var VP=N(Tw=>{"use strict";h();Object.defineProperty(Tw,"__esModule",{value:!0});Tw.fs=void 0;var OHe=_te();Tw.fs=OHe});var WP=N(Nw=>{"use strict";h();Object.defineProperty(Nw,"__esModule",{value:!0});Nw.joinPathSegments=void 0;function KHe(t,e,r){return t.endsWith(r)?t+e:t+r+e}Nw.joinPathSegments=KHe});var Jte=N(Pu=>{"use strict";h();Object.defineProperty(Pu,"__esModule",{value:!0});Pu.readdir=Pu.readdirWithFileTypes=Pu.read=void 0;var HHe=Mg(),Ute=Mte(),JHe=qP(),Gte=VP(),Ote=WP();function jHe(t,e,r){if(!e.stats&&JHe.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Kte(t,e,r);return}Hte(t,e,r)}Pu.read=jHe;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=>YHe(a,e));Ute(o,(a,A)=>{if(a!==null){Mw(r,a);return}zP(r,A)})})}Pu.readdirWithFileTypes=Kte;function YHe(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=>{HHe.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 qHe=Mg(),$He=qP(),jte=VP(),Yte=WP();function VHe(t,e){return!e.stats&&$He.IS_SUPPORT_READDIR_WITH_FILE_TYPES?qte(t,e):$te(t,e)}Lu.read=VHe;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=qHe.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 WHe(t){return t===void 0?_u.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},_u.FILE_SYSTEM_ADAPTER),t)}_u.createFileSystemAdapter=WHe});var zte=N(ZP=>{"use strict";h();Object.defineProperty(ZP,"__esModule",{value:!0});var zHe=require("path"),XHe=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,zHe.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new XHe.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(),eJe=Vte(),e1=zte();Uu.Settings=e1.default;function tJe(t,e,r){if(typeof e=="function"){Xte.read(t,t1(),e);return}Xte.read(t,t1(e),r)}Uu.scandir=tJe;function rJe(t,e){let r=t1(e);return eJe.read(t,r)}Uu.scandirSync=rJe;function t1(t={}){return t instanceof e1.default?t:new e1.default(t)}});var ere=N((u3t,Zte)=>{"use strict";h();function nJe(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=nJe});var rre=N((g3t,r1)=>{"use strict";h();var iJe=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=iJe(sJe),i=null,s=null,o=0,a=null,A={push:f,drain:ps,saturated:ps,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:ps,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||ps,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||ps,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=ps}function y(){i=null,s=null,A.drain(),A.drain=ps}function B(){var Q=i;for(i=null,s=null;Q;){var v=Q.next,D=Q.callback,S=Q.errorHandler,x=Q.value,w=Q.context;Q.value=null,Q.callback=ps,Q.errorHandler=null,S&&S(new Error("abort"),x),D.call(w,new Error("abort")),Q.release(Q),Q=v}A.drain=ps}function E(Q){a=Q}}function ps(){}function sJe(){this.value=null,this.callback=ps,this.next=null,this.release=ps,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=ps,t.errorHandler&&s(r,o),i.call(t.context,r,n),t.release(t)}}function oJe(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(ps),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(ps),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=oJe});var Lw=N(fA=>{"use strict";h();Object.defineProperty(fA,"__esModule",{value:!0});fA.joinPathSegments=fA.replacePathSegmentSeparator=fA.isAppliedFilter=fA.isFatalError=void 0;function aJe(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}fA.isFatalError=aJe;function AJe(t,e){return t===null||t(e)}fA.isAppliedFilter=AJe;function cJe(t,e){return t.split(/[/\\]/).join(e)}fA.replacePathSegmentSeparator=cJe;function uJe(t,e,r){return t===""?e:t.endsWith(r)?t+e:t+r+e}fA.joinPathSegments=uJe});var s1=N(i1=>{"use strict";h();Object.defineProperty(i1,"__esModule",{value:!0});var lJe=Lw(),n1=class{constructor(e,r){this._root=e,this._settings=r,this._root=lJe.replacePathSegmentSeparator(e,r.pathSegmentSeparator)}};i1.default=n1});var A1=N(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});var gJe=require("events"),pJe=Pw(),dJe=rre(),_w=Lw(),fJe=s1(),o1=class extends fJe.default{constructor(e,r){super(e,r),this._settings=r,this._scandir=pJe.scandir,this._emitter=new gJe.EventEmitter,this._queue=dJe(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 hJe=A1(),c1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new hJe.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(r=>{mJe(e,r)}),this._reader.onEntry(r=>{this._storage.push(r)}),this._reader.onEnd(()=>{CJe(e,this._storage)}),this._reader.read()}};u1.default=c1;function mJe(t,e){t(e)}function CJe(t,e){t(null,e)}});var ire=N(g1=>{"use strict";h();Object.defineProperty(g1,"__esModule",{value:!0});var IJe=require("stream"),EJe=A1(),l1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new EJe.default(this._root,this._settings),this._stream=new IJe.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 BJe=Pw(),Uw=Lw(),yJe=s1(),p1=class extends yJe.default{constructor(){super(...arguments),this._scandir=BJe.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 QJe=sre(),f1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new QJe.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 DJe=require("path"),wJe=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,DJe.sep),this.fsScandirSettings=new wJe.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(),bJe=ire(),vJe=ore(),I1=are();hA.Settings=I1.default;function SJe(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=SJe;function xJe(t,e){let r=Gw(e);return new vJe.default(t,r).read()}hA.walkSync=xJe;function FJe(t,e){let r=Gw(e);return new bJe.default(t,r).read()}hA.walkStream=FJe;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 kJe=require("path"),RJe=Mg(),cre=hc(),E1=class{constructor(e){this._settings=e,this._fsStatSettings=new RJe.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return kJe.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 TJe=require("stream"),NJe=Mg(),MJe=Ow(),PJe=Kw(),y1=class extends PJe.default{constructor(){super(...arguments),this._walkStream=MJe.walkStream,this._stat=NJe.stat}dynamic(e,r){return this._walkStream(e,r)}static(e,r){let n=e.map(this._getFullEntryPath,this),i=new TJe.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 LJe=Ow(),_Je=Kw(),UJe=D1(),w1=class extends _Je.default{constructor(){super(...arguments),this._walkAsync=LJe.walk,this._readerStream=new UJe.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 GJe=lre(),x1=class extends GJe.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(),OJe=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 OJe.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 KJe=hc(),M1=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return KJe.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 HJe=require("path"),JJe=pre(),jJe=dre(),YJe=fre(),qJe=mre(),U1=class{constructor(e){this._settings=e,this.errorFilter=new YJe.default(this._settings),this.entryFilter=new jJe.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new JJe.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new qJe.default(this._settings)}_getRootDirectory(e){return HJe.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 $Je=ure(),VJe=Jw(),O1=class extends VJe.default{constructor(){super(...arguments),this._reader=new $Je.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 WJe=require("stream"),zJe=D1(),XJe=Jw(),H1=class extends XJe.default{constructor(){super(...arguments),this._reader=new zJe.default(this._settings)}read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e),i=this.api(r,e,n),s=new WJe.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(),eje=Ow(),tje=Kw(),j1=class extends tje.default{constructor(){super(...arguments),this._walkSync=eje.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 rje=Ere(),nje=Jw(),q1=class extends nje.default{constructor(){super(...arguments),this._reader=new rje.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"),ije=require("os"),sje=Math.max(ije.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,sje),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((AKt,Dre)=>{"use strict";h();var Qre=Dte(),oje=Cre(),aje=Ire(),Aje=Bre(),W1=yre(),fo=hc();async function z1(t,e){pa(t);let r=X1(t,oje.default,e),n=await Promise.all(r);return fo.array.flatten(n)}(function(t){t.glob=t,t.globSync=e,t.globStream=r,t.async=t;function e(c,u){pa(c);let l=X1(c,Aje.default,u);return fo.array.flatten(l)}t.sync=e;function r(c,u){pa(c);let l=X1(c,aje.default,u);return fo.stream.merge(l)}t.stream=r;function n(c,u){pa(c);let l=[].concat(c),d=new W1.default(u);return Qre.generate(l,d)}t.generateTasks=n;function i(c,u){pa(c);let l=new W1.default(u);return fo.pattern.isDynamicPattern(c,l)}t.isDynamicPattern=i;function s(c){return pa(c),fo.path.escape(c)}t.escapePath=s;function o(c){return pa(c),fo.path.convertPathToPattern(c)}t.convertPathToPattern=o;let a;(function(c){function u(d){return pa(d),fo.path.escapePosixPath(d)}c.escapePath=u;function l(d){return pa(d),fo.path.convertPosixPathToPattern(d)}c.convertPathToPattern=l})(a=t.posix||(t.posix={}));let A;(function(c){function u(d){return pa(d),fo.path.escapeWindowsPath(d)}c.escapePath=u;function l(d){return pa(d),fo.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 pa(t){if(![].concat(t).every(n=>fo.string.isString(n)&&!fo.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,uKt,vre,lKt,gKt,Sre,pKt,xre=L(()=>{h();wre=z(require("node:fs"),1),bre=z(require("node:fs/promises"),1);uKt=eL.bind(void 0,"stat","isFile"),vre=eL.bind(void 0,"stat","isDirectory"),lKt=eL.bind(void 0,"lstat","isSymbolicLink"),gKt=tL.bind(void 0,"statSync","isFile"),Sre=tL.bind(void 0,"statSync","isDirectory"),pKt=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,CKt,IKt,jw=L(()=>{h();kre=require("node:util"),nL=require("node:child_process"),rL=z(require("node:path"),1),Rre=require("node:url");Fre();CKt=(0,kre.promisify)(nL.execFile);IKt=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,cje,Ure,Gre,uje,lje,gje,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();cje=["**/node_modules","**/flow-typed","**/coverage","**/.git"],Ure={absolute:!0,dot:!0},Gre="**/.gitignore",uje=(t,e)=>oI(t)?"!"+Pg.default.posix.join(e,t.slice(1)):Pg.default.posix.join(e,t),lje=(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=>uje(n,r))},gje=(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=>lje(i,e)),n=(0,_re.default)().add(r);return i=>(i=mc(i),i=gje(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??[],...cje]}),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,pje,Vre,Wre,Yre,qre,aL,dje,zre,Xre,Yw,Zre,fje,ene,tne,rne,nne,ine,sne,AL,qw,LKt,_Kt,UKt,GKt,OKt,KKt,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();pje=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())],pje(t),t),dje=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)},dje(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},fje=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),fje(e)]),i=await Promise.all(r.map(s=>(0,hf.default)(s.patterns,s.options)));return rne(i,n)}),LKt=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)}),_Kt=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))}),UKt=Yw((t,e)=>t.some(r=>hf.default.isDynamicPattern(r,e))),GKt=Xre(sne),OKt=Yw(AL),{convertPathToPattern:KKt}=hf.default});function mf(t){let e=Date.now();return new Promise((r,n)=>{let s=hje(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((r8t,See)=>{"use strict";h();var qKe=Cw(),{MAX_LENGTH:wee,CHAR_BACKSLASH:DP,CHAR_BACKTICK:$Ke,CHAR_COMMA:VKe,CHAR_DOT:WKe,CHAR_LEFT_PARENTHESES:zKe,CHAR_RIGHT_PARENTHESES:XKe,CHAR_LEFT_CURLY_BRACE:ZKe,CHAR_RIGHT_CURLY_BRACE:eHe,CHAR_LEFT_SQUARE_BRACKET:bee,CHAR_RIGHT_SQUARE_BRACKET:vee,CHAR_DOUBLE_QUOTE:tHe,CHAR_SINGLE_QUOTE:rHe,CHAR_NO_BREAK_SPACE:nHe,CHAR_ZERO_WIDTH_NOBREAK_SPACE:iHe}=Dee(),sHe=(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===iHe||d===nHe)){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===zKe){o=p({type:"paren",nodes:[]}),s.push(o),p({type:"text",value:d});continue}if(d===XKe){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===tHe||d===rHe||d===$Ke){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===eHe){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===VKe&&l>0){if(o.ranges>0){o.ranges=0;let f=o.nodes.shift();o.nodes=[f,{type:"text",value:qKe(o)}]}p({type:"comma",value:d}),o.commas++;continue}if(d===WKe&&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=sHe});var Ree=N((i8t,kee)=>{"use strict";h();var Fee=Cw(),oHe=Iee(),aHe=yee(),AHe=xee(),Gs=(t,e={})=>{let r=[];if(Array.isArray(t))for(let n of t){let i=Gs.create(n,e);Array.isArray(i)?r.push(...i):r.push(i)}else r=[].concat(Gs.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(r=[...new Set(r)]),r};Gs.parse=(t,e={})=>AHe(t,e);Gs.stringify=(t,e={})=>Fee(typeof t=="string"?Gs.parse(t,e):t,e);Gs.compile=(t,e={})=>(typeof t=="string"&&(t=Gs.parse(t,e)),oHe(t,e));Gs.expand=(t,e={})=>{typeof t=="string"&&(t=Gs.parse(t,e));let r=aHe(t,e);return e.noempty===!0&&(r=r.filter(Boolean)),e.nodupes===!0&&(r=[...new Set(r)]),r};Gs.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Gs.compile(t,e):Gs.expand(t,e);kee.exports=Gs});var rI=N((o8t,Lee)=>{"use strict";h();var cHe=require("path"),pA="\\\\/",Tee=`[^${pA}]`,fc="\\.",uHe="\\+",lHe="\\?",Bw="\\/",gHe="(?=.)",Nee="[^/]",wP=`(?:${Bw}|$)`,Mee=`(?:^|${Bw})`,bP=`${fc}{1,2}${wP}`,pHe=`(?!${fc})`,dHe=`(?!${Mee}${bP})`,fHe=`(?!${fc}{0,1}${wP})`,hHe=`(?!${bP})`,mHe=`[^.${Bw}]`,CHe=`${Nee}*?`,Pee={DOT_LITERAL:fc,PLUS_LITERAL:uHe,QMARK_LITERAL:lHe,SLASH_LITERAL:Bw,ONE_CHAR:gHe,QMARK:Nee,END_ANCHOR:wP,DOTS_SLASH:bP,NO_DOT:pHe,NO_DOTS:dHe,NO_DOT_SLASH:fHe,NO_DOTS_SLASH:hHe,QMARK_NO_DOT:mHe,STAR:CHe,START_ANCHOR:Mee},IHe={...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}]|$)`},EHe={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:EHe,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:cHe.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?IHe:Pee}}});var nI=N(gs=>{"use strict";h();var BHe=require("path"),yHe=process.platform==="win32",{REGEX_BACKSLASH:QHe,REGEX_REMOVE_BACKSLASH:DHe,REGEX_SPECIAL_CHARS:wHe,REGEX_SPECIAL_CHARS_GLOBAL:bHe}=rI();gs.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);gs.hasRegexChars=t=>wHe.test(t);gs.isRegexChar=t=>t.length===1&&gs.hasRegexChars(t);gs.escapeRegex=t=>t.replace(bHe,"\\$1");gs.toPosixSlashes=t=>t.replace(QHe,"/");gs.removeBackslashes=t=>t.replace(DHe,e=>e==="\\"?"":e);gs.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};gs.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:yHe===!0||BHe.sep==="\\";gs.escapeLast=(t,e,r)=>{let n=t.lastIndexOf(e,r);return n===-1?t:t[n-1]==="\\"?gs.escapeLast(t,e,n-1):`${t.slice(0,n)}\\${t.slice(n)}`};gs.removePrefix=(t,e={})=>{let r=t;return r.startsWith("./")&&(r=r.slice(2),e.prefix="./"),r};gs.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((u8t,Jee)=>{"use strict";h();var _ee=nI(),{CHAR_ASTERISK:vP,CHAR_AT:vHe,CHAR_BACKWARD_SLASH:iI,CHAR_COMMA:SHe,CHAR_DOT:SP,CHAR_EXCLAMATION_MARK:xP,CHAR_FORWARD_SLASH:Hee,CHAR_LEFT_CURLY_BRACE:FP,CHAR_LEFT_PARENTHESES:kP,CHAR_LEFT_SQUARE_BRACKET:xHe,CHAR_PLUS:FHe,CHAR_QUESTION_MARK:Uee,CHAR_RIGHT_CURLY_BRACE:kHe,CHAR_RIGHT_PARENTHESES:Gee,CHAR_RIGHT_SQUARE_BRACKET:RHe}=rI(),Oee=t=>t===Hee||t===iI,Kee=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},THe=(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},x=()=>c>=n,w=()=>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++;x()!==!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===SHe){if(d=S.isBrace=!0,p=S.isGlob=!0,E=!0,i===!0)continue;break}if(D===kHe&&(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===FHe||D===vHe||D===vP||D===Uee||D===xP)===!0&&w()===kP){if(p=S.isGlob=!0,f=S.isExtglob=!0,E=!0,D===xP&&c===u&&(B=!0),i===!0){for(;x()!==!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===xHe){for(;x()!==!0&&(j=P());){if(j===iI){I=S.backslashes=!0,P();continue}if(j===RHe){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(;x()!==!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 G=A,J="",_="";u>0&&(J=A.slice(0,u),A=A.slice(u),l-=u),G&&p===!0&&l>0?(G=A.slice(0,l),_=A.slice(l)):p===!0?(G="",_=A):G=A,G&&G!==""&&G!=="/"&&G!==A&&Oee(G.charCodeAt(G.length-1))&&(G=G.slice(0,-1)),r.unescape===!0&&(_&&(_=_ee.removeBackslashes(_)),G&&I===!0&&(G=_ee.removeBackslashes(G)));let K={prefix:J,input:t,start:u,base:G,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=THe});var $ee=N((g8t,qee)=>{"use strict";h();var yw=rI(),Os=nI(),{MAX_LENGTH:Qw,POSIX_REGEX_SOURCE:NHe,REGEX_NON_SPECIAL_CHARS:MHe,REGEX_SPECIAL_CHARS_BACKREF:PHe,REPLACEMENTS:Yee}=yw,LHe=(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=>Os.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=Os.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,x=r.bash===!0?v(r):E;r.capture&&(x=`(${x})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let w={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=Os.removePrefix(t,w),i=t.length;let P=[],G=[],J=[],_=s,K,j=()=>w.index===i-1,ee=w.peek=(le=1)=>t[w.index+le],U=w.advance=()=>t[++w.index]||"",Y=()=>t.slice(w.index+1),H=(le="",be=0)=>{w.consumed+=le,w.index+=be},Z=le=>{w.output+=le.output!=null?le.output:le.value,H(le.value)},ue=()=>{let le=1;for(;ee()==="!"&&(ee(2)!=="("||ee(3)==="?");)U(),w.start++,le++;return le%2===0?!1:(w.negated=!0,w.start++,!0)},ge=le=>{w[le]++,J.push(le)},he=le=>{w[le]--,J.pop()},X=le=>{if(_.type==="globstar"){let be=w.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&&(w.output=w.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=x,w.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=w.parens,de.output=w.output;let ke=(r.capture?"(":"")+de.open;ge("parens"),X({type:le,value:be,output:w.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=x;if(le.inner&&le.inner.length>1&&le.inner.includes("/")&&(ke=v(r)),(ke!==x||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"&&(w.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(PHe,(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?x:""):x: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?(w.output=t,w):(w.output=Os.wrapOutput(be,w,e),w)}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,w.index+=Qe,Qe%2!==0&&(K+="\\")),r.unescape===!0?K=U():K+=U(),w.brackets===0){X({type:"text",value:K});continue}}if(w.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=NHe[rt];if(nt){_.value=Qe+nt,w.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(w.quotes===1&&K!=='"'){K=Os.escapeRegex(K),_.value+=K,Z({value:K});continue}if(K==='"'){w.quotes=w.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(w.parens===0&&r.strictBrackets===!0)throw new SyntaxError(uf("opening","("));let de=P[P.length-1];if(de&&w.parens===de.parens+1){Je(P.pop());continue}X({type:"paren",value:K,output:w.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(w.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||Os.hasRegexChars(de))continue;let ke=Os.escapeRegex(_.value);if(w.output=w.output.slice(0,-_.value.length),r.literalBrackets===!0){w.output+=ke,_.value=ke;continue}_.value=`(${a}${ke}|${_.value})`,w.output+=_.value;continue}if(K==="{"&&r.nobrace!==!0){ge("braces");let de={type:"brace",value:K,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};G.push(de),X(de);continue}if(K==="}"){let de=G[G.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=LHe(rt,r),w.backtrack=!0}if(de.comma!==!0&&de.dots!==!0){let Qe=w.output.slice(0,de.outputIndex),rt=w.tokens.slice(de.tokensIndex);de.value=de.output="\\{",K=ke="\\}",w.output=Qe;for(let nt of rt)w.output+=nt.output||nt.value}X({type:"brace",value:K,output:ke}),he("braces"),G.pop();continue}if(K==="|"){P.length>0&&P[P.length-1].conditions++,X({type:"text",value:K});continue}if(K===","){let de=K,ke=G[G.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"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),_=s;continue}X({type:"slash",value:K,output:g});continue}if(K==="."){if(w.braces>0&&_.type==="dot"){_.value==="."&&(_.output=l);let de=G[G.length-1];_.type="dots",_.output+=K,_.value+=K,de.dots=!0;continue}if(w.braces+w.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==="<"&&!Os.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&&w.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")||w.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=MHe.exec(Y());de&&(K+=de[0],w.index+=de[0].length),X({type:"text",value:K});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=K,_.output=x,w.backtrack=!0,w.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=w.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 Vr=t[w.index+4];if(Vr&&Vr!=="/")break;le=le.slice(3),H("/**",3)}if(de.type==="bos"&&j()){_.type="globstar",_.value+=K,_.output=v(r),w.output=_.output,w.globstar=!0,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&!rt&&j()){w.output=w.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=v(r)+(r.strictSlashes?")":"|$)"),_.value+=K,w.globstar=!0,w.output+=de.output+_.output,H(K);continue}if(de.type==="slash"&&de.prev.type!=="bos"&&le[0]==="/"){let Vr=le[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(de.output+_.output).length),de.output=`(?:${de.output}`,_.type="globstar",_.output=`${v(r)}${g}|${g}${Vr})`,_.value+=K,w.output+=de.output+_.output,w.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})`,w.output=_.output,w.globstar=!0,H(K+U()),X({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-_.output.length),_.type="globstar",_.output=v(r),_.value+=K,w.output+=_.output,w.globstar=!0,H(K);continue}let be={type:"star",value:K,output:x};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}(w.index===w.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(w.output+=C,_.output+=C):r.dot===!0?(w.output+=I,_.output+=I):(w.output+=D,_.output+=D),ee()!=="*"&&(w.output+=p,_.output+=p)),X(be)}for(;w.brackets>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","]"));w.output=Os.escapeLast(w.output,"["),he("brackets")}for(;w.parens>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing",")"));w.output=Os.escapeLast(w.output,"("),he("parens")}for(;w.braces>0;){if(r.strictBrackets===!0)throw new SyntaxError(uf("closing","}"));w.output=Os.escapeLast(w.output,"{"),he("braces")}if(r.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${g}?`}),w.backtrack===!0){w.output="";for(let le of w.tokens)w.output+=le.output!=null?le.output:le.value,le.suffix&&(w.output+=le.suffix)}return w};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=Os.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 x=E(S[1]);return x?x+o+S[2]:void 0}}},Q=Os.removePrefix(t,I),v=E(Q);return v&&r.strictSlashes!==!0&&(v+=`${a}?`),v};qee.exports=RP});var Wee=N((d8t,Vee)=>{"use strict";h();var _He=require("path"),UHe=jee(),TP=$ee(),NP=nI(),GHe=rI(),OHe=t=>t&&typeof t=="object"&&!Array.isArray(t),un=(t,e,r=!1)=>{if(Array.isArray(t)){let u=t.map(d=>un(d,e,r));return d=>{for(let g of u){let p=g(d);if(p)return p}return!1}}let n=OHe(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?un.compileRe(t,e):un.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=un(i.ignore,u,r)}let c=(u,l=!1)=>{let{isMatch:d,match:g,output:p}=un.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};un.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=un.matchBase(t,e,r,i):a=e.exec(A)),{isMatch:!!a,match:a,output:A}};un.matchBase=(t,e,r,n=NP.isWindows(r))=>(e instanceof RegExp?e:un.makeRe(e,r)).test(_He.basename(t));un.isMatch=(t,e,r)=>un(e,r)(t);un.parse=(t,e)=>Array.isArray(t)?t.map(r=>un.parse(r,e)):TP(t,{...e,fastpaths:!1});un.scan=(t,e)=>UHe(t,e);un.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=un.toRegex(a,e);return n===!0&&(A.state=t),A};un.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)),un.compileRe(i,e,r,n)};un.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/$^/}};un.constants=GHe;Vee.exports=un});var Xee=N((h8t,zee)=>{"use strict";h();zee.exports=Wee()});var Dw=N((C8t,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},kr=(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};kr.match=kr;kr.matcher=(t,e)=>dA(t,e);kr.isMatch=(t,e,r)=>dA(e,r)(t);kr.any=kr.isMatch;kr.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(kr(t,e,{...r,onResult:s}));for(let a of i)o.has(a)||n.add(a);return[...n]};kr.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=>kr.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 kr.isMatch(t,e,{...r,contains:!0})};kr.matchKeys=(t,e,r)=>{if(!MP.isObject(t))throw new TypeError("Expected the first argument to be an object");let n=kr(Object.keys(t),e,r),i={};for(let s of n)i[s]=t[s];return i};kr.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};kr.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};kr.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))};kr.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)};kr.makeRe=(...t)=>dA.makeRe(...t);kr.scan=(...t)=>dA.scan(...t);kr.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};kr.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!rte(t)?[t]:tte(t,e)};kr.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return kr.braces(t,{...e,expand:!0})};kr.hasBraces=rte;nte.exports=kr});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"),KHe=WZ(),PP=Dw(),ste="**",HHe="\\",JHe=/[*?]|^!/,jHe=/\[[^[]*]/,YHe=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,qHe=/[!*+?@]\([^(]*\)/,$He=/,|\.\./,VHe=/(?!^)\/{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(HHe)||JHe.test(t)||jHe.test(t)||YHe.test(t)||e.extglob!==!1&&qHe.test(t)||e.braceExpansion!==!1&&WHe(t))}tt.isDynamicPattern=ate;function WHe(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 $He.test(n)}function zHe(t){return ww(t)?t.slice(1):t}tt.convertToPositivePattern=zHe;function XHe(t){return"!"+t}tt.convertToNegativePattern=XHe;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 e4e(t){return t.filter(Ate)}tt.getPositivePatterns=e4e;function t4e(t){return t.filter(e=>!LP(e))}tt.getPatternsInsideCurrentDirectory=t4e;function r4e(t){return t.filter(LP)}tt.getPatternsOutsideCurrentDirectory=r4e;function LP(t){return t.startsWith("..")||t.startsWith("./..")}tt.isPatternRelatedToParentDirectory=LP;function n4e(t){return KHe(t,{flipBackslashes:!1})}tt.getBaseDirectory=n4e;function i4e(t){return t.includes(ste)}tt.hasGlobStar=i4e;function cte(t){return t.endsWith("/"+ste)}tt.endsWithSlashGlobStar=cte;function s4e(t){let e=ite.basename(t);return cte(t)||ote(e)}tt.isAffectDepthOfReadingPattern=s4e;function o4e(t){return t.reduce((e,r)=>e.concat(ute(r)),[])}tt.expandPatternsWithBraceExpansion=o4e;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 a4e(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=a4e;function lte(t,e){return PP.makeRe(t,e)}tt.makeRe=lte;function A4e(t,e){return t.map(r=>lte(r,e))}tt.convertPatternsToRe=A4e;function c4e(t,e){return e.some(r=>r.test(t))}tt.matchAny=c4e;function u4e(t){return t.replace(VHe,"/")}tt.removeDuplicateSlashes=u4e;function l4e(t){let e=[],r=[];for(let n of t)gte(n)?e.push(n):r.push(n);return[e,r]}tt.partitionAbsoluteAndRelative=l4e;function gte(t){return ite.isAbsolute(t)}tt.isAbsolute=gte});var mte=N((y8t,hte)=>{"use strict";h();var g4e=require("stream"),dte=g4e.PassThrough,p4e=Array.prototype.slice;hte.exports=d4e;function d4e(){let t=[],e=p4e.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 f4e=mte();function h4e(t){let e=f4e(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=h4e;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 m4e(t){return typeof t=="string"}lf.isString=m4e;function C4e(t){return t===""}lf.isEmpty=C4e});var hc=N(Ti=>{"use strict";h();Object.defineProperty(Ti,"__esModule",{value:!0});Ti.string=Ti.stream=Ti.pattern=Ti.path=Ti.fs=Ti.errno=Ti.array=void 0;var I4e=LZ();Ti.array=I4e;var E4e=_Z();Ti.errno=E4e;var B4e=UZ();Ti.fs=B4e;var y4e=HZ();Ti.path=y4e;var Q4e=pte();Ti.pattern=Q4e;var D4e=Ite();Ti.stream=D4e;var w4e=Ete();Ti.string=w4e});var Dte=N(Ni=>{"use strict";h();Object.defineProperty(Ni,"__esModule",{value:!0});Ni.convertPatternGroupToTask=Ni.convertPatternGroupsToTasks=Ni.groupPatternsByBaseDirectory=Ni.getNegativePatternsAsPositive=Ni.getPositivePatterns=Ni.convertPatternsToTasks=Ni.generate=void 0;var ga=hc();function b4e(t,e){let r=Bte(t,e),n=Bte(e.ignore,e),i=yte(r),s=Qte(r,n),o=i.filter(u=>ga.pattern.isStaticPattern(u,e)),a=i.filter(u=>ga.pattern.isDynamicPattern(u,e)),A=_P(o,s,!1),c=_P(a,s,!0);return A.concat(c)}Ni.generate=b4e;function Bte(t,e){let r=t;return e.braceExpansion&&(r=ga.pattern.expandPatternsWithBraceExpansion(r)),e.baseNameMatch&&(r=r.map(n=>n.includes("/")?n:`**/${n}`)),r.map(n=>ga.pattern.removeDuplicateSlashes(n))}function _P(t,e,r){let n=[],i=ga.pattern.getPatternsOutsideCurrentDirectory(t),s=ga.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}Ni.convertPatternsToTasks=_P;function yte(t){return ga.pattern.getPositivePatterns(t)}Ni.getPositivePatterns=yte;function Qte(t,e){return ga.pattern.getNegativePatterns(t).concat(e).map(ga.pattern.convertToPositivePattern)}Ni.getNegativePatternsAsPositive=Qte;function UP(t){let e={};return t.reduce((r,n)=>{let i=ga.pattern.getBaseDirectory(n);return i in r?r[i].push(n):r[i]=[n],r},e)}Ni.groupPatternsByBaseDirectory=UP;function GP(t,e,r){return Object.keys(t).map(n=>OP(n,t[n],e,r))}Ni.convertPatternGroupsToTasks=GP;function OP(t,e,r,n){return{dynamic:n,positive:e,negative:r,base:t,patterns:[].concat(e,r.map(ga.pattern.convertToNegativePattern))}}Ni.convertPatternGroupToTask=OP});var bte=N(vw=>{"use strict";h();Object.defineProperty(vw,"__esModule",{value:!0});vw.read=void 0;function v4e(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=v4e;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 S4e(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=S4e});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 x4e(t){return t===void 0?Nu.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Nu.FILE_SYSTEM_ADAPTER),t)}Nu.createFileSystemAdapter=x4e});var xte=N(JP=>{"use strict";h();Object.defineProperty(JP,"__esModule",{value:!0});var F4e=Ste(),HP=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=F4e.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(),k4e=vte(),jP=xte();Mu.Settings=jP.default;function R4e(t,e,r){if(typeof e=="function"){Fte.read(t,YP(),e);return}Fte.read(t,YP(e),r)}Mu.stat=R4e;function T4e(t,e){let r=YP(e);return k4e.read(t,r)}Mu.statSync=T4e;function YP(t={}){return t instanceof jP.default?t:new jP.default(t)}});var Tte=N((K8t,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((J8t,Nte)=>{h();Nte.exports=M4e;var N4e=Tte();function M4e(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?N4e(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),P4e=Number.parseInt(Fw[1],10),Lte=10,L4e=10,_4e=Pte>Lte,U4e=Pte===Lte&&P4e>=L4e;kw.IS_SUPPORT_READDIR_WITH_FILE_TYPES=_4e||U4e});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 G4e(t,e){return new $P(t,e)}Rw.createDirentFromStats=G4e});var VP=N(Tw=>{"use strict";h();Object.defineProperty(Tw,"__esModule",{value:!0});Tw.fs=void 0;var O4e=_te();Tw.fs=O4e});var WP=N(Nw=>{"use strict";h();Object.defineProperty(Nw,"__esModule",{value:!0});Nw.joinPathSegments=void 0;function K4e(t,e,r){return t.endsWith(r)?t+e:t+r+e}Nw.joinPathSegments=K4e});var Jte=N(Pu=>{"use strict";h();Object.defineProperty(Pu,"__esModule",{value:!0});Pu.readdir=Pu.readdirWithFileTypes=Pu.read=void 0;var H4e=Mg(),Ute=Mte(),J4e=qP(),Gte=VP(),Ote=WP();function j4e(t,e,r){if(!e.stats&&J4e.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Kte(t,e,r);return}Hte(t,e,r)}Pu.read=j4e;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=>Y4e(a,e));Ute(o,(a,A)=>{if(a!==null){Mw(r,a);return}zP(r,A)})})}Pu.readdirWithFileTypes=Kte;function Y4e(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=>{H4e.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 q4e=Mg(),$4e=qP(),jte=VP(),Yte=WP();function V4e(t,e){return!e.stats&&$4e.IS_SUPPORT_READDIR_WITH_FILE_TYPES?qte(t,e):$te(t,e)}Lu.read=V4e;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=q4e.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 W4e(t){return t===void 0?_u.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},_u.FILE_SYSTEM_ADAPTER),t)}_u.createFileSystemAdapter=W4e});var zte=N(ZP=>{"use strict";h();Object.defineProperty(ZP,"__esModule",{value:!0});var z4e=require("path"),X4e=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,z4e.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new X4e.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(),eJe=Vte(),e1=zte();Uu.Settings=e1.default;function tJe(t,e,r){if(typeof e=="function"){Xte.read(t,t1(),e);return}Xte.read(t,t1(e),r)}Uu.scandir=tJe;function rJe(t,e){let r=t1(e);return eJe.read(t,r)}Uu.scandirSync=rJe;function t1(t={}){return t instanceof e1.default?t:new e1.default(t)}});var ere=N((u3t,Zte)=>{"use strict";h();function nJe(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=nJe});var rre=N((g3t,r1)=>{"use strict";h();var iJe=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=iJe(sJe),i=null,s=null,o=0,a=null,A={push:f,drain:ps,saturated:ps,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:ps,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||ps,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||ps,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=ps}function y(){i=null,s=null,A.drain(),A.drain=ps}function B(){var Q=i;for(i=null,s=null;Q;){var v=Q.next,D=Q.callback,S=Q.errorHandler,x=Q.value,w=Q.context;Q.value=null,Q.callback=ps,Q.errorHandler=null,S&&S(new Error("abort"),x),D.call(w,new Error("abort")),Q.release(Q),Q=v}A.drain=ps}function E(Q){a=Q}}function ps(){}function sJe(){this.value=null,this.callback=ps,this.next=null,this.release=ps,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=ps,t.errorHandler&&s(r,o),i.call(t.context,r,n),t.release(t)}}function oJe(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(ps),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(ps),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=oJe});var Lw=N(fA=>{"use strict";h();Object.defineProperty(fA,"__esModule",{value:!0});fA.joinPathSegments=fA.replacePathSegmentSeparator=fA.isAppliedFilter=fA.isFatalError=void 0;function aJe(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}fA.isFatalError=aJe;function AJe(t,e){return t===null||t(e)}fA.isAppliedFilter=AJe;function cJe(t,e){return t.split(/[/\\]/).join(e)}fA.replacePathSegmentSeparator=cJe;function uJe(t,e,r){return t===""?e:t.endsWith(r)?t+e:t+r+e}fA.joinPathSegments=uJe});var s1=N(i1=>{"use strict";h();Object.defineProperty(i1,"__esModule",{value:!0});var lJe=Lw(),n1=class{constructor(e,r){this._root=e,this._settings=r,this._root=lJe.replacePathSegmentSeparator(e,r.pathSegmentSeparator)}};i1.default=n1});var A1=N(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});var gJe=require("events"),pJe=Pw(),dJe=rre(),_w=Lw(),fJe=s1(),o1=class extends fJe.default{constructor(e,r){super(e,r),this._settings=r,this._scandir=pJe.scandir,this._emitter=new gJe.EventEmitter,this._queue=dJe(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 hJe=A1(),c1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new hJe.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(r=>{mJe(e,r)}),this._reader.onEntry(r=>{this._storage.push(r)}),this._reader.onEnd(()=>{CJe(e,this._storage)}),this._reader.read()}};u1.default=c1;function mJe(t,e){t(e)}function CJe(t,e){t(null,e)}});var ire=N(g1=>{"use strict";h();Object.defineProperty(g1,"__esModule",{value:!0});var IJe=require("stream"),EJe=A1(),l1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new EJe.default(this._root,this._settings),this._stream=new IJe.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 BJe=Pw(),Uw=Lw(),yJe=s1(),p1=class extends yJe.default{constructor(){super(...arguments),this._scandir=BJe.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 QJe=sre(),f1=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new QJe.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 DJe=require("path"),wJe=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,DJe.sep),this.fsScandirSettings=new wJe.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(),bJe=ire(),vJe=ore(),I1=are();hA.Settings=I1.default;function SJe(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=SJe;function xJe(t,e){let r=Gw(e);return new vJe.default(t,r).read()}hA.walkSync=xJe;function FJe(t,e){let r=Gw(e);return new bJe.default(t,r).read()}hA.walkStream=FJe;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 kJe=require("path"),RJe=Mg(),cre=hc(),E1=class{constructor(e){this._settings=e,this._fsStatSettings=new RJe.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return kJe.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 TJe=require("stream"),NJe=Mg(),MJe=Ow(),PJe=Kw(),y1=class extends PJe.default{constructor(){super(...arguments),this._walkStream=MJe.walkStream,this._stat=NJe.stat}dynamic(e,r){return this._walkStream(e,r)}static(e,r){let n=e.map(this._getFullEntryPath,this),i=new TJe.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 LJe=Ow(),_Je=Kw(),UJe=D1(),w1=class extends _Je.default{constructor(){super(...arguments),this._walkAsync=LJe.walk,this._readerStream=new UJe.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 GJe=lre(),x1=class extends GJe.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(),OJe=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 OJe.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 KJe=hc(),M1=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return KJe.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 HJe=require("path"),JJe=pre(),jJe=dre(),YJe=fre(),qJe=mre(),U1=class{constructor(e){this._settings=e,this.errorFilter=new YJe.default(this._settings),this.entryFilter=new jJe.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new JJe.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new qJe.default(this._settings)}_getRootDirectory(e){return HJe.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 $Je=ure(),VJe=Jw(),O1=class extends VJe.default{constructor(){super(...arguments),this._reader=new $Je.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 WJe=require("stream"),zJe=D1(),XJe=Jw(),H1=class extends XJe.default{constructor(){super(...arguments),this._reader=new zJe.default(this._settings)}read(e){let r=this._getRootDirectory(e),n=this._getReaderOptions(e),i=this.api(r,e,n),s=new WJe.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(),eje=Ow(),tje=Kw(),j1=class extends tje.default{constructor(){super(...arguments),this._walkSync=eje.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 rje=Ere(),nje=Jw(),q1=class extends nje.default{constructor(){super(...arguments),this._reader=new rje.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"),ije=require("os"),sje=Math.max(ije.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,sje),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((AKt,Dre)=>{"use strict";h();var Qre=Dte(),oje=Cre(),aje=Ire(),Aje=Bre(),W1=yre(),fo=hc();async function z1(t,e){pa(t);let r=X1(t,oje.default,e),n=await Promise.all(r);return fo.array.flatten(n)}(function(t){t.glob=t,t.globSync=e,t.globStream=r,t.async=t;function e(c,u){pa(c);let l=X1(c,Aje.default,u);return fo.array.flatten(l)}t.sync=e;function r(c,u){pa(c);let l=X1(c,aje.default,u);return fo.stream.merge(l)}t.stream=r;function n(c,u){pa(c);let l=[].concat(c),d=new W1.default(u);return Qre.generate(l,d)}t.generateTasks=n;function i(c,u){pa(c);let l=new W1.default(u);return fo.pattern.isDynamicPattern(c,l)}t.isDynamicPattern=i;function s(c){return pa(c),fo.path.escape(c)}t.escapePath=s;function o(c){return pa(c),fo.path.convertPathToPattern(c)}t.convertPathToPattern=o;let a;(function(c){function u(d){return pa(d),fo.path.escapePosixPath(d)}c.escapePath=u;function l(d){return pa(d),fo.path.convertPosixPathToPattern(d)}c.convertPathToPattern=l})(a=t.posix||(t.posix={}));let A;(function(c){function u(d){return pa(d),fo.path.escapeWindowsPath(d)}c.escapePath=u;function l(d){return pa(d),fo.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 pa(t){if(![].concat(t).every(n=>fo.string.isString(n)&&!fo.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,uKt,vre,lKt,gKt,Sre,pKt,xre=L(()=>{h();wre=z(require("node:fs"),1),bre=z(require("node:fs/promises"),1);uKt=eL.bind(void 0,"stat","isFile"),vre=eL.bind(void 0,"stat","isDirectory"),lKt=eL.bind(void 0,"lstat","isSymbolicLink"),gKt=tL.bind(void 0,"statSync","isFile"),Sre=tL.bind(void 0,"statSync","isDirectory"),pKt=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,CKt,IKt,jw=L(()=>{h();kre=require("node:util"),nL=require("node:child_process"),rL=z(require("node:path"),1),Rre=require("node:url");Fre();CKt=(0,kre.promisify)(nL.execFile);IKt=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,cje,Ure,Gre,uje,lje,gje,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();cje=["**/node_modules","**/flow-typed","**/coverage","**/.git"],Ure={absolute:!0,dot:!0},Gre="**/.gitignore",uje=(t,e)=>oI(t)?"!"+Pg.default.posix.join(e,t.slice(1)):Pg.default.posix.join(e,t),lje=(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=>uje(n,r))},gje=(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=>lje(i,e)),n=(0,_re.default)().add(r);return i=>(i=mc(i),i=gje(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??[],...cje]}),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,pje,Vre,Wre,Yre,qre,aL,dje,zre,Xre,Yw,Zre,fje,ene,tne,rne,nne,ine,sne,AL,qw,LKt,_Kt,UKt,GKt,OKt,KKt,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();pje=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())],pje(t),t),dje=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)},dje(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},fje=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),fje(e)]),i=await Promise.all(r.map(s=>(0,hf.default)(s.patterns,s.options)));return rne(i,n)}),LKt=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)}),_Kt=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))}),UKt=Yw((t,e)=>t.some(r=>hf.default.isDynamicPattern(r,e))),GKt=Xre(sne),OKt=Yw(AL),{convertPathToPattern:KKt}=hf.default});function mf(t){let e=Date.now();return new Promise((r,n)=>{let s=hje(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 hje(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.202606092106.da31a10"}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.202606100020.95cbe0b"}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.202606100020.95cbe0b"),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.202606100020.95cbe0b"),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 Sje(t,e,r){let n,i=Fje(r,e.toLowerCase());switch(e.toLowerCase()){case"react":let s=await xje(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 xje(t){if((0,Ai.existsSync)((0,da.join)(t,"./tsconfig.json")))return!0;let e=wN(t);return e&&(0,Ai.existsSync)((0,da.join)(e,"./package.json"))?(0,Ai.readFileSync)((0,da.join)(e,"./package.json"),"utf-8").includes("typescript"):!1}function Fje(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=kje(n,o.path),A=(0,da.resolve)(t,a);if("code"in o){let c=await Tje(t,e,o.code,Rje(o.path),i);(0,Ai.existsSync)(A)||(0,Ai.mkdirSync)((0,da.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 kje(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 Rje(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 Tje(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,da.join)(t,"src"))?"src/":"";switch(e.toLowerCase()){case"angular":return`./${n}app/components/`;case"html":return"./";default:return`./${n}components/`}}var da,Ai,Ou,mL=L(()=>{"use strict";h();rr();da=require("node:path"),Ai=require("node:fs");GC();xk();Ou=z(Er(),1);Ms();hr();Xr()});var qne=N((
|
|
1490
|
+
${e}`}async function Sje(t,e,r){let n,i=Fje(r,e.toLowerCase());switch(e.toLowerCase()){case"react":let s=await xje(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 xje(t){if((0,Ai.existsSync)((0,da.join)(t,"./tsconfig.json")))return!0;let e=wN(t);return e&&(0,Ai.existsSync)((0,da.join)(e,"./package.json"))?(0,Ai.readFileSync)((0,da.join)(e,"./package.json"),"utf-8").includes("typescript"):!1}function Fje(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=kje(n,o.path),A=(0,da.resolve)(t,a);if("code"in o){let c=await Tje(t,e,o.code,Rje(o.path),i);(0,Ai.existsSync)(A)||(0,Ai.mkdirSync)((0,da.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 kje(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 Rje(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 Tje(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,da.join)(t,"src"))?"src/":"";switch(e.toLowerCase()){case"angular":return`./${n}app/components/`;case"html":return"./";default:return`./${n}components/`}}var da,Ai,Ou,mL=L(()=>{"use strict";h();rr();da=require("node:path"),Ai=require("node:fs");GC();xk();Ou=z(Er(),1);Ms();hr();Xr()});var qne=N((VHt,Yne)=>{"use strict";h();var Hne=require("child_process"),Nje=Hne.spawn,Mje=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":Mje("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 Nje("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 Ks(t,e,r,n=5e3,i="SIGTERM"){if(typeof e!="number"&&(!e||(uI(e)?e.getExitCode()!==null:e.exitCode!==null)))return null;if(r?.aborted)return nn(r.reason);let s=new Promise((c,u)=>{r?.addEventListener("abort",()=>{u(new Error("killProcess aborted by the user"))},{once:!0})}),o,a;if(typeof e=="number"?o=e:(a=e,o=uI(a)?a.getPid():a.pid),!o){if(t?.Sentry?.captureMessage("killProcess: no pid (process never spawned or already exited)",{level:"info",extra:{procType:a?uI(a)?"DevCommandProcess":"ChildProcess":"number"}}),a)try{a.kill("SIGKILL")}catch{}return null}let A=c=>{if(a){if(uI(a)?a.getExitCode()!==null:a.exitCode!==null||a.signalCode!==null){c();return}uI(a)?a.onClose(()=>c()):a.on("close",c)}else{let l=Math.floor(n/100),d=0,g=()=>{if(!Ww(o)){c();return}++d>=l||setTimeout(g,100)};g()}};try{return await Promise.race([new Promise((c,u)=>(0,CL.default)(o,i,l=>{if(l){u(l);return}a?.removeAllListeners(),A(c)})),new Promise((c,u)=>setTimeout(()=>u(new Error(`${i} killProcess timeout`)),n)),s]),null}catch(c){if(c.code==="ESRCH")return null;t?.Sentry?.captureException(c,{level:"warning"});try{return await Promise.race([new Promise((u,l)=>(0,CL.default)(o,"SIGKILL",d=>{if(d){l(d);return}a?.removeAllListeners(),A(u)})),new Promise((u,l)=>setTimeout(()=>l(new Error("SIGKILL killProcess timeout")),n)),s]),null}catch(u){return u.code==="ESRCH"||!Ww(o)?null:(t?.Sentry?.captureException(u,{level:"warning"}),u instanceof Error?u:new Error("killProcess: failed to kill process: "+String(u)))}}finally{a&&a.removeAllListeners()}}var lI,CL,zw,$ne,Vne,EL,Pje,IL,Xw,_g,Lje,Wne,_je,Uje,BL,yL,uI,fa=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();Pje=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(Ks(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){Pje.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;Lje=()=>(_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},_je=t=>(t=t.trim(),t.includes(`
|
|
1492
1492
|
`)||t.includes(`\r
|
|
1493
1493
|
`)),Uje=(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=Lje(),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(_je(t)){let n=Uje(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,Gje,tHt,zne=L(()=>{"use strict";h();Ef=require("zod"),Gje=Ef.z.object({kind:Ef.z.literal("postgres"),migrations:Ef.z.literal("drizzle"),schemaDir:Ef.z.string().default("drizzle")}),tHt=Ef.z.object({database:Gje.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,Oje,Kje,Hje,Jje,jje,DL,Yje,qje,$je,Vje,Wje,zje,Xje,Zje,eYe,tYe,sie,wL=L(()=>{"use strict";h();ye=require("zod");Oje=ye.z.object({type:ye.z.literal("url"),value:ye.z.string()}).meta({title:"URL"}),Kje=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"}),Hje=ye.z.object({type:ye.z.literal("template"),name:ye.z.string(),id:ye.z.number()}).meta({title:"Template"}),Jje=ye.z.object({type:ye.z.literal("builder"),html:ye.z.string()}).meta({title:"BuilderContentAttachment"}),jje=ye.z.object({type:ye.z.literal("figma"),html:ye.z.string()}).meta({title:"FigmaContentAttachment"}),DL=ye.z.discriminatedUnion("type",[Kje,Hje,Oje,Jje,jje]).meta({title:"Attachment"}),Yje=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"}),qje=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"}),$je=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"}),Vje=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"}),Wje=ye.z.discriminatedUnion("type",[Yje,$je,qje,Vje]).meta({title:"TextCitationParam"}),zje=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"}),Xje=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(Wje).nullish(),ephemeral:ye.z.boolean().optional(),thoughtSignature:ye.z.string().optional(),tag:ye.z.string().optional()}).meta({title:"ContentMessageItemText"}),eYe=ye.z.object({type:ye.z.literal("image"),source:ye.z.discriminatedUnion("type",[zje,Xje]),cache:ye.z.boolean().optional(),ephemeral:ye.z.boolean().optional()}).meta({title:"ContentMessageItemImage"}),tYe=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,eYe,tYe]))]),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 qn,aie,bL=L(()=>{"use strict";h();qn=require("zod"),aie=qn.z.object({client:qn.z.string(),clientVersion:qn.z.string(),nodeVersion:qn.z.string(),systemPlatform:qn.z.string(),frameworks:qn.z.array(qn.z.string()),systemEOL:qn.z.string(),systemArch:qn.z.string(),systemShell:qn.z.string().optional(),inGitRepo:qn.z.boolean().optional()}).catchall(qn.z.union([qn.z.string(),qn.z.array(qn.z.string()),qn.z.boolean(),qn.z.undefined()])).meta({title:"UserContext"})});var $n,Bf,rYe,nYe,Aie,Zw=L(()=>{"use strict";h();$n=require("zod"),Bf=$n.z.object({key:$n.z.string(),value:$n.z.string(),isSecret:$n.z.boolean(),placeholder:$n.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:$n.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"EnvironmentVariable"}),rYe=$n.z.object({key:$n.z.string(),type:$n.z.literal("mise"),tool:$n.z.string(),version:$n.z.string().optional()}).meta({title:"SetupMiseDependency"}),nYe=$n.z.object({key:$n.z.string(),type:$n.z.literal("script"),name:$n.z.string(),script:$n.z.string()}).meta({title:"SetupScriptDependency"}),Aie=$n.z.discriminatedUnion("type",[rYe,nYe]).meta({title:"SetupDependency"})});function die(t){return t==="interrupt"||t==="interrupt-clear"||t==="interrupt-replace"}function xL(t){return t===void 0?{...K9e}:t==="next-turn"?{schedule:"next-turn",coalesce:"merge"}:t==="until-idle"?{schedule:"until-idle",coalesce:"preserve-order"}:{schedule:t.schedule,coalesce:t.coalesce}}var b,iYe,CHt,sYe,oYe,uie,aYe,AYe,cYe,uYe,IHt,t0,lYe,gYe,pYe,dYe,fYe,hYe,EHt,mYe,CYe,IYe,EYe,BYe,yYe,QYe,DYe,wYe,bYe,vYe,SYe,xYe,FYe,kYe,vL,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,i9e,s9e,e0,o9e,a9e,A9e,c9e,u9e,l9e,lie,gie,BHt,yHt,g9e,p9e,d9e,f9e,h9e,m9e,C9e,I9e,E9e,B9e,y9e,Q9e,D9e,SL,w9e,b9e,v9e,S9e,x9e,F9e,k9e,R9e,T9e,N9e,M9e,P9e,L9e,_9e,U9e,G9e,pie,O9e,K9e,H9e,cie,J9e,j9e,Y9e,fie,q9e,r0,QHt,$9e,V9e,W9e,hie,z9e,X9e,Z9e,mie,e6e,DHt,t6e,r6e,wHt,bHt,vHt,SHt,Cie=L(()=>{"use strict";h();b=require("zod");wL();bL();Zw();iYe=b.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."}),CHt=b.z.enum(["named","default"]).meta({title:"ImportType"}),sYe=b.z.object({filePath:b.z.string(),content:b.z.string().optional(),importance:b.z.number().optional(),dropReason:b.z.string().optional(),wasIncluded:b.z.boolean().optional(),virtual:b.z.boolean().optional()}).meta({title:"ProjectFile"}),oYe=b.z.object({id:b.z.string(),name:b.z.string(),content:b.z.string(),type:b.z.enum(["always","agent-mode"]).optional(),filePath:b.z.string().optional(),glob:b.z.string().optional(),description:b.z.string().optional(),allowedTools:b.z.array(b.z.string()).optional(),hideUI:b.z.boolean().optional(),isSkill:b.z.boolean().optional(),disableModelInvocation:b.z.boolean().optional(),userInvocable:b.z.boolean().optional(),scope:b.z.enum(["project","user","plugin"]).optional(),pluginName:b.z.string().optional()}).meta({title:"CustomInstruction"}),uie=b.z.enum(["auto","none","minimal","low","medium","high","xhigh","max"]).meta({title:"ReasoningEffort"}),aYe=b.z.object({name:b.z.string(),description:b.z.string().optional()}).meta({title:"CustomAgentInfo"}),AYe=b.z.record(b.z.string(),b.z.union([b.z.string(),b.z.array(b.z.string())])).meta({title:"AgentModelOverrides"}),cYe=b.z.enum(["react","html","mitosis","react-native","angular","vue","svelte","qwik","solid","marko","swiftui","jetpack-compose","flutter"]).meta({title:"CodeGenFramework"}),uYe=b.z.enum(["tailwind","tailwind-precise","emotion","styled-components","styled-jsx","react-native"]).meta({title:"CodeGenStyleLibrary"}),IHt=b.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.",lYe=b.z.object({file_path:b.z.string().meta({description:t0}),offset:b.z.number().nullish().meta({description:"The line number to start reading from."}),limit:b.z.number().nullish().meta({description:"The number of lines to read."})}).meta({title:"ReadToolInput"}),gYe=b.z.object({pattern:b.z.string().meta({description:"The pattern to search for"})}).meta({title:"GlobSearchToolInput"}),pYe=b.z.object({query:b.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:b.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:b.z.string().nullish().meta({description:"Optional glob pattern to exclude specific files or directories"}),case_sensitive:b.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"}),dYe=b.z.object({skill:b.z.string().meta({description:"The name of a skill from the available-skills list. Do not guess names."}),args:b.z.string().nullish().meta({description:"Optional invocation arguments; forwarded with the skill body in the tool result."})}).meta({title:"SkillToolInput"}),fYe=b.z.object({name:b.z.string().meta({description:"The name of the rule to get"})}).meta({title:"GetRuleToolInput"}),hYe=b.z.object({url:b.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"}),EHt=b.z.object({}).meta({title:"GetBuildOutputToolInput"}),mYe=b.z.object({restart:b.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:b.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:b.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:b.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:b.z.tuple([b.z.string(),b.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:b.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"}),CYe=b.z.object({}).meta({title:"DevServerLogsInput"}),IYe=b.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."}),EYe=b.z.object({}).meta({title:"DevServerRestartInput",description:"Restarts the dev server with current configuration."}),BYe=b.z.object({description:b.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:b.z.string().meta({description:"The shell command to run, for example 'npm install --save uuid', 'yarn test' or 'npm run build'..."}),timeout:b.z.number().nullish().meta({description:"Optional timeout in milliseconds (max/default 600000)"})}).meta({title:"BashToolInput"}),yYe=b.z.object({command:b.z.string().nullish().meta({description:"The PowerShell command to run, for example 'npm install' or 'yarn test'"}),timeout:b.z.number().nullish().meta({description:"The timeout in milliseconds for the command to run. Choose an appropriate timeout based on the command"}),description:b.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"}),QYe=b.z.object({query:b.z.string().meta({description:"The question to search on the internet, be specific and concise."})}).meta({title:"WebSearchToolInput"}),DYe=b.z.object({title:b.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:b.z.string().meta({description:t0}),content:b.z.string().meta({description:"Actual content to write into the file, use an empty string to remove the file"})}).meta({title:"WriteFileInput"}),wYe=b.z.object({title:b.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:b.z.string().meta({description:`${t0} The content of this path must be previously known.`}),old_str:b.z.string().meta({description:"The text to replace"}),new_str:b.z.string().meta({description:"The text to replace it with (must be different from old_str)"}),replace_all:b.z.boolean().optional().meta({description:"Replace all occurences of old_str (default false)"}),apply_with_error:b.z.boolean().optional()}).meta({title:"SearchReplaceInput"}),bYe=b.z.object({title:b.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:b.z.string().meta({description:`${t0} The content of this path must be previously known.`}),edits:b.z.array(b.z.object({old_str:b.z.string().meta({description:"The text to replace (must match the file contents exactly, including all whitespace and indentation)"}),new_str:b.z.string().meta({description:"The edited text to replace the old_str"}),replace_all:b.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:b.z.boolean().nullish()}).meta({title:"MultiSearchReplaceInput"}),vYe=b.z.object({query:b.z.string(),type:b.z.enum(["image","video"]),orientation:b.z.enum(["landscape","portrait","square"]).nullish(),hex_color:b.z.string().nullish()}).meta({title:"FindMediaToolInput"}),SYe=b.z.object({query:b.z.string().meta({description:"The text prompt describing the media to find or generate"}),type:b.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:b.z.enum(["landscape","portrait","square"]).nullish().meta({description:"The orientation/aspect ratio of the media (landscape=wide, portrait=tall, square=1:1)"}),hex_color:b.z.string().nullish().meta({description:"Optionally use to find images with the predominant specified hex color, for example '#000000' or '#FFFFFF'"}),input_image_urls:b.z.array(b.z.string()).nullish().meta({description:'Reference image URLs for AI image generation (only used with type: "gen-image")'})}).meta({title:"MediaToolInput"}),xYe=b.z.object({content:b.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:b.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:b.z.union([b.z.literal("architecture").meta({description:"System structure, layers, and responsibilities"}),b.z.literal("data-and-sync").meta({description:"Data storage, persistence, synchronization, IPC, and state flow"}),b.z.literal("patterns-and-standards").meta({description:"Canonical ways of doing things in this codebase"}),b.z.literal("coupling-and-duplication").meta({description:"Cross-file, cross-surface, or duplicated logic that must stay aligned"}),b.z.literal("ui-and-ux-contracts").meta({description:"User-visible behavior, UX guarantees, and UI rules"}),b.z.literal("concurrency-and-lifecycle").meta({description:"Async behavior, ordering, lifecycle, and race prevention"}),b.z.literal("invariants").meta({description:"Hard rules that must always remain true"}),b.z.literal("security-and-trust").meta({description:"Security, permissions, and trust boundaries"}),b.z.literal("gotchas").meta({description:"Known sharp edges that will break things if ignored"}),b.z.literal("constraints-and-limits").meta({description:"System limits, assumptions, and non-obvious constraints"}),b.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:b.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:b.z.number().optional(),glob_auto_include:b.z.boolean().optional().meta({description:"Whenever the memory should be included whenever the glob is matched."})}).meta({title:"MemoryToolInput"}),FYe=b.z.object({query:b.z.string(),limit:b.z.number().optional(),minSimilarity:b.z.number().optional()}).meta({title:"SearchMemoriesToolInput"}),kYe=b.z.object({outcome:b.z.enum(["worked","failed","partial","unknown"]).meta({description:"Overall exchange outcome based on user reaction"}),memory_scores:b.z.object({}).catchall(b.z.enum(["worked","failed","partial","unknown"])).meta({description:"Score for each memory used: { memory_id: outcome }"})}).meta({title:"ScoreMemoriesToolInput"}),vL=b.z.object({label:b.z.string(),description:b.z.string()}).meta({title:"LabelOption"}),RYe=b.z.strictObject({label:b.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:b.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:b.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"}),TYe=b.z.strictObject({question:b.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:b.z.string().meta({description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:b.z.array(RYe).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:b.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"}),NYe=b.z.strictObject({questions:b.z.array(TYe).min(1,"Must have at least 1 question").max(4).meta({description:"Questions to ask the user (1-4 questions)"})}).meta({title:"AskUserQuestionToolInput"}),MYe=b.z.object({description:b.z.string().meta({description:"A short (3-5 word) description of the task"}),prompt:b.z.string().meta({description:"The task for the agent to perform"}),subagent_type:b.z.string().optional().meta({description:"The type of specialized agent to use for this task"}),resume:b.z.string().optional().meta({description:"Optional agent ID to resume from"}),origin_channel_id:b.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:b.z.array(b.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"}),PYe=b.z.object({checkpoint_id:b.z.string().meta({description:"The checkpoint ID to revert back to. All changes from this checkpoint to HEAD will be reverted."})}).meta({title:"RevertToolInput"}),LYe=b.z.object({}).meta({title:"TodoReadToolInput"}),_Ye=b.z.object({}).meta({title:"RunningAgentsToolInput"}),UYe=b.z.object({mode:b.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:b.z.array(b.z.object({content:b.z.string().meta({description:"The imperative form describing what needs to be done"}),status:b.z.enum(["pending","in_progress","completed"]),id:b.z.string()}))}).meta({title:"TodoWriteToolInput"}),GYe=b.z.object({subject:b.z.string().meta({description:"A brief title for the task"}),description:b.z.string().meta({description:"What needs to be done"}),metadata:b.z.looseObject({}).optional()}).meta({title:"TaskCreateToolInput"}),OYe=b.z.object({taskId:b.z.string().meta({description:"The ID of the task to update"}),subject:b.z.string().optional().meta({description:"New subject for the task"}),description:b.z.string().optional().meta({description:"New description for the task"}),status:b.z.enum(["pending","in_progress","completed","deleted"]).optional().meta({description:"New status for the task"}),owner:b.z.string().optional().meta({description:"New owner for the task"}),addBlocks:b.z.array(b.z.string()).optional().meta({description:"Task IDs that this task blocks"}),addBlockedBy:b.z.array(b.z.string()).optional().meta({description:"Task IDs that block this task"}),metadata:b.z.looseObject({}).optional()}).meta({title:"TaskUpdateToolInput"}),KYe=b.z.object({}).meta({title:"TaskListToolInput"}),HYe=b.z.object({filePath:b.z.string().meta({description:"The path of the Mitosis file to edit (e.g., index.lite.tsx)"}),old_str:b.z.string().meta({description:"Content to be replaced, this substring should appear verbatim in the selected file_path"}),new_str:b.z.string().meta({description:"New content to replace the old content with"})}).meta({title:"BuilderEditToolInput"}),JYe=b.z.object({href:b.z.string().optional(),selector:b.z.string().optional(),width:b.z.number().optional(),height:b.z.number().optional()}).meta({title:"GetScreenshotToolInput"}),jYe=b.z.object({href:b.z.string().meta({description:"The URL or relative path to navigate the preview to (e.g., '/about' or 'https://example.com')"})}).meta({title:"NavigatePreviewToolInput"}),YYe=b.z.object({url:b.z.string().meta({description:"The URL to fetch content from"}),prompt:b.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:b.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"}),qYe=b.z.object({category:b.z.enum(["reusable_knowledge","one_off","bad_quality"]).optional(),gif_id:b.z.string().optional(),timeline_id:b.z.string().optional(),recording_id:b.z.string().optional(),important_files:b.z.array(b.z.object({file_path:b.z.string().meta({description:"The relative path of the file to read"}),relevance:b.z.enum(["high","medium","low"]).optional().meta({description:"The relevance of the file based on the initial user_prompt"}),offset:b.z.number().optional().meta({description:"The offset of the file to read, in lines"}),limit:b.z.number().optional().meta({description:"The limit of the file to read, in lines"})}))}).meta({title:"ExplorationMetadataToolInput"}),$Ye=b.z.object({}).meta({title:"EnterPlanModeToolInput"}),VYe=b.z.object({plan:b.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:b.z.boolean().optional()}).meta({title:"ExitPlanModeToolInput"}),WYe=b.z.object({uri:b.z.string().meta({description:"The URI of the resource to read, matching a resource template pattern (e.g., 'file:///path/to/file')"}),serverName:b.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"}),zYe=b.z.enum(["navigation","interaction","assertion","error","milestone","code-change","observation","verified"]).meta({title:"TimelineEventCategory"}),XYe=b.z.enum(["succeeded","couldnt_verify","failed","other"]).meta({title:"TestOutcome"}),ZYe=b.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"}),e9e=b.z.object({title:b.z.string().meta({description:"A descriptive title for this frame (e.g., 'Login page loaded', 'Form submitted successfully')"}),frame:b.z.literal("last-image").meta({description:"The frame source. Use 'last-image' to record the most recent screenshot."}),category:zYe.optional().meta({description:"Category of this frame for timeline organization. Default: 'milestone'"}),description:b.z.string().optional().meta({description:"Optional longer description providing context about what this frame shows."}),pr_highlight:b.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"}),t9e=b.z.object({outcome:XYe.meta({description:"The structured test outcome"}),summary:b.z.string().meta({description:"A concise 1\u20132 sentence summary explaining the test outcome"}),details:b.z.string().optional().meta({description:"Optional additional context: error messages, steps attempted, etc."}),test_case_id:b.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:b.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:b.z.string().optional().meta({description:"Human-readable failure explanation. E.g., 'Login page returned 403 \u2014 test account may have been disabled'"}),console_errors:b.z.string().optional(),network_failures:b.z.string().optional(),steps_attempted:b.z.string().optional(),urls_tested:b.z.array(b.z.string()).optional()}).meta({title:"ReportTestOutcomeToolInput"}),r9e=b.z.object({projectOverview:b.z.object({framework:b.z.string().nullable(),packageManager:b.z.enum(["npm","yarn","pnpm","bun"]).nullable(),isMonorepo:b.z.boolean(),detectedLanguage:b.z.enum(["typescript","javascript"]).nullable()}),rootDirectory:b.z.object({path:b.z.string(),reason:b.z.string()}).nullable(),installCommand:b.z.object({command:b.z.string(),reason:b.z.string()}).nullable(),runtimeDependencies:b.z.array(b.z.object({tool:b.z.string(),version:b.z.string(),source:b.z.string()})),devServer:b.z.object({command:b.z.string(),url:b.z.string(),port:b.z.number(),reason:b.z.string()}).nullable(),environmentVariables:b.z.array(b.z.object({key:b.z.string(),description:b.z.string(),isRequired:b.z.boolean(),isSecret:b.z.boolean(),defaultValue:b.z.string().nullable(),source:b.z.string()})),validationScript:b.z.object({command:b.z.string(),reason:b.z.string()}).nullable(),npmrcContents:b.z.string().nullable(),hasHotModuleReload:b.z.object({value:b.z.boolean(),reason:b.z.string()}).nullable()}).meta({title:"SetupAnalysisValues"}),n9e=b.z.object({config:r9e,message:b.z.string().optional()}).meta({title:"ProposeConfigToolInput"}),i9e=b.z.enum(["installCommand","devServer","validationScript","environmentVariables"]).meta({title:"SetupValueField"}),s9e=b.z.object({field:i9e.meta({description:"Which field to update"}),value:b.z.object({command:b.z.string().optional().meta({description:"The command to run (for installCommand, devServer, validationScript)"}),url:b.z.string().optional().meta({description:"Dev server URL (only for devServer)"}),port:b.z.number().optional().meta({description:"Dev server port (only for devServer)"}),environmentVariables:b.z.array(b.z.object({key:b.z.string().meta({description:"Variable name"}),description:b.z.string().optional().meta({description:"What this variable is for"}),isRequired:b.z.boolean().optional().meta({description:"Whether this variable is required"}),isSecret:b.z.boolean().optional().meta({description:"Whether this is a secret/credential"}),defaultValue:b.z.string().nullish()})).optional()}),reason:b.z.string()}).meta({title:"UpdateSetupValueToolInput"}),e0=b.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))"}),o9e=b.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:b.z.string().meta({description:"Brief summary of configuration outcome (what succeeded or what's needed)"}),questions:b.z.array(b.z.object({question:b.z.string().meta({description:"Full question text"}),context:b.z.string().meta({description:"Why this information is needed"}),header:b.z.string().optional().meta({description:'Short label (e.g., "API Key", "Database URL")'}),type:b.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:b.z.string().optional().meta({description:"Placeholder/hint text for 'text' type questions (e.g., 'Enter your API key', 'https://localhost:3000')"}),options:b.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:b.z.boolean().optional().meta({description:"Repository contains multiple packages/apps"}),isMicrofrontend:b.z.boolean().optional().meta({description:"Frontend code served over multiple ports/servers"}),setupNeedsCredentials:b.z.boolean().optional().meta({description:"Setup requires credentials (e.g., NPM_TOKEN for private packages)"}),devServerNeedsCredentials:b.z.boolean().optional().meta({description:"Dev server needs special environment variables to run"}),needsVPN:b.z.boolean().optional().meta({description:"Setup requires a VPN connection"}),autoReload:b.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:b.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:b.z.array(b.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:b.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"}),a9e=["running","stopped","starting","failed","unset"],A9e=["not-installed","installing","installed","install-failed","install-aborted"],c9e=["ok-2xx","error-4xx","error-5xx","error-fetch","stopped","connecting"],u9e=["unset","running","stopped","success","failure"],l9e=b.z.object({question:b.z.string(),context:b.z.string(),whatYouTried:b.z.string().optional(),header:b.z.string().optional().meta({description:"Short label (e.g., 'API Key', 'Database URL')"}),type:b.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:b.z.string().optional().meta({description:"Placeholder text for text-type questions"}),options:b.z.array(vL).optional()}),lie=b.z.object({setupCommand:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on setupState === 'installed'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),setupDependencies:b.z.object({value:b.z.array(Aie).optional(),verified:b.z.boolean().meta({description:"Based on setupState === 'installed'"})}),devCommand:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on devState === 'running'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),devServer:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds waiting for the server to respond"})}),validateCommand:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on validateState === 'success'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),appOrigin:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"})}),defaultOrigin:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Always true if set (used with wildcard appOrigin)"})}),environmentVariables:b.z.object({value:b.z.array(Bf).optional(),verified:b.z.boolean().meta({description:"Based on devState === 'running'"})}),autoDetectDevServer:b.z.object({value:b.z.boolean().optional(),verified:b.z.boolean().meta({description:"Always true if set"})}),autoDetectDevServerPatterns:b.z.object({value:b.z.array(b.z.string()).optional(),verified:b.z.boolean().meta({description:"Always true if set"})}),hasHotModuleReload:b.z.object({value:b.z.boolean().optional(),reason:b.z.string().optional().meta({description:"Detection-only, not auto-applied"})})}),gie=b.z.object({setupState:b.z.enum(A9e),devState:b.z.enum(a9e),httpServerState:b.z.enum(c9e),validateState:b.z.enum(u9e)}),BHt=b.z.object({id:b.z.string().meta({description:"Auto-generated document ID"}),projectId:b.z.string(),branchName:b.z.string(),createdAt:b.z.number(),updatedAt:b.z.number(),ownerId:b.z.string(),state:e0.meta({description:"Configuration state from Exit tool"}),running:b.z.boolean().default(!1),previousStates:b.z.array(e0).optional(),summary:b.z.string().meta({description:"Summary from Exit tool"}),questions:b.z.array(l9e).optional(),configuration:lie,sessionId:b.z.string(),orchestratorStates:gie,peakDiskUsage:b.z.number().optional().meta({description:"Peak disk usage in bytes"}),peakMemoryUsage:b.z.number().optional().meta({description:"Peak memory usage in bytes"}),screenshotUrl:b.z.string().optional().meta({description:"Screenshot URL from verification (e.g., error page screenshot)"}),isMonorepo:b.z.boolean().optional(),isMicrofrontend:b.z.boolean().optional(),setupNeedsCredentials:b.z.boolean().optional(),devServerNeedsCredentials:b.z.boolean().optional(),projectDescription:b.z.string().optional(),cost:b.z.number().optional(),durationMs:b.z.number().optional(),needsVPN:b.z.boolean().optional(),autoReload:b.z.boolean().optional(),usesBuilderCms:b.z.boolean().optional(),stack:b.z.array(b.z.string()).optional()}).meta({title:"ProposedConfig",description:"Configuration proposed by the configuration agent, stored in Firebase"}),yHt=b.z.object({projectId:b.z.string(),branchName:b.z.string(),state:e0,summary:b.z.string(),questions:b.z.array(b.z.object({question:b.z.string(),context:b.z.string(),whatYouTried:b.z.string().optional(),header:b.z.string().optional(),options:b.z.array(vL).optional(),multiSelect:b.z.boolean().optional()})).optional(),configuration:lie,sessionId:b.z.string(),orchestratorStates:gie,peakDiskUsage:b.z.number().optional(),peakMemoryUsage:b.z.number().optional(),screenshotUrl:b.z.string().optional(),isMonorepo:b.z.boolean().optional(),isMicrofrontend:b.z.boolean().optional(),setupNeedsCredentials:b.z.boolean().optional(),devServerNeedsCredentials:b.z.boolean().optional(),needsVPN:b.z.boolean().optional(),projectDescription:b.z.string().optional(),autoReload:b.z.boolean().optional(),usesBuilderCms:b.z.boolean().optional(),stack:b.z.array(b.z.string()).optional()}).meta({title:"ProposeConfigParams"}),g9e=b.z.object({command:b.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:b.z.array(b.z.object({tool:b.z.string().meta({description:"The tool/binary to verify (e.g., 'node', 'npm', 'git')"}),version:b.z.string().optional().meta({description:"Optional version requirement (e.g., '>=18.0.0', '20.x')"})})).optional()}).meta({title:"VerifySetupCommandToolInput"}),p9e=b.z.object({command:b.z.string().meta({description:"The dev server command to run (e.g., 'npm run dev', 'cd packages/frontend && yarn dev')"})}).meta({title:"VerifyDevCommandToolInput"}),d9e=b.z.object({autoDetect:b.z.boolean().meta({description:"Whether to automatically detect the dev server URL from terminal output"}),autoDetectPattern:b.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:b.z.string().optional().meta({description:"The hardcoded dev server URL to use when autoDetect is false (e.g., 'http://localhost:3000')"}),appOrigin:b.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:b.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"}),f9e=b.z.object({command:b.z.string(),timeout:b.z.number().optional().meta({description:"Default: 300000 (5 minutes)"})}).meta({title:"VerifyValidateCommandToolInput"}),h9e=b.z.object({key:b.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:b.z.string().meta({description:"The environment variable value. Must be a concrete value, not a placeholder."}),secret:b.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"})}).meta({title:"ProposeEnvVariableToolInput"}),m9e=b.z.object({key:b.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:b.z.string().meta({description:"The environment variable value. Use clear placeholder like 'PLACEHOLDER_DATABASE_URL' if actual value is unknown."}),secret:b.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"}),placeholder:b.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:b.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"SetEnvVariableToolInput"}),C9e=b.z.object({path:b.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:b.z.string().optional().meta({description:"Plain text content to write to the file. Mutually exclusive with `base64`."}),base64:b.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"}),I9e=b.z.object({channel_id:b.z.string().meta({description:"The channel identifier in URI format (see supported formats in the tool description)"}),markdown:b.z.string().meta({description:"The message content to send in markdown format"}),status:b.z.enum(["starting","question","will-follow-up","done:success","done:error"]),loading_message:b.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:b.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:b.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"}),E9e=b.z.object({project_id:b.z.string().meta({description:"The project ID to create the branch in"}),message:b.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:b.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:b.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:b.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:b.z.enum(["normal","planning","deep-research"]).optional(),model:b.z.enum(["auto","opus","sonnet","haiku"]).optional(),attachment_urls:b.z.array(b.z.string()).optional(),git_base_branch:b.z.string().optional(),auto_archive_on_idle:b.z.boolean().optional()}).meta({title:"SpawnBranchToolInput"}),B9e=b.z.object({repo_url:b.z.string().meta({description:"Repository URL (regular Git URL or template:// URL)"}),name:b.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:b.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:b.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:b.z.string().optional().meta({description:"Only valid for template:// URLs \u2014 creates a branch with this message"})}).meta({title:"CreateProjectToolInput"}),y9e=b.z.object({}).meta({title:"GetAvailableReposToolInput"}),Q9e=b.z.object({project_id:b.z.string().meta({description:"The project ID containing the branch"}),branch_name:b.z.string().meta({description:"The name of the branch to read"})}).meta({title:"ReadBranchToolInput"}),D9e=b.z.object({project_id:b.z.string().meta({description:"The project ID containing the branch"}),branch_name:b.z.string().meta({description:"The name of the branch to archive"}),builder_user_id:b.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:b.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=b.z.enum(["high","medium","low"]).meta({title:"ReviewSeverity"}),w9e=b.z.object({file_path:b.z.string().meta({description:"Relative file path - MUST be a file that appears in the PR diff"}),line:b.z.number().meta({description:"Line number in the file (end line for multi-line). MUST be a line within the PR diff"}),start_line:b.z.number().optional().meta({description:"For multi-line comments (optional)"}),side:b.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:b.z.string().meta({description:"Brief plain-text issue title. MUST NOT start with severity emojis"}),body:b.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:b.z.string().optional(),gif_id:b.z.string().optional().meta({description:"Per-comment GIF (optional)"})}).meta({title:"PRReviewComment"}),b9e=b.z.enum(["looks_good","has_findings","blocking"]).meta({title:"ReviewVerdict"}),v9e=b.z.object({summary:b.z.string().meta({description:"Your detailed analysis of the changes (displayed in a collapsible 'Review Details' section)"}),comments:b.z.array(w9e).optional(),risk_level:SL.optional(),verdict:b9e.optional()}).meta({title:"SubmitPRReviewToolInput"}),S9e=b.z.object({thread_node_ids:b.z.array(b.z.string()).meta({description:"GraphQL thread node_ids (PRRT_...) from previous review response"})}).meta({title:"ResolveQACommentsToolInput"}),x9e=b.z.object({title:b.z.string().meta({description:"Brief summary of the issue (e.g., 'Button click has no effect')"}),description:b.z.string().meta({description:"Detailed description of what went wrong, what was expected, and what actually happened"}),debugInfo:b.z.string().optional().meta({description:"Optional console errors, stack traces, or other diagnostic information"})}).meta({title:"ReportUIIssueToolInput"}),F9e=b.z.object({file_path:b.z.string().meta({description:"File path where the issue occurs (e.g., 'packages/api/src/auth.ts')"}),line:b.z.number().meta({description:"End line number of the issue range (or single line if no start_line)"}),start_line:b.z.number().optional().meta({description:"Optional start line for multi-line issues. When provided, the comment spans from start_line to line"}),title:b.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:b.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"}),k9e=b.z.object({issue:b.z.string().meta({description:"What's blocking execution"}),steps_attempted:b.z.string().meta({description:"What was tried before escalating"}),current_url:b.z.string().meta({description:"Current browser URL"}),test_case_id:b.z.string().meta({description:"Which test case is blocked"})}).meta({title:"EscalateToPlanner"}),R9e=b.z.object({}).meta({title:"GetLastBrowserTestToolInput"}),T9e=b.z.object({file_path:b.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"}),N9e=b.z.object({event_id:b.z.string().meta({description:"The codegen event ID to load (e.g. cgen-<eventId>)."})}).meta({title:"GetCodegenEventToolInput"}),M9e=b.z.object({session_or_event_id:b.z.string().meta({description:"A session ID or codegen event ID. When an event ID is given, its session is resolved first."}),limit:b.z.number().optional().meta({description:"Maximum number of events to return."})}).meta({title:"ListCodegenSessionEventsToolInput"}),P9e=b.z.object({url:b.z.string().meta({description:"The prototype URL (e.g., https://builder.io/app/projects/<projectId>/<branchName>)"}),project_id:b.z.string().optional().meta({description:"The project ID (optional, parsed from URL if not provided)"}),branch_name:b.z.string().optional().meta({description:"The branch name (optional, parsed from URL if not provided)"})}).meta({title:"PullPrototypeToolInput"}),L9e=b.z.object({project_id:b.z.string().meta({description:"The Builder.io project ID containing the branch"}),branch_name:b.z.string().meta({description:"The Fusion branch name to push and open a PR for"}),builder_user_id:b.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:b.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"}),_9e=b.z.object({name:b.z.string().meta({description:'Human-readable name of the service to connect, e.g. "Jira", "Linear", "Sentry"'}),url:b.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"}),U9e=b.z.object({Read:lYe,Write:DYe,Edit:wYe,ReadRule:fYe,Skill:dYe,GetStyleInspiration:hYe,GetScreenshot:JYe,NavigatePreview:jYe,MultiEdit:bYe,FindMedia:vYe,Media:SYe,AddMemory:xYe,SearchMemories:FYe,ScoreMemories:kYe,Bash:BYe,PowerShell:yYe,WebSearch:QYe,AskUserQuestion:NYe,Agent:MYe,Grep:pYe,Glob:gYe,DevServerControl:mYe,DevServerLogs:CYe,DevServerRestart:EYe,Revert:PYe,TodoRead:LYe,TodoWrite:UYe,TaskCreate:GYe,TaskUpdate:OYe,TaskList:KYe,BuilderEdit:HYe,WebFetch:YYe,ExplorationMetadata:qYe,EnterPlanMode:$Ye,ExitPlanMode:VYe,ReadMcpResource:WYe,RecordFrame:e9e,SubmitPRReview:v9e,ProposeConfig:n9e,UpdateSetupValue:s9e,Exit:o9e,ResolveQAComments:S9e,GetLastBrowserTest:R9e,ReportUIIssue:x9e,ReportIssue:F9e,ReportTestOutcome:t9e,VerifySetupCommand:g9e,VerifyDevCommand:p9e,VerifyDevServer:d9e,VerifyValidateCommand:f9e,ProposeEnvVariable:h9e,SetEnvVariable:m9e,SetFileOverride:C9e,SendMessage:I9e,SpawnBranch:E9e,CreateProject:B9e,GetAvailableRepos:y9e,ReadBranch:Q9e,ArchiveBranch:D9e,RunningAgents:_Ye,IDEDiagnostics:T9e,EscalateToPlanner:k9e,PullPrototype:P9e,ConnectMCP:_9e,EnsurePR:L9e,GenerateDesignSystemAgentMd:IYe,GetCodegenEvent:N9e,ListCodegenSessionEvents:M9e}),G9e=U9e.keyof().meta({title:"CodeGenTools"}),pie=b.z.enum(["planning","normal","auto-planning","deep-research"]).meta({title:"SessionMode"}),O9e=b.z.enum(["quality","quality-v4","quality-v4-agent"]).meta({title:"CodeGenMode"}),K9e={schedule:"next-turn",coalesce:"merge"};H9e=["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=b.z.enum(H9e).meta({title:"BaseCodeGenPosition"}),J9e=b.z.union([cie,b.z.templateLiteral([cie,"-agent"])]).meta({title:"CodeGenPosition"}),j9e=b.z.object({designSystems:b.z.array(b.z.string())}).meta({title:"RepoIndexingConfig"}),Y9e=b.z.object({name:b.z.string(),description:b.z.string().optional(),inputSchema:b.z.any().optional(),serverName:b.z.string(),deferLoading:b.z.boolean().optional()}).meta({title:"LocalMCPTools"}),fie=b.z.union([b.z.templateLiteral(["repair-",b.z.string()]),b.z.literal("user-normal"),b.z.literal("user-figma"),b.z.literal("user-pdf"),b.z.literal("user-image"),b.z.literal("setup-agent"),b.z.templateLiteral(["background-",b.z.string()]),b.z.templateLiteral(["indexing-",b.z.string()])]).meta({title:"CodeGenCategory"}),q9e=b.z.enum(["editCode","modifyMcpServers","modifyProjectSettings","createBranches","sendPullRequests","view"]).meta({title:"UserSourcePermission"}),r0={role:b.z.enum(["user","agent"]),principals:b.z.array(b.z.string()).optional().meta({description:"teams/roles like ['developer', 'admin']"}),jobs:b.z.array(b.z.string()).optional().meta({description:"job titles like ['designer', 'developer'] - used for role-aware communication instead of principals when available"}),permissions:b.z.array(q9e).optional(),channelId:b.z.string().optional()},QHt=b.z.object(r0).meta({title:"UserSourceBase"}),$9e=b.z.object({...r0,source:b.z.enum(["slack","telegram","whatsapp","teams","jira","linear","github","gitlab","azure","bitbucket"]),userId:b.z.string().optional().meta({description:"User ID from the external platform (Slack user ID, GitHub user id, etc.)"}),userName:b.z.string().optional(),userEmail:b.z.string().optional(),photoURL:b.z.string().optional(),builderUserId:b.z.string().optional().meta({description:"Resolved Builder user ID for attribution/credits"}),link:b.z.string().optional().meta({description:"Optional link (e.g. comment/PR URL) for git provider sources"})}).meta({title:"UserSourceOther"}),V9e=b.z.object({...r0,source:b.z.literal("builder.io"),userId:b.z.string().optional(),userName:b.z.string().optional(),userEmail:b.z.string().optional(),photoURL:b.z.string().optional()}).meta({title:"UserSourceBuilder"}),W9e=b.z.object({...r0,source:b.z.literal("agent"),userId:b.z.string().optional(),userName:b.z.string().optional(),userEmail:b.z.string().optional()}).meta({title:"UserSourceAgent"}),hie=b.z.discriminatedUnion("source",[$9e,V9e,W9e]).meta({title:"UserSource"}),z9e=b.z.enum(["read","write","list"]).meta({title:"Permission"}),X9e=b.z.object({action:b.z.enum(["allow","deny"]).meta({description:"whether this rule allows or denies access"}),resource:b.z.string().meta({description:"what \u2014 supports glob patterns like /files/*.txt"}),permissions:b.z.array(z9e).meta({description:"actions this rule applies to"}),description:b.z.string().optional().meta({description:"custom message, in deny case, this is the error message. This will override denyDescription on AclPolicy if defined."}),principals:b.z.array(b.z.string()).optional().meta({description:"array of teams/roles this rule applies to (e.g., ['developer', 'admin'])"})}).meta({title:"AclEntry"}),Z9e=b.z.object({secrets:b.z.array(b.z.string()).optional(),entries:b.z.array(X9e).optional(),denyDescription:b.z.string().optional().meta({description:"Default message to use when a resource is denied access"})}).meta({title:"AclPolicy"}),mie=b.z.object({text:b.z.string(),tag:b.z.string().optional(),ephemeral:b.z.boolean().optional()}).meta({title:"SystemReminderObj"}),e6e=b.z.union([b.z.string(),mie]).meta({title:"SystemReminder"}),DHt=b.z.looseObject({position:J9e,eventName:b.z.string().optional(),sessionId:b.z.string(),codeGenMode:O9e.optional(),sessionMode:pie.optional(),url:b.z.string().optional(),diffActions:b.z.boolean().optional(),planningPrompt:b.z.boolean().optional(),customInstructions:b.z.array(oYe).optional(),customAgents:b.z.array(aYe).optional(),systemPromptOverride:b.z.union([b.z.string(),b.z.array(b.z.string())]).optional(),userPrompt:b.z.string().optional(),systemReminders:b.z.array(e6e).optional(),ephemeralUserPrompt:b.z.string().optional(),uiContextPrompt:b.z.string().optional(),displayUserPrompt:b.z.string().optional(),files:b.z.array(sYe).optional(),rerankFiles:b.z.number().optional(),toolResults:b.z.array(sie).optional(),attachments:b.z.array(DL).optional(),beforeCommit:iYe.optional(),workingDirectory:b.z.string().optional(),includeRelevantMemories:b.z.boolean().optional(),encryptKey:b.z.string().optional(),modelOverride:b.z.string().optional(),errorIfHadCompaction:b.z.boolean().optional(),softContextWindow:b.z.number().optional(),promptVersion:b.z.enum(["v1","v2","v3"]).optional(),reasoning:uie.optional(),redactUserMessages:b.z.boolean().optional(),redactLLMMessages:b.z.boolean().optional(),environmentVariables:b.z.array(Bf).optional(),skipCommandSecurity:b.z.boolean().optional(),builderContent:b.z.custom().optional(),framework:cYe.optional(),styleLibrary:uYe.optional(),typescript:b.z.boolean().optional(),userContext:aie.optional(),aclPolicy:Z9e.optional(),repoIndexingConfig:j9e.optional(),recommendedRoot:b.z.string().optional(),enabledTools:b.z.array(G9e).optional(),enabledMCPs:b.z.array(b.z.string()).optional(),skippedMCPs:b.z.array(b.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:b.z.boolean().optional(),interruptActiveTask:b.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:b.z.array(Y9e).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:b.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:b.z.number().optional(),maxAgentTiming:b.z.number().optional(),maxTokens:b.z.number().optional().meta({description:"Maximum output tokens allowed in the LLM response. This will set the maximum token output for the LLM."}),maxPages:b.z.number().optional(),autoContinue:b.z.number().optional(),isManualContinue:b.z.boolean().optional(),llmSuggestions:b.z.boolean().optional(),conclusionText:b.z.boolean().optional(),mcpServers:b.z.boolean().optional(),pingEvents:b.z.boolean().optional(),forceCompact:b.z.boolean().optional(),hadPagination:b.z.boolean().optional(),category:fie.optional(),metadata:b.z.record(b.z.string(),b.z.any()).optional(),searchResponse:b.z.any().nullish(),prettierConfig:b.z.custom().optional(),role:b.z.enum(["user","agent"]).optional(),user:hie.optional(),projectId:b.z.string().optional(),branchName:b.z.string().optional(),repoHash:b.z.string().optional(),repoBranch:b.z.string().optional(),parentSessionId:b.z.string().optional().meta({description:"Immediate parent session id when this completion runs inside a sub-agent."}),mainSessionId:b.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:b.z.string().optional(),vcpId:b.z.string().optional(),repair:b.z.boolean().optional(),systemReminderPrompt:b.z.string().optional()}).meta({title:"CodeGenInputOptions"}),t6e=b.z.enum(["force-push","merge-push","ff-push","safe-push","none"]).meta({title:"AutoPushMode"}),r6e=b.z.object({remoteBranches:b.z.enum(["both","main","ai"]).optional(),fastForward:b.z.enum(["never","required","auto"]).optional(),canPush:b.z.boolean().optional(),uncommittedChanges:b.z.enum(["stash","commit","fail"]).optional(),requestRefresh:b.z.boolean().optional(),allowUnrelatedHistory:b.z.boolean().optional(),resetToBase:b.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:b.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"}),wHt=b.z.object({idempotencyKey:b.z.string().optional(),user:hie.optional(),userPrompt:b.z.string(),uiContextPrompt:b.z.string().optional(),ephemeralUserPrompt:b.z.string().optional(),displayPrompt:b.z.string().optional(),files:b.z.array(b.z.string()).optional(),systemReminders:b.z.array(mie).optional(),includeBaseFiles:b.z.boolean().optional(),attachments:b.z.array(DL).optional(),logsCheckpoint:b.z.boolean().optional(),dropAbortedPrompt:b.z.boolean().optional(),runValidateCommand:b.z.boolean().optional(),modelOverride:b.z.string().optional(),agentModelOverrides:AYe.optional(),softContextWindow:b.z.number().optional(),maxCompletions:b.z.number().optional(),isManualContinue:b.z.boolean().optional(),includeRelevantMemories:b.z.boolean().optional(),category:fie.optional(),metadata:b.z.record(b.z.string(),b.z.any()).optional(),autoPush:t6e.optional(),syncChanges:r6e.optional(),enabledMCPs:b.z.array(b.z.string()).optional(),skippedMCPs:b.z.array(b.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:b.z.boolean().optional(),agentType:b.z.string().optional().meta({description:"Custom agent type to use for this message"}),enableQAReviewTool:b.z.boolean().optional().meta({description:"Enable AddQAReview tool for QA PR review branches"}),reasoning:uie.optional().meta({description:"Per-message reasoning effort override"}),repair:b.z.boolean().optional(),forceCompact:b.z.boolean().optional().meta({description:"Force compaction of the conversation before generating the next completion"})}).meta({title:"GenerateUserMessage"}),bHt=b.z.object({diff:b.z.string().meta({description:"Git diff from previous commit"}),userMessages:b.z.array(b.z.string()).meta({description:"User messages sent during AI work"}),recentCommits:b.z.array(b.z.string()).meta({description:"Last 10 commits from main branch for style reference"}),longCommit:b.z.boolean().optional().meta({description:"Whether to generate a long commit message"}),projectId:b.z.string().optional().meta({description:"Project ID for fetching project-specific commit instructions"})}).meta({title:"CommitMessageRequest"}),vHt=b.z.object({message:b.z.string().meta({description:"Full commit message"}),title:b.z.string().meta({description:"First line (50-72 chars) - the commit title"}),body:b.z.string().optional().meta({description:"Optional extended description"})}).meta({title:"CommitMessageResponse"}),SHt=b.z.object({sessionId:b.z.string(),toolId:b.z.string(),approved:b.z.boolean(),reason:b.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,n6e,gI,PHt,LHt,yie,i6e,_Ht,s6e,UHt,GHt,OHt,KHt,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",n6e="BuilderIO/dsi-starter",gI=[...kL,yf,n6e],PHt=gI.map(t=>`https://github.com/${t}`),LHt=720*60*60*1e3;yie=Ze.z.enum(["queued","building","uploading","deploying","live","failed","canceled"]),i6e=Ze.z.object({buildCommand:Ze.z.string().optional(),nodeVersion:Ze.z.string().optional()}),_Ht=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:i6e.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"})}),s6e=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)'})}),UHt=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"})}),GHt=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)"})}),OHt=s6e.pick({id:!0,status:!0,url:!0,createdAt:!0,completedAt:!0,error:!0}).meta({title:"DeployListItem"}),KHt=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 o6e(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=o6e(t)}catch{return null}let{platform:r,type:n,ids:i}=e;return r==="slack"?a6e(n,i):null}function a6e(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=Lje(),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(_je(t)){let n=Uje(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,Gje,t4t,zne=L(()=>{"use strict";h();Ef=require("zod"),Gje=Ef.z.object({kind:Ef.z.literal("postgres"),migrations:Ef.z.literal("drizzle"),schemaDir:Ef.z.string().default("drizzle")}),t4t=Ef.z.object({database:Gje.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,Oje,Kje,Hje,Jje,jje,DL,Yje,qje,$je,Vje,Wje,zje,Xje,Zje,eYe,tYe,sie,wL=L(()=>{"use strict";h();ye=require("zod");Oje=ye.z.object({type:ye.z.literal("url"),value:ye.z.string()}).meta({title:"URL"}),Kje=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"}),Hje=ye.z.object({type:ye.z.literal("template"),name:ye.z.string(),id:ye.z.number()}).meta({title:"Template"}),Jje=ye.z.object({type:ye.z.literal("builder"),html:ye.z.string()}).meta({title:"BuilderContentAttachment"}),jje=ye.z.object({type:ye.z.literal("figma"),html:ye.z.string()}).meta({title:"FigmaContentAttachment"}),DL=ye.z.discriminatedUnion("type",[Kje,Hje,Oje,Jje,jje]).meta({title:"Attachment"}),Yje=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"}),qje=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"}),$je=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"}),Vje=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"}),Wje=ye.z.discriminatedUnion("type",[Yje,$je,qje,Vje]).meta({title:"TextCitationParam"}),zje=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"}),Xje=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(Wje).nullish(),ephemeral:ye.z.boolean().optional(),thoughtSignature:ye.z.string().optional(),tag:ye.z.string().optional()}).meta({title:"ContentMessageItemText"}),eYe=ye.z.object({type:ye.z.literal("image"),source:ye.z.discriminatedUnion("type",[zje,Xje]),cache:ye.z.boolean().optional(),ephemeral:ye.z.boolean().optional()}).meta({title:"ContentMessageItemImage"}),tYe=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,eYe,tYe]))]),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 qn,aie,bL=L(()=>{"use strict";h();qn=require("zod"),aie=qn.z.object({client:qn.z.string(),clientVersion:qn.z.string(),nodeVersion:qn.z.string(),systemPlatform:qn.z.string(),frameworks:qn.z.array(qn.z.string()),systemEOL:qn.z.string(),systemArch:qn.z.string(),systemShell:qn.z.string().optional(),inGitRepo:qn.z.boolean().optional()}).catchall(qn.z.union([qn.z.string(),qn.z.array(qn.z.string()),qn.z.boolean(),qn.z.undefined()])).meta({title:"UserContext"})});var $n,Bf,rYe,nYe,Aie,Zw=L(()=>{"use strict";h();$n=require("zod"),Bf=$n.z.object({key:$n.z.string(),value:$n.z.string(),isSecret:$n.z.boolean(),placeholder:$n.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:$n.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"EnvironmentVariable"}),rYe=$n.z.object({key:$n.z.string(),type:$n.z.literal("mise"),tool:$n.z.string(),version:$n.z.string().optional()}).meta({title:"SetupMiseDependency"}),nYe=$n.z.object({key:$n.z.string(),type:$n.z.literal("script"),name:$n.z.string(),script:$n.z.string()}).meta({title:"SetupScriptDependency"}),Aie=$n.z.discriminatedUnion("type",[rYe,nYe]).meta({title:"SetupDependency"})});function die(t){return t==="interrupt"||t==="interrupt-clear"||t==="interrupt-replace"}function xL(t){return t===void 0?{...K9e}:t==="next-turn"?{schedule:"next-turn",coalesce:"merge"}:t==="until-idle"?{schedule:"until-idle",coalesce:"preserve-order"}:{schedule:t.schedule,coalesce:t.coalesce}}var b,iYe,C4t,sYe,oYe,uie,aYe,AYe,cYe,uYe,I4t,t0,lYe,gYe,pYe,dYe,fYe,hYe,E4t,mYe,CYe,IYe,EYe,BYe,yYe,QYe,DYe,wYe,bYe,vYe,SYe,xYe,FYe,kYe,vL,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,i9e,s9e,e0,o9e,a9e,A9e,c9e,u9e,l9e,lie,gie,B4t,y4t,g9e,p9e,d9e,f9e,h9e,m9e,C9e,I9e,E9e,B9e,y9e,Q9e,D9e,SL,w9e,b9e,v9e,S9e,x9e,F9e,k9e,R9e,T9e,N9e,M9e,P9e,L9e,_9e,U9e,G9e,pie,O9e,K9e,H9e,cie,J9e,j9e,Y9e,fie,q9e,r0,Q4t,$9e,V9e,W9e,hie,z9e,X9e,Z9e,mie,e6e,D4t,t6e,r6e,w4t,b4t,v4t,S4t,Cie=L(()=>{"use strict";h();b=require("zod");wL();bL();Zw();iYe=b.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."}),C4t=b.z.enum(["named","default"]).meta({title:"ImportType"}),sYe=b.z.object({filePath:b.z.string(),content:b.z.string().optional(),importance:b.z.number().optional(),dropReason:b.z.string().optional(),wasIncluded:b.z.boolean().optional(),virtual:b.z.boolean().optional()}).meta({title:"ProjectFile"}),oYe=b.z.object({id:b.z.string(),name:b.z.string(),content:b.z.string(),type:b.z.enum(["always","agent-mode"]).optional(),filePath:b.z.string().optional(),glob:b.z.string().optional(),description:b.z.string().optional(),allowedTools:b.z.array(b.z.string()).optional(),hideUI:b.z.boolean().optional(),isSkill:b.z.boolean().optional(),disableModelInvocation:b.z.boolean().optional(),userInvocable:b.z.boolean().optional(),scope:b.z.enum(["project","user","plugin"]).optional(),pluginName:b.z.string().optional()}).meta({title:"CustomInstruction"}),uie=b.z.enum(["auto","none","minimal","low","medium","high","xhigh","max"]).meta({title:"ReasoningEffort"}),aYe=b.z.object({name:b.z.string(),description:b.z.string().optional()}).meta({title:"CustomAgentInfo"}),AYe=b.z.record(b.z.string(),b.z.union([b.z.string(),b.z.array(b.z.string())])).meta({title:"AgentModelOverrides"}),cYe=b.z.enum(["react","html","mitosis","react-native","angular","vue","svelte","qwik","solid","marko","swiftui","jetpack-compose","flutter"]).meta({title:"CodeGenFramework"}),uYe=b.z.enum(["tailwind","tailwind-precise","emotion","styled-components","styled-jsx","react-native"]).meta({title:"CodeGenStyleLibrary"}),I4t=b.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.",lYe=b.z.object({file_path:b.z.string().meta({description:t0}),offset:b.z.number().nullish().meta({description:"The line number to start reading from."}),limit:b.z.number().nullish().meta({description:"The number of lines to read."})}).meta({title:"ReadToolInput"}),gYe=b.z.object({pattern:b.z.string().meta({description:"The pattern to search for"})}).meta({title:"GlobSearchToolInput"}),pYe=b.z.object({query:b.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:b.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:b.z.string().nullish().meta({description:"Optional glob pattern to exclude specific files or directories"}),case_sensitive:b.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"}),dYe=b.z.object({skill:b.z.string().meta({description:"The name of a skill from the available-skills list. Do not guess names."}),args:b.z.string().nullish().meta({description:"Optional invocation arguments; forwarded with the skill body in the tool result."})}).meta({title:"SkillToolInput"}),fYe=b.z.object({name:b.z.string().meta({description:"The name of the rule to get"})}).meta({title:"GetRuleToolInput"}),hYe=b.z.object({url:b.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"}),E4t=b.z.object({}).meta({title:"GetBuildOutputToolInput"}),mYe=b.z.object({restart:b.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:b.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:b.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:b.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:b.z.tuple([b.z.string(),b.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:b.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"}),CYe=b.z.object({}).meta({title:"DevServerLogsInput"}),IYe=b.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."}),EYe=b.z.object({}).meta({title:"DevServerRestartInput",description:"Restarts the dev server with current configuration."}),BYe=b.z.object({description:b.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:b.z.string().meta({description:"The shell command to run, for example 'npm install --save uuid', 'yarn test' or 'npm run build'..."}),timeout:b.z.number().nullish().meta({description:"Optional timeout in milliseconds (max/default 600000)"})}).meta({title:"BashToolInput"}),yYe=b.z.object({command:b.z.string().nullish().meta({description:"The PowerShell command to run, for example 'npm install' or 'yarn test'"}),timeout:b.z.number().nullish().meta({description:"The timeout in milliseconds for the command to run. Choose an appropriate timeout based on the command"}),description:b.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"}),QYe=b.z.object({query:b.z.string().meta({description:"The question to search on the internet, be specific and concise."})}).meta({title:"WebSearchToolInput"}),DYe=b.z.object({title:b.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:b.z.string().meta({description:t0}),content:b.z.string().meta({description:"Actual content to write into the file, use an empty string to remove the file"})}).meta({title:"WriteFileInput"}),wYe=b.z.object({title:b.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:b.z.string().meta({description:`${t0} The content of this path must be previously known.`}),old_str:b.z.string().meta({description:"The text to replace"}),new_str:b.z.string().meta({description:"The text to replace it with (must be different from old_str)"}),replace_all:b.z.boolean().optional().meta({description:"Replace all occurences of old_str (default false)"}),apply_with_error:b.z.boolean().optional()}).meta({title:"SearchReplaceInput"}),bYe=b.z.object({title:b.z.string().meta({description:"Human readable description of the change or generated code, it's mandatory"}),file_path:b.z.string().meta({description:`${t0} The content of this path must be previously known.`}),edits:b.z.array(b.z.object({old_str:b.z.string().meta({description:"The text to replace (must match the file contents exactly, including all whitespace and indentation)"}),new_str:b.z.string().meta({description:"The edited text to replace the old_str"}),replace_all:b.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:b.z.boolean().nullish()}).meta({title:"MultiSearchReplaceInput"}),vYe=b.z.object({query:b.z.string(),type:b.z.enum(["image","video"]),orientation:b.z.enum(["landscape","portrait","square"]).nullish(),hex_color:b.z.string().nullish()}).meta({title:"FindMediaToolInput"}),SYe=b.z.object({query:b.z.string().meta({description:"The text prompt describing the media to find or generate"}),type:b.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:b.z.enum(["landscape","portrait","square"]).nullish().meta({description:"The orientation/aspect ratio of the media (landscape=wide, portrait=tall, square=1:1)"}),hex_color:b.z.string().nullish().meta({description:"Optionally use to find images with the predominant specified hex color, for example '#000000' or '#FFFFFF'"}),input_image_urls:b.z.array(b.z.string()).nullish().meta({description:'Reference image URLs for AI image generation (only used with type: "gen-image")'})}).meta({title:"MediaToolInput"}),xYe=b.z.object({content:b.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:b.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:b.z.union([b.z.literal("architecture").meta({description:"System structure, layers, and responsibilities"}),b.z.literal("data-and-sync").meta({description:"Data storage, persistence, synchronization, IPC, and state flow"}),b.z.literal("patterns-and-standards").meta({description:"Canonical ways of doing things in this codebase"}),b.z.literal("coupling-and-duplication").meta({description:"Cross-file, cross-surface, or duplicated logic that must stay aligned"}),b.z.literal("ui-and-ux-contracts").meta({description:"User-visible behavior, UX guarantees, and UI rules"}),b.z.literal("concurrency-and-lifecycle").meta({description:"Async behavior, ordering, lifecycle, and race prevention"}),b.z.literal("invariants").meta({description:"Hard rules that must always remain true"}),b.z.literal("security-and-trust").meta({description:"Security, permissions, and trust boundaries"}),b.z.literal("gotchas").meta({description:"Known sharp edges that will break things if ignored"}),b.z.literal("constraints-and-limits").meta({description:"System limits, assumptions, and non-obvious constraints"}),b.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:b.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:b.z.number().optional(),glob_auto_include:b.z.boolean().optional().meta({description:"Whenever the memory should be included whenever the glob is matched."})}).meta({title:"MemoryToolInput"}),FYe=b.z.object({query:b.z.string(),limit:b.z.number().optional(),minSimilarity:b.z.number().optional()}).meta({title:"SearchMemoriesToolInput"}),kYe=b.z.object({outcome:b.z.enum(["worked","failed","partial","unknown"]).meta({description:"Overall exchange outcome based on user reaction"}),memory_scores:b.z.object({}).catchall(b.z.enum(["worked","failed","partial","unknown"])).meta({description:"Score for each memory used: { memory_id: outcome }"})}).meta({title:"ScoreMemoriesToolInput"}),vL=b.z.object({label:b.z.string(),description:b.z.string()}).meta({title:"LabelOption"}),RYe=b.z.strictObject({label:b.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:b.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:b.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"}),TYe=b.z.strictObject({question:b.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:b.z.string().meta({description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:b.z.array(RYe).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:b.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"}),NYe=b.z.strictObject({questions:b.z.array(TYe).min(1,"Must have at least 1 question").max(4).meta({description:"Questions to ask the user (1-4 questions)"})}).meta({title:"AskUserQuestionToolInput"}),MYe=b.z.object({description:b.z.string().meta({description:"A short (3-5 word) description of the task"}),prompt:b.z.string().meta({description:"The task for the agent to perform"}),subagent_type:b.z.string().optional().meta({description:"The type of specialized agent to use for this task"}),resume:b.z.string().optional().meta({description:"Optional agent ID to resume from"}),origin_channel_id:b.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:b.z.array(b.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"}),PYe=b.z.object({checkpoint_id:b.z.string().meta({description:"The checkpoint ID to revert back to. All changes from this checkpoint to HEAD will be reverted."})}).meta({title:"RevertToolInput"}),LYe=b.z.object({}).meta({title:"TodoReadToolInput"}),_Ye=b.z.object({}).meta({title:"RunningAgentsToolInput"}),UYe=b.z.object({mode:b.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:b.z.array(b.z.object({content:b.z.string().meta({description:"The imperative form describing what needs to be done"}),status:b.z.enum(["pending","in_progress","completed"]),id:b.z.string()}))}).meta({title:"TodoWriteToolInput"}),GYe=b.z.object({subject:b.z.string().meta({description:"A brief title for the task"}),description:b.z.string().meta({description:"What needs to be done"}),metadata:b.z.looseObject({}).optional()}).meta({title:"TaskCreateToolInput"}),OYe=b.z.object({taskId:b.z.string().meta({description:"The ID of the task to update"}),subject:b.z.string().optional().meta({description:"New subject for the task"}),description:b.z.string().optional().meta({description:"New description for the task"}),status:b.z.enum(["pending","in_progress","completed","deleted"]).optional().meta({description:"New status for the task"}),owner:b.z.string().optional().meta({description:"New owner for the task"}),addBlocks:b.z.array(b.z.string()).optional().meta({description:"Task IDs that this task blocks"}),addBlockedBy:b.z.array(b.z.string()).optional().meta({description:"Task IDs that block this task"}),metadata:b.z.looseObject({}).optional()}).meta({title:"TaskUpdateToolInput"}),KYe=b.z.object({}).meta({title:"TaskListToolInput"}),HYe=b.z.object({filePath:b.z.string().meta({description:"The path of the Mitosis file to edit (e.g., index.lite.tsx)"}),old_str:b.z.string().meta({description:"Content to be replaced, this substring should appear verbatim in the selected file_path"}),new_str:b.z.string().meta({description:"New content to replace the old content with"})}).meta({title:"BuilderEditToolInput"}),JYe=b.z.object({href:b.z.string().optional(),selector:b.z.string().optional(),width:b.z.number().optional(),height:b.z.number().optional()}).meta({title:"GetScreenshotToolInput"}),jYe=b.z.object({href:b.z.string().meta({description:"The URL or relative path to navigate the preview to (e.g., '/about' or 'https://example.com')"})}).meta({title:"NavigatePreviewToolInput"}),YYe=b.z.object({url:b.z.string().meta({description:"The URL to fetch content from"}),prompt:b.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:b.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"}),qYe=b.z.object({category:b.z.enum(["reusable_knowledge","one_off","bad_quality"]).optional(),gif_id:b.z.string().optional(),timeline_id:b.z.string().optional(),recording_id:b.z.string().optional(),important_files:b.z.array(b.z.object({file_path:b.z.string().meta({description:"The relative path of the file to read"}),relevance:b.z.enum(["high","medium","low"]).optional().meta({description:"The relevance of the file based on the initial user_prompt"}),offset:b.z.number().optional().meta({description:"The offset of the file to read, in lines"}),limit:b.z.number().optional().meta({description:"The limit of the file to read, in lines"})}))}).meta({title:"ExplorationMetadataToolInput"}),$Ye=b.z.object({}).meta({title:"EnterPlanModeToolInput"}),VYe=b.z.object({plan:b.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:b.z.boolean().optional()}).meta({title:"ExitPlanModeToolInput"}),WYe=b.z.object({uri:b.z.string().meta({description:"The URI of the resource to read, matching a resource template pattern (e.g., 'file:///path/to/file')"}),serverName:b.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"}),zYe=b.z.enum(["navigation","interaction","assertion","error","milestone","code-change","observation","verified"]).meta({title:"TimelineEventCategory"}),XYe=b.z.enum(["succeeded","couldnt_verify","failed","other"]).meta({title:"TestOutcome"}),ZYe=b.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"}),e9e=b.z.object({title:b.z.string().meta({description:"A descriptive title for this frame (e.g., 'Login page loaded', 'Form submitted successfully')"}),frame:b.z.literal("last-image").meta({description:"The frame source. Use 'last-image' to record the most recent screenshot."}),category:zYe.optional().meta({description:"Category of this frame for timeline organization. Default: 'milestone'"}),description:b.z.string().optional().meta({description:"Optional longer description providing context about what this frame shows."}),pr_highlight:b.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"}),t9e=b.z.object({outcome:XYe.meta({description:"The structured test outcome"}),summary:b.z.string().meta({description:"A concise 1\u20132 sentence summary explaining the test outcome"}),details:b.z.string().optional().meta({description:"Optional additional context: error messages, steps attempted, etc."}),test_case_id:b.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:b.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:b.z.string().optional().meta({description:"Human-readable failure explanation. E.g., 'Login page returned 403 \u2014 test account may have been disabled'"}),console_errors:b.z.string().optional(),network_failures:b.z.string().optional(),steps_attempted:b.z.string().optional(),urls_tested:b.z.array(b.z.string()).optional()}).meta({title:"ReportTestOutcomeToolInput"}),r9e=b.z.object({projectOverview:b.z.object({framework:b.z.string().nullable(),packageManager:b.z.enum(["npm","yarn","pnpm","bun"]).nullable(),isMonorepo:b.z.boolean(),detectedLanguage:b.z.enum(["typescript","javascript"]).nullable()}),rootDirectory:b.z.object({path:b.z.string(),reason:b.z.string()}).nullable(),installCommand:b.z.object({command:b.z.string(),reason:b.z.string()}).nullable(),runtimeDependencies:b.z.array(b.z.object({tool:b.z.string(),version:b.z.string(),source:b.z.string()})),devServer:b.z.object({command:b.z.string(),url:b.z.string(),port:b.z.number(),reason:b.z.string()}).nullable(),environmentVariables:b.z.array(b.z.object({key:b.z.string(),description:b.z.string(),isRequired:b.z.boolean(),isSecret:b.z.boolean(),defaultValue:b.z.string().nullable(),source:b.z.string()})),validationScript:b.z.object({command:b.z.string(),reason:b.z.string()}).nullable(),npmrcContents:b.z.string().nullable(),hasHotModuleReload:b.z.object({value:b.z.boolean(),reason:b.z.string()}).nullable()}).meta({title:"SetupAnalysisValues"}),n9e=b.z.object({config:r9e,message:b.z.string().optional()}).meta({title:"ProposeConfigToolInput"}),i9e=b.z.enum(["installCommand","devServer","validationScript","environmentVariables"]).meta({title:"SetupValueField"}),s9e=b.z.object({field:i9e.meta({description:"Which field to update"}),value:b.z.object({command:b.z.string().optional().meta({description:"The command to run (for installCommand, devServer, validationScript)"}),url:b.z.string().optional().meta({description:"Dev server URL (only for devServer)"}),port:b.z.number().optional().meta({description:"Dev server port (only for devServer)"}),environmentVariables:b.z.array(b.z.object({key:b.z.string().meta({description:"Variable name"}),description:b.z.string().optional().meta({description:"What this variable is for"}),isRequired:b.z.boolean().optional().meta({description:"Whether this variable is required"}),isSecret:b.z.boolean().optional().meta({description:"Whether this is a secret/credential"}),defaultValue:b.z.string().nullish()})).optional()}),reason:b.z.string()}).meta({title:"UpdateSetupValueToolInput"}),e0=b.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))"}),o9e=b.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:b.z.string().meta({description:"Brief summary of configuration outcome (what succeeded or what's needed)"}),questions:b.z.array(b.z.object({question:b.z.string().meta({description:"Full question text"}),context:b.z.string().meta({description:"Why this information is needed"}),header:b.z.string().optional().meta({description:'Short label (e.g., "API Key", "Database URL")'}),type:b.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:b.z.string().optional().meta({description:"Placeholder/hint text for 'text' type questions (e.g., 'Enter your API key', 'https://localhost:3000')"}),options:b.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:b.z.boolean().optional().meta({description:"Repository contains multiple packages/apps"}),isMicrofrontend:b.z.boolean().optional().meta({description:"Frontend code served over multiple ports/servers"}),setupNeedsCredentials:b.z.boolean().optional().meta({description:"Setup requires credentials (e.g., NPM_TOKEN for private packages)"}),devServerNeedsCredentials:b.z.boolean().optional().meta({description:"Dev server needs special environment variables to run"}),needsVPN:b.z.boolean().optional().meta({description:"Setup requires a VPN connection"}),autoReload:b.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:b.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:b.z.array(b.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:b.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"}),a9e=["running","stopped","starting","failed","unset"],A9e=["not-installed","installing","installed","install-failed","install-aborted"],c9e=["ok-2xx","error-4xx","error-5xx","error-fetch","stopped","connecting"],u9e=["unset","running","stopped","success","failure"],l9e=b.z.object({question:b.z.string(),context:b.z.string(),whatYouTried:b.z.string().optional(),header:b.z.string().optional().meta({description:"Short label (e.g., 'API Key', 'Database URL')"}),type:b.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:b.z.string().optional().meta({description:"Placeholder text for text-type questions"}),options:b.z.array(vL).optional()}),lie=b.z.object({setupCommand:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on setupState === 'installed'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),setupDependencies:b.z.object({value:b.z.array(Aie).optional(),verified:b.z.boolean().meta({description:"Based on setupState === 'installed'"})}),devCommand:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on devState === 'running'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),devServer:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds waiting for the server to respond"})}),validateCommand:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on validateState === 'success'"}),elapsed:b.z.number().optional().meta({description:"Time taken in milliseconds (if verified)"})}),appOrigin:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Based on httpServerState === 'ok-2xx'"})}),defaultOrigin:b.z.object({value:b.z.string().optional(),verified:b.z.boolean().meta({description:"Always true if set (used with wildcard appOrigin)"})}),environmentVariables:b.z.object({value:b.z.array(Bf).optional(),verified:b.z.boolean().meta({description:"Based on devState === 'running'"})}),autoDetectDevServer:b.z.object({value:b.z.boolean().optional(),verified:b.z.boolean().meta({description:"Always true if set"})}),autoDetectDevServerPatterns:b.z.object({value:b.z.array(b.z.string()).optional(),verified:b.z.boolean().meta({description:"Always true if set"})}),hasHotModuleReload:b.z.object({value:b.z.boolean().optional(),reason:b.z.string().optional().meta({description:"Detection-only, not auto-applied"})})}),gie=b.z.object({setupState:b.z.enum(A9e),devState:b.z.enum(a9e),httpServerState:b.z.enum(c9e),validateState:b.z.enum(u9e)}),B4t=b.z.object({id:b.z.string().meta({description:"Auto-generated document ID"}),projectId:b.z.string(),branchName:b.z.string(),createdAt:b.z.number(),updatedAt:b.z.number(),ownerId:b.z.string(),state:e0.meta({description:"Configuration state from Exit tool"}),running:b.z.boolean().default(!1),previousStates:b.z.array(e0).optional(),summary:b.z.string().meta({description:"Summary from Exit tool"}),questions:b.z.array(l9e).optional(),configuration:lie,sessionId:b.z.string(),orchestratorStates:gie,peakDiskUsage:b.z.number().optional().meta({description:"Peak disk usage in bytes"}),peakMemoryUsage:b.z.number().optional().meta({description:"Peak memory usage in bytes"}),screenshotUrl:b.z.string().optional().meta({description:"Screenshot URL from verification (e.g., error page screenshot)"}),isMonorepo:b.z.boolean().optional(),isMicrofrontend:b.z.boolean().optional(),setupNeedsCredentials:b.z.boolean().optional(),devServerNeedsCredentials:b.z.boolean().optional(),projectDescription:b.z.string().optional(),cost:b.z.number().optional(),durationMs:b.z.number().optional(),needsVPN:b.z.boolean().optional(),autoReload:b.z.boolean().optional(),usesBuilderCms:b.z.boolean().optional(),stack:b.z.array(b.z.string()).optional()}).meta({title:"ProposedConfig",description:"Configuration proposed by the configuration agent, stored in Firebase"}),y4t=b.z.object({projectId:b.z.string(),branchName:b.z.string(),state:e0,summary:b.z.string(),questions:b.z.array(b.z.object({question:b.z.string(),context:b.z.string(),whatYouTried:b.z.string().optional(),header:b.z.string().optional(),options:b.z.array(vL).optional(),multiSelect:b.z.boolean().optional()})).optional(),configuration:lie,sessionId:b.z.string(),orchestratorStates:gie,peakDiskUsage:b.z.number().optional(),peakMemoryUsage:b.z.number().optional(),screenshotUrl:b.z.string().optional(),isMonorepo:b.z.boolean().optional(),isMicrofrontend:b.z.boolean().optional(),setupNeedsCredentials:b.z.boolean().optional(),devServerNeedsCredentials:b.z.boolean().optional(),needsVPN:b.z.boolean().optional(),projectDescription:b.z.string().optional(),autoReload:b.z.boolean().optional(),usesBuilderCms:b.z.boolean().optional(),stack:b.z.array(b.z.string()).optional()}).meta({title:"ProposeConfigParams"}),g9e=b.z.object({command:b.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:b.z.array(b.z.object({tool:b.z.string().meta({description:"The tool/binary to verify (e.g., 'node', 'npm', 'git')"}),version:b.z.string().optional().meta({description:"Optional version requirement (e.g., '>=18.0.0', '20.x')"})})).optional()}).meta({title:"VerifySetupCommandToolInput"}),p9e=b.z.object({command:b.z.string().meta({description:"The dev server command to run (e.g., 'npm run dev', 'cd packages/frontend && yarn dev')"})}).meta({title:"VerifyDevCommandToolInput"}),d9e=b.z.object({autoDetect:b.z.boolean().meta({description:"Whether to automatically detect the dev server URL from terminal output"}),autoDetectPattern:b.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:b.z.string().optional().meta({description:"The hardcoded dev server URL to use when autoDetect is false (e.g., 'http://localhost:3000')"}),appOrigin:b.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:b.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"}),f9e=b.z.object({command:b.z.string(),timeout:b.z.number().optional().meta({description:"Default: 300000 (5 minutes)"})}).meta({title:"VerifyValidateCommandToolInput"}),h9e=b.z.object({key:b.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:b.z.string().meta({description:"The environment variable value. Must be a concrete value, not a placeholder."}),secret:b.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"})}).meta({title:"ProposeEnvVariableToolInput"}),m9e=b.z.object({key:b.z.string().meta({description:"The environment variable name (e.g., 'NODE_ENV', 'API_KEY')"}),value:b.z.string().meta({description:"The environment variable value. Use clear placeholder like 'PLACEHOLDER_DATABASE_URL' if actual value is unknown."}),secret:b.z.boolean().optional().meta({description:"Whether this is a secret value (will be masked in logs). Default: false"}),placeholder:b.z.boolean().optional().meta({description:"If true, indicates this is a placeholder value that needs user replacement"}),explanation:b.z.string().optional().meta({description:"Explanation of why this env var is needed and what value the user should provide"})}).meta({title:"SetEnvVariableToolInput"}),C9e=b.z.object({path:b.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:b.z.string().optional().meta({description:"Plain text content to write to the file. Mutually exclusive with `base64`."}),base64:b.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"}),I9e=b.z.object({channel_id:b.z.string().meta({description:"The channel identifier in URI format (see supported formats in the tool description)"}),markdown:b.z.string().meta({description:"The message content to send in markdown format"}),status:b.z.enum(["starting","question","will-follow-up","done:success","done:error"]),loading_message:b.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:b.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:b.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"}),E9e=b.z.object({project_id:b.z.string().meta({description:"The project ID to create the branch in"}),message:b.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:b.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:b.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:b.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:b.z.enum(["normal","planning","deep-research"]).optional(),model:b.z.enum(["auto","opus","sonnet","haiku"]).optional(),attachment_urls:b.z.array(b.z.string()).optional(),git_base_branch:b.z.string().optional(),auto_archive_on_idle:b.z.boolean().optional()}).meta({title:"SpawnBranchToolInput"}),B9e=b.z.object({repo_url:b.z.string().meta({description:"Repository URL (regular Git URL or template:// URL)"}),name:b.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:b.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:b.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:b.z.string().optional().meta({description:"Only valid for template:// URLs \u2014 creates a branch with this message"})}).meta({title:"CreateProjectToolInput"}),y9e=b.z.object({}).meta({title:"GetAvailableReposToolInput"}),Q9e=b.z.object({project_id:b.z.string().meta({description:"The project ID containing the branch"}),branch_name:b.z.string().meta({description:"The name of the branch to read"})}).meta({title:"ReadBranchToolInput"}),D9e=b.z.object({project_id:b.z.string().meta({description:"The project ID containing the branch"}),branch_name:b.z.string().meta({description:"The name of the branch to archive"}),builder_user_id:b.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:b.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=b.z.enum(["high","medium","low"]).meta({title:"ReviewSeverity"}),w9e=b.z.object({file_path:b.z.string().meta({description:"Relative file path - MUST be a file that appears in the PR diff"}),line:b.z.number().meta({description:"Line number in the file (end line for multi-line). MUST be a line within the PR diff"}),start_line:b.z.number().optional().meta({description:"For multi-line comments (optional)"}),side:b.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:b.z.string().meta({description:"Brief plain-text issue title. MUST NOT start with severity emojis"}),body:b.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:b.z.string().optional(),gif_id:b.z.string().optional().meta({description:"Per-comment GIF (optional)"})}).meta({title:"PRReviewComment"}),b9e=b.z.enum(["looks_good","has_findings","blocking"]).meta({title:"ReviewVerdict"}),v9e=b.z.object({summary:b.z.string().meta({description:"Your detailed analysis of the changes (displayed in a collapsible 'Review Details' section)"}),comments:b.z.array(w9e).optional(),risk_level:SL.optional(),verdict:b9e.optional()}).meta({title:"SubmitPRReviewToolInput"}),S9e=b.z.object({thread_node_ids:b.z.array(b.z.string()).meta({description:"GraphQL thread node_ids (PRRT_...) from previous review response"})}).meta({title:"ResolveQACommentsToolInput"}),x9e=b.z.object({title:b.z.string().meta({description:"Brief summary of the issue (e.g., 'Button click has no effect')"}),description:b.z.string().meta({description:"Detailed description of what went wrong, what was expected, and what actually happened"}),debugInfo:b.z.string().optional().meta({description:"Optional console errors, stack traces, or other diagnostic information"})}).meta({title:"ReportUIIssueToolInput"}),F9e=b.z.object({file_path:b.z.string().meta({description:"File path where the issue occurs (e.g., 'packages/api/src/auth.ts')"}),line:b.z.number().meta({description:"End line number of the issue range (or single line if no start_line)"}),start_line:b.z.number().optional().meta({description:"Optional start line for multi-line issues. When provided, the comment spans from start_line to line"}),title:b.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:b.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"}),k9e=b.z.object({issue:b.z.string().meta({description:"What's blocking execution"}),steps_attempted:b.z.string().meta({description:"What was tried before escalating"}),current_url:b.z.string().meta({description:"Current browser URL"}),test_case_id:b.z.string().meta({description:"Which test case is blocked"})}).meta({title:"EscalateToPlanner"}),R9e=b.z.object({}).meta({title:"GetLastBrowserTestToolInput"}),T9e=b.z.object({file_path:b.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"}),N9e=b.z.object({event_id:b.z.string().meta({description:"The codegen event ID to load (e.g. cgen-<eventId>)."})}).meta({title:"GetCodegenEventToolInput"}),M9e=b.z.object({session_or_event_id:b.z.string().meta({description:"A session ID or codegen event ID. When an event ID is given, its session is resolved first."}),limit:b.z.number().optional().meta({description:"Maximum number of events to return."})}).meta({title:"ListCodegenSessionEventsToolInput"}),P9e=b.z.object({url:b.z.string().meta({description:"The prototype URL (e.g., https://builder.io/app/projects/<projectId>/<branchName>)"}),project_id:b.z.string().optional().meta({description:"The project ID (optional, parsed from URL if not provided)"}),branch_name:b.z.string().optional().meta({description:"The branch name (optional, parsed from URL if not provided)"})}).meta({title:"PullPrototypeToolInput"}),L9e=b.z.object({project_id:b.z.string().meta({description:"The Builder.io project ID containing the branch"}),branch_name:b.z.string().meta({description:"The Fusion branch name to push and open a PR for"}),builder_user_id:b.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:b.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"}),_9e=b.z.object({name:b.z.string().meta({description:'Human-readable name of the service to connect, e.g. "Jira", "Linear", "Sentry"'}),url:b.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"}),U9e=b.z.object({Read:lYe,Write:DYe,Edit:wYe,ReadRule:fYe,Skill:dYe,GetStyleInspiration:hYe,GetScreenshot:JYe,NavigatePreview:jYe,MultiEdit:bYe,FindMedia:vYe,Media:SYe,AddMemory:xYe,SearchMemories:FYe,ScoreMemories:kYe,Bash:BYe,PowerShell:yYe,WebSearch:QYe,AskUserQuestion:NYe,Agent:MYe,Grep:pYe,Glob:gYe,DevServerControl:mYe,DevServerLogs:CYe,DevServerRestart:EYe,Revert:PYe,TodoRead:LYe,TodoWrite:UYe,TaskCreate:GYe,TaskUpdate:OYe,TaskList:KYe,BuilderEdit:HYe,WebFetch:YYe,ExplorationMetadata:qYe,EnterPlanMode:$Ye,ExitPlanMode:VYe,ReadMcpResource:WYe,RecordFrame:e9e,SubmitPRReview:v9e,ProposeConfig:n9e,UpdateSetupValue:s9e,Exit:o9e,ResolveQAComments:S9e,GetLastBrowserTest:R9e,ReportUIIssue:x9e,ReportIssue:F9e,ReportTestOutcome:t9e,VerifySetupCommand:g9e,VerifyDevCommand:p9e,VerifyDevServer:d9e,VerifyValidateCommand:f9e,ProposeEnvVariable:h9e,SetEnvVariable:m9e,SetFileOverride:C9e,SendMessage:I9e,SpawnBranch:E9e,CreateProject:B9e,GetAvailableRepos:y9e,ReadBranch:Q9e,ArchiveBranch:D9e,RunningAgents:_Ye,IDEDiagnostics:T9e,EscalateToPlanner:k9e,PullPrototype:P9e,ConnectMCP:_9e,EnsurePR:L9e,GenerateDesignSystemAgentMd:IYe,GetCodegenEvent:N9e,ListCodegenSessionEvents:M9e}),G9e=U9e.keyof().meta({title:"CodeGenTools"}),pie=b.z.enum(["planning","normal","auto-planning","deep-research"]).meta({title:"SessionMode"}),O9e=b.z.enum(["quality","quality-v4","quality-v4-agent"]).meta({title:"CodeGenMode"}),K9e={schedule:"next-turn",coalesce:"merge"};H9e=["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=b.z.enum(H9e).meta({title:"BaseCodeGenPosition"}),J9e=b.z.union([cie,b.z.templateLiteral([cie,"-agent"])]).meta({title:"CodeGenPosition"}),j9e=b.z.object({designSystems:b.z.array(b.z.string())}).meta({title:"RepoIndexingConfig"}),Y9e=b.z.object({name:b.z.string(),description:b.z.string().optional(),inputSchema:b.z.any().optional(),serverName:b.z.string(),deferLoading:b.z.boolean().optional()}).meta({title:"LocalMCPTools"}),fie=b.z.union([b.z.templateLiteral(["repair-",b.z.string()]),b.z.literal("user-normal"),b.z.literal("user-figma"),b.z.literal("user-pdf"),b.z.literal("user-image"),b.z.literal("setup-agent"),b.z.templateLiteral(["background-",b.z.string()]),b.z.templateLiteral(["indexing-",b.z.string()])]).meta({title:"CodeGenCategory"}),q9e=b.z.enum(["editCode","modifyMcpServers","modifyProjectSettings","createBranches","sendPullRequests","view"]).meta({title:"UserSourcePermission"}),r0={role:b.z.enum(["user","agent"]),principals:b.z.array(b.z.string()).optional().meta({description:"teams/roles like ['developer', 'admin']"}),jobs:b.z.array(b.z.string()).optional().meta({description:"job titles like ['designer', 'developer'] - used for role-aware communication instead of principals when available"}),permissions:b.z.array(q9e).optional(),channelId:b.z.string().optional()},Q4t=b.z.object(r0).meta({title:"UserSourceBase"}),$9e=b.z.object({...r0,source:b.z.enum(["slack","telegram","whatsapp","teams","jira","linear","github","gitlab","azure","bitbucket"]),userId:b.z.string().optional().meta({description:"User ID from the external platform (Slack user ID, GitHub user id, etc.)"}),userName:b.z.string().optional(),userEmail:b.z.string().optional(),photoURL:b.z.string().optional(),builderUserId:b.z.string().optional().meta({description:"Resolved Builder user ID for attribution/credits"}),link:b.z.string().optional().meta({description:"Optional link (e.g. comment/PR URL) for git provider sources"})}).meta({title:"UserSourceOther"}),V9e=b.z.object({...r0,source:b.z.literal("builder.io"),userId:b.z.string().optional(),userName:b.z.string().optional(),userEmail:b.z.string().optional(),photoURL:b.z.string().optional()}).meta({title:"UserSourceBuilder"}),W9e=b.z.object({...r0,source:b.z.literal("agent"),userId:b.z.string().optional(),userName:b.z.string().optional(),userEmail:b.z.string().optional()}).meta({title:"UserSourceAgent"}),hie=b.z.discriminatedUnion("source",[$9e,V9e,W9e]).meta({title:"UserSource"}),z9e=b.z.enum(["read","write","list"]).meta({title:"Permission"}),X9e=b.z.object({action:b.z.enum(["allow","deny"]).meta({description:"whether this rule allows or denies access"}),resource:b.z.string().meta({description:"what \u2014 supports glob patterns like /files/*.txt"}),permissions:b.z.array(z9e).meta({description:"actions this rule applies to"}),description:b.z.string().optional().meta({description:"custom message, in deny case, this is the error message. This will override denyDescription on AclPolicy if defined."}),principals:b.z.array(b.z.string()).optional().meta({description:"array of teams/roles this rule applies to (e.g., ['developer', 'admin'])"})}).meta({title:"AclEntry"}),Z9e=b.z.object({secrets:b.z.array(b.z.string()).optional(),entries:b.z.array(X9e).optional(),denyDescription:b.z.string().optional().meta({description:"Default message to use when a resource is denied access"})}).meta({title:"AclPolicy"}),mie=b.z.object({text:b.z.string(),tag:b.z.string().optional(),ephemeral:b.z.boolean().optional()}).meta({title:"SystemReminderObj"}),e6e=b.z.union([b.z.string(),mie]).meta({title:"SystemReminder"}),D4t=b.z.looseObject({position:J9e,eventName:b.z.string().optional(),sessionId:b.z.string(),codeGenMode:O9e.optional(),sessionMode:pie.optional(),url:b.z.string().optional(),diffActions:b.z.boolean().optional(),planningPrompt:b.z.boolean().optional(),customInstructions:b.z.array(oYe).optional(),customAgents:b.z.array(aYe).optional(),systemPromptOverride:b.z.union([b.z.string(),b.z.array(b.z.string())]).optional(),userPrompt:b.z.string().optional(),systemReminders:b.z.array(e6e).optional(),ephemeralUserPrompt:b.z.string().optional(),uiContextPrompt:b.z.string().optional(),displayUserPrompt:b.z.string().optional(),files:b.z.array(sYe).optional(),rerankFiles:b.z.number().optional(),toolResults:b.z.array(sie).optional(),attachments:b.z.array(DL).optional(),beforeCommit:iYe.optional(),workingDirectory:b.z.string().optional(),includeRelevantMemories:b.z.boolean().optional(),encryptKey:b.z.string().optional(),modelOverride:b.z.string().optional(),errorIfHadCompaction:b.z.boolean().optional(),softContextWindow:b.z.number().optional(),promptVersion:b.z.enum(["v1","v2","v3"]).optional(),reasoning:uie.optional(),redactUserMessages:b.z.boolean().optional(),redactLLMMessages:b.z.boolean().optional(),environmentVariables:b.z.array(Bf).optional(),skipCommandSecurity:b.z.boolean().optional(),builderContent:b.z.custom().optional(),framework:cYe.optional(),styleLibrary:uYe.optional(),typescript:b.z.boolean().optional(),userContext:aie.optional(),aclPolicy:Z9e.optional(),repoIndexingConfig:j9e.optional(),recommendedRoot:b.z.string().optional(),enabledTools:b.z.array(G9e).optional(),enabledMCPs:b.z.array(b.z.string()).optional(),skippedMCPs:b.z.array(b.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:b.z.boolean().optional(),interruptActiveTask:b.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:b.z.array(Y9e).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:b.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:b.z.number().optional(),maxAgentTiming:b.z.number().optional(),maxTokens:b.z.number().optional().meta({description:"Maximum output tokens allowed in the LLM response. This will set the maximum token output for the LLM."}),maxPages:b.z.number().optional(),autoContinue:b.z.number().optional(),isManualContinue:b.z.boolean().optional(),llmSuggestions:b.z.boolean().optional(),conclusionText:b.z.boolean().optional(),mcpServers:b.z.boolean().optional(),pingEvents:b.z.boolean().optional(),forceCompact:b.z.boolean().optional(),hadPagination:b.z.boolean().optional(),category:fie.optional(),metadata:b.z.record(b.z.string(),b.z.any()).optional(),searchResponse:b.z.any().nullish(),prettierConfig:b.z.custom().optional(),role:b.z.enum(["user","agent"]).optional(),user:hie.optional(),projectId:b.z.string().optional(),branchName:b.z.string().optional(),repoHash:b.z.string().optional(),repoBranch:b.z.string().optional(),parentSessionId:b.z.string().optional().meta({description:"Immediate parent session id when this completion runs inside a sub-agent."}),mainSessionId:b.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:b.z.string().optional(),vcpId:b.z.string().optional(),repair:b.z.boolean().optional(),systemReminderPrompt:b.z.string().optional()}).meta({title:"CodeGenInputOptions"}),t6e=b.z.enum(["force-push","merge-push","ff-push","safe-push","none"]).meta({title:"AutoPushMode"}),r6e=b.z.object({remoteBranches:b.z.enum(["both","main","ai"]).optional(),fastForward:b.z.enum(["never","required","auto"]).optional(),canPush:b.z.boolean().optional(),uncommittedChanges:b.z.enum(["stash","commit","fail"]).optional(),requestRefresh:b.z.boolean().optional(),allowUnrelatedHistory:b.z.boolean().optional(),resetToBase:b.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:b.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"}),w4t=b.z.object({idempotencyKey:b.z.string().optional(),user:hie.optional(),userPrompt:b.z.string(),uiContextPrompt:b.z.string().optional(),ephemeralUserPrompt:b.z.string().optional(),displayPrompt:b.z.string().optional(),files:b.z.array(b.z.string()).optional(),systemReminders:b.z.array(mie).optional(),includeBaseFiles:b.z.boolean().optional(),attachments:b.z.array(DL).optional(),logsCheckpoint:b.z.boolean().optional(),dropAbortedPrompt:b.z.boolean().optional(),runValidateCommand:b.z.boolean().optional(),modelOverride:b.z.string().optional(),agentModelOverrides:AYe.optional(),softContextWindow:b.z.number().optional(),maxCompletions:b.z.number().optional(),isManualContinue:b.z.boolean().optional(),includeRelevantMemories:b.z.boolean().optional(),category:fie.optional(),metadata:b.z.record(b.z.string(),b.z.any()).optional(),autoPush:t6e.optional(),syncChanges:r6e.optional(),enabledMCPs:b.z.array(b.z.string()).optional(),skippedMCPs:b.z.array(b.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:b.z.boolean().optional(),agentType:b.z.string().optional().meta({description:"Custom agent type to use for this message"}),enableQAReviewTool:b.z.boolean().optional().meta({description:"Enable AddQAReview tool for QA PR review branches"}),reasoning:uie.optional().meta({description:"Per-message reasoning effort override"}),repair:b.z.boolean().optional(),forceCompact:b.z.boolean().optional().meta({description:"Force compaction of the conversation before generating the next completion"})}).meta({title:"GenerateUserMessage"}),b4t=b.z.object({diff:b.z.string().meta({description:"Git diff from previous commit"}),userMessages:b.z.array(b.z.string()).meta({description:"User messages sent during AI work"}),recentCommits:b.z.array(b.z.string()).meta({description:"Last 10 commits from main branch for style reference"}),longCommit:b.z.boolean().optional().meta({description:"Whether to generate a long commit message"}),projectId:b.z.string().optional().meta({description:"Project ID for fetching project-specific commit instructions"})}).meta({title:"CommitMessageRequest"}),v4t=b.z.object({message:b.z.string().meta({description:"Full commit message"}),title:b.z.string().meta({description:"First line (50-72 chars) - the commit title"}),body:b.z.string().optional().meta({description:"Optional extended description"})}).meta({title:"CommitMessageResponse"}),S4t=b.z.object({sessionId:b.z.string(),toolId:b.z.string(),approved:b.z.boolean(),reason:b.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,n6e,gI,P4t,L4t,yie,i6e,_4t,s6e,U4t,G4t,O4t,K4t,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",n6e="BuilderIO/dsi-starter",gI=[...kL,yf,n6e],P4t=gI.map(t=>`https://github.com/${t}`),L4t=720*60*60*1e3;yie=Ze.z.enum(["queued","building","uploading","deploying","live","failed","canceled"]),i6e=Ze.z.object({buildCommand:Ze.z.string().optional(),nodeVersion:Ze.z.string().optional()}),_4t=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:i6e.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"})}),s6e=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)'})}),U4t=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"})}),G4t=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)"})}),O4t=s6e.pick({id:!0,status:!0,url:!0,createdAt:!0,completedAt:!0,error:!0}).meta({title:"DeployListItem"}),K4t=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 o6e(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=o6e(t)}catch{return null}let{platform:r,type:n,ids:i}=e;return r==="slack"?a6e(n,i):null}function a6e(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>
|
|
@@ -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 vpt(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 Spt(){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,tBe,r4,_t,Pn,Kr,$c,Bs,xp,Hh,JS,YS,BB,Yh,yB,Ql,Jh,qh,jh,IB,xa,VK,WK,zK,eBe,XK,ZK,EB,e4,t4,Fp,rBe=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)}};tBe=t=>{throw TypeError(t)},r4=(t,e,r)=>e.has(t)||tBe("Cannot "+r),_t=(t,e,r)=>(r4(t,e,"read from private field"),r?r.call(t):e.get(t)),Pn=(t,e,r)=>e.has(t)?tBe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Kr=(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(),Pn(this,xa),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Pn(this,Bs),Pn(this,xp),Pn(this,Hh),Pn(this,JS),Pn(this,YS),Pn(this,BB),Pn(this,Yh),Pn(this,yB,null),Pn(this,Ql),Pn(this,Jh),Pn(this,qh,null),Pn(this,jh,null),Pn(this,IB,null),Pn(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?Kr(this,Hh,new URL(s.url)):Kr(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,Bs)===this.CLOSED)return;Kr(this,Bs,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)}),Pn(this,zK,s=>{Kr(this,Ql,void 0),!(s.name==="AbortError"||s.type==="aborted")&&$c(this,xa,e4).call(this,$K(s))}),Pn(this,XK,s=>{typeof s.id=="string"&&Kr(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)}),Pn(this,ZK,s=>{Kr(this,BB,s)}),Pn(this,t4,()=>{Kr(this,Yh,void 0),_t(this,Bs)===this.CONNECTING&&$c(this,xa,VK).call(this)});try{if(e instanceof URL)Kr(this,xp,e);else if(typeof e=="string")Kr(this,xp,new URL(e,Spt()));else throw new Error("Invalid URL")}catch{throw vpt("An invalid or illegal string was specified")}Kr(this,Jh,HS({onEvent:_t(this,XK),onRetry:_t(this,ZK)})),Kr(this,Bs,this.CONNECTING),Kr(this,BB,3e3),Kr(this,YS,(n=r?.fetch)!=null?n:globalThis.fetch),Kr(this,JS,(i=r?.withCredentials)!=null?i:!1),$c(this,xa,VK).call(this)}get readyState(){return _t(this,Bs)}get url(){return _t(this,xp).href}get withCredentials(){return _t(this,JS)}get onerror(){return _t(this,qh)}set onerror(e){Kr(this,qh,e)}get onmessage(){return _t(this,jh)}set onmessage(e){Kr(this,jh,e)}get onopen(){return _t(this,IB)}set onopen(e){Kr(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,Bs)!==this.CLOSED&&(_t(this,Ql)&&_t(this,Ql).abort(),Kr(this,Bs,this.CLOSED),Kr(this,Ql,void 0))}};Bs=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(){Kr(this,Bs,this.CONNECTING),Kr(this,Ql,new AbortController),_t(this,YS)(_t(this,xp),$c(this,xa,eBe).call(this)).then(_t(this,WK)).catch(_t(this,zK))},WK=new WeakMap,zK=new WeakMap,eBe=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,Bs)!==this.CLOSED&&Kr(this,Bs,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,Bs)===this.CLOSED)return;Kr(this,Bs,this.CONNECTING);let n=new jS("error",{code:e,message:t});(r=_t(this,qh))==null||r.call(this,n),this.dispatchEvent(n),Kr(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,nBe=L(()=>{h();rBe();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 Tn("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 Tn;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 Tn("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 Tn("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 Tn;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,iBe=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 xpt,Dl,WS,sBe=L(()=>{h();n4();ha();bf();iBe();xpt={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??xpt}async _authThenStart(){if(!this._authProvider)throw new Tn("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 Tn;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 Tn("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 Tn("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 Tn;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 Tn;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(),use(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 oBe=N((osr,Fpt)=>{Fpt.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((asr,Vc)=>{h();var aBe=require("fs"),s4=require("path"),kpt=require("os"),Rpt=require("crypto"),Tpt=oBe(),o4=Tpt.version,Npt=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Mpt(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 vpt(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 Spt(){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,tBe,rH,_t,Pn,Kr,$c,Bs,xp,Hh,JS,YS,BB,Yh,yB,Ql,Jh,qh,jh,IB,xa,VK,WK,zK,eBe,XK,ZK,EB,eH,tH,Fp,rBe=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)}};tBe=t=>{throw TypeError(t)},rH=(t,e,r)=>e.has(t)||tBe("Cannot "+r),_t=(t,e,r)=>(rH(t,e,"read from private field"),r?r.call(t):e.get(t)),Pn=(t,e,r)=>e.has(t)?tBe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Kr=(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(),Pn(this,xa),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Pn(this,Bs),Pn(this,xp),Pn(this,Hh),Pn(this,JS),Pn(this,YS),Pn(this,BB),Pn(this,Yh),Pn(this,yB,null),Pn(this,Ql),Pn(this,Jh),Pn(this,qh,null),Pn(this,jh,null),Pn(this,IB,null),Pn(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?Kr(this,Hh,new URL(s.url)):Kr(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,Bs)===this.CLOSED)return;Kr(this,Bs,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)}),Pn(this,zK,s=>{Kr(this,Ql,void 0),!(s.name==="AbortError"||s.type==="aborted")&&$c(this,xa,eH).call(this,$K(s))}),Pn(this,XK,s=>{typeof s.id=="string"&&Kr(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)}),Pn(this,ZK,s=>{Kr(this,BB,s)}),Pn(this,tH,()=>{Kr(this,Yh,void 0),_t(this,Bs)===this.CONNECTING&&$c(this,xa,VK).call(this)});try{if(e instanceof URL)Kr(this,xp,e);else if(typeof e=="string")Kr(this,xp,new URL(e,Spt()));else throw new Error("Invalid URL")}catch{throw vpt("An invalid or illegal string was specified")}Kr(this,Jh,HS({onEvent:_t(this,XK),onRetry:_t(this,ZK)})),Kr(this,Bs,this.CONNECTING),Kr(this,BB,3e3),Kr(this,YS,(n=r?.fetch)!=null?n:globalThis.fetch),Kr(this,JS,(i=r?.withCredentials)!=null?i:!1),$c(this,xa,VK).call(this)}get readyState(){return _t(this,Bs)}get url(){return _t(this,xp).href}get withCredentials(){return _t(this,JS)}get onerror(){return _t(this,qh)}set onerror(e){Kr(this,qh,e)}get onmessage(){return _t(this,jh)}set onmessage(e){Kr(this,jh,e)}get onopen(){return _t(this,IB)}set onopen(e){Kr(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,Bs)!==this.CLOSED&&(_t(this,Ql)&&_t(this,Ql).abort(),Kr(this,Bs,this.CLOSED),Kr(this,Ql,void 0))}};Bs=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(){Kr(this,Bs,this.CONNECTING),Kr(this,Ql,new AbortController),_t(this,YS)(_t(this,xp),$c(this,xa,eBe).call(this)).then(_t(this,WK)).catch(_t(this,zK))},WK=new WeakMap,zK=new WeakMap,eBe=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,Bs)!==this.CLOSED&&Kr(this,Bs,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,Bs)===this.CLOSED)return;Kr(this,Bs,this.CONNECTING);let n=new jS("error",{code:e,message:t});(r=_t(this,qh))==null||r.call(this,n),this.dispatchEvent(n),Kr(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,nBe=L(()=>{h();rBe();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 Tn("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 Tn;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 Tn("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 Tn("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 Tn;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,iBe=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 xpt,Dl,WS,sBe=L(()=>{h();nH();ha();bf();iBe();xpt={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??xpt}async _authThenStart(){if(!this._authProvider)throw new Tn("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 Tn;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 Tn("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 Tn("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 Tn;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 Tn;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(),use(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 oBe=N((osr,Fpt)=>{Fpt.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((asr,Vc)=>{h();var aBe=require("fs"),sH=require("path"),kpt=require("os"),Rpt=require("crypto"),Tpt=oBe(),oH=Tpt.version,Npt=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Mpt(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
|
|
1752
1752
|
`);let n;for(;(n=Npt.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 Ppt(t){let e=cBe(t),r=ei.configDotenv({path:e});if(!r.parsed)throw new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);let n=ABe(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),A=Upt(r,a);s=ei.decrypt(A.ciphertext,A.key);break}catch(a){if(o+1>=i)throw a}return ei.parse(s)}function Lpt(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(qpt(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 x=0;x<=v;x++){x>0&&(It.debug(` Retry ${x}/${v} for ${E.name}...`),await new Promise(w=>setTimeout(w,3e3)));try{let{client:w,transport:P,protocol:G}=await uBe(E,n);It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${x>0?` (attempt ${x+1})`:""}`),s.push({client:w,transport:P,status:{status:"ok",protocol:G,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(w){if(D=w,w instanceof Tn||
|
|
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(w=>setTimeout(w,3e3)));let S,x;try{S=new mB({name:"Builder",version:"1.0.0"}),x=new OS({command:E.command,args:E.args||[],cwd:r,env:{...process.env,...E.env}}),await S.connect(x),It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${D>0?` (attempt ${D+1})`:""}`),s.push({client:S,transport:x,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(w){let P=w instanceof Error?w.message:"Unknown error",G=Math.round(performance.now()-Q);if(S?await
|
|
1753
|
+
`),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}function Ppt(t){let e=cBe(t),r=ei.configDotenv({path:e});if(!r.parsed)throw new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);let n=ABe(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),A=Upt(r,a);s=ei.decrypt(A.ciphertext,A.key);break}catch(a){if(o+1>=i)throw a}return ei.parse(s)}function Lpt(t){console.log(`[dotenv@${oH}][INFO] ${t}`)}function _pt(t){console.log(`[dotenv@${oH}][WARN] ${t}`)}function zS(t){console.log(`[dotenv@${oH}][DEBUG] ${t}`)}function ABe(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 Upt(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 cBe(t){let e=sH.resolve(process.cwd(),".env");return t&&t.path&&t.path.length>0&&(e=t.path),e.endsWith(".vault")?e:`${e}.vault`}function Gpt(t){return t[0]==="~"?sH.join(kpt.homedir(),t.slice(1)):t}function Opt(t){Lpt("Loading env from encrypted .env.vault");let e=ei._parseVault(t),r=process.env;return t&&t.processEnv!=null&&(r=t.processEnv),ei.populate(r,e,t),{parsed:e}}function Kpt(t){let e=sH.resolve(process.cwd(),".env"),r="utf8",n=!!(t&&t.debug);t&&(t.path!=null&&(e=Gpt(t.path)),t.encoding!=null?r=t.encoding:n&&zS("No encoding is specified. UTF-8 is used by default"));try{let i=ei.parse(aBe.readFileSync(e,{encoding:r})),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),ei.populate(s,i,t),{parsed:i}}catch(i){return n&&zS(`Failed to load ${e} ${i.message}`),{error:i}}}function Hpt(t){let e=cBe(t);return ABe(t).length===0?ei.configDotenv(t):aBe.existsSync(e)?ei._configVault(t):(_pt(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),ei.configDotenv(t))}function Jpt(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=Rpt.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 jpt(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 ei={configDotenv:Kpt,_configVault:Opt,_parseVault:Ppt,config:Hpt,decrypt:Jpt,parse:Mpt,populate:jpt};Vc.exports.configDotenv=ei.configDotenv;Vc.exports._configVault=ei._configVault;Vc.exports._parseVault=ei._parseVault;Vc.exports.config=ei.config;Vc.exports.decrypt=ei.decrypt;Vc.exports.parse=ei.parse;Vc.exports.populate=ei.populate;Vc.exports=ei});function qpt(t){return{length:t.length,looksLikeJWT:t.split(".").length===3,hasEnvPlaceholder:/\$\{[^}]+\}/.test(t)}}function AH(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 $pt(t,e,r){let n=Vh.isAbsolute(e)?e:Vh.join(r,e);try{if(!t.existsSync(n))return{};let i=(0,lBe.config)({path:n});if(i.error)throw i.error;return i.parsed||{}}catch(i){return ys.captureException(i,{level:"warning",tags:{operation:"load-mcp-config",envFilePath:n}}),{}}}function Vpt(){return new Set}function Wpt(t){return t.scope?t.scope==="plugin"?"plugin":"local":"builtin"}function zpt(t){switch(t.scope){case"plugin":return 0;case"user":return 1;case"project":return 2;default:return 3}}async function cH(t,e,r){try{await e.close()}catch(n){ys.captureException(n,{level:"warning",tags:{operation:"load-mcp-config"}})}if(r)try{await r.close()}catch(n){ys.captureException(n,{level:"warning",tags:{operation:"load-mcp-config"}})}}async function Xpt(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 uBe(t,e){let r,n;try{r=new mB({name:"Builder",version:"1.0.0"});let i=new URL(t.url),s=await Xpt(t.url),o=t.headers?.Authorization||!s?t.headers:{...t.headers,...s},a=t.connectTimeoutMs??Ypt;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 pBe(t,e,r,n){let i=Vpt(),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:zpt(E),originalIndex:Q})).sort((E,Q)=>E.localPrecedence!==Q.localPrecedence?Q.localPrecedence-E.localPrecedence:E.originalIndex-Q.originalIndex),g=boe(d);for(let E of g.warnings)ys.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:Wpt(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(qpt(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 x=0;x<=v;x++){x>0&&(It.debug(` Retry ${x}/${v} for ${E.name}...`),await new Promise(w=>setTimeout(w,3e3)));try{let{client:w,transport:P,protocol:G}=await uBe(E,n);It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${x>0?` (attempt ${x+1})`:""}`),s.push({client:w,transport:P,status:{status:"ok",protocol:G,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(w){if(D=w,w instanceof Tn||AH(w))break;if(x<v){let G=w instanceof Error?w.message:"Unknown error",J=Math.round(performance.now()-Q);It.debug(` \u2717 Attempt ${x+1} failed after ${J}ms: ${G}`);continue}}}if(!S){let x=D,w=x instanceof Error?x.message:"Unknown error",P=Math.round(performance.now()-Q),G=x instanceof Tn||AH(x);It.error(` \u2717 Connection FAILED after ${P}ms${v>0&&!G?` (${v+1} attempts)`:""}: ${w}`),G&&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:G?"auth_required":"error",message:w,connectionDurationMs:performance.now()-Q,resolutionDurationMs:0,...f(E)},serverName:E.name,normalizedServerName:BA(E.name),serverType:E.type,url:E.url,authRequired:G,oauth:E.oauth,serverDef:G?E:void 0}),ys.captureException(x,{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(w=>setTimeout(w,3e3)));let S,x;try{S=new mB({name:"Builder",version:"1.0.0"}),x=new OS({command:E.command,args:E.args||[],cwd:r,env:{...process.env,...E.env}}),await S.connect(x),It.debug(` \u2713 Connected successfully in ${Math.round(performance.now()-Q)}ms${D>0?` (attempt ${D+1})`:""}`),s.push({client:S,transport:x,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(w){let P=w instanceof Error?w.message:"Unknown error",G=Math.round(performance.now()-Q);if(S?await cH(e,S,x):x&&await x.close(),D<v){It.debug(` \u2717 Attempt ${D+1} failed after ${G}ms: ${P}`);continue}It.error(` \u2717 Connection FAILED after ${G}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}),ys.captureException(w,{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 x=E.client,w=await x.getServerCapabilities();if(E.status.capabilities={tools:!!w?.tools,resources:!!w?.resources,prompts:!!w?.prompts},It.debug(` Capabilities: tools=${!!w?.tools}, resources=${!!w?.resources}`),!w||w.tools){let P=await x.listTools(void 0,{signal:Q});if(P.tools&&P.tools.length>0?It.debug(` \u2713 Found ${P.tools.length} tool(s): ${P.tools.map(G=>G.name).join(", ")}`):It.debug(" No tools found"),P.tools)for(let G of P.tools){let J=G.name;Qoe(J)||It.debug(` \u2717 Tool name is invalid: ${J}`);let _=Doe(E.normalizedServerName,J),K=woe(u,_,{serverName:E.serverName,originalToolName:J});a.set(K,{client:E,tool:{...G,name:K},originalName:J}),A.push({...G,name:K,serverName:E.serverName}),S.push({name:G.name,description:G.description}),D++}}if(w?.resources){let P=await x.listResources(void 0,{signal:Q});if(P.resources&&P.resources.length>0?It.debug(` \u2713 Found ${P.resources.length} resource(s): ${P.resources.map(G=>G.name||G.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 x.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(x){It.error(`Local MCP ${E.serverName} error`,x),E.status.message=x instanceof Error?x.message:"Unknown error",E.status.status="error",ys.captureException(x,{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 voe(E,Q,S=>{ys.captureMessage("Duplicate local MCP auth tool skipped",{level:"warning",extra:{toolName:S.name,candidateName:S.candidate.name,existingName:S.existingName}})}).map(S=>{let x=v.get(S.name);return{name:S.name,description:S.description,inputSchema:S.input_schema,serverName:x?.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:Soe(S),isError:S.isError===!0}}catch(S){throw ys.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,gBe.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),ys.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 nn(i.reason);let g=[];for(let[p,f]of l.entries()){if(i?.aborted)throw nn(i.reason);try{let m={};if(f.envFile){let C=Qa(f.envFile,c);m=await $pt(t,C,e)}if(u(f)){let C=edt(f,p,c,m);g.push(C)}else{let C=Zpt(f,p,c,m);g.push(C)}}catch(m){ys.captureException(m,{level:"warning",tags:{operation:"load-mcp-config",serverName:p,workingDirectory:e}})}}return g}var ys,lBe,Vh,gBe,It,Ypt,fBe=L(()=>{"use strict";h();AEe();XEe();nBe();sBe();bf();ys=z(require("@sentry/node"),1);O0();lBe=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 voe(E,Q,S=>{ys.captureMessage("Duplicate local MCP auth tool skipped",{level:"warning",extra:{toolName:S.name,candidateName:S.candidate.name,existingName:S.existingName}})}).map(S=>{let x=v.get(S.name);return{name:S.name,description:S.description,inputSchema:S.input_schema,serverName:x?.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:Soe(S),isError:S.isError===!0}}catch(S){throw ys.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 cH(e,v.client,v.transport):v.transport&&await v.transport.close(),v.client=void 0,v.transport=void 0;for(let[S,x]of Array.from(a.entries()))x.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:x,protocol:w}=await uBe(v.serverDef,Q);v.client=S,v.transport=x,v.status={status:"ok",protocol:w,connectionDurationMs:performance.now()-D,resolutionDurationMs:0,...f(v.serverDef)},v.authRequired=!1;let P=await m(v,Q);return A.sort((G,J)=>G.name.localeCompare(J.name)),{success:!0,toolsAdded:P}}catch(S){let x=S instanceof Error?S.message:"Unknown error",w=S instanceof Tn||AH(S);return v.status={status:w?"auth_required":"error",message:x,connectionDurationMs:performance.now()-D,resolutionDurationMs:0,...f(v.serverDef)},v.authRequired=w,ys.captureException(S,{level:"warning",tags:{operation:"local-mcp-reconnect",serverName:v.serverName,url:v.url}}),{success:!1,toolsAdded:0,message:x}}},cleanup:async()=>{await Promise.all(s.map(async E=>{E.client?await cH(e,E.client,E.transport):E.transport&&await E.transport.close()}))}}}function Zpt(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 edt(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 dBe(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,gBe.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),ys.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 nn(i.reason);let g=[];for(let[p,f]of l.entries()){if(i?.aborted)throw nn(i.reason);try{let m={};if(f.envFile){let C=Qa(f.envFile,c);m=await $pt(t,C,e)}if(u(f)){let C=edt(f,p,c,m);g.push(C)}else{let C=Zpt(f,p,c,m);g.push(C)}}catch(m){ys.captureException(m,{level:"warning",tags:{operation:"load-mcp-config",serverName:p,workingDirectory:e}})}}return g}var ys,lBe,Vh,gBe,It,Ypt,fBe=L(()=>{"use strict";h();AEe();XEe();nBe();sBe();bf();ys=z(require("@sentry/node"),1);O0();lBe=z(aH(),1);RO();Vh=z(require("node:path"),1),gBe=require("node:os");Ic();Bt();w0();v_();It=ve("MCP",{debug:()=>!!(process.env.DEBUG||process.env.FUSION_DEBUG==="true")}),Ypt=1e4});function tdt(t){return t==="project"?(0,QB.join)(process.cwd(),"mcp.json"):(0,QB.join)((0,hBe.homedir)(),".builder","mcp.json")}function rdt(t){return t==="project"?"project":"user"}function ndt(t){if(!(0,OA.existsSync)(t))return{};let e=(0,OA.readFileSync)(t,"utf8");return e.trim()?JSON.parse(e):{}}function idt(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 sdt(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 mBe(t,e,r){let n=sdt(t),i=tdt(e),s=ndt(i),o=s.mcpServers??{},a=o[n];if(!a)throw new Error(`No MCP server "${n}" in ${rdt(e)} config (${i}).`);return r?a.disabled=!0:delete a.disabled,o[n]=a,s.mcpServers=o,idt(i,s),{scope:e,path:i,name:n,disabled:r}}var OA,hBe,QB,CBe=L(()=>{"use strict";h();OA=require("node:fs"),hBe=require("node:os"),QB=require("node:path");O0()});function odt(t){return t.replace(/^[ab]\//,"")}function adt(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 uH(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 adt(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=odt(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 IBe=L(()=>{"use strict";h()});var wl,EBe=L(()=>{"use strict";h();wl=(...t)=>{typeof process<"u"&&process.env.DEBUG==="true"&&console.debug("[DEBUG] ",...t)}});var Adt,Wh,BBe,cdt,udt,ldt,XS,l4=L(()=>{"use strict";h();EBe();Adt=()=>{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=Adt(),BBe=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)},cdt=async()=>Wh.getRandomValues(new Uint8Array(16)),udt=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)},ldt=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 cdt();wl("validateEncryptionKey: Generated test IV",i);let s=await udt(r,i,n);wl("validateEncryptionKey: Encrypted test data",s);let o=new Uint8Array(s);wl("validateEncryptionKey: Encrypted test data array",o);let a=await ldt(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 yBe(t){return t.length<=g4?t:t.slice(0,g4)+`... [+${t.length-g4} chars]`}var gdt,g4,ZS,QBe=L(()=>{"use strict";h();Rr();Qr();hr();gdt=5e3,g4=8e3,ZS=class{#r;#c;#s;#n=[];#i;#o=!1;#g=Promise.resolve();constructor(e){this.#r=e.credentials,this.#c=e.replayId,this.#s=e.debug??!1;let r=setInterval(()=>{this.#a()},gdt);r.unref?.(),this.#i=r}recordText(e,r=Date.now()){this.#o||this.#e({ts:r,type:"text",content:yBe(e)})}recordReasoning(e,r=Date.now()){this.#o||this.#e({ts:r,type:"thinking",content:yBe(e)})}recordCheckpoint(e=Date.now(),r="",n){this.#o||this.#e({ts:e,type:"checkpoint",label:r,imageUrl:n})}#e(e){e.type!=="checkpoint"&&!e.content||this.#n.push(e)}async#a(){if(this.#n.length===0)return;let e=this.#n;return this.#n=[],this.#g=this.#g.catch(()=>{}).then(()=>this.#B(e)),this.#g}async#B(e){try{let r=new URL(`${Ne}/codegen/replay/${encodeURIComponent(this.#c)}/actions`);this.#r.builderPublicKey&&r.searchParams.set("apiKey",this.#r.builderPublicKey),this.#r.userId&&r.searchParams.set("userId",this.#r.userId);let n={"content-type":"application/json"};this.#r.builderPrivateKey&&(n.authorization=`Bearer ${this.#r.builderPrivateKey}`),await Fe(r,{method:"POST",body:JSON.stringify({actions:e}),headers:n,keepalive:!0},this.#s)}catch{}}async flush(){await this.#a(),await this.#g.catch(()=>{})}async close(){this.#o||(this.#o=!0,this.#i&&clearInterval(this.#i),await this.flush())}}});var p4,DBe,pdt,wBe=L(()=>{h();p4=(t,e,r)=>{let n=t instanceof RegExp?DBe(t,r):t,i=e instanceof RegExp?DBe(e,r):e,s=n!==null&&i!=null&&pdt(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)}},DBe=(t,e)=>{let r=e.match(t);return r?r[0]:null},pdt=(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 wdt(t){return t.replace(Idt,bBe).replace(Edt,vBe).replace(Bdt,f4).replace(ydt,SBe).replace(Qdt,xBe)}function bdt(t){return t.replace(ddt,"\\").replace(fdt,"{").replace(hdt,"}").replace(mdt,",").replace(Cdt,".")}function FBe(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=FBe(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function kBe(t,e={}){if(!t)return[];let{max:r=Ddt}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),DB(wdt(t),r,!0).map(bdt)}function vdt(t){return"{"+t+"}"}function Sdt(t){return/^-?0\d/.test(t)}function xdt(t,e){return t<=e}function Fdt(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=FBe(i.body),l.length===1&&l[0]!==void 0&&(l=DB(l[0],e,!1).map(vdt),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=xdt;p<g&&(m*=-1,C=Fdt);let y=l.some(Sdt);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 bBe,vBe,f4,SBe,xBe,ddt,fdt,hdt,mdt,Cdt,Idt,Edt,Bdt,ydt,Qdt,Ddt,RBe=L(()=>{h();wBe();bBe="\0SLASH"+Math.random()+"\0",vBe="\0OPEN"+Math.random()+"\0",f4="\0CLOSE"+Math.random()+"\0",SBe="\0COMMA"+Math.random()+"\0",xBe="\0PERIOD"+Math.random()+"\0",ddt=new RegExp(bBe,"g"),fdt=new RegExp(vBe,"g"),hdt=new RegExp(f4,"g"),mdt=new RegExp(SBe,"g"),Cdt=new RegExp(xBe,"g"),Idt=/\\\\/g,Edt=/\\{/g,Bdt=/\\}/g,ydt=/\\,/g,Qdt=/\\\./g,Ddt=1e5});var wB,TBe=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 kdt,bB,Rdt,NBe,MBe,PBe=L(()=>{h();kdt={"[: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,"\\$&"),Rdt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),NBe=t=>t.join(""),MBe=(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(kdt))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[Rdt(f),!1,u-r,!1]}let d="["+(c?"^":"")+NBe(n)+"]",g="["+(c?"":"^")+NBe(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 Qs,Tdt,h4,LBe,Ndt,Mdt,Pdt,_Be,Ldt,tx,_dt,Udt,Gdt,Odt,m4,UBe,GBe,Kdt,kp,C4=L(()=>{h();PBe();ex();Tdt=new Set(["!","?","+","*","@"]),h4=t=>Tdt.has(t),LBe=t=>h4(t.type),Ndt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Mdt=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),Pdt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),_Be=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Ldt="(?!(?:^|/)\\.\\.?(?:$|/))",tx="(?!\\.)",_dt=new Set(["[","."]),Udt=new Set(["..","."]),Gdt=new Set("().*{}+?[]^$\\!"),Odt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),m4="[^/]",UBe=m4+"*?",GBe=m4+"+?",Kdt=0,kp=class{type;#r;#c;#s=!1;#n=[];#i;#o;#g;#e=!1;#a;#B;#w=!1;id=++Kdt;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#r.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#n.length,parts:this.#n}}constructor(e,r,n={}){this.type=e,e&&(this.#c=!0),this.#i=r,this.#r=this.#i?this.#i.#r:this,this.#a=this.#r===this?n:this.#r.#a,this.#g=this.#r===this?[]:this.#r.#g,e==="!"&&!this.#r.#e&&this.#g.push(this),this.#o=this.#i?this.#i.#n.length:0}get hasMagic(){if(this.#c!==void 0)return this.#c;for(let e of this.#n)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#c=!0;return this.#c}toString(){return this.#B!==void 0?this.#B:this.type?this.#B=this.type+"("+this.#n.map(e=>String(e)).join("|")+")":this.#B=this.#n.map(e=>String(e)).join("")}#N(){if(this!==this.#r)throw new Error("should only call on root");if(this.#e)return this;this.toString(),this.#e=!0;let e;for(;e=this.#g.pop();){if(e.type!=="!")continue;let r=e,n=r.#i;for(;n;){for(let i=r.#o+1;!n.type&&i<n.#n.length;i++)for(let s of e.#n){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(n.#n[i])}r=n,n=r.#i}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof Qs&&r.#i===this))throw new Error("invalid part: "+r);this.#n.push(r)}}toJSON(){let e=this.type===null?this.#n.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#n.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#r||this.#r.#e&&this.#i?.type==="!")&&e.push({}),e}isStart(){if(this.#r===this)return!0;if(!this.#i?.isStart())return!1;if(this.#o===0)return!0;let e=this.#i;for(let r=0;r<this.#o;r++){let n=e.#n[r];if(!(n instanceof Qs&&n.type==="!"))return!1}return!0}isEnd(){if(this.#r===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#n.length:0;return this.#o===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new Qs(this.type,e);for(let n of this.#n)r.copyIn(n);return r}static#R(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 Qs(C,r);f=Qs.#R(e,y,f,i,s+1),r.push(y);continue}m+=C}return r.push(m),f}let l=n+1,d=new Qs(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.#A(f))){let C=r&&r.#A(f)?0:1;d.push(p),p="";let I=new Qs(f,d);d.push(I),l=Qs.#R(e,I,l,i,s+C);continue}if(f==="|"){d.push(p),p="",g.push(d),d=new Qs(null,r);continue}if(f===")")return p===""&&r.#n.length===0&&(r.#w=!0),d.push(p),p="",r.push(...g,d),l;p+=f}return r.type=null,r.#c=void 0,r.#n=[e.substring(n-1)],l}#S(e){return this.#d(e,Mdt)}#d(e,r=Ndt){if(!e||typeof e!="object"||e.type!==null||e.#n.length!==1||this.type===null)return!1;let n=e.#n[0];return!n||typeof n!="object"||n.type===null?!1:this.#A(n.type,r)}#A(e,r=Pdt){return!!r.get(this.type)?.includes(e)}#b(e,r){let n=e.#n[0],i=new Qs(null,n,this.options);i.#n.push(""),n.push(i),this.#t(e,r)}#t(e,r){let n=e.#n[0];this.#n.splice(r,1,...n.#n);for(let i of n.#n)typeof i=="object"&&(i.#i=this);this.#B=void 0}#p(e){return!!_Be.get(this.type)?.has(e)}#J(e){if(!e||typeof e!="object"||e.type!==null||e.#n.length!==1||this.type===null||this.#n.length!==1)return!1;let r=e.#n[0];return!r||typeof r!="object"||r.type===null?!1:this.#p(r.type)}#M(e){let r=_Be.get(this.type),n=e.#n[0],i=r?.get(n.type);if(!i)return!1;this.#n=n.#n;for(let s of this.#n)typeof s=="object"&&(s.#i=this);this.type=i,this.#B=void 0,this.#w=!1}static fromGlob(e,r={}){let n=new Qs(null,void 0,r);return Qs.#R(e,n,0,r,0),n}toMMPattern(){if(this!==this.#r)return this.#r.toMMPattern();let e=this.toString(),[r,n,i,s]=this.toRegExpSource();if(!(i||this.#c||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#r===this&&(this.#q(),this.#N()),!LBe(this)){let A=this.isStart()&&this.isEnd()&&!this.#n.some(g=>typeof g!="string"),c=this.#n.map(g=>{let[p,f,m,C]=typeof g=="string"?Qs.#P(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.#n[0]=="string"&&!(this.#n.length===1&&Udt.has(this.#n[0]))){let p=_dt,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?Ldt:m?tx:""}let l="";return this.isEnd()&&this.#r.#e&&this.#i?.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.#n=[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.#w)a=(this.isStart()&&!r?tx:"")+GBe;else{let A=this.type==="!"?"))"+(this.isStart()&&!r&&!e?tx:"")+UBe+")":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]}#q(){if(LBe(this)){let e=0,r=!1;do{r=!0;for(let n=0;n<this.#n.length;n++){let i=this.#n[n];typeof i=="object"&&(i.#q(),this.#d(i)?(r=!1,this.#t(i,n)):this.#S(i)?(r=!1,this.#b(i,n)):this.#J(i)&&(r=!1,this.#M(i)))}}while(!r&&++e<10)}else for(let e of this.#n)typeof e=="object"&&e.#q();this.#B=void 0}#T(e){return this.#n.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#P(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+=(Gdt.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,s+=n&&/^[*]+$/.test(e)?GBe:UBe,r=!0;continue}else a=!1;if(c==="\\"){A===e.length-1?s+="\\\\":i=!0;continue}if(c==="["){let[u,l,d,g]=MBe(e,A);if(d){s+=u,o=o||l,A+=d-1,r=r||g;continue}}if(c==="?"){s+=m4,r=!0;continue}s+=Odt(c)}return[s,bl(e),!!r,o]}};Qs=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 Ei,Hdt,Jdt,jdt,Ydt,qdt,$dt,Vdt,Wdt,zdt,Xdt,Zdt,eft,tft,rft,nft,ift,sft,oft,HBe,JBe,jBe,OBe,aft,Gi,Aft,cft,uft,lft,gft,_o,pft,YBe,dft,fft,KBe,hft,zh,qBe=L(()=>{h();RBe();TBe();C4();E4();ex();C4();E4();ex();Ei=(t,e,r={})=>(wB(e),!r.nocomment&&e.charAt(0)==="#"?!1:new zh(e,r).match(t)),Hdt=/^\*+([^+@!?\*\[\(]*)$/,Jdt=t=>e=>!e.startsWith(".")&&e.endsWith(t),jdt=t=>e=>e.endsWith(t),Ydt=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),qdt=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),$dt=/^\*+\.\*+$/,Vdt=t=>!t.startsWith(".")&&t.includes("."),Wdt=t=>t!=="."&&t!==".."&&t.includes("."),zdt=/^\.\*+$/,Xdt=t=>t!=="."&&t!==".."&&t.startsWith("."),Zdt=/^\*+$/,eft=t=>t.length!==0&&!t.startsWith("."),tft=t=>t.length!==0&&t!=="."&&t!=="..",rft=/^\?+([^+@!?\*\[\(]*)?$/,nft=([t,e=""])=>{let r=HBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},ift=([t,e=""])=>{let r=JBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},sft=([t,e=""])=>{let r=JBe([t]);return e?n=>r(n)&&n.endsWith(e):r},oft=([t,e=""])=>{let r=HBe([t]);return e?n=>r(n)&&n.endsWith(e):r},HBe=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},JBe=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},jBe=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",OBe={win32:{sep:"\\"},posix:{sep:"/"}},aft=jBe==="win32"?OBe.win32.sep:OBe.posix.sep;Ei.sep=aft;Gi=Symbol("globstar **");Ei.GLOBSTAR=Gi;Aft="[^/]",cft=Aft+"*?",uft="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",lft="(?:(?!(?:\\/|^)\\.).)*?",gft=(t,e={})=>r=>Ei(r,t,e);Ei.filter=gft;_o=(t,e={})=>Object.assign({},t,e),pft=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ei;let e=Ei;return Object.assign((n,i,s={})=>e(n,i,_o(t,s)),{Minimatch:class extends e.Minimatch{constructor(i,s={}){super(i,_o(t,s))}static defaults(i){return e.defaults(_o(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,s,o={}){super(i,s,_o(t,o))}static fromGlob(i,s={}){return e.AST.fromGlob(i,_o(t,s))}},unescape:(n,i={})=>e.unescape(n,_o(t,i)),escape:(n,i={})=>e.escape(n,_o(t,i)),filter:(n,i={})=>e.filter(n,_o(t,i)),defaults:n=>e.defaults(_o(t,n)),makeRe:(n,i={})=>e.makeRe(n,_o(t,i)),braceExpand:(n,i={})=>e.braceExpand(n,_o(t,i)),match:(n,i,s={})=>e.match(n,i,_o(t,s)),sep:e.sep,GLOBSTAR:Gi})};Ei.defaults=pft;YBe=(t,e={})=>(wB(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:kBe(t,{max:e.braceExpandMax}));Ei.braceExpand=YBe;dft=(t,e={})=>new zh(t,e).makeRe();Ei.makeRe=dft;fft=(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};Ei.match=fft;KBe=/[?*]|[+@!]\(.*?\)|\[|\]/,hft=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||jBe,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]==="?"||!KBe.test(s[2]))&&!KBe.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(Gi)?this.#r(e,r,n,i,s):this.#s(e,r,n,i,s)}#r(e,r,n,i,s){let o=r.indexOf(Gi,s),a=r.lastIndexOf(Gi),[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===Gi?(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===Gi)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 YBe(this.pattern,this.options)}parse(e){wB(e);let r=this.options;if(e==="**")return Gi;if(e==="")return"";let n,i=null;(n=e.match(Zdt))?i=r.dot?tft:eft:(n=e.match(Hdt))?i=(r.nocase?r.dot?qdt:Ydt:r.dot?jdt:Jdt)(n[1]):(n=e.match(rft))?i=(r.nocase?r.dot?ift:nft:r.dot?sft:oft)(n):(n=e.match($dt))?i=r.dot?Wdt:Vdt:(n=e.match(zdt))&&(i=Xdt);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?cft:r.dot?uft:lft,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"?hft(l):l===Gi?Gi:l._src});c.forEach((l,d)=>{let g=c[d+1],p=c[d-1];l!==Gi||p===Gi||(p===void 0?g!==void 0&&g!==Gi?c[d+1]="(?:\\/|"+n+"\\/)?"+g:c[d]=n:g===void 0?c[d-1]=p+"(?:\\/|\\/"+n+")?":g!==Gi&&(c[d-1]=p+"(?:\\/|\\/"+n+"\\/)"+g,c[d+1]=Gi))});let u=c.filter(l=>l!==Gi);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 Ei.defaults(e).Minimatch}};Ei.AST=kp;Ei.Minimatch=zh;Ei.escape=I4;Ei.unescape=bl});async function mft(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 Cft(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $Be(t){return t.replace(/[*?{}[\]!]/g,"").replace(/\/+/g,"/").toLowerCase()}async function Ift(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=`${Cft(i)}.md`,a=VBe.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)=>$Be(g).localeCompare($Be(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 Eft(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 WBe(t,e){if(!e)return[];let r=e.replace(/\\/g,"/");return t.filter(n=>n.glob?Eft(n.glob).some(s=>{try{return Ei(r,s.replace(/\\/g,"/"),{matchBase:!0})}catch{return!1}}):!1)}async function zBe(t,e,r,n){try{return await mft(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 Ift(e,r)}catch(n){t.Sentry?.captureException(new Error("Failed to sync memories to disk",{cause:n}))}}var rx,VBe,
|
|
1767
|
+
`):void 0})}return r}var IBe=L(()=>{"use strict";h()});var wl,EBe=L(()=>{"use strict";h();wl=(...t)=>{typeof process<"u"&&process.env.DEBUG==="true"&&console.debug("[DEBUG] ",...t)}});var Adt,Wh,BBe,cdt,udt,ldt,XS,lH=L(()=>{"use strict";h();EBe();Adt=()=>{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=Adt(),BBe=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)},cdt=async()=>Wh.getRandomValues(new Uint8Array(16)),udt=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)},ldt=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 cdt();wl("validateEncryptionKey: Generated test IV",i);let s=await udt(r,i,n);wl("validateEncryptionKey: Encrypted test data",s);let o=new Uint8Array(s);wl("validateEncryptionKey: Encrypted test data array",o);let a=await ldt(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 yBe(t){return t.length<=gH?t:t.slice(0,gH)+`... [+${t.length-gH} chars]`}var gdt,gH,ZS,QBe=L(()=>{"use strict";h();Rr();Qr();hr();gdt=5e3,gH=8e3,ZS=class{#r;#c;#s;#n=[];#i;#o=!1;#g=Promise.resolve();constructor(e){this.#r=e.credentials,this.#c=e.replayId,this.#s=e.debug??!1;let r=setInterval(()=>{this.#a()},gdt);r.unref?.(),this.#i=r}recordText(e,r=Date.now()){this.#o||this.#e({ts:r,type:"text",content:yBe(e)})}recordReasoning(e,r=Date.now()){this.#o||this.#e({ts:r,type:"thinking",content:yBe(e)})}recordCheckpoint(e=Date.now(),r="",n){this.#o||this.#e({ts:e,type:"checkpoint",label:r,imageUrl:n})}#e(e){e.type!=="checkpoint"&&!e.content||this.#n.push(e)}async#a(){if(this.#n.length===0)return;let e=this.#n;return this.#n=[],this.#g=this.#g.catch(()=>{}).then(()=>this.#B(e)),this.#g}async#B(e){try{let r=new URL(`${Ne}/codegen/replay/${encodeURIComponent(this.#c)}/actions`);this.#r.builderPublicKey&&r.searchParams.set("apiKey",this.#r.builderPublicKey),this.#r.userId&&r.searchParams.set("userId",this.#r.userId);let n={"content-type":"application/json"};this.#r.builderPrivateKey&&(n.authorization=`Bearer ${this.#r.builderPrivateKey}`),await Fe(r,{method:"POST",body:JSON.stringify({actions:e}),headers:n,keepalive:!0},this.#s)}catch{}}async flush(){await this.#a(),await this.#g.catch(()=>{})}async close(){this.#o||(this.#o=!0,this.#i&&clearInterval(this.#i),await this.flush())}}});var pH,DBe,pdt,wBe=L(()=>{h();pH=(t,e,r)=>{let n=t instanceof RegExp?DBe(t,r):t,i=e instanceof RegExp?DBe(e,r):e,s=n!==null&&i!=null&&pdt(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)}},DBe=(t,e)=>{let r=e.match(t);return r?r[0]:null},pdt=(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 wdt(t){return t.replace(Idt,bBe).replace(Edt,vBe).replace(Bdt,fH).replace(ydt,SBe).replace(Qdt,xBe)}function bdt(t){return t.replace(ddt,"\\").replace(fdt,"{").replace(hdt,"}").replace(mdt,",").replace(Cdt,".")}function FBe(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=FBe(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function kBe(t,e={}){if(!t)return[];let{max:r=Ddt}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),DB(wdt(t),r,!0).map(bdt)}function vdt(t){return"{"+t+"}"}function Sdt(t){return/^-?0\d/.test(t)}function xdt(t,e){return t<=e}function Fdt(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=FBe(i.body),l.length===1&&l[0]!==void 0&&(l=DB(l[0],e,!1).map(vdt),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=xdt;p<g&&(m*=-1,C=Fdt);let y=l.some(Sdt);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 bBe,vBe,fH,SBe,xBe,ddt,fdt,hdt,mdt,Cdt,Idt,Edt,Bdt,ydt,Qdt,Ddt,RBe=L(()=>{h();wBe();bBe="\0SLASH"+Math.random()+"\0",vBe="\0OPEN"+Math.random()+"\0",fH="\0CLOSE"+Math.random()+"\0",SBe="\0COMMA"+Math.random()+"\0",xBe="\0PERIOD"+Math.random()+"\0",ddt=new RegExp(bBe,"g"),fdt=new RegExp(vBe,"g"),hdt=new RegExp(fH,"g"),mdt=new RegExp(SBe,"g"),Cdt=new RegExp(xBe,"g"),Idt=/\\\\/g,Edt=/\\{/g,Bdt=/\\}/g,ydt=/\\,/g,Qdt=/\\\./g,Ddt=1e5});var wB,TBe=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 kdt,bB,Rdt,NBe,MBe,PBe=L(()=>{h();kdt={"[: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,"\\$&"),Rdt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),NBe=t=>t.join(""),MBe=(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(kdt))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[Rdt(f),!1,u-r,!1]}let d="["+(c?"^":"")+NBe(n)+"]",g="["+(c?"":"^")+NBe(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 Qs,Tdt,hH,LBe,Ndt,Mdt,Pdt,_Be,Ldt,tx,_dt,Udt,Gdt,Odt,mH,UBe,GBe,Kdt,kp,CH=L(()=>{h();PBe();ex();Tdt=new Set(["!","?","+","*","@"]),hH=t=>Tdt.has(t),LBe=t=>hH(t.type),Ndt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Mdt=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),Pdt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),_Be=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Ldt="(?!(?:^|/)\\.\\.?(?:$|/))",tx="(?!\\.)",_dt=new Set(["[","."]),Udt=new Set(["..","."]),Gdt=new Set("().*{}+?[]^$\\!"),Odt=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),mH="[^/]",UBe=mH+"*?",GBe=mH+"+?",Kdt=0,kp=class{type;#r;#c;#s=!1;#n=[];#i;#o;#g;#e=!1;#a;#B;#w=!1;id=++Kdt;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#r.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#n.length,parts:this.#n}}constructor(e,r,n={}){this.type=e,e&&(this.#c=!0),this.#i=r,this.#r=this.#i?this.#i.#r:this,this.#a=this.#r===this?n:this.#r.#a,this.#g=this.#r===this?[]:this.#r.#g,e==="!"&&!this.#r.#e&&this.#g.push(this),this.#o=this.#i?this.#i.#n.length:0}get hasMagic(){if(this.#c!==void 0)return this.#c;for(let e of this.#n)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#c=!0;return this.#c}toString(){return this.#B!==void 0?this.#B:this.type?this.#B=this.type+"("+this.#n.map(e=>String(e)).join("|")+")":this.#B=this.#n.map(e=>String(e)).join("")}#N(){if(this!==this.#r)throw new Error("should only call on root");if(this.#e)return this;this.toString(),this.#e=!0;let e;for(;e=this.#g.pop();){if(e.type!=="!")continue;let r=e,n=r.#i;for(;n;){for(let i=r.#o+1;!n.type&&i<n.#n.length;i++)for(let s of e.#n){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(n.#n[i])}r=n,n=r.#i}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof Qs&&r.#i===this))throw new Error("invalid part: "+r);this.#n.push(r)}}toJSON(){let e=this.type===null?this.#n.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#n.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#r||this.#r.#e&&this.#i?.type==="!")&&e.push({}),e}isStart(){if(this.#r===this)return!0;if(!this.#i?.isStart())return!1;if(this.#o===0)return!0;let e=this.#i;for(let r=0;r<this.#o;r++){let n=e.#n[r];if(!(n instanceof Qs&&n.type==="!"))return!1}return!0}isEnd(){if(this.#r===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#n.length:0;return this.#o===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new Qs(this.type,e);for(let n of this.#n)r.copyIn(n);return r}static#R(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 Qs(C,r);f=Qs.#R(e,y,f,i,s+1),r.push(y);continue}m+=C}return r.push(m),f}let l=n+1,d=new Qs(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.#A(f))){let C=r&&r.#A(f)?0:1;d.push(p),p="";let I=new Qs(f,d);d.push(I),l=Qs.#R(e,I,l,i,s+C);continue}if(f==="|"){d.push(p),p="",g.push(d),d=new Qs(null,r);continue}if(f===")")return p===""&&r.#n.length===0&&(r.#w=!0),d.push(p),p="",r.push(...g,d),l;p+=f}return r.type=null,r.#c=void 0,r.#n=[e.substring(n-1)],l}#S(e){return this.#d(e,Mdt)}#d(e,r=Ndt){if(!e||typeof e!="object"||e.type!==null||e.#n.length!==1||this.type===null)return!1;let n=e.#n[0];return!n||typeof n!="object"||n.type===null?!1:this.#A(n.type,r)}#A(e,r=Pdt){return!!r.get(this.type)?.includes(e)}#b(e,r){let n=e.#n[0],i=new Qs(null,n,this.options);i.#n.push(""),n.push(i),this.#t(e,r)}#t(e,r){let n=e.#n[0];this.#n.splice(r,1,...n.#n);for(let i of n.#n)typeof i=="object"&&(i.#i=this);this.#B=void 0}#p(e){return!!_Be.get(this.type)?.has(e)}#J(e){if(!e||typeof e!="object"||e.type!==null||e.#n.length!==1||this.type===null||this.#n.length!==1)return!1;let r=e.#n[0];return!r||typeof r!="object"||r.type===null?!1:this.#p(r.type)}#M(e){let r=_Be.get(this.type),n=e.#n[0],i=r?.get(n.type);if(!i)return!1;this.#n=n.#n;for(let s of this.#n)typeof s=="object"&&(s.#i=this);this.type=i,this.#B=void 0,this.#w=!1}static fromGlob(e,r={}){let n=new Qs(null,void 0,r);return Qs.#R(e,n,0,r,0),n}toMMPattern(){if(this!==this.#r)return this.#r.toMMPattern();let e=this.toString(),[r,n,i,s]=this.toRegExpSource();if(!(i||this.#c||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${r}$`,a),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#r===this&&(this.#q(),this.#N()),!LBe(this)){let A=this.isStart()&&this.isEnd()&&!this.#n.some(g=>typeof g!="string"),c=this.#n.map(g=>{let[p,f,m,C]=typeof g=="string"?Qs.#P(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.#n[0]=="string"&&!(this.#n.length===1&&Udt.has(this.#n[0]))){let p=_dt,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?Ldt:m?tx:""}let l="";return this.isEnd()&&this.#r.#e&&this.#i?.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.#n=[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.#w)a=(this.isStart()&&!r?tx:"")+GBe;else{let A=this.type==="!"?"))"+(this.isStart()&&!r&&!e?tx:"")+UBe+")":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]}#q(){if(LBe(this)){let e=0,r=!1;do{r=!0;for(let n=0;n<this.#n.length;n++){let i=this.#n[n];typeof i=="object"&&(i.#q(),this.#d(i)?(r=!1,this.#t(i,n)):this.#S(i)?(r=!1,this.#b(i,n)):this.#J(i)&&(r=!1,this.#M(i)))}}while(!r&&++e<10)}else for(let e of this.#n)typeof e=="object"&&e.#q();this.#B=void 0}#T(e){return this.#n.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#P(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+=(Gdt.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,s+=n&&/^[*]+$/.test(e)?GBe:UBe,r=!0;continue}else a=!1;if(c==="\\"){A===e.length-1?s+="\\\\":i=!0;continue}if(c==="["){let[u,l,d,g]=MBe(e,A);if(d){s+=u,o=o||l,A+=d-1,r=r||g;continue}}if(c==="?"){s+=mH,r=!0;continue}s+=Odt(c)}return[s,bl(e),!!r,o]}};Qs=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 Ei,Hdt,Jdt,jdt,Ydt,qdt,$dt,Vdt,Wdt,zdt,Xdt,Zdt,eft,tft,rft,nft,ift,sft,oft,HBe,JBe,jBe,OBe,aft,Gi,Aft,cft,uft,lft,gft,_o,pft,YBe,dft,fft,KBe,hft,zh,qBe=L(()=>{h();RBe();TBe();CH();EH();ex();CH();EH();ex();Ei=(t,e,r={})=>(wB(e),!r.nocomment&&e.charAt(0)==="#"?!1:new zh(e,r).match(t)),Hdt=/^\*+([^+@!?\*\[\(]*)$/,Jdt=t=>e=>!e.startsWith(".")&&e.endsWith(t),jdt=t=>e=>e.endsWith(t),Ydt=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),qdt=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),$dt=/^\*+\.\*+$/,Vdt=t=>!t.startsWith(".")&&t.includes("."),Wdt=t=>t!=="."&&t!==".."&&t.includes("."),zdt=/^\.\*+$/,Xdt=t=>t!=="."&&t!==".."&&t.startsWith("."),Zdt=/^\*+$/,eft=t=>t.length!==0&&!t.startsWith("."),tft=t=>t.length!==0&&t!=="."&&t!=="..",rft=/^\?+([^+@!?\*\[\(]*)?$/,nft=([t,e=""])=>{let r=HBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},ift=([t,e=""])=>{let r=JBe([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},sft=([t,e=""])=>{let r=JBe([t]);return e?n=>r(n)&&n.endsWith(e):r},oft=([t,e=""])=>{let r=HBe([t]);return e?n=>r(n)&&n.endsWith(e):r},HBe=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},JBe=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},jBe=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",OBe={win32:{sep:"\\"},posix:{sep:"/"}},aft=jBe==="win32"?OBe.win32.sep:OBe.posix.sep;Ei.sep=aft;Gi=Symbol("globstar **");Ei.GLOBSTAR=Gi;Aft="[^/]",cft=Aft+"*?",uft="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",lft="(?:(?!(?:\\/|^)\\.).)*?",gft=(t,e={})=>r=>Ei(r,t,e);Ei.filter=gft;_o=(t,e={})=>Object.assign({},t,e),pft=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ei;let e=Ei;return Object.assign((n,i,s={})=>e(n,i,_o(t,s)),{Minimatch:class extends e.Minimatch{constructor(i,s={}){super(i,_o(t,s))}static defaults(i){return e.defaults(_o(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,s,o={}){super(i,s,_o(t,o))}static fromGlob(i,s={}){return e.AST.fromGlob(i,_o(t,s))}},unescape:(n,i={})=>e.unescape(n,_o(t,i)),escape:(n,i={})=>e.escape(n,_o(t,i)),filter:(n,i={})=>e.filter(n,_o(t,i)),defaults:n=>e.defaults(_o(t,n)),makeRe:(n,i={})=>e.makeRe(n,_o(t,i)),braceExpand:(n,i={})=>e.braceExpand(n,_o(t,i)),match:(n,i,s={})=>e.match(n,i,_o(t,s)),sep:e.sep,GLOBSTAR:Gi})};Ei.defaults=pft;YBe=(t,e={})=>(wB(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:kBe(t,{max:e.braceExpandMax}));Ei.braceExpand=YBe;dft=(t,e={})=>new zh(t,e).makeRe();Ei.makeRe=dft;fft=(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};Ei.match=fft;KBe=/[?*]|[+@!]\(.*?\)|\[|\]/,hft=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||jBe,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]==="?"||!KBe.test(s[2]))&&!KBe.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(Gi)?this.#r(e,r,n,i,s):this.#s(e,r,n,i,s)}#r(e,r,n,i,s){let o=r.indexOf(Gi,s),a=r.lastIndexOf(Gi),[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===Gi?(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===Gi)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 YBe(this.pattern,this.options)}parse(e){wB(e);let r=this.options;if(e==="**")return Gi;if(e==="")return"";let n,i=null;(n=e.match(Zdt))?i=r.dot?tft:eft:(n=e.match(Hdt))?i=(r.nocase?r.dot?qdt:Ydt:r.dot?jdt:Jdt)(n[1]):(n=e.match(rft))?i=(r.nocase?r.dot?ift:nft:r.dot?sft:oft)(n):(n=e.match($dt))?i=r.dot?Wdt:Vdt:(n=e.match(zdt))&&(i=Xdt);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?cft:r.dot?uft:lft,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"?hft(l):l===Gi?Gi:l._src});c.forEach((l,d)=>{let g=c[d+1],p=c[d-1];l!==Gi||p===Gi||(p===void 0?g!==void 0&&g!==Gi?c[d+1]="(?:\\/|"+n+"\\/)?"+g:c[d]=n:g===void 0?c[d-1]=p+"(?:\\/|\\/"+n+")?":g!==Gi&&(c[d-1]=p+"(?:\\/|\\/"+n+"\\/)"+g,c[d+1]=Gi))});let u=c.filter(l=>l!==Gi);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 Ei.defaults(e).Minimatch}};Ei.AST=kp;Ei.Minimatch=zh;Ei.escape=IH;Ei.unescape=bl});async function mft(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 Cft(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $Be(t){return t.replace(/[*?{}[\]!]/g,"").replace(/\/+/g,"/").toLowerCase()}async function Ift(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=`${Cft(i)}.md`,a=VBe.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)=>$Be(g).localeCompare($Be(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 Eft(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 WBe(t,e){if(!e)return[];let r=e.replace(/\\/g,"/");return t.filter(n=>n.glob?Eft(n.glob).some(s=>{try{return Ei(r,s.replace(/\\/g,"/"),{matchBase:!0})}catch{return!1}}):!1)}async function zBe(t,e,r,n){try{return await mft(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 Ift(e,r)}catch(n){t.Sentry?.captureException(new Error("Failed to sync memories to disk",{cause:n}))}}var rx,VBe,BH=L(()=>{"use strict";h();rx=z(require("node:fs/promises"),1),VBe=z(require("node:path"),1);qBe();Qr();hr()});var ZBe,XBe=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 yft,Qft,Dft,Xh,
|
|
1799
|
+
`});var yft,Qft,Dft,Xh,yH=L(()=>{"use strict";h();XBe();yft="explorer",Qft='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.',Dft=["Read","Glob","Skill","Grep","WebSearch","SearchMemories","ExplorationMetadata"],Xh={name:yft,description:Qft,systemPrompt:ZBe,tools:Dft,model:"opa5-mini",includeMemories:!0}});var tye,eye=L(()=>{tye=`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,vft,ix,
|
|
1820
|
+
`});var bft,vft,ix,QH=L(()=>{"use strict";h();eye();bft="general-purpose",vft="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:vft,systemPrompt:tye}});function Sft(){if(vB!==void 0)return vB;try{return vB=require("prettier"),vB}catch{return vB=null,null}}function Uo(t){try{return JSON.stringify(t)}catch{return String(t)}}var vl,wH,sx,nye,cx,ox,iye,vB,rye,xft,Fft,kft,Rft,ka,DH,Zh=L(()=>{"use strict";h();Cp();che();Rr();_s();Qr();hr();vl=z(require("node:fs"),1),wH=require("node:crypto");TO();NO();dhe();mhe();xv();PL();pI();Rhe();sx=z(require("node:os"),1);t8();Fi();Bt();Ghe();Ov();Zhe();rme();Js();r8();nye=z(require("chokidar"),1);i8();FH();ume();TH();rr();cx=z(require("node:events"),1);JI();ox=require("node:crypto");Ap();pme();tU();jI();mI();Tu();fBe();z_();CBe();w0();Fo();IBe();iye=require("node:fs/promises");lH();HI();kB();Ic();QBe();BH();fa();K0();uw();Jv();yH();QH();rye=["ask-to-continue","credits-limit-daily","credits-limit-monthly","credits-limit-user","credits-limit-other","invalid-last-message"],xft=["initial-with-url","initial-without-url","success"],Fft=1800*1e3,kft=2147483647,Rft=t=>{let e=Number(process.env.AGENT_TIMEOUT_OVERRIDE_MS),r=Number.isFinite(e)&&e>0?e:t&&Number.isFinite(t)&&t>0?t:Fft;return Math.min(r,kft)},ka=class t{#r;#c;#s=!1;#n;#i=[];#o;#g;#e;#a;#B;#w;#N;#R;#S;#d;#A=!!(process.env.DEBUG||process.env.FUSION_DEBUG==="true");#b=!1;#t=ve("Agent",{debug:()=>this.#A});#p=new cx.default;#J=new Map;#M=new Set;#q;#T;#P;#Oe=[];#se=void 0;#St="";#re;#xt=Promise.resolve(void 0);#X=[];#U;#$=[];#At=!1;#we;#Z=new Map;#oe=new Map;#Ke=new Map;#He=[];#ae;#Xt=0;#Ae;#ee;#m;#I;#Ft;#ct;#ut;#Je=!1;#be;#ve=void 0;#lt;#Se;#je;#ce;#f;#h=[];#F;#kt;#C;#gt;#G;#xe=0;#ue;#D;#Rt=[];#Tt=new Set;#u;#E;#y;#Ye;#V;#le;#pt;#qe=!1;#Nt=0;#ge=null;#pe=0;#ne=!1;#$e;#Ve;#L;#We;#Mt;#Pt;#de=[];#ze=[];#dt=!1;#fe=new Map;#Fe=new Map;#ke={};#x={};#Lt=!1;#Xe;#_t;#ft=!1;#Zt=new Set;#Re;#_={};#ht;#Ze=[];#et=0;#he=null;#me=void 0;#Ut=void 0;#v=new Map;#Q={watcher:null,listeners:new Set,debounceMs:300,pendingEvents:[]};#Gt=!1;#l=null;#tt=new Set;#rt=new Map;#Te=new Map;#Ne=new Map;#Me=new Map;static#nt=3e4;#Pe=null;#Ce=[];get primaryGitPath(){return this.#h[0]?.path||this.#f}#Le(e){if(!e)return this.primaryGitPath;let r=this.#h.find(n=>n.folderName===e);if(!r)throw new Error(`Folder "${e}" not found in git-enabled folders`);return r.path}#Ot(e,r){if(typeof e!="string")throw new TypeError(`#parsePathWithFolder: 'path' must be a string, received ${typeof e}: ${Uo(e)}`);if(r)return{repoPath:this.#Le(r),relativePath:e};for(let n of this.#h){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.#V=e.modelOverride,this.#le=e.agentModelOverrides,this.#a=e.credentials,"initialUrl"in e){let n=dye(e.initialUrl).id;n?this.#ee=n:this.#B=e.initialUrl}typeof e.autoImportLocalMCPs=="boolean"&&(this.#Gt=e.autoImportLocalMCPs),"sessionOrCompletionId"in e?this.#ee=e.sessionOrCompletionId:this.#ee=e.fusionConfig?.sessionId;let r=e.workingDirectory??e.fusionConfig?.workingDirectory;if(this.#f=r?e.sys.resolve(e.sys.cwd(),r):e.sys.getCwdDir(),this.#N=e.skipFileDiff??!0,this.#w=e.position,this.#U=e.privacyMode??e.fusionConfig?.privacyMode,this.#m=e.devServerOrchestrator,this.#I=e.git??!1,this.#S=e.softContextWindow,this.#I&&(process.env.GIT_CEILING_DIRECTORIES=this.#f),this.#Ft=e.gitAutoInit??!1,this.#u=e.fusionConfig,this.#dt=e.asyncSubAgents??!1,this.#o=xL(e.queueMode),this.#q=e.fusionConfig?.autoPush,this.#E=e.fusionConfig?.projectId,this.#y=e.fusionConfig?.branchName,this.#T=e.fusionConfig?.featureBranch,this.#P=e.fusionConfig?.aiBranch,this.#$e=e.fusionConfig?.proxyOrigin,this.#Ve=e.fusionConfig?.proxyDefaultOrigin,this.#ct=e.fusionStatusMonitor,process.env.FUSION_ENV_ORIGIN&&(this.#Mt=process.env.FUSION_ENV_ORIGIN),this.#L=e.agentType,this.#We=e.defaultSyncChanges,this.#Lt=e.persistSessionLocally??!1,this.#Xe=e.parentSessionId,this.#_t=e.mainSessionId,e.enabledTools)this.#D=DH(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.#U?.enabled||this.#U?.redactUserMessages||this.#U?.redactLLMMessages);i||n.push("WebSearch"),this.#E&&!i&&this.getCommitMode()!=="commits"&&n.push("SearchMemories"),i||n.push("GetScreenshot"),n.push("NavigatePreview"),this.#m&&(n.push("DevServerLogs"),n.push("DevServerRestart"),n.push("ProposeEnvVariable")),process.env.FUSION_IDE_PORT&&n.push("IDEDiagnostics"),n.push("PullPrototype"),this.#D=DH(this.#u,n)}if(this.#kt=e.maxTokens,this.#pt=e.reasoning,this.#lt=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.#gt=e.mcpServers??!1,this.#F=this.#f,this.#h=[],this.#C?.folders.length){let n=this.#C.folders.filter(i=>i.enableGit);this.#h=n.map(i=>({folderName:i.name??i.path,path:this.#e.resolve(this.#f,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.#h.length===0&&(this.#h=[{folderName:this.#e.basename(this.#f),path:this.#f,branchName:"main"}]),this.#Re=Dye(this.#C),this.#C?.folders[0]&&this.#H()&&(this.#F=this.#e.resolve(this.#f,this.#C.folders[0].path)),this.#p.on("idle",()=>{let n=this.#et;if(this.#et=0,this.#E==null&&this.#y==null||this.#Xe)return;this.clearSessionCanHandleTools(),this.#t.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.#x.gif_id,planContent:this.#er,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.#h}get workingDirectory(){return this.#f}get bashWorkingDirectory(){return this.#F}getSessionMode(){return this.#r?.sessionMode??"normal"}get#er(){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.#V=e||void 0,await this.#De()}#tr(){if(!this.#L||!this.#le)return;let e=this.#le[this.#L];if(e){if(typeof e=="string")return ul(e);if(Array.isArray(e)&&e.length){let r=this.#fe.get(this.#L)??0;return this.#fe.set(this.#L,r+1),ul(e[r%e.length])}}}removeSystemReminder(e){let r=this.#$.findIndex(n=>n.tag===e);r!==-1&&this.#$.splice(r,1)}getMemoriesForFile(e){let r=WBe(this.#Rt,e).filter(n=>!this.#Tt.has(n.id));for(let n of r)this.#Tt.add(n.id);return r}#mt(){return Eye(this.#u?.environmentVariables??[],this.#m?.environmentVariables??[])}#rr(){if(this.#At)return;let e=this.#mt();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.#$.findIndex(n=>n.tag===e.tag):-1;return r!==-1?e.text?(this.#$[r]=e,{operation:"update"}):(this.#$.splice(r,1),{operation:"delete"}):e.text?(this.#$.push(e),{operation:"add"}):{operation:"noop"}}setDefaultAutoPush(e){this.#q=e}async setPrivacyMode(e){if(e&&e.enabled){if(!e.encryptKey&&!this.#we)this.#we=await BBe();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.#U=e}getLocalMcpStatus(){return this.#G?.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.#p.emit("step",n)}async authenticateMcpServer(e){let r=this.#G;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.#p}),{started:!0}}async clearMcpAuth(e){let r=this.#G;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.#G;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.#G?.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=mBe(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.#ut||(this.#ut=this.#sr(e)),await this.#ut}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.#nr().then(e=>(this.#be=void 0,e))),this.#be}async#nr(){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#ir(){try{let e=Sft();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.#lt=e,this.#r&&(this.#r.customInstructions=await this.#_e())}async setCustomAgents(e){this.#Se=e,this.#r&&(this.#r.customAgents=await this.#it())}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.#nr().then(e=>(this.#be=void 0,e))),this.#be}async#nr(){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#ir(){try{let e=Sft();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.#lt=e,this.#r&&(this.#r.customInstructions=await this.#_e())}async setCustomAgents(e){this.#Se=e,this.#r&&(this.#r.customAgents=await this.#it())}async#_e(){let e=await RH({sys:this.#e,projectDir:this.#f,currentDir:this.#h.map(n=>n.path),rootDir:"/",allowedCommands:A0(this.#u?.allowedCommands??[]),skipCommandSecurity:this.#u?.skipCommandSecurity===!0}),r=SB(this.#lt,this.#u?.customInstructions??[]);return SB(r,e)}async#it(){if(!this.#D?.includes("Agent"))return[];let e=await cme({sys:this.#e,projectDir:this.#f,currentDir:this.#h.map(n=>n.path),rootDir:"/"}),r=SB(this.#Se,this.#u?.customAgents??[]);return SB(r,e)}async#sr(e){try{if(this.#qe)throw new Error("Code session already closed");if(this.#r)throw new Error("Session context already initialized");this.#t.debug(`Current AI working directory: ${this.#f}`),await this.setPrivacyMode(this.#U);let r=await this.#ar(),n=await this.#ir();r&&(this.#_=await this.#j());let i=this.#h[0]?.repoUrl;if(this.#Ye=await Lv(i),!this.#Ye)try{let u=await this.git(["remote","get-url","origin"],{cwd:this.#f});u&&(this.#Ye=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.#t.debug(`Session recovered (sessionId=${s}, turnsCount=${o.turns.length})`)):s=(0,ox.randomUUID)(),this.#T||(this.#T=r?.featureBranch?.trim());let a={turns:o?.turns??[],sessionId:s,customInstructions:await this.#_e(),customAgents:await this.#it(),title:o?.title,beforeCommit:o?.beforeCommit,createdUnixTime:o?.createdUnixTime??Date.now(),updatedUnixTime:o?.updatedUnixTime??Date.now(),userContext:await fye(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.#x=o?.metadata??{};let A=this.#x.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.#p.on("step",u=>{u.type!=="delta"&&this.#t.debug(`(${u.type}): ${Sf(JSON.stringify(u),400)}`)}),await this.#cr(a),this.#r=a,this.#L){let u=await this.getNamedAgentConfig(this.#L,this.getSessionId(),e.signal);if(u.success){if(this.#R=u.options.includeMemories,this.#D=u.options.enabledTools,this.#V=u.options.modelOverride,this.#ce=u.options.systemPromptOverride,this.#w=u.options.position,this.#o=xL(u.options.queueMode),this.#dt=u.options.asyncSubAgents??!1,this.#S=u.options.softContextWindow,this.#We=u.options.defaultSyncChanges,this.#je={...this.#je,...u.options.builtInMCPServerConfig},u.options.builtInMCPServerConfig?.chrome&&!this.#st){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.#gt=u.options.mcpServers)}else this.#t.error(u.response)}try{let u=await dBe(this.#e,this.primaryGitPath,this.#je,this.#Gt,e.signal);u.length>0?(this.#t.debug(`Initializing ${u.length} local MCP server(s)...`),this.#G=await pBe(u,this.#e,this.primaryGitPath,e.signal)):this.#t.debug(`No local MCP servers found in: ${this.primaryGitPath}`),this.#G&&this.#Ee()}catch(u){this.#t.error("Failed to initialize local MCP servers:",u,{loggerOptions:{debug:!0}})}if(this.#I&&this.#E&&this.#D?.includes("SearchMemories")){let u=await zBe(this.#e,this.#a,this.#E,e.signal);await nx(this.#e,u,this.#e.join(this.#F,".builder","memories")),this.#Rt=u,this.#D&&u.length===0&&(this.#D=this.#D.filter(l=>l!=="SearchMemories"))}let c=this.#m;if(c){let u=()=>{this.#p.emit("step",SH(c,this.#u))},l=()=>{this.#p.emit("step",SH(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.#He.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.#t.error(r),this.#e.Sentry?.captureException(r,{tags:{operation:"codegen-initialize-session"}}),r}}async#Ct(e,r){let n="reminder:health";this.removeSystemReminder(n);let i=this.#m;if(!i||this.#L==="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.#Et(),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=Cye(B??""));let v="",D="",S="error",x="Try to fix",w="repair-unknown";if(l==="not-installed"||l==="install-failed"||l==="install-aborted"||l==="failed"||I||C||y||E||A.length>0){if(I&&(w="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){w="repair-merge-conflict",x="Resolve conflict",v="Merge conflict detected - changes from different sources need to be combined";let J=this.#ht,_=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/${G} ${_?" -- this is main/feature branch (work here needs to be preserved)":"-- same branch pushed by remote"}
|
|
1881
1881
|
`),J}}if(n){let G=await this.#Kt(!0,C);await this.git(G,{cwd:C.path})}if(v)try{await this.git(["stash","pop"],{cwd:I})}catch(G){this.#e.Sentry?.captureException(G,{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.#j();if(c&&(this.#_={...this.#_,...m}),n){let C=await this.#Ue(!1);if(!C.success)throw C.error}else await this.#k(),await this.#Qe({lastCommit:xo(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.#t.error(`Error syncing changes from branches: ${u}`,{loggerOptions:{debug:!0}}),await this.#k(),c){let d=await this.#j();this.#_={...this.#_,...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#j(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.#t.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.#T)throw new Error("Feature branch is missing");return this.#T}getAiBranch(){if(!this.#P)throw new Error("AI branch is missing");return this.#P}async git(e,r){let n=e[0];(n==="push"||n==="fetch"||n==="pull")&&await this.#It();let s=typeof r=="object"?{sys:this.#e,...r}:r,o=await this.#Jt(()=>this.#Cr(e,s));return this.#hr(n)&&(this.#Me.clear(),this.#Te.clear(),this.#Ne.clear()),o}static#fr=new Set(["commit","merge","rebase","checkout","switch","pull","fetch","reset","cherry-pick","revert","am","stash","push"]);#hr(e){return!!e&&t.#fr.has(e)}async#W(e){if(this.#h.length===0)return{success:!0,partialSuccess:!1,results:[]};let n=(await Promise.allSettled(this.#h.map(o=>e(o)))).map((o,a)=>({folderName:this.#h[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}}#Ht(e){let r=wn(e),n=this.#h.find(a=>{let A=wn(a.folderName);return r.startsWith(A+"/")||r===A});if(n)return n;let i=e.startsWith("/")||e.includes(":")?e:this.#e.resolve(this.#f,e),s=wn(i);return this.#h.find(a=>{let A=wn(a.path);return s.startsWith(A+"/")||s===A})}#mr(e){let r=new Map;for(let n of e){let i=this.#Ht(n);if(i){let s=r.get(i.folderName)||[];s.push(n),r.set(i.folderName,s)}}return r}#Jt(e){let r=this.#xt.then(()=>e());return this.#xt=r.catch(()=>{}),r}async#Cr(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 zs("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.#b=!0):!e&&this.#b&&(delete process.env.DEBUG,this.#b=!1)}async createTerminal(e){let r=this.#m,n=e?.terminalId||`pty_${Date.now()}_${(0,ox.randomUUID)()}`,i=this.#yt().find(y=>y.terminalId===n),s=new Set,o=new Set;if(i&&e?.terminalId){if(!e?.force)return i;let y=this.#v.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.#v.get(n);E&&(E.state=B?"error":"exited",E.exitCode=y);for(let Q of o)Q(y);this.#v.delete(n),l.forEach(Q=>Q())},p=e?.cwd||this.#F,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.#v.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.#t.error(`Error syncing changes from branches: ${u}`,{loggerOptions:{debug:!0}}),await this.#k(),c){let d=await this.#j();this.#_={...this.#_,...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#j(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.#t.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.#T)throw new Error("Feature branch is missing");return this.#T}getAiBranch(){if(!this.#P)throw new Error("AI branch is missing");return this.#P}async git(e,r){let n=e[0];(n==="push"||n==="fetch"||n==="pull")&&await this.#It();let s=typeof r=="object"?{sys:this.#e,...r}:r,o=await this.#Jt(()=>this.#Cr(e,s));return this.#hr(n)&&(this.#Me.clear(),this.#Te.clear(),this.#Ne.clear()),o}static#fr=new Set(["commit","merge","rebase","checkout","switch","pull","fetch","reset","cherry-pick","revert","am","stash","push"]);#hr(e){return!!e&&t.#fr.has(e)}async#W(e){if(this.#h.length===0)return{success:!0,partialSuccess:!1,results:[]};let n=(await Promise.allSettled(this.#h.map(o=>e(o)))).map((o,a)=>({folderName:this.#h[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}}#Ht(e){let r=wn(e),n=this.#h.find(a=>{let A=wn(a.folderName);return r.startsWith(A+"/")||r===A});if(n)return n;let i=e.startsWith("/")||e.includes(":")?e:this.#e.resolve(this.#f,e),s=wn(i);return this.#h.find(a=>{let A=wn(a.path);return s.startsWith(A+"/")||s===A})}#mr(e){let r=new Map;for(let n of e){let i=this.#Ht(n);if(i){let s=r.get(i.folderName)||[];s.push(n),r.set(i.folderName,s)}}return r}#Jt(e){let r=this.#xt.then(()=>e());return this.#xt=r.catch(()=>{}),r}async#Cr(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 zs("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.#b=!0):!e&&this.#b&&(delete process.env.DEBUG,this.#b=!1)}async createTerminal(e){let r=this.#m,n=e?.terminalId||`pty_${Date.now()}_${(0,ox.randomUUID)()}`,i=this.#yt().find(y=>y.terminalId===n),s=new Set,o=new Set;if(i&&e?.terminalId){if(!e?.force)return i;let y=this.#v.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.#v.get(n);E&&(E.state=B?"error":"exited",E.exitCode=y);for(let Q of o)Q(y);this.#v.delete(n),l.forEach(Q=>Q())},p=e?.cwd||this.#F,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.#v.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=xH(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.#v.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.#v.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}#yt(){let e=this.getSessionContext(),r=Array.from(this.#v.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.#F,createdAt:e.createdUnixTime,lastWrittenAt:Date.now(),createdBy:"fusion",readonly:!0,builtIn:!0,exitCode:void 0,state:"running",command:void 0});let i=this.#m;if(i){let s=Date.now();if(i.devState!=="unset"&&n.push({terminalId:"dev-command",title:"Dev Command",cwd:this.#F,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.#F,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.#F,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.#p.emit("step",{type:"terminals",terminals:this.#yt()})}updateTerminal({terminalId:e,cols:r,rows:n,title:i}){if(e==="dev-command"){if(r||n){let o=this.#m;if(o?.devCommandProcess?.resize)return o.devCommandProcess.resize(r,n),!0}return!1}let s=this.#v.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.#m;return i?.devCommandProcess?.write?(i.devCommandProcess.write(r),!0):!1}let n=this.#v.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.#m;return i?.devCommandProcess?.kill?(i.devCommandProcess.kill(r),!0):!1}let n=this.#v.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.#v.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.#v.delete(e),r&&this.#ye(),!0}async restartTerminal({terminalId:e}){if(e==="dev-command"){let i=this.#m;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.#m;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.#m)try{return await this.#Wt(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="bash-tools")return!1;let r=this.#v.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.#v.get(e)?(this.#ye(),!0):!1):!1}subscribeTerminal({terminalId:e,onData:r,onExit:n}){if(e==="dev-command"){let i=this.#m;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.#m;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.#m;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.#p.on("step",i),()=>{this.#p.off("step",i)}}else{let i=this.#v.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.#f,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.#f);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,x=v.data.lines.text.trimEnd(),w=v.data.submatches||[],P,G;w.length>0&&(P=w[0].start,G=w[0].end),m.add(D);let J={filePath:D,lineNumber:S,lineContent:x,columnStart:P,columnEnd:G,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#Ir(){let e=this.#Pe;if(e&&Date.now()-e.timestamp<t.#nt)return e.promise;let r=this.#u?.accessControl,n=cl({basePath:this.#F,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#Er(){let e=this.#Pe;if(e?.fuse)return e.fuse;let r=await this.#Ir(),n=Fhe(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.#Er()).search(r,{limit:n});return{matches:s.map(a=>{let{fullPath:A,basename:c,dirname:u}=a.item,l=khe(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)),Xhe(this.#e,r)}getSessionId(){return this.getSessionContext().sessionId}getMainSessionId(){return this.#_t??this.getSessionId()}updateMetadata(e){this.#Qt(e,!1)}getMetadata(){return this.#x}#st=null;setTimeline(e){this.#st=e}getTimeline(){return this.#st}getSpaceId(){return this.#a.builderPublicKey}async revertToCommitSnapshot(e){await this.waitUntilBlockingPendingPromises(),await this.abortMerge(!1),await this.#ie(!1);let n=(await this.#W(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.#t.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.#j();this.#_={...this.#_,...i},await this.#k(),this.requestRefresh(),await this.#Qe({lastCommit:xo(i)})}async revertToCommitHash(e){let r=fh(e,this.gitRepoContexts[0]?.folderName),n=Object.keys(r).length===0?e:xo(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.#W(async c=>{let u=al(e,c.folderName,this.gitRepoContexts[0]?.folderName);if(!u)return this.#t.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.#ot(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.#t.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.#t.debug(u)}let A=fh(e,this.gitRepoContexts[0]?.folderName);this.#_={...this.#_,...A},await this.#k(),r&&this.requestRefresh()}async resetToCommitHash(e,r=!0){let n=fh(e,this.gitRepoContexts[0]?.folderName),i=Object.keys(n).length===0?e:xo(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.#p.emit("step",{type:"batch",steps:[{type:"state",newState:"replay",abortable:!1,previousState:I},...this.#Vt(),{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e},{type:"state",newState:I,abortable:!1,previousState:"replay"}]})}else f.length>0&&this.#p.emit("step",{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e})}return await this.#Yt(),{undone:Array.from(u.keys()),message:"The restore operation was successful"}}async#Yt(e){return await this.#m?.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 uye(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.#yr({...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.#x,hasPlanToApply:this.#Ie,...e},this.#A);return this.#Lt&&this.#Br(),this.#K(n,"completionFinalize")}#Br(){try{let e=this.#e.getCwdDir(),r=this.getSessionId();if(this.#ft){e8(this.#e,e,r).catch(()=>{});return}let n=Pv(this.#e,e).then(i=>{if(i.some(l=>l.sessionId===r)){this.#ft=!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:_he(c);return Lhe(this.#e,e,r,u).then(()=>{this.#ft=!0})}).catch(()=>{});this.#K(n,"saveLocalHistory")}catch{}}#yr(e){let r=xB(this.#e,this.#a,"/codegen/feedback",e,this.#A);return this.#K(r,"completionFeedback")}#O(e,r,n={}){this.#m?.emitter.emit("metrics",{durations:[{key:e,ms:r,attributes:n}]})}#K(e,r,n=!1){let i=Go();this.#t.debug(`(addToPendingPromises-${i}): adding ${r} (blocking: ${n})`),this.#de.push(e),n&&this.#ze.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.#t.debug(`(addToPendingPromises-${i}): removing ${r} (blocking: ${n})`);let a=this.#ze.indexOf(e);a!==-1&&this.#ze.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}#Y(e){let r=this.getSessionContext(),n=r.state;return n!==e?(r.state=e,this.#p.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.#p.removeListener("step",o),n())};s=setTimeout(()=>{this.#p.removeListener("step",o),n()},r),this.#p.on("step",o)})}getProxyConfig(){return qie({devServerUrl:this.#u?.serverUrl,proxyOrigin:this.#$e,proxyDefaultOrigin:this.#Ve,proxyDestination:this.#Mt})}async clearSession(){this.#t.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.#it(),this.#$.length=0,this.#At=!1,this.#x={},this.#re=void 0,this.#Je=!1,this.#et=0,this.#he=null,this.#me=void 0,this.#Ze=[],this.clearMessageQueue(!1),this.queueGitStatusReminder({trigger:"session-start"}),this.#p.emit("step",this.#$t())}async clearMessageQueue(e=!1){let r=[],n=this.getSessionMode();if(e)for(let i of this.#i)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.#i.length=0,this.#Ge(),r.length>0&&this.#p.emit("step",{type:"batch",steps:r})}updateMessage(e){if(e.type==="delete"){let r=this.#i.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&this.#i.splice(r,1)}else if(e.type==="move"){let r=this.#i.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&Qye(this.#i,r,r+e.delta)}this.#Ge()}async flushMessageQueue(){this.#t.debug("(flushMessageQueue): flushing message queue"),await this.abort({cleanCurrentMessage:!1,flushMessageQueue:!0}),this.#n&&this.#n()}#qt(e){let r=e.idempotencyKey;if(r){let n=this.#i.findIndex(i=>i.idempotencyKey===r);if(n>=0)return this.#i[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=Uhe(n.proxyDefaultOrigin,this.#Re||void 0)}return this.#o.coalesce==="replace-latest"&&(this.#i.length=0),this.#i.push(e),!0}async sendMessage(e){this.#Je=!1;let r=this.#o.schedule,n=die(r)&&(this.#c!==void 0||this.#g!==void 0);if(r==="interrupt-clear"&&(this.#t.debug("(sendMessage): interrupt-clear schedule \u2014 clearing session"),await this.clearSession()),n&&r==="interrupt-replace"){this.#t.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.#qt(o)&&i++;else this.#qt(e)&&i++;if(i===0)return null;this.#t.debug(`(sendMessage): added messages(${i}) to queue(${this.#i.length})`),this.#Ge();let s=this.#i[this.#i.length-1];return s?(this.cancelAllPendingToolFulfilments(s.userPrompt),n&&this.#c&&(this.#t.debug(`(sendMessage): ${r} \u2014 aborting current run`),this.#c.abort(),this.#c=void 0),s.queue?this.#n&&this.#n():await this.flushMessageQueue(),await Sl(),s.idempotencyKey):null}#Qr(){if(this.#o.schedule==="until-idle")return;let e=this.#i;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.#g=b4(r),this.#re=this.#g.user,this.#g.softContextWindow&&(this.#S=Math.min(this.#S??3e4,this.#g.softContextWindow)),this.#o.coalesce==="preserve-order"?(this.#i.shift(),this.#Ge()):this.clearMessageQueue(!0),this.#g}#Dr(){let e=this.#i.length===0||this.#Je,r=new Promise(n=>{e?this.#n=n:n()}).then(()=>{let n=this.#i;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.#i.length=0),s.user&&!s.forceCompact){this.#re=s.user;let o=this.getSessionMode();this.#p.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.#g=s,this.#re=s.user,this.#g.softContextWindow&&(this.#S=Math.min(this.#S??3e4,this.#g.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.#g){let s=i.idempotencyKey;i=P4(this.#g,i),i.idempotencyKey=s}return this.clearMessageQueue(!0),this.#g=i,this.#re=i.user,i});return{shouldWait:e,promise:r}}#Ge(){this.#p.emit("step",{type:"message-queue",queue:this.#i.map(e=>({idempotencyKey:e.idempotencyKey,displayPrompt:e.displayPrompt,user:e.user}))})}#Qt(e,r=!1){r&&(this.#x={}),Object.assign(this.#x,e),this.#p.emit("step",{type:"metadata",...this.#x})}async waitForSetupCommand(e){let r=this.#m;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.#m&&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.#m;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.#pt,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.#m;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.#v.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.#v.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}#yt(){let e=this.getSessionContext(),r=Array.from(this.#v.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.#F,createdAt:e.createdUnixTime,lastWrittenAt:Date.now(),createdBy:"fusion",readonly:!0,builtIn:!0,exitCode:void 0,state:"running",command:void 0});let i=this.#m;if(i){let s=Date.now();if(i.devState!=="unset"&&n.push({terminalId:"dev-command",title:"Dev Command",cwd:this.#F,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.#F,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.#F,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.#p.emit("step",{type:"terminals",terminals:this.#yt()})}updateTerminal({terminalId:e,cols:r,rows:n,title:i}){if(e==="dev-command"){if(r||n){let o=this.#m;if(o?.devCommandProcess?.resize)return o.devCommandProcess.resize(r,n),!0}return!1}let s=this.#v.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.#m;return i?.devCommandProcess?.write?(i.devCommandProcess.write(r),!0):!1}let n=this.#v.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.#m;return i?.devCommandProcess?.kill?(i.devCommandProcess.kill(r),!0):!1}let n=this.#v.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.#v.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.#v.delete(e),r&&this.#ye(),!0}async restartTerminal({terminalId:e}){if(e==="dev-command"){let i=this.#m;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.#m;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.#m)try{return await this.#Wt(),!0}catch(s){return this.#e.Sentry?.captureException(s),!1}return!1}if(e==="bash-tools")return!1;let r=this.#v.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.#v.get(e)?(this.#ye(),!0):!1):!1}subscribeTerminal({terminalId:e,onData:r,onExit:n}){if(e==="dev-command"){let i=this.#m;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.#m;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.#m;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.#p.on("step",i),()=>{this.#p.off("step",i)}}else{let i=this.#v.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.#f,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.#f);for(let f of g)MH(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.#f,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.#H()?".":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.#F,stdio:["ignore","pipe","pipe"]}}),g=new Mi(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,x=v.data.lines.text.trimEnd(),w=v.data.submatches||[],P,G;w.length>0&&(P=w[0].start,G=w[0].end),m.add(D);let J={filePath:D,lineNumber:S,lineContent:x,columnStart:P,columnEnd:G,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#Ir(){let e=this.#Pe;if(e&&Date.now()-e.timestamp<t.#nt)return e.promise;let r=this.#u?.accessControl,n=cl({basePath:this.#F,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#Er(){let e=this.#Pe;if(e?.fuse)return e.fuse;let r=await this.#Ir(),n=Fhe(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.#Er()).search(r,{limit:n});return{matches:s.map(a=>{let{fullPath:A,basename:c,dirname:u}=a.item,l=khe(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)),Xhe(this.#e,r)}getSessionId(){return this.getSessionContext().sessionId}getMainSessionId(){return this.#_t??this.getSessionId()}updateMetadata(e){this.#Qt(e,!1)}getMetadata(){return this.#x}#st=null;setTimeline(e){this.#st=e}getTimeline(){return this.#st}getSpaceId(){return this.#a.builderPublicKey}async revertToCommitSnapshot(e){await this.waitUntilBlockingPendingPromises(),await this.abortMerge(!1),await this.#ie(!1);let n=(await this.#W(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.#t.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.#j();this.#_={...this.#_,...i},await this.#k(),this.requestRefresh(),await this.#Qe({lastCommit:xo(i)})}async revertToCommitHash(e){let r=fh(e,this.gitRepoContexts[0]?.folderName),n=Object.keys(r).length===0?e:xo(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.#W(async c=>{let u=al(e,c.folderName,this.gitRepoContexts[0]?.folderName);if(!u)return this.#t.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.#ot(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.#t.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.#t.debug(u)}let A=fh(e,this.gitRepoContexts[0]?.folderName);this.#_={...this.#_,...A},await this.#k(),r&&this.requestRefresh()}async resetToCommitHash(e,r=!0){let n=fh(e,this.gitRepoContexts[0]?.folderName),i=Object.keys(n).length===0?e:xo(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.#p.emit("step",{type:"batch",steps:[{type:"state",newState:"replay",abortable:!1,previousState:I},...this.#Vt(),{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e},{type:"state",newState:I,abortable:!1,previousState:"replay"}]})}else f.length>0&&this.#p.emit("step",{type:"restore",files:Array.from(u.keys()),lastCompletionId:C,location:e})}return await this.#Yt(),{undone:Array.from(u.keys()),message:"The restore operation was successful"}}async#Yt(e){return await this.#m?.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 uye(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.#yr({...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.#x,hasPlanToApply:this.#Ie,...e},this.#A);return this.#Lt&&this.#Br(),this.#K(n,"completionFinalize")}#Br(){try{let e=this.#e.getCwdDir(),r=this.getSessionId();if(this.#ft){e8(this.#e,e,r).catch(()=>{});return}let n=Pv(this.#e,e).then(i=>{if(i.some(l=>l.sessionId===r)){this.#ft=!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:_he(c);return Lhe(this.#e,e,r,u).then(()=>{this.#ft=!0})}).catch(()=>{});this.#K(n,"saveLocalHistory")}catch{}}#yr(e){let r=xB(this.#e,this.#a,"/codegen/feedback",e,this.#A);return this.#K(r,"completionFeedback")}#O(e,r,n={}){this.#m?.emitter.emit("metrics",{durations:[{key:e,ms:r,attributes:n}]})}#K(e,r,n=!1){let i=Go();this.#t.debug(`(addToPendingPromises-${i}): adding ${r} (blocking: ${n})`),this.#de.push(e),n&&this.#ze.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.#t.debug(`(addToPendingPromises-${i}): removing ${r} (blocking: ${n})`);let a=this.#ze.indexOf(e);a!==-1&&this.#ze.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}#Y(e){let r=this.getSessionContext(),n=r.state;return n!==e?(r.state=e,this.#p.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.#p.removeListener("step",o),n())};s=setTimeout(()=>{this.#p.removeListener("step",o),n()},r),this.#p.on("step",o)})}getProxyConfig(){return qie({devServerUrl:this.#u?.serverUrl,proxyOrigin:this.#$e,proxyDefaultOrigin:this.#Ve,proxyDestination:this.#Mt})}async clearSession(){this.#t.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.#it(),this.#$.length=0,this.#At=!1,this.#x={},this.#re=void 0,this.#Je=!1,this.#et=0,this.#he=null,this.#me=void 0,this.#Ze=[],this.clearMessageQueue(!1),this.queueGitStatusReminder({trigger:"session-start"}),this.#p.emit("step",this.#$t())}async clearMessageQueue(e=!1){let r=[],n=this.getSessionMode();if(e)for(let i of this.#i)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.#i.length=0,this.#Ge(),r.length>0&&this.#p.emit("step",{type:"batch",steps:r})}updateMessage(e){if(e.type==="delete"){let r=this.#i.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&this.#i.splice(r,1)}else if(e.type==="move"){let r=this.#i.findIndex(n=>n.idempotencyKey===e.idempotencyKey);r>=0&&Qye(this.#i,r,r+e.delta)}this.#Ge()}async flushMessageQueue(){this.#t.debug("(flushMessageQueue): flushing message queue"),await this.abort({cleanCurrentMessage:!1,flushMessageQueue:!0}),this.#n&&this.#n()}#qt(e){let r=e.idempotencyKey;if(r){let n=this.#i.findIndex(i=>i.idempotencyKey===r);if(n>=0)return this.#i[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=Uhe(n.proxyDefaultOrigin,this.#Re||void 0)}return this.#o.coalesce==="replace-latest"&&(this.#i.length=0),this.#i.push(e),!0}async sendMessage(e){this.#Je=!1;let r=this.#o.schedule,n=die(r)&&(this.#c!==void 0||this.#g!==void 0);if(r==="interrupt-clear"&&(this.#t.debug("(sendMessage): interrupt-clear schedule \u2014 clearing session"),await this.clearSession()),n&&r==="interrupt-replace"){this.#t.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.#qt(o)&&i++;else this.#qt(e)&&i++;if(i===0)return null;this.#t.debug(`(sendMessage): added messages(${i}) to queue(${this.#i.length})`),this.#Ge();let s=this.#i[this.#i.length-1];return s?(this.cancelAllPendingToolFulfilments(s.userPrompt),n&&this.#c&&(this.#t.debug(`(sendMessage): ${r} \u2014 aborting current run`),this.#c.abort(),this.#c=void 0),s.queue?this.#n&&this.#n():await this.flushMessageQueue(),await Sl(),s.idempotencyKey):null}#Qr(){if(this.#o.schedule==="until-idle")return;let e=this.#i;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.#g=bH(r),this.#re=this.#g.user,this.#g.softContextWindow&&(this.#S=Math.min(this.#S??3e4,this.#g.softContextWindow)),this.#o.coalesce==="preserve-order"?(this.#i.shift(),this.#Ge()):this.clearMessageQueue(!0),this.#g}#Dr(){let e=this.#i.length===0||this.#Je,r=new Promise(n=>{e?this.#n=n:n()}).then(()=>{let n=this.#i;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.#i.length=0),s.user&&!s.forceCompact){this.#re=s.user;let o=this.getSessionMode();this.#p.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.#g=s,this.#re=s.user,this.#g.softContextWindow&&(this.#S=Math.min(this.#S??3e4,this.#g.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.#g){let s=i.idempotencyKey;i=PH(this.#g,i),i.idempotencyKey=s}return this.clearMessageQueue(!0),this.#g=i,this.#re=i.user,i});return{shouldWait:e,promise:r}}#Ge(){this.#p.emit("step",{type:"message-queue",queue:this.#i.map(e=>({idempotencyKey:e.idempotencyKey,displayPrompt:e.displayPrompt,user:e.user}))})}#Qt(e,r=!1){r&&(this.#x={}),Object.assign(this.#x,e),this.#p.emit("step",{type:"metadata",...this.#x})}async waitForSetupCommand(e){let r=this.#m;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.#m&&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.#m;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.#pt,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.#m;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.#Qt({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.#t.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.#t.warn(`[${a}] Cleanup failed: ${U instanceof Error?U.message:String(U)}`)}if(s.resetAfterRun&&o)try{await this.resetToCommitHash(o,!1)}catch(U){this.#t.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.#M.has(e);return n||i}setSessionCanHandleTools(e){for(let r of e)this.#M.add(r)}clearSessionCanHandleTools(){this.#M.clear()}setProxyOrigin(e,r){if(e!==this.#$e||r!==this.#Ve){this.#$e=e,this.#Ve=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#wr(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.#r)throw new Error("Session context not initialized");return this.#r}async runSetupCommand(){return await this.#m?.runSetupCommand()}abortSetupCommand(){return this.#m?.abortSetupCommand()}abortValidateCommand(){return this.#m?.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)}#br(e){let r=this.getSessionId();if(!r)return;let n={name:e.name,input:e.input,messageValid:e.messageValid,createdAt:Date.now()};this.#x.pendingToolFulfilments||(this.#x.pendingToolFulfilments={}),this.#x.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.#Ke.set(e.id,i),i.finally(()=>{this.#Ke.get(e.id)===i&&this.#Ke.delete(e.id)})}async#Dt(e){let r=!!this.#x.pendingToolFulfilments?.[e]||this.#oe.has(e);if(this.#x.pendingToolFulfilments&&delete this.#x.pendingToolFulfilments[e],this.#oe.delete(e),!r)return;let n=this.getSessionId();if(!n)return;let i=this.#Ke.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.#Dt(e);let i=typeof r=="string"?r:r?.toolResult??"";return this.#t.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.#Dt(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=nn(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.#bt()){let e=this.getLinesStats();await this.sendFeedback({position:this.#w,acceptedLines:e.net,linesOfCodeAdded:e.added,linesOfCodeRemoved:e.removed})}}async abort(e){this.#A&&this.#t.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.#g=void 0,this.#et=0,this.clearMessageQueue()),this.#Je=!n,this.cancelAllPendingToolFulfilments(),this.#pe=0,this.#c?(this.#s=!0,this.#c.abort(),this.#c=void 0,this.getSessionContext().state==="generating"&&this.#Y("abort"),!0):!1}async stopEventLoop(){this.#t.info("Stopping event loop"),await this.abort({cleanCurrentMessage:!0}),this.#d?.abort(),this.#d=void 0,this.#n&&this.#n()}requestRefresh(){this.#p.emit("step",{type:"builder-action",action:"refresh",metadata:{}})}async configureDevOrchestrator(e){let r=this.#m,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.#mt(),{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.#v.values())(o.state==="running"||o.state==="starting")&&(o.stale=!0,s=!0);s&&this.#ye()}}return n}#vr(){for(let e of Array.from(this.#v.keys()))try{this.disposeTerminal({terminalId:e})}catch{}this.#v.clear()}async#wt(){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}}#Sr(){if(this.#Q.watcher)return;let e=this.#h.map(A=>A.path),r=new Map;for(let A of this.#h)r.set(A.path,
|
|
1906
|
+
${cw(this.#mt(),{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.#v.values())(o.state==="running"||o.state==="starting")&&(o.stale=!0,s=!0);s&&this.#ye()}}return n}#vr(){for(let e of Array.from(this.#v.keys()))try{this.disposeTerminal({terminalId:e})}catch{}this.#v.clear()}async#wt(){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}}#Sr(){if(this.#Q.watcher)return;let e=this.#h.map(A=>A.path),r=new Map;for(let A of this.#h)r.set(A.path,kH(A.path));let n=A=>{for(let c of this.#h)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.#zt(u))return!0;let l=r.get(c);return l?l(u):!1},s,o=!1;try{s=nye.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.#t.error(`Failed to initialize file watcher: ${A instanceof Error?A.message:String(A)}`),this.#t.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.#h.length>1&&u){let g=this.#h.find(p=>p.path===u);g&&!this.#H()&&(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.#t.error(`File watcher error: ${A instanceof Error?A.message:String(A)}`),this.#t.error("Closing file watcher to prevent further errors. File watching will be disabled."),this.#wt().catch(()=>{}))}),this.#Q.watcher=s,this.#t.debug(`Initialized global file watcher on: ${e.join(", ")}`)}subscribeToFileChanges(e){return this.#Q.listeners.size===0&&this.#Sr(),this.#Q.listeners.add(e),this.#t.debug(`Subscribed to file changes(${this.#Q.listeners.size} active listeners)`),async()=>{this.#Q.listeners.delete(e),this.#t.debug(`Unsubscribed from file changes(${this.#Q.listeners.size} remaining listeners)`),this.#Q.listeners.size===0&&this.#Q.watcher&&(await this.#wt(),this.#t.debug("Closed global file watcher (no more listeners)"))}}async tsServerInit(){try{return this.#l?{ok:!0,cwd:this.#f}:(this.#l=new Hv(this.#f),this.#l.setEventHandler(e=>{for(let r of this.#tt)r(e)}),await this.#l.start(),{ok:!0,cwd:this.#f})}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.#tt.add(e),()=>{this.#tt.delete(e)}}async close(e){if(this.#qe)return;if(this.#t.info("Closing code gen server",{reason:e?.reason}),this.#qe=!0,this.#b&&(delete process.env.DEBUG,this.#b=!1),this.#He.forEach(n=>n()),this.#vr(),await this.#wt(),this.#l&&(this.#l.dispose(),this.#l=null),this.#tt.clear(),this.#G)try{this.#t.debug("Cleaning up local MCP servers"),await this.#G.cleanup()}catch(n){this.#e.Sentry?.captureException(n,{level:"warning",tags:{operation:"local-mcp-cleanup"}})}await this.stopEventLoop(),await this.waitUntilState("close",5e3),this.#p.removeAllListeners(),await Promise.allSettled(this.#de);let r=e?.uploadGitBackup??!1;if(r){let n=await this.needsBackup();this.#A&&this.#t.debug(`Closing code gen server: ${JSON.stringify({uploadGitBackup:r,needsBackup:n})}`),n&&await this.uploadBackup()}else this.#A&&this.#t.debug(`Closing code gen server: ${JSON.stringify({uploadGitBackup:r})}`)}async#k(){if(this.#h.length===0||this.#Xe)return null;let r=(await this.#W(async i=>this.#Fr(i))).results.filter(i=>i.success&&i.result).map(i=>i.result);if(r.length===0)return null;for(let i of r)this.#p.emit("step",i);return this.#Oe=r,this.#K(this.#xr(r),"updateBranchUnpushedStatus",!1),r.some(i=>i.hasMergeConflict)&&await this.#De(),r[0]}async#xr(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.#t.error(`Failed to update branch unpushed status: ${i.status} ${i.statusText}`,{loggerOptions:{debug:!0}})}catch(n){this.#t.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.#Oe.length===0||this.#L)return;let r=this.#Oe.map(n=>wye(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.#j();Object.keys(n).length>0&&(r.beforeCommit=xo(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.#Ct(!0,"all");return e=this.getSessionContext(),e.state!=="generating"&&e.state!=="close"?(this.#Ae=r,this.#p.emit("step",{type:"wait-for-input",id:this.getLastCompletionId()??"initial",state:e.state,suggestion:r,sessionMode:e.sessionMode,hasPlanToApply:this.#Ie,modelOverride:this.#V}),!0):!1}async#Fr(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.#h[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.#bt(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.#at(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.#Ur(s);return{type:"git",folderName:e.folderName,remoteBranchExists:A,remoteBranchHasChanges:c,hasGeneratingPlaceholder:await this.#Lr(),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--}}#$t(){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}}#Vt(){let e=this.getSessionContext(),r=e.turns,n=[];n.push(this.#$t()),Object.keys(this.#x).length>0&&n.push({type:"metadata",...this.#x}),this.#i.length>0&&n.push({type:"message-queue",queue:this.#i.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.#Oe),s.push(...this.#Vt()),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.#yt()});let A=this.#m;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.#p.on("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)+1);return this.waitForEventLoop(),()=>{this.#p.off("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)-1)}}waitUntilPendingPromises(e){let r=Go();return this.#t.debug(`(waitUntilPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#de),e).then(()=>Sl()).then(()=>{this.#t.debug(`(waitUntilPendingPromises-${r}): finished`)})}waitUntilBlockingPendingPromises(e){let r=Go();return this.#t.debug(`(waitUntilBlockingPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#ze),e).then(()=>Sl()).then(()=>{this.#t.debug(`(waitUntilBlockingPendingPromises-${r}): finished`)})}waitUntilIdle(e){let r=Go();return this.waitForEventLoop(),this.#t.debug(`(waitUntilIdle-${r}): started`),Wc(Sl().then(()=>this.waitUntilPendingPromises()).then(()=>{let n=this.getSessionContext();return this.#t.debug(`(waitUntilIdle-${r}): starting in ${n.state} `),n.state==="generating"?(0,cx.once)(this.#p,"idle"):Promise.resolve(void 0)}).then(()=>this.waitUntilPendingPromises()).then(()=>{this.#t.debug(`(waitUntilIdle-${r}): idle reached in ${this.getSessionContext().state} `)}),e)}async#Wt(e){let r=this.#m;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.#Et()).length===0&&(await this.#ot()||await this.manualCommit({add:".",commitMessage:"Validate command fixes"}))),n}waitForEventLoop(){return this.#ae?this.#ae:this.#ae=this.#kr()}async#kr(){if(this.#ae||this.#d)throw new Error("Event loop already started");this.#t.debug("(eventLoop): started");let e=Iye(),r=c=>{c.type==="error"&&this.#pe>0&&(rye.includes(c.code)||(c.restoreCredits=this.#pe,this.#pe=0,gye(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.#t.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.#t.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.#p.emit("step",c)};this.#d=new AbortController;let n=this.#d.signal,i=this.#m,s=this.getSessionContext(),o=()=>this.getLastCompletionId();this.#e.Sentry?.setContext("codeGen",{sessionId:s.sessionId,get completionId(){return o()}}),await this.#K(this.#k(),"initial-emitGitStatus");let a=setInterval(()=>{this.canHandleTool("GetScreenshot")&&(this.#xe>0||this.#k().catch(()=>{}))},6e4),A=()=>clearInterval(a);if(this.#He.push(A),process.env.FUSION_IDE_PORT){let c=setInterval(()=>{Vie().then(u=>{let l=JSON.stringify(u);l!==this.#St&&(this.#St=l,this.#p.emit("step",{type:"ide",context:u}),this.queueSystemReminder({text:u?zie(u):"",tag:"reminder:ide-context"}))}).catch(()=>{})},1e3);this.#He.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.#Dr();if(this.#t.debug(`(eventLoop-${c}): started (shouldWait: ${u.shouldWait})`),u.shouldWait){await this.#Yt();let g=await this.#De();if(n.aborted)break;g&&yye(u.promise,500).then(p=>{p&&(this.#t.debug(`(eventLoop-${c}): emitting idle on next message wait`),this.#p.emit("idle"))})}let l=await u.promise;if(n.aborted)break;if(!l)continue;this.#c=new AbortController,this.#s=!1;let d=Dn([n,this.#c.signal]);try{if(this.#Ae=void 0,l.logsCheckpoint&&i?.addCheckpoint(),d?.aborted)throw nn(d.reason);this.#Y("generating"),i?.abortValidateCommand();let g=l.syncChanges??this.#We;g&&(this.#t.debug(`(eventLoop-${c}): syncing changes from remote`),await this.syncChangesFromRemote(g),await this.#Ct(!1,"critical")),l.sessionMode&&l.sessionMode!==s.sessionMode&&this.switchSessionMode(l.sessionMode),await this.#Rr(l,d,r),this.#s||this.#Y("success");let p=this.#s?"none":l.autoPush??this.#q??"none";if(p!=="none"&&this.#I&&(this.#t.debug(`(eventLoop-${c}): autoPush: ${p}`),await this.waitUntilBlockingPendingPromises(),(await this.#Et()).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.#h.length>1)for(let C of this.#h)await this.#Ue({...m,folderName:C.folderName});else await this.#Ue(m)}this.#Ae=void 0}catch(g){g instanceof Error?g.name==="AbortError"||this.#s?(r({type:"user-abort",hasContinueMessage:this.#i.length>0}),this.#Y("abort")):g instanceof qe?(this.#g=void 0,r({type:"error",code:"cli-network-error",message:g.message}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#Y("error")):g instanceof dt?(this.#g=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.#Y("error")):g instanceof ai?(this.#g=void 0,r({type:"error",code:g.code,message:g.message}),rye.includes(g.code)||this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#Y("error")):(this.#g=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.#Y("error")):this.#Y(this.#s?"abort":"error")}this.#Xt++}}catch(c){throw this.#e.Sentry?.captureException(c,{level:"fatal"}),c}finally{A(),this.#d=void 0,this.#ae=void 0,e()}this.#t.debug("(eventLoop): emitting idle on close"),this.#p.emit("idle"),this.#Y("close")}async#Rr(e,r,n){this.#pe=0,this.#ne=!1;let i=this.getSessionContext(),s=e.displayPrompt||e.userPrompt||"";s&&this.#Ze.push(s);let o;if(e.agentType&&e.agentType!==this.#L){let Q=await this.getNamedAgentConfig(e.agentType,this.getSessionId(),r);Q.success&&(o={enabledTools:this.#D,modelOverride:this.#V,systemPromptOverride:this.#ce,position:this.#w,includeMemories:this.#R},this.#D=Q.options.enabledTools,this.#V=Q.options.modelOverride,this.#ce=Q.options.systemPromptOverride,this.#w=Q.options.position,this.#R=Q.options.includeMemories)}let a=e.maxCompletions??this.#u?.maxAgentCompletions,A=a??ux,c=a??aye,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.#t.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 nn(r.reason);try{if(this.cancelAllPendingToolFulfilments(),m||(m=await this.#Mr(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.#Tr(i,m,r,n),{shouldContinue:D,completions:S,filesChanged:x}=v;if(this.#A&&this.#t.debug(`(agentCompletion-${B}): completion: ${JSON.stringify(v)}`),d=!1,m=void 0,u=0,g||=x,p||=x,f||=v.navigatePreviewCalled,l+=S,this.#ne||=x,this.#g=void 0,x&&this.#m?.addCheckpoint(),r?.aborted)throw nn(r.reason);let w=this.#Qr();if(w){let G=w.syncChanges??this.#We;G&&await this.syncChangesFromRemote(G)}let{hasHealthIssue:P}=await this.#or();if(w){this.#t.debug(`(agentCompletion-${B}): consumed queued messages`),d=!0,e=w,l=0;continue}if(!D){if(r?.aborted)throw nn(r.reason);let G=this.getSessionMode();if((G==="planning"||G==="auto-planning")&&!this.#Ie&&!y&&I<3){this.#t.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.#t.debug(`(agentCompletion-${B}): has health issue, continuing`),I++;continue}let J=this.#m,_=e.runValidateCommand??!0;if(J?.validateCommand&&_&&C<2&&this.#ne&&G==="normal"){p=!0,C++,n({type:"start",name:"validate-command",id:"validate-command",title:"Validate Command",content:""});let K=e.autoPush;this.#t.debug(`(agentCompletion-${B}): running validate command`),this.#Wt(r).then(j=>{if(this.#t.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.#j();Object.keys(n).length>0&&(r.beforeCommit=xo(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.#Ct(!0,"all");return e=this.getSessionContext(),e.state!=="generating"&&e.state!=="close"?(this.#Ae=r,this.#p.emit("step",{type:"wait-for-input",id:this.getLastCompletionId()??"initial",state:e.state,suggestion:r,sessionMode:e.sessionMode,hasPlanToApply:this.#Ie,modelOverride:this.#V}),!0):!1}async#Fr(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.#h[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.#bt(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.#at(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.#Ur(s);return{type:"git",folderName:e.folderName,remoteBranchExists:A,remoteBranchHasChanges:c,hasGeneratingPlaceholder:await this.#Lr(),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--}}#$t(){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}}#Vt(){let e=this.getSessionContext(),r=e.turns,n=[];n.push(this.#$t()),Object.keys(this.#x).length>0&&n.push({type:"metadata",...this.#x}),this.#i.length>0&&n.push({type:"message-queue",queue:this.#i.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.#Oe),s.push(...this.#Vt()),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.#yt()});let A=this.#m;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.#p.on("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)+1);return this.waitForEventLoop(),()=>{this.#p.off("step",r);for(let s of i)this.#J.set(s,(this.#J.get(s)??0)-1)}}waitUntilPendingPromises(e){let r=Go();return this.#t.debug(`(waitUntilPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#de),e).then(()=>Sl()).then(()=>{this.#t.debug(`(waitUntilPendingPromises-${r}): finished`)})}waitUntilBlockingPendingPromises(e){let r=Go();return this.#t.debug(`(waitUntilBlockingPendingPromises-${r}): started`),Wc(Promise.allSettled(this.#ze),e).then(()=>Sl()).then(()=>{this.#t.debug(`(waitUntilBlockingPendingPromises-${r}): finished`)})}waitUntilIdle(e){let r=Go();return this.waitForEventLoop(),this.#t.debug(`(waitUntilIdle-${r}): started`),Wc(Sl().then(()=>this.waitUntilPendingPromises()).then(()=>{let n=this.getSessionContext();return this.#t.debug(`(waitUntilIdle-${r}): starting in ${n.state} `),n.state==="generating"?(0,cx.once)(this.#p,"idle"):Promise.resolve(void 0)}).then(()=>this.waitUntilPendingPromises()).then(()=>{this.#t.debug(`(waitUntilIdle-${r}): idle reached in ${this.getSessionContext().state} `)}),e)}async#Wt(e){let r=this.#m;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.#Et()).length===0&&(await this.#ot()||await this.manualCommit({add:".",commitMessage:"Validate command fixes"}))),n}waitForEventLoop(){return this.#ae?this.#ae:this.#ae=this.#kr()}async#kr(){if(this.#ae||this.#d)throw new Error("Event loop already started");this.#t.debug("(eventLoop): started");let e=Iye(),r=c=>{c.type==="error"&&this.#pe>0&&(rye.includes(c.code)||(c.restoreCredits=this.#pe,this.#pe=0,gye(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.#t.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.#t.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.#p.emit("step",c)};this.#d=new AbortController;let n=this.#d.signal,i=this.#m,s=this.getSessionContext(),o=()=>this.getLastCompletionId();this.#e.Sentry?.setContext("codeGen",{sessionId:s.sessionId,get completionId(){return o()}}),await this.#K(this.#k(),"initial-emitGitStatus");let a=setInterval(()=>{this.canHandleTool("GetScreenshot")&&(this.#xe>0||this.#k().catch(()=>{}))},6e4),A=()=>clearInterval(a);if(this.#He.push(A),process.env.FUSION_IDE_PORT){let c=setInterval(()=>{Vie().then(u=>{let l=JSON.stringify(u);l!==this.#St&&(this.#St=l,this.#p.emit("step",{type:"ide",context:u}),this.queueSystemReminder({text:u?zie(u):"",tag:"reminder:ide-context"}))}).catch(()=>{})},1e3);this.#He.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.#Dr();if(this.#t.debug(`(eventLoop-${c}): started (shouldWait: ${u.shouldWait})`),u.shouldWait){await this.#Yt();let g=await this.#De();if(n.aborted)break;g&&yye(u.promise,500).then(p=>{p&&(this.#t.debug(`(eventLoop-${c}): emitting idle on next message wait`),this.#p.emit("idle"))})}let l=await u.promise;if(n.aborted)break;if(!l)continue;this.#c=new AbortController,this.#s=!1;let d=Dn([n,this.#c.signal]);try{if(this.#Ae=void 0,l.logsCheckpoint&&i?.addCheckpoint(),d?.aborted)throw nn(d.reason);this.#Y("generating"),i?.abortValidateCommand();let g=l.syncChanges??this.#We;g&&(this.#t.debug(`(eventLoop-${c}): syncing changes from remote`),await this.syncChangesFromRemote(g),await this.#Ct(!1,"critical")),l.sessionMode&&l.sessionMode!==s.sessionMode&&this.switchSessionMode(l.sessionMode),await this.#Rr(l,d,r),this.#s||this.#Y("success");let p=this.#s?"none":l.autoPush??this.#q??"none";if(p!=="none"&&this.#I&&(this.#t.debug(`(eventLoop-${c}): autoPush: ${p}`),await this.waitUntilBlockingPendingPromises(),(await this.#Et()).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.#h.length>1)for(let C of this.#h)await this.#Ue({...m,folderName:C.folderName});else await this.#Ue(m)}this.#Ae=void 0}catch(g){g instanceof Error?g.name==="AbortError"||this.#s?(r({type:"user-abort",hasContinueMessage:this.#i.length>0}),this.#Y("abort")):g instanceof qe?(this.#g=void 0,r({type:"error",code:"cli-network-error",message:g.message}),this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#Y("error")):g instanceof dt?(this.#g=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.#Y("error")):g instanceof ai?(this.#g=void 0,r({type:"error",code:g.code,message:g.message}),rye.includes(g.code)||this.#e.Sentry?.captureException(g,{tags:{operation:"codegen-stream"}}),this.#Y("error")):(this.#g=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.#Y("error")):this.#Y(this.#s?"abort":"error")}this.#Xt++}}catch(c){throw this.#e.Sentry?.captureException(c,{level:"fatal"}),c}finally{A(),this.#d=void 0,this.#ae=void 0,e()}this.#t.debug("(eventLoop): emitting idle on close"),this.#p.emit("idle"),this.#Y("close")}async#Rr(e,r,n){this.#pe=0,this.#ne=!1;let i=this.getSessionContext(),s=e.displayPrompt||e.userPrompt||"";s&&this.#Ze.push(s);let o;if(e.agentType&&e.agentType!==this.#L){let Q=await this.getNamedAgentConfig(e.agentType,this.getSessionId(),r);Q.success&&(o={enabledTools:this.#D,modelOverride:this.#V,systemPromptOverride:this.#ce,position:this.#w,includeMemories:this.#R},this.#D=Q.options.enabledTools,this.#V=Q.options.modelOverride,this.#ce=Q.options.systemPromptOverride,this.#w=Q.options.position,this.#R=Q.options.includeMemories)}let a=e.maxCompletions??this.#u?.maxAgentCompletions,A=a??ux,c=a??aye,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.#t.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 nn(r.reason);try{if(this.cancelAllPendingToolFulfilments(),m||(m=await this.#Mr(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.#Tr(i,m,r,n),{shouldContinue:D,completions:S,filesChanged:x}=v;if(this.#A&&this.#t.debug(`(agentCompletion-${B}): completion: ${JSON.stringify(v)}`),d=!1,m=void 0,u=0,g||=x,p||=x,f||=v.navigatePreviewCalled,l+=S,this.#ne||=x,this.#g=void 0,x&&this.#m?.addCheckpoint(),r?.aborted)throw nn(r.reason);let w=this.#Qr();if(w){let G=w.syncChanges??this.#We;G&&await this.syncChangesFromRemote(G)}let{hasHealthIssue:P}=await this.#or();if(w){this.#t.debug(`(agentCompletion-${B}): consumed queued messages`),d=!0,e=w,l=0;continue}if(!D){if(r?.aborted)throw nn(r.reason);let G=this.getSessionMode();if((G==="planning"||G==="auto-planning")&&!this.#Ie&&!y&&I<3){this.#t.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.#t.debug(`(agentCompletion-${B}): has health issue, continuing`),I++;continue}let J=this.#m,_=e.runValidateCommand??!0;if(J?.validateCommand&&_&&C<2&&this.#ne&&G==="normal"){p=!0,C++,n({type:"start",name:"validate-command",id:"validate-command",title:"Validate Command",content:""});let K=e.autoPush;this.#t.debug(`(agentCompletion-${B}): running validate command`),this.#Wt(r).then(j=>{if(this.#t.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.#H()&&r.length>0)if(this.#h.length>1)n=`Notice: This is a multi-repo workspace with folders: ${this.#h.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}}#_r(){return["status","--porcelain=v1","-z","--ignore-submodules=dirty"]}async#ot(e){try{let r=this.#_r();return(await this.git(r,{cwd:e})).trim().length===0}catch{return!1}}async#Ur(e){try{return await this.git(["diff","--cached","--quiet"],{cwd:e}),!1}catch{return!0}}async#Gr(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.#Zt.add(o),i.push(o))}}catch(o){e.Sentry?.captureException(o)}return i}#H(){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}: ${Uo(e)}`);return lme({filePath:e,forceWorkspace:r,workspace:this.#C,workingDirectory:this.#f,sys:this.#e,canCollapseWorkspace:this.#H()})}#z(){try{let e=this.getSessionContext();return Fa(e.turns)?.user.principals}catch{return}}absolutePathToWorkspaceUrl(e){return gme({absolutePath:e,workspace:this.#C,workingDirectory:this.#f,sys:this.#e,canCollapseWorkspace:this.#H()})}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}: ${Uo(e)}`);if(!r){let n=Co(pi(e),"read",this.#u?.accessControl,this.#z());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.#f,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=Co(pi(e),"read",this.#u?.accessControl,this.#z());if(!r.allowed)throw new dt(`ACL denied: ${r.message}`);try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(!ll({resolvedPath:n,workingDirectory:this.#f,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.#f,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#at(e){let r;e?r=this.#h.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#vt(e){let r=this.#Te.get(e);if(r&&Date.now()-r.timestamp<t.#nt)return r.promise;let n=(async()=>{let i=await this.#at(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.#f,s=e,i&&u.startsWith(i)&&(s=u.substring(i.length),s.startsWith("/")&&(s=s.substring(1)))}let o=r??await this.#vt(i),a=`${i}:${o}:${s}`,A=this.#Me.get(a);if(A&&Date.now()-A.timestamp<t.#nt)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#Or(e){let r=this.#Ne.get(e);if(r&&Date.now()-r.timestamp<t.#nt)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.#vt(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#Kr(e,r){return r==="remote-current-branch"?this.#Or(e):this.#vt(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}: ${Uo(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}: ${Uo(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.#Ot(r.path,r.folderName),a=this.#e.join(s,o),A=this.#I?await this.#Kr(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.#Ot(r.filePath,r.folderName),s=this.#e.join(n,i),o=await this.#at(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.#k()}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.#k()}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.#k()}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}: ${Uo(e)}`);let r=n=>n.startsWith(this.#f)?this.#e.relative(this.#f,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=Co(pi(e),"read",this.#u?.accessControl,this.#z());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}: ${Uo(e)}`);if(!n){let i=Co(pi(e),"write",this.#u?.accessControl,this.#z());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.#f,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}: ${Uo(e)}`);let r=Co(pi(e),"list",this.#u?.accessControl,this.#z());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.#f,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,iye.readdir)(n,{withFileTypes:!0})).map(c=>c.name+(c.isDirectory()?"/":""));if(this.#H()){let c=A.map(u=>wn(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=wn(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}: ${Uo(e)}`);if(!r){let n=Co(pi(e),"read",this.#u?.accessControl,this.#z());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}#Hr(e){let r=wn(this.#e.resolve(e)),n=this.absolutePathToWorkspaceUrl(r);return n!==void 0?wn(n):wn(this.#e.relative(this.#f,r))}async#Jr(e){let r=[],n=async i=>{let s=this.#e.resolve(i);if(!ll({resolvedPath:s,workingDirectory:this.#f,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}: ${Uo(e)}`);if(!r){let n=Co(pi(e),"write",this.#u?.accessControl,this.#z());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.#f,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.#Jr(n);for(let o of s){let a=Co(this.#Hr(o),"write",this.#u?.accessControl,this.#z());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.#r?.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.#t.warn("No git remotes configured, cannot get diff from remote"),d}if(!a){this.#t.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.#t.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.#t.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.#t.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.#t.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.#rt.get(r);if(n)return n;let i=this.#jr(e).catch(s=>{throw this.#rt.get(r)===i&&this.#rt.delete(r),s});return this.#rt.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.#at(s),A;try{A=(await this.git(["merge-base",a,"HEAD"],{cwd:s})).trim()}catch(l){throw l instanceof Oo&&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}}#_r(){return["status","--porcelain=v1","-z","--ignore-submodules=dirty"]}async#ot(e){try{let r=this.#_r();return(await this.git(r,{cwd:e})).trim().length===0}catch{return!1}}async#Ur(e){try{return await this.git(["diff","--cached","--quiet"],{cwd:e}),!1}catch{return!0}}async#Gr(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.#Zt.add(o),i.push(o))}}catch(o){e.Sentry?.captureException(o)}return i}#H(){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}: ${Uo(e)}`);return lme({filePath:e,forceWorkspace:r,workspace:this.#C,workingDirectory:this.#f,sys:this.#e,canCollapseWorkspace:this.#H()})}#z(){try{let e=this.getSessionContext();return Fa(e.turns)?.user.principals}catch{return}}absolutePathToWorkspaceUrl(e){return gme({absolutePath:e,workspace:this.#C,workingDirectory:this.#f,sys:this.#e,canCollapseWorkspace:this.#H()})}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}: ${Uo(e)}`);if(!r){let n=Co(pi(e),"read",this.#u?.accessControl,this.#z());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.#f,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=Co(pi(e),"read",this.#u?.accessControl,this.#z());if(!r.allowed)throw new dt(`ACL denied: ${r.message}`);try{let{resolvedPath:n}=this.resolveWorkspacePath(e,!1);if(!ll({resolvedPath:n,workingDirectory:this.#f,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.#f,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#at(e){let r;e?r=this.#h.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#vt(e){let r=this.#Te.get(e);if(r&&Date.now()-r.timestamp<t.#nt)return r.promise;let n=(async()=>{let i=await this.#at(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.#f,s=e,i&&u.startsWith(i)&&(s=u.substring(i.length),s.startsWith("/")&&(s=s.substring(1)))}let o=r??await this.#vt(i),a=`${i}:${o}:${s}`,A=this.#Me.get(a);if(A&&Date.now()-A.timestamp<t.#nt)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#Or(e){let r=this.#Ne.get(e);if(r&&Date.now()-r.timestamp<t.#nt)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.#vt(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#Kr(e,r){return r==="remote-current-branch"?this.#Or(e):this.#vt(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}: ${Uo(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}: ${Uo(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.#Ot(r.path,r.folderName),a=this.#e.join(s,o),A=this.#I?await this.#Kr(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.#Ot(r.filePath,r.folderName),s=this.#e.join(n,i),o=await this.#at(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.#k()}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.#k()}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.#k()}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}: ${Uo(e)}`);let r=n=>n.startsWith(this.#f)?this.#e.relative(this.#f,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=Co(pi(e),"read",this.#u?.accessControl,this.#z());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}: ${Uo(e)}`);if(!n){let i=Co(pi(e),"write",this.#u?.accessControl,this.#z());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.#f,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}: ${Uo(e)}`);let r=Co(pi(e),"list",this.#u?.accessControl,this.#z());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.#f,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,iye.readdir)(n,{withFileTypes:!0})).map(c=>c.name+(c.isDirectory()?"/":""));if(this.#H()){let c=A.map(u=>wn(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=wn(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}: ${Uo(e)}`);if(!r){let n=Co(pi(e),"read",this.#u?.accessControl,this.#z());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}#Hr(e){let r=wn(this.#e.resolve(e)),n=this.absolutePathToWorkspaceUrl(r);return n!==void 0?wn(n):wn(this.#e.relative(this.#f,r))}async#Jr(e){let r=[],n=async i=>{let s=this.#e.resolve(i);if(!ll({resolvedPath:s,workingDirectory:this.#f,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}: ${Uo(e)}`);if(!r){let n=Co(pi(e),"write",this.#u?.accessControl,this.#z());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.#f,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.#Jr(n);for(let o of s){let a=Co(this.#Hr(o),"write",this.#u?.accessControl,this.#z());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.#r?.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.#t.warn("No git remotes configured, cannot get diff from remote"),d}if(!a){this.#t.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.#t.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.#t.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.#t.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.#t.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.#rt.get(r);if(n)return n;let i=this.#jr(e).catch(s=>{throw this.#rt.get(r)===i&&this.#rt.delete(r),s});return this.#rt.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.#at(s),A;try{A=(await this.git(["merge-base",a,"HEAD"],{cwd:s})).trim()}catch(l){throw l instanceof Oo&&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()===""?[]:uH(u,r)}catch(o){throw o instanceof Tp||this.#t.error("getDiffFromParentBranch error:",o),o}}},DH=(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 Nft(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 bye(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 Nft(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 Nft(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 bye(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 Nft(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,LH.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,LH.exit)(1);let g=d.trim();/^\d+$/.test(g)?i.serverUrl=`http://localhost:${g}`:i.serverUrl=new URL(g).href}await _H(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 _H(t,e,r){let n=await bye(t,r);await t.writeFile(n,JSON.stringify(Mft(e,"workingDirectory","projectId","authenticateProxy","privacyMode"),null,2))}function vye(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 LH,bye,Mft,NB=L(()=>{"use strict";h();Js();rr();LH=require("process");Ap();bye=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])},Mft=(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 Lft(t){let e=[".npm",".local",".cache"];try{let r=`/${t}`,n=`/${t}-backup`;if(ti.existsSync(n)){let i=ti.readdirSync(n);for(let s of i)if(!e.includes(s)){let o=Bi.join(r,s);if(!ti.existsSync(o))try{ti.cpSync(Bi.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 ti,ri,Bi,U4,xye,px,G4,Pft,Sye,em,O4=L(()=>{"use strict";h();ti=z(require("node:fs"),1),ri=z(require("fs/promises"),1),Bi=z(require("node:path"),1);fa();Ic();Js();U4=z(require("dns/promises"),1);Bt();xye=z(require("net"),1),px=require("undici");Ov();Fo();Ap();Fo();G4=ve("Init"),Pft=t=>!!(t.name&&t.path),Sye=t=>!!(t.name&&t.path&&t.repoName&&t.repoUrl),em=class{logIdCounter=0;initStatusLogs=[];sys;config;debug=!0;#r=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 zs(e,r,{cwd:n,sys:this.sys,retry:i})}async git(e,r,n,i,s){return zs("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.#r.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=Bi.join(i,p.path);if(!ti.existsSync(f))throw new Error(`Backup mode: Repository directory does not exist at ${f}`);if(!ti.existsSync(Bi.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 zs("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.#r.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.#r.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(Pft)??[];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.#r.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.#r.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.#r.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.#r.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(ti.existsSync(e))try{let n=(await ri.readdir(e)).length>0,i=ti.existsSync(Bi.join(e,".git"));return n&&!i}catch{return!1}return!1}async step1CheckDirectories(e,r){this.addInitLog("log","Checking directories",{step:"check-directories"}),ti.existsSync(e)||await ri.mkdir(e,{recursive:!0}),e.startsWith("/root")&&Lft("root"),this.addInitLog("log",`Volume directory exists: ${e}`,{step:"check-directories"});for(let n of r){let i=Bi.join(e,n.path);if(ti.existsSync(i))this.addInitLog("log",`Directory already exists: ${i}`,{step:"check-directories"});else{this.addInitLog("log",`Creating directory: ${i}`,{step:"create-directories"});try{await ri.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=Bi.join(e,"temp-cloning"),i=async()=>{ti.existsSync(n)&&(this.addInitLog("log",`Removing temp cloning directory: ${n}`,{step:"configure-git-repos"}),await ri.rm(n,{recursive:!0,force:!0}))};await i(),this.addInitLog("log",`Creating temp cloning path: ${n}`,{step:"configure-git-repos"}),await ri.mkdir(n,{recursive:!0});let s=await this.fetchGitConfigsOnce(),o=r.find(a=>a.enableGit);try{for(let a of r){let A=Bi.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 ri.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(!Sye(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=Bi.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(!Sye(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"&&ti.existsSync(A)){if((await ri.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 ri.rm(A,{recursive:!0,force:!0})}await ri.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=Bi.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=Bi.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=xye.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=Bi.dirname(e);return await ri.mkdir(r,{recursive:!0}),r}async cleanupLockFiles(e){let r=Bi.join(e,".git");try{let i=(await ri.readdir(r)).filter(o=>o.endsWith(".lock"));if(i.length===0)return;let s=[];for(let o of i){let a=Bi.join(r,o);try{await ri.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])},Mft=(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 Lft(t){let e=[".npm",".local",".cache"];try{let r=`/${t}`,n=`/${t}-backup`;if(ti.existsSync(n)){let i=ti.readdirSync(n);for(let s of i)if(!e.includes(s)){let o=Bi.join(r,s);if(!ti.existsSync(o))try{ti.cpSync(Bi.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 ti,ri,Bi,UH,xye,px,GH,Pft,Sye,em,OH=L(()=>{"use strict";h();ti=z(require("node:fs"),1),ri=z(require("fs/promises"),1),Bi=z(require("node:path"),1);fa();Ic();Js();UH=z(require("dns/promises"),1);Bt();xye=z(require("net"),1),px=require("undici");Ov();Fo();Ap();Fo();GH=ve("Init"),Pft=t=>!!(t.name&&t.path),Sye=t=>!!(t.name&&t.path&&t.repoName&&t.repoUrl),em=class{logIdCounter=0;initStatusLogs=[];sys;config;debug=!0;#r=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 zs(e,r,{cwd:n,sys:this.sys,retry:i})}async git(e,r,n,i,s){return zs("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.#r.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=Bi.join(i,p.path);if(!ti.existsSync(f))throw new Error(`Backup mode: Repository directory does not exist at ${f}`);if(!ti.existsSync(Bi.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 zs("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.#r.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.#r.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(Pft)??[];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.#r.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.#r.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.#r.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.#r.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(ti.existsSync(e))try{let n=(await ri.readdir(e)).length>0,i=ti.existsSync(Bi.join(e,".git"));return n&&!i}catch{return!1}return!1}async step1CheckDirectories(e,r){this.addInitLog("log","Checking directories",{step:"check-directories"}),ti.existsSync(e)||await ri.mkdir(e,{recursive:!0}),e.startsWith("/root")&&Lft("root"),this.addInitLog("log",`Volume directory exists: ${e}`,{step:"check-directories"});for(let n of r){let i=Bi.join(e,n.path);if(ti.existsSync(i))this.addInitLog("log",`Directory already exists: ${i}`,{step:"check-directories"});else{this.addInitLog("log",`Creating directory: ${i}`,{step:"create-directories"});try{await ri.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=Bi.join(e,"temp-cloning"),i=async()=>{ti.existsSync(n)&&(this.addInitLog("log",`Removing temp cloning directory: ${n}`,{step:"configure-git-repos"}),await ri.rm(n,{recursive:!0,force:!0}))};await i(),this.addInitLog("log",`Creating temp cloning path: ${n}`,{step:"configure-git-repos"}),await ri.mkdir(n,{recursive:!0});let s=await this.fetchGitConfigsOnce(),o=r.find(a=>a.enableGit);try{for(let a of r){let A=Bi.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 ri.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(!Sye(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=Bi.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(!Sye(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"&&ti.existsSync(A)){if((await ri.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 ri.rm(A,{recursive:!0,force:!0})}await ri.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=Bi.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=Bi.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=xye.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=Bi.dirname(e);return await ri.mkdir(r,{recursive:!0}),r}async cleanupLockFiles(e){let r=Bi.join(e,".git");try{let i=(await ri.readdir(r)).filter(o=>o.endsWith(".lock"));if(i.length===0)return;let s=[];for(let o of i){let a=Bi.join(r,o);try{await ri.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(ti.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&&(ti.rmSync(Bi.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 ri.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 _ft(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 Fye(t){try{let e=new URL(t);return e.username||e.password?(e.username="",e.password="",e.toString()):t}catch{return"<repo>"}}async function kye(t,e,r,n){let{url:i,localDir:s}=r;if(!r.connectedProjectId&&!NL.test(i)){n(`skip clone \u2014 refusing non-github URL: ${Fye(i)}`);return}let o=t.join(e,s);if(await t.exists(o)){n(`skip clone \u2014 ${s} already present`);return}n(`cloning ${Fye(i)} \u2192 sources/${s}`);try{await zs("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 Rye(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=_ft(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 kye(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 kye(e,o,u.manifest.githubRepo,s),{written:u.files.length,skipped:!1,sourcesDir:o}}var Np,kl,Tye=L(()=>{"use strict";h();Js();Np=require("node:fs/promises"),kl=require("node:path");Qr();hr();Rr();Fo()});function Pye(){process.on("SIGINT",dx),process.on("SIGTERM",dx)}function Lye(){process.removeListener("SIGINT",dx),process.removeListener("SIGTERM",dx)}var Nye,Mye,dx,
|
|
1941
|
+
`).includes(e))return r}catch{}return this.git(["config","--global","--add","safe.directory",e],e)}}});function _ft(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 Fye(t){try{let e=new URL(t);return e.username||e.password?(e.username="",e.password="",e.toString()):t}catch{return"<repo>"}}async function kye(t,e,r,n){let{url:i,localDir:s}=r;if(!r.connectedProjectId&&!NL.test(i)){n(`skip clone \u2014 refusing non-github URL: ${Fye(i)}`);return}let o=t.join(e,s);if(await t.exists(o)){n(`skip clone \u2014 ${s} already present`);return}n(`cloning ${Fye(i)} \u2192 sources/${s}`);try{await zs("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 Rye(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=_ft(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 kye(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 kye(e,o,u.manifest.githubRepo,s),{written:u.files.length,skipped:!1,sourcesDir:o}}var Np,kl,Tye=L(()=>{"use strict";h();Js();Np=require("node:fs/promises"),kl=require("node:path");Qr();hr();Rr();Fo()});function Pye(){process.on("SIGINT",dx),process.on("SIGTERM",dx)}function Lye(){process.removeListener("SIGINT",dx),process.removeListener("SIGTERM",dx)}var Nye,Mye,dx,KH=L(()=>{"use strict";h();Nye=z(require("@sentry/node"),1),Mye=z(require("@amplitude/analytics-node"),1),dx=async()=>{let t=process.env.BUILDER_DISABLE_AMPLITUDE==="true",e=[Nye.flush()];t||e.push(Mye.flush().promise),await Promise.allSettled(e),process.exit(0)}});function _ye(){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){Uft.error("Error sampling:",i)}},5e3),t.unref())},stop:()=>{t&&(clearInterval(t),t=void 0)}}}var Uft,Uye=L(()=>{"use strict";h();Bt();Uft=ve("EventLoopMonitor")});function Oye(){let t=process.constrainedMemory?.();if(t){let{rss:r}=process.memoryUsage();return Math.min(1,r/t)}let e=Gye.getHeapStatistics();return Math.min(1,1-e.total_available_size/e.heap_size_limit)}var Gye,Kye=L(()=>{"use strict";h();Gye=z(require("v8"),1)});function Oft(){try{let t=Hye.statfsSync(Gft),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 Kft(){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 Jye(t,e,r,n){let i=null,s=_ye(),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=Oye(),p=Oft(),f=Kft();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,Hye,Gft,jye=L(()=>{"use strict";h();Qr();hr();Ap();Uye();Kye();Ra=z(require("node:os"),1),Hye=z(require("node:fs"),1),Gft="/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 HH=L(()=>{"use strict";h();Qr();hr()});var zc,Yye,Mp,hx,JH,jH,qye,Hft,$ye=L(()=>{"use strict";h();OH();zc=require("node:fs"),Yye=require("fs/promises");HH();rr();Xr();Bt();Mp=ve("DryRunBackup"),hx="/app-backup-test",JH="/app/.mark",jH={operation:"dry-run-backup-git",dryRunBackupGit:"true"},qye=async(t,e)=>{let r=await Hft(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:jH})),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)},Hft=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)(JH)&&(0,zc.readFileSync)(JH,"utf8")===s)return null;if((0,zc.writeFileSync)(JH,s),$.info("Attempting dry run backup git"),n.currentStep!=="init-success")return{success:!1,error:"main-init-failed"};(0,zc.existsSync)(hx)&&await(0,Yye.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:jH}),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:jH}),{success:!1,error:"error"}}}});function YH(t){Object.assign(Vye,t)}function qH(t){return!!Vye[t]}var Vye,Wye=L(()=>{"use strict";h();Vye={}});async function Xye(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(Ds.existsSync(r)){Ln.info(`Lock file already exists at: ${r}`);let A=null;try{let c=Ds.readFileSync(r,"utf8");A=JSON.parse(c)}catch(c){Ln.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{Ds.unlinkSync(r)}catch(u){Ln.warn("Failed to remove corrupted lock file:",u)}}if(A)if(Ww(A.pid))switch(n){case"exit":Ln.error("Another instance is already running."),Ln.error(`Existing process PID: ${A.pid}`),Ln.error(`Existing process started at: ${new Date(A.createdAt).toISOString()}`),process.exit(-10);case"replace":Ln.info("Replacing existing lock file (conflictBehavior: replace)"),Ln.info(`Previous process PID: ${A.pid}`);break;case"kill":if(Ln.info("Attempting to kill existing process (conflictBehavior: kill)"),A.pid===process.pid){Ln.info("Skipping kill, same process");break}Ln.info(`Attempting to kill process ${A.pid}...`);let c=await Ks(t,A.pid);c&&(Ln.error(`Failed to kill process ${A.pid}, exiting...`,c),process.exit(-10)),Ln.info(`Process ${A.pid} terminated successfully`);break}else{Ln.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{Ds.unlinkSync(r)}catch(c){Ln.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=zye.dirname(r);Ds.existsSync(A)||Ds.mkdirSync(A,{recursive:!0}),Ds.writeFileSync(r,JSON.stringify(a,null,2),"utf8"),Ln.info(`Lock file created at: ${r}`);let c=!1,u=()=>{if(!c){try{Ds.existsSync(r)&&(Ds.unlinkSync(r),Ln.info(`Lock file removed: ${r}`))}catch(l){Ln.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 Ln.error(`Failed to create lock file at ${r}:`,A),A}}var Ds,zye,Ln,Zye=L(()=>{"use strict";h();Ds=z(require("node:fs"),1),zye=z(require("node:path"),1);fa();Bt();Ln=ve("LockFile")});var tQe,eQe=L(()=>{tQe=`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
|
-
`,tmt=["mcp:chrome","Read","Grep","Glob","Bash","Edit","Write","Media","WebFetch","WebSearch","Skill","ReadBranch","TaskCreate","TaskUpdate","TaskList"],rmt="gpt5-mini",eDe={name:Zht,description:emt,tools:tmt,systemPrompt:ZQe,model:rmt,position:"org-worker",needDevServer:!1,mcpServers:!0,includeMemories:!1}});function imt(t){try{let e=rDe.readFileSync(t,"utf-8");return JSON.parse(e).jobs??[]}catch{return[]}}function smt(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 omt(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 nDe(t){let{cronFilePath:e,syncIntervalMs:r=3e4,...n}=t,i=null;function s(){let a=imt(e);(i===null||smt(i,a))&&omt(a,n).then(()=>{i=a}).catch(A=>{nmt.error("Failed to sync cron configs to service:",A)})}s();let o=setInterval(s,r);return()=>{clearInterval(o)}}var rDe,nmt,iDe=L(()=>{"use strict";h();rDe=z(require("node:fs"),1);hr();Bt();nmt=ve("CronChecker")});function
|
|
4057
|
+
`,tmt=["mcp:chrome","Read","Grep","Glob","Bash","Edit","Write","Media","WebFetch","WebSearch","Skill","ReadBranch","TaskCreate","TaskUpdate","TaskList"],rmt="gpt5-mini",eDe={name:Zht,description:emt,tools:tmt,systemPrompt:ZQe,model:rmt,position:"org-worker",needDevServer:!1,mcpServers:!0,includeMemories:!1}});function imt(t){try{let e=rDe.readFileSync(t,"utf-8");return JSON.parse(e).jobs??[]}catch{return[]}}function smt(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 omt(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 nDe(t){let{cronFilePath:e,syncIntervalMs:r=3e4,...n}=t,i=null;function s(){let a=imt(e);(i===null||smt(i,a))&&omt(a,n).then(()=>{i=a}).catch(A=>{nmt.error("Failed to sync cron configs to service:",A)})}s();let o=setInterval(s,r);return()=>{clearInterval(o)}}var rDe,nmt,iDe=L(()=>{"use strict";h();rDe=z(require("node:fs"),1);hr();Bt();nmt=ve("CronChecker")});function VH(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 $H(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 cmt(t,e){let r={...t};for(let n of amt)delete r[n];for(let n of Amt){let i=r[n];typeof i=="string"&&(r[n]=mx(i,e)??i)}return r}function umt(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 lmt(t,e){bs.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=ws.join(e,n);bs.mkdirSync(s,{recursive:!0});let o=i.map(umt).join(`
|
|
4060
4060
|
|
|
4061
|
-
`);bs.writeFileSync(ws.join(s,"thread.log"),o)}}function gmt(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=ws.join(i,"org","projects"),o=ws.join(i,"org");bs.mkdirSync(s,{recursive:!0}),bs.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 x of c.environmentVariables)process.env[x.key]=x.value;let f=new Map(d.map(x=>[x.userId,x])),m=new Map(u.map(x=>[x.id,x])),C=new Map;for(let x of l)x.state==="active"&&C.set(x.projectId,(C.get(x.projectId)??0)+1);function I(x){let w=x.repoFullName??x.id;return w.split("/").pop()===x.name?w:ws.join(w,x.name)}for(let x of u){let w=ws.join(s,I(x));bs.mkdirSync(w,{recursive:!0});let P=l.filter(_=>_.projectId===x.id).map(_=>cmt(_,f));bs.writeFileSync(ws.join(w,"project.json"),JSON.stringify({...x,branches:P},null,2));let G=l.filter(_=>_.projectId===x.id);bs.writeFileSync(ws.join(w,"AGENTS.md"),gmt(x,C.get(x.id)??0,f,G));let J=g.filter(_=>_.projectId===x.id);J.length>0&&await nx(e,J,ws.join(w,"memories"))}let y=Date.now();function B(x){return{branchName:x.name,friendlyName:x.friendlyName,description:x.description,url:`https://builder.io/app/projects/${x.projectId}/${x.name}`,projectId:x.projectId,projectName:m.get(x.projectId)?.name,state:x.state,createdAt:typeof x.createdAt=="number"?x.createdAt:void 0,updatedAt:x.lastUpdatedAt,metadata:x.metadata,lastUpdatedAgo:V4(y-(typeof x.lastUpdatedAt=="number"?x.lastUpdatedAt:y)),createdBy:mx(x.createdBy,f,{omit:["jobFunctions"]}),deletedBy:mx(x.deletedBy,f,{omit:["jobFunctions"]}),deletedAt:x.deletedAt,archiveReason:x.archiveReason,pr:x.prNumber&&x.prUrl?{prNumber:x.prNumber,prUrl:x.prUrl,prStatus:x.prStatus,prStatusUpdatedAt:x.prStatusUpdatedAt}:void 0,prsByFolder:x.prInfoByFolder?Object.fromEntries(Object.entries(x.prInfoByFolder).map(([w,P])=>[w,{prNumber:P.prNumber,prUrl:P.prUrl,prStatus:P.status,updatedAt:P.updatedAt}])):void 0}}let E=y-10080*60*1e3,Q=l.filter(x=>x.state==="active"&&typeof x.lastUpdatedAt=="number"&&x.lastUpdatedAt>E).map(B);bs.writeFileSync(ws.join(o,"active-branches.json"),JSON.stringify(Q,null,2));let v=l.filter(x=>x.state==="deleted"||x.state==="archived").map(B);bs.writeFileSync(ws.join(o,"archived-branches.json"),JSON.stringify(v,null,2));let D=new Map;for(let x of l){let w=D.get(x.projectId)??[];w.push(x),D.set(x.projectId,w)}let S=u.map(x=>{let w=D.get(x.id)??[],P=new Map;for(let J of w)J.createdBy&&P.set(J.createdBy,(P.get(J.createdBy)??0)+1);let G=[...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:x.id,projectName:x.name,repoUrl:x.repoUrl,description:x.description??x.repoDescription,branchCount:C.get(x.id)??0,url:`https://builder.io/app/projects/${x.id}`,moreInfoPath:`org/projects/${I(x)}/`,topUsers:G}}).sort((x,w)=>w.branchCount-x.branchCount||x.projectName.localeCompare(w.projectName));if(bs.writeFileSync(ws.join(o,"projects.json"),JSON.stringify(S,null,2)),p.length>0){let x=ws.join(i,"org","channels");lmt(p,x)}}var bs,ws,amt,Amt,W4=L(()=>{"use strict";h();bs=z(require("node:fs"),1),ws=z(require("node:path"),1);Qr();B4();amt=["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"],Amt=["createdBy","deletedBy","lastUpdateBy","archivedBy"]});function sDe(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 dmt(){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 ADe(t){let e=dmt();if(!e)return;Pp.info("Snapshot mode activated",{projectId:e.projectId,triggerEventId:e.triggerEventId}),t(async()=>{try{await pmt("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 oDe,aDe,pmt,Pp,cDe=L(()=>{"use strict";h();oDe=require("node:child_process"),aDe=require("node:util");Bt();pmt=(0,aDe.promisify)(oDe.execFile),Pp=ve("SnapshotMode")});async function hmt(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 uDe(t){let e=t,r=100;for(let n=0;n<r;n++){if(await hmt(e))return e;e=Math.floor(Math.random()*16384)+49152}throw new Error(`Could not find an available port after ${r} attempts`)}async function mmt(t,e){let r=parseInt(process.env.FUSION_SERVER_PORT??""),n=isNaN(r)?fmt: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 uDe(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 uDe(i+1);return{httpPort:i,httpsPort:o}}function lDe(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 CDe(t){let{signal:e,sys:r,sharedState:n}=t,i=Xs?.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=Xs?.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 IDe({sys:t,args:e,existingSession:r}){r&&(Ko=Promise.resolve(r),Xs=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(vye(t,i),e.fusionInit&&sY(!0),i.privacyMode?.encryptKey&&!await XS(i.privacyMode.encryptKey))throw new Error("Invalid encryption key: key failed validation");await Xye(t,i);let s=await Cmt(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 Imt(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=Jye(t,s,i,c)),Rl&&Rl.start(),setInterval(()=>{LB(c)},5e3);let C=wmt(t,i,n),I=!1,y=!1,B=!1,E=Q=>async()=>{LB(c);let v=CDe({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:Xs?.getLastCompletionId()},tags:{operation:"shutdown",setupState:v.setupState,launchPhase:v.launchPhase}});let S=Xs?.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:Xs?.getSessionId()},extra:{shutdownContext:v,subAgents:S.map(x=>({id:x.id,subagentType:x.subagentType,ranForMs:Date.now()-x.startedAt,turns:x.turns,state:x.state,toolsRunning:x.toolsRunning,resumed:x.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 x=[new Promise(w=>g.close(w))];if(p&&x.push(new Promise(w=>p.close(w))),await Promise.race([Promise.all(x),new Promise(w=>setTimeout(w,1e3))]),u&&(await u.close(),u=void 0),!y&&c.initState?.success){y=!0;let w=await Ta();c.state="closing",w&&(xe.info("Closing codeGenServer"),Ix&&(Ix(),Ix=void 0),Ex&&(clearInterval(Ex),Ex=void 0),await w.close({uploadGitBackup:!!i.autoBackupGit,reason:`signal-${Q}`}),Ko=void 0)}await t.Sentry?.flush(2e3),process.env.BUILDER_DISABLE_AMPLITUDE!=="true"&&await mDe.flush().promise,process.exit(0)}catch(x){t.Sentry?.captureException(x);let w=x instanceof Error?x.message:String(x);xe.error(`\u274C FAILED TO CLOSE SERVER: ${w}`),process.exit(1)}};if(Lye(),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&&qye({sys:t,fusionConfig:i,debug:!0,credentials:s},v.initState).then(x=>{x&&(c._attemptDryRunBackupOutcome=x.success?"success":x.error)}).catch(x=>{t.Sentry?.captureException(x,{tags:{operation:"dry-run-backup-git",dryRunBackupGit:"true"}})})}try{u=Emt(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 Bmt({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 Cmt(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 lDe(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 lDe(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 Imt(t,e,r,n,i){let s=!!e.isLocal||!!i?.local,{httpPort:o,httpsPort:a}=await mmt(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"),x=D&&E.url?.includes("/editor-ready");!s&&D&&!S&&!x&&xe.debug(`[HTTP]: ${E.url}`),!S&&!x&&E.query._skip_activity!=="true"&&(r.lastRequestTime=performance.now()),v()});let c=t.builderPrivateKey,u=e.authenticateProxy??!1;EDe({sys:n,app:A,validBuilderPrivateKey:c,authenticateProxy:u,isLocal:s,sharedState:r,fusionConfig:e,launchLogger:xe});let l=pDe.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=dDe.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 Emt(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}),ADe(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 Bmt({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=CDe({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:x,canHandleTools:w,fireAndForget:P,context:{featureFlags:G}}=v.body;if(!S&&!x)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"),G&&Y4(G);let J=await rm(t,e,n,u,void 0,l,void 0,n.privacyMode);if(P){Array.isArray(w)&&w.length>0&&J.setSessionCanHandleTools(w),J.waitForEventLoop(),await J.sendMessage(S?{userPrompt:S}:x),D.status(200),D.write(JSON.stringify({type:"success",message:"Message sent"})+`
|
|
4061
|
+
`);bs.writeFileSync(ws.join(s,"thread.log"),o)}}function gmt(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=$H(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=$H(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=VH(i-d.lastUpdatedAt),p=$H(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=VH(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=ws.join(i,"org","projects"),o=ws.join(i,"org");bs.mkdirSync(s,{recursive:!0}),bs.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 x of c.environmentVariables)process.env[x.key]=x.value;let f=new Map(d.map(x=>[x.userId,x])),m=new Map(u.map(x=>[x.id,x])),C=new Map;for(let x of l)x.state==="active"&&C.set(x.projectId,(C.get(x.projectId)??0)+1);function I(x){let w=x.repoFullName??x.id;return w.split("/").pop()===x.name?w:ws.join(w,x.name)}for(let x of u){let w=ws.join(s,I(x));bs.mkdirSync(w,{recursive:!0});let P=l.filter(_=>_.projectId===x.id).map(_=>cmt(_,f));bs.writeFileSync(ws.join(w,"project.json"),JSON.stringify({...x,branches:P},null,2));let G=l.filter(_=>_.projectId===x.id);bs.writeFileSync(ws.join(w,"AGENTS.md"),gmt(x,C.get(x.id)??0,f,G));let J=g.filter(_=>_.projectId===x.id);J.length>0&&await nx(e,J,ws.join(w,"memories"))}let y=Date.now();function B(x){return{branchName:x.name,friendlyName:x.friendlyName,description:x.description,url:`https://builder.io/app/projects/${x.projectId}/${x.name}`,projectId:x.projectId,projectName:m.get(x.projectId)?.name,state:x.state,createdAt:typeof x.createdAt=="number"?x.createdAt:void 0,updatedAt:x.lastUpdatedAt,metadata:x.metadata,lastUpdatedAgo:VH(y-(typeof x.lastUpdatedAt=="number"?x.lastUpdatedAt:y)),createdBy:mx(x.createdBy,f,{omit:["jobFunctions"]}),deletedBy:mx(x.deletedBy,f,{omit:["jobFunctions"]}),deletedAt:x.deletedAt,archiveReason:x.archiveReason,pr:x.prNumber&&x.prUrl?{prNumber:x.prNumber,prUrl:x.prUrl,prStatus:x.prStatus,prStatusUpdatedAt:x.prStatusUpdatedAt}:void 0,prsByFolder:x.prInfoByFolder?Object.fromEntries(Object.entries(x.prInfoByFolder).map(([w,P])=>[w,{prNumber:P.prNumber,prUrl:P.prUrl,prStatus:P.status,updatedAt:P.updatedAt}])):void 0}}let E=y-10080*60*1e3,Q=l.filter(x=>x.state==="active"&&typeof x.lastUpdatedAt=="number"&&x.lastUpdatedAt>E).map(B);bs.writeFileSync(ws.join(o,"active-branches.json"),JSON.stringify(Q,null,2));let v=l.filter(x=>x.state==="deleted"||x.state==="archived").map(B);bs.writeFileSync(ws.join(o,"archived-branches.json"),JSON.stringify(v,null,2));let D=new Map;for(let x of l){let w=D.get(x.projectId)??[];w.push(x),D.set(x.projectId,w)}let S=u.map(x=>{let w=D.get(x.id)??[],P=new Map;for(let J of w)J.createdBy&&P.set(J.createdBy,(P.get(J.createdBy)??0)+1);let G=[...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:x.id,projectName:x.name,repoUrl:x.repoUrl,description:x.description??x.repoDescription,branchCount:C.get(x.id)??0,url:`https://builder.io/app/projects/${x.id}`,moreInfoPath:`org/projects/${I(x)}/`,topUsers:G}}).sort((x,w)=>w.branchCount-x.branchCount||x.projectName.localeCompare(w.projectName));if(bs.writeFileSync(ws.join(o,"projects.json"),JSON.stringify(S,null,2)),p.length>0){let x=ws.join(i,"org","channels");lmt(p,x)}}var bs,ws,amt,Amt,WH=L(()=>{"use strict";h();bs=z(require("node:fs"),1),ws=z(require("node:path"),1);Qr();BH();amt=["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"],Amt=["createdBy","deletedBy","lastUpdateBy","archivedBy"]});function sDe(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 dmt(){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 ADe(t){let e=dmt();if(!e)return;Pp.info("Snapshot mode activated",{projectId:e.projectId,triggerEventId:e.triggerEventId}),t(async()=>{try{await pmt("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 oDe,aDe,pmt,Pp,cDe=L(()=>{"use strict";h();oDe=require("node:child_process"),aDe=require("node:util");Bt();pmt=(0,aDe.promisify)(oDe.execFile),Pp=ve("SnapshotMode")});async function hmt(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 uDe(t){let e=t,r=100;for(let n=0;n<r;n++){if(await hmt(e))return e;e=Math.floor(Math.random()*16384)+49152}throw new Error(`Could not find an available port after ${r} attempts`)}async function mmt(t,e){let r=parseInt(process.env.FUSION_SERVER_PORT??""),n=isNaN(r)?fmt: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 uDe(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 uDe(i+1);return{httpPort:i,httpsPort:o}}function lDe(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 CDe(t){let{signal:e,sys:r,sharedState:n}=t,i=Xs?.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=Xs?.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 IDe({sys:t,args:e,existingSession:r}){r&&(Ko=Promise.resolve(r),Xs=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(vye(t,i),e.fusionInit&&sY(!0),i.privacyMode?.encryptKey&&!await XS(i.privacyMode.encryptKey))throw new Error("Invalid encryption key: key failed validation");await Xye(t,i);let s=await Cmt(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 Imt(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=Jye(t,s,i,c)),Rl&&Rl.start(),setInterval(()=>{LB(c)},5e3);let C=wmt(t,i,n),I=!1,y=!1,B=!1,E=Q=>async()=>{LB(c);let v=CDe({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:Xs?.getLastCompletionId()},tags:{operation:"shutdown",setupState:v.setupState,launchPhase:v.launchPhase}});let S=Xs?.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:Xs?.getSessionId()},extra:{shutdownContext:v,subAgents:S.map(x=>({id:x.id,subagentType:x.subagentType,ranForMs:Date.now()-x.startedAt,turns:x.turns,state:x.state,toolsRunning:x.toolsRunning,resumed:x.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 x=[new Promise(w=>g.close(w))];if(p&&x.push(new Promise(w=>p.close(w))),await Promise.race([Promise.all(x),new Promise(w=>setTimeout(w,1e3))]),u&&(await u.close(),u=void 0),!y&&c.initState?.success){y=!0;let w=await Ta();c.state="closing",w&&(xe.info("Closing codeGenServer"),Ix&&(Ix(),Ix=void 0),Ex&&(clearInterval(Ex),Ex=void 0),await w.close({uploadGitBackup:!!i.autoBackupGit,reason:`signal-${Q}`}),Ko=void 0)}await t.Sentry?.flush(2e3),process.env.BUILDER_DISABLE_AMPLITUDE!=="true"&&await mDe.flush().promise,process.exit(0)}catch(x){t.Sentry?.captureException(x);let w=x instanceof Error?x.message:String(x);xe.error(`\u274C FAILED TO CLOSE SERVER: ${w}`),process.exit(1)}};if(Lye(),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&&qye({sys:t,fusionConfig:i,debug:!0,credentials:s},v.initState).then(x=>{x&&(c._attemptDryRunBackupOutcome=x.success?"success":x.error)}).catch(x=>{t.Sentry?.captureException(x,{tags:{operation:"dry-run-backup-git",dryRunBackupGit:"true"}})})}try{u=Emt(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 Bmt({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 Cmt(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 lDe(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 lDe(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 Imt(t,e,r,n,i){let s=!!e.isLocal||!!i?.local,{httpPort:o,httpsPort:a}=await mmt(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"),x=D&&E.url?.includes("/editor-ready");!s&&D&&!S&&!x&&xe.debug(`[HTTP]: ${E.url}`),!S&&!x&&E.query._skip_activity!=="true"&&(r.lastRequestTime=performance.now()),v()});let c=t.builderPrivateKey,u=e.authenticateProxy??!1;EDe({sys:n,app:A,validBuilderPrivateKey:c,authenticateProxy:u,isLocal:s,sharedState:r,fusionConfig:e,launchLogger:xe});let l=pDe.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=dDe.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 Emt(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}),ADe(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 Bmt({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=CDe({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:x,canHandleTools:w,fireAndForget:P,context:{featureFlags:G}}=v.body;if(!S&&!x)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"),G&&YH(G);let J=await rm(t,e,n,u,void 0,l,void 0,n.privacyMode);if(P){Array.isArray(w)&&w.length>0&&J.setSessionCanHandleTools(w),J.waitForEventLoop(),await J.sendMessage(S?{userPrompt:S}:x),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(w)?w:[]});try{await J.sendMessage(S?{userPrompt:S}:x),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 lmt(t,e){bs.rmSync(e,{recursive:!0,force:!0});let r=new
|
|
|
4067
4067
|
|
|
4068
4068
|
`),D.end()):D.status(500).json({error:x})}finally{xe.debug("(generate): finished")}}),p.post("/sync",async(v,D)=>{try{xe.debug("(sync): started");let x=await(await rm(t,e,n,u,void 0,l)).syncChangesFromRemote(v.body);D.json({ok:!0,result:x})}catch(S){t.Sentry?.captureException(S);let x=S instanceof Error?S.message:String(S);D.status(500).json({error:x})}finally{xe.debug("(sync): finished")}}),p.post("/tool-result",async(v,D)=>{try{let{toolCallId:S,result:x}=v.body;if(!S)return D.status(400).json({error:"No toolCallId provided"});let w=await Ta();if(!w)return D.status(404).json({error:"No active session found"});let P=typeof x=="string"?x:{toolResult:x?.toolResult??"",isError:!!x?.isError};if(!w.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 x=S instanceof Error?S.message:String(S);D.status(500).json({error:x})}}),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 x=await Ta();if(!x)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 w=setInterval(async()=>{let G={type:"ping"};D.write(JSON.stringify(G)+`
|
|
4069
4069
|
`)},5e3),P=x.connectToEventLoop(!1,G=>{D.write(JSON.stringify(G)+`
|
|
4070
|
-
`)},{canHandleTools:Array.isArray(S)?S:[]});try{await x.waitUntilIdle()}finally{P(),clearInterval(w)}}finally{D.end(),xe.debug("(connect): finished")}}),p.get("/get-zip",async(v,D)=>{l.activeOperations++;try{let x=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(x)}"`),await new Promise((w,P)=>{D.download(x,G=>{t.unlink(x).catch(J=>{t.Sentry?.captureException(J)}),G?P(G):w()})})}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 x=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((w,P)=>{v.download(x,G=>{t.unlink(x).catch(J=>{t.Sentry?.captureException(J)}),G?P(G):w()})})}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,x=Array.isArray(S)?S.join("/"):S;if(xe.debug("folderName",x),typeof x!="string"){D.status(400).json({error:"Invalid folder name"});return}let w=x.length===0?".":x;await f(D,w)}),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:x=!1}=v.body||{},w=await d({force:S,forcedFullBackup:x});w?.success?D.json(w):D.status(500).json(w)}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:x}=await Promise.resolve().then(()=>(oh(),QE));if(!x.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:x.getWorkspacePath()});return}let w=S();D.json({enabled:!0,...w.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:x}=await Promise.resolve().then(()=>(oh(),QE));if(!x.isEnabled()){D.status(400).json({error:"VS Code tunnel has been disabled for this environment."});return}let w=S();if(w.getStatus()==="running"){D.json({message:"Tunnel already running",enabled:!0,...w.getInfo()});return}let G=x.getTunnelName(n.projectId,n.branchName),J=x.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${G}`),w.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 w.start({name:G,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:x}=await Promise.resolve().then(()=>(oh(),QE));if(!x.isEnabled()){D.status(400).json({error:"VS Code tunnel is not enabled"});return}let w=S();await w.stop(),xe.info("\u{1F517} VS Code tunnel stopped"),D.json({message:"Tunnel stopped",enabled:!0,...w.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 x=t.join(fDe.default.homedir(),".builder","recordings"),w=t.join(x,S),P;try{P=(await t.stat(w)).size,xe.debug(`[download-gif] File found: ${w} (${P} bytes)`)}catch{try{let j=await
|
|
4070
|
+
`)},{canHandleTools:Array.isArray(S)?S:[]});try{await x.waitUntilIdle()}finally{P(),clearInterval(w)}}finally{D.end(),xe.debug("(connect): finished")}}),p.get("/get-zip",async(v,D)=>{l.activeOperations++;try{let x=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(x)}"`),await new Promise((w,P)=>{D.download(x,G=>{t.unlink(x).catch(J=>{t.Sentry?.captureException(J)}),G?P(G):w()})})}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 x=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((w,P)=>{v.download(x,G=>{t.unlink(x).catch(J=>{t.Sentry?.captureException(J)}),G?P(G):w()})})}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,x=Array.isArray(S)?S.join("/"):S;if(xe.debug("folderName",x),typeof x!="string"){D.status(400).json({error:"Invalid folder name"});return}let w=x.length===0?".":x;await f(D,w)}),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:x=!1}=v.body||{},w=await d({force:S,forcedFullBackup:x});w?.success?D.json(w):D.status(500).json(w)}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:x}=await Promise.resolve().then(()=>(oh(),QE));if(!x.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:x.getWorkspacePath()});return}let w=S();D.json({enabled:!0,...w.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:x}=await Promise.resolve().then(()=>(oh(),QE));if(!x.isEnabled()){D.status(400).json({error:"VS Code tunnel has been disabled for this environment."});return}let w=S();if(w.getStatus()==="running"){D.json({message:"Tunnel already running",enabled:!0,...w.getInfo()});return}let G=x.getTunnelName(n.projectId,n.branchName),J=x.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${G}`),w.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 w.start({name:G,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:x}=await Promise.resolve().then(()=>(oh(),QE));if(!x.isEnabled()){D.status(400).json({error:"VS Code tunnel is not enabled"});return}let w=S();await w.stop(),xe.info("\u{1F517} VS Code tunnel stopped"),D.json({message:"Tunnel stopped",enabled:!0,...w.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 x=t.join(fDe.default.homedir(),".builder","recordings"),w=t.join(x,S),P;try{P=(await t.stat(w)).size,xe.debug(`[download-gif] File found: ${w} (${P} bytes)`)}catch{try{let j=await t4.default.promises.readdir(x);xe.debug(`[download-gif] File NOT found: ${w}. Recordings dir contains: [${j.join(", ")}]`)}catch{xe.debug(`[download-gif] File NOT found: ${w}. Recordings dir does not exist: ${x}`)}D.status(404).json({error:"GIF not found for this session",path:w});return}let G=hDe.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[G]||"application/octet-stream"),D.setHeader("Content-Disposition",`inline; filename="${S}"`),D.setHeader("Content-Length",P);let _=t4.default.createReadStream(w);_.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(),x=await Pv(t,S);D.json({history:x})}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 x=(n.autoShutdownThresholdMinutes??60)*60,w=x*1e3,P=!1,G=setInterval(async()=>{let J=performance.now()-l.containerStateTimestamp;if(l.containerState==="idle"&&J>w){if(P){xe.info("\u23F0 Shutdown already in progress");return}xe.info(`\u23F0 Threshold reached (${Math.round(x)} seconds without requests)`),P=!0;try{(await g("inactivity-timeout"))?.success&&clearInterval(G)}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(G))}let m;if(!n.nativeApp){let v=vs(n.serverUrl),D=BDe(),S=!u&&v?wx(v,t):void 0,x=(w,P,G)=>{if(w.url?.startsWith(Tl)){G();return}else{let J=u?.proxyMiddleware??S,_=vs(typeof w.headers["fusion-forwarded-target"]=="string"?w.headers["fusion-forwarded-target"].toLowerCase():void 0),K=w.headers["fusion-forwarded-default-origin"]==="true",j=J&&K;if(_&&CA(_)&&!j&&_.origin!==J?.target.origin){D.web(w,P,{target:_.origin,...gDe(_.protocol)&&{secure:!1,agent:Qx}});return}else if(J)J(w,P,G);else{P.status(502).json({error:"The proxy is not ready yet. Dev Server URL is configured."});return}}};i.use("/",x),m=(w,P,G)=>{let{pathname:J}=new URL(w.url??"/","wss://base.url"),_=u?.proxyMiddleware??S,K=vs(typeof w.headers["fusion-forwarded-target"]=="string"?w.headers["fusion-forwarded-target"].toLowerCase():void 0),j=w.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(w,P,G,{target:K.origin,...gDe(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(w,P,G)}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 lmt(t,e){bs.rmSync(e,{recursive:!0,force:!0});let r=new
|
|
|
4077
4077
|
\r
|
|
4078
4078
|
`),D.destroy();return}C.handleUpgrade(v,D,S,function(G){G.emit("connection",G,v)})}else if(m)m(v,D,S);else{t.debug(`Native app mode: Rejecting WebSocket connection to: ${x}`),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),Qmt({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),x=D.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${S}`);let w=v();w.on("error",P=>{xe.error(`\u274C VS Code tunnel error: ${P}`),t.Sentry?.captureException(new Error(String(P)),{tags:{operation:"vscode-tunnel-error-event"}})}),w.start({name:S,workspacePath:x,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 Qmt({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&&Xs&&Xs.getSessionId()!==l){yx?.abort(),o=!1;let m=Xs;Ko=void 0,Xs=void 0,m.close({reason:"forceSessionReload"})}else if(p&&r.isLocal&&l&&!Xs&&Ko){yx?.abort(),o=!1;let m=Ko;Ko=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=Go();!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}})}ymt.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 Dmt(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(FQe),c.push(NQe)),d&&(c.push(Xh),c.push(rQe),c.push(oQe)),r.branchType==="setup-project"&&(c.push(Xh),c.push(YQe)),r.branchType==="org-agent"&&(c.push(WQe),c.push(eDe)),r.branchType==="design-system-indexing"&&(c.push(uQe),c.push(dQe),c.push(CQe),c.push(yQe),c.push(bQe)),r.branchType||(c.push(Xh),c.push(ix),c.push(_Qe),c.push(KQe));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 yDe();if(f)throw en(f),f}r.branchType==="design-system-indexing"&&r.figmaDecodeJobId&&await Rye({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=nDe({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;sDe(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 Ko||Promise.resolve(void 0)}function rm(t,e,r,n,i,s,o,a){if(!Ko){yx=new AbortController;let A=Dmt(t,e,r,n,i,s,yx.signal,o,a);Ko=A,A.then(c=>{Ko===A&&(Xs=c)}).catch(()=>{})}return Ko}function wmt(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 gDe(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,pDe,dDe,Dx,tH,fDe,hDe,mDe,MB,xe,fmt,Ko,Xs,yx,Rl,Ix,Ex,ymt,vmt,nH=L(()=>{"use strict";h();PB=z(JG(),1),pDe=z(require("node:http"),1),dDe=z(require("node:https"),1),Dx=z(require("net"),1),tH=z(require("node:fs"),1),fDe=z(require("node:os"),1),hDe=z(require("node:path"),1),mDe=z(require("@amplitude/analytics-node"),1),MB=z(Er(),1);Rr();Ms();_s();ihe();Zh();rr();Bt();iH();TB();Js();NB();O4();kB();sH();Qr();hr();Tye();Ic();K4();Xr();jye();t8();$ye();Ov();Wye();H4();Zye();nQe();aQe();lQe();fQe();IQe();QQe();vQe();kQe();MQe();UQe();HQe();Q4();y4();qQe();zQe();tDe();iDe();W4();eH();l4();Fi();pI();Fo();cDe();xe=ve("Launch"),fmt=48752;Rl=null;ymt=["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"];vmt=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 QDe,DDe,wDe,bDe,oH,Smt,Tl,Nl,xmt,EDe,Fmt,iH=L(()=>{"use strict";h();QDe=z(JG(),1),DDe=z(mde(),1),wDe=require("node:child_process"),bDe=require("node:util"),oH=z(require("node:path"),1);Ap();$G();oh();nH();Smt=(0,bDe.promisify)(wDe.execFile),Tl="/_builder.io",Nl=Tl+"/api",xmt={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"},EDe=({sys:t,app:e,validBuilderPrivateKey:r,authenticateProxy:n,isLocal:i,sharedState:s,fusionConfig:o,launchLogger:a})=>{e.set("etag",!1),e.use((0,DDe.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(Fmt({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",QDe.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 Smt("git",["fsck","--connectivity-only"],{cwd:g,timeout:15e3})}catch{c.status(200).json({healthy:!1});return}}c.status(200).json({healthy:!0})})},Fmt=({validBuilderPrivateKey:t,authenticateProxy:e})=>(r,n,i)=>{let s=r.path.startsWith(Tl);if(Object.values(xmt).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,_n,BDe,wx,kmt,Rmt,Tmt,vDe,SDe,Nmt,Qx,sH=L(()=>{"use strict";h();aH=z(Mae(),1);iH();kB();Bt();Xc=()=>!!process.env.DEBUG_FUSION_PROXY,_n=ve("Proxy",{debug:Xc}),BDe=()=>{let t=(0,aH.createProxyServer)({changeOrigin:!0,ws:!0});return t.on("proxyReqWs",(e,r,n)=>{Xc()&&_n.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(r.headers,null,2));let i=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),_n.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("proxyReq",(e,r,n)=>{Xc()&&(_n.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(r.headers,null,2)),_n.debug("proxyReq: removing headers. Initial host:",e.host));let i=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),_n.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("error",e=>{_n.error(`Proxy error: ${e.message}`)}),t},wx=(t,e)=>{let r=(0,aH.createProxyServer)(Nmt(t));return r.on("proxyReqWs",(o,a,A)=>{Xc()&&_n.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(a.headers,null,2));let c=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),_n.debug("proxyReq: removing headers. Final host:",o.host))}),r.on("proxyReq",(o,a,A)=>{Xc()&&(_n.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(a.headers,null,2)),_n.debug("proxyReq: removing headers. Initial host:",o.host));let c=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),_n.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(SDe(f))return;let m=o.headers[f]||"";A.setHeader(f,m)}),A.statusCode=c},p=kmt(a);if(u&&u.includes("text/html")&&c===200&&!p){let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{vDe(f,o,A,c)});return}else if(p||c!==200||l>d||u&&!u.includes("text/html")){g(),_n.debug("proxyRes: piping to response"),o.pipe(A);return}else{let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{Rmt({body:f})?vDe(f,o,A,c):(g(),_n.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}`),_n.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),Qmt({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),x=D.getWorkspacePath();xe.info(`\u{1F517} Starting VS Code tunnel: ${S}`);let w=v();w.on("error",P=>{xe.error(`\u274C VS Code tunnel error: ${P}`),t.Sentry?.captureException(new Error(String(P)),{tags:{operation:"vscode-tunnel-error-event"}})}),w.start({name:S,workspacePath:x,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 Qmt({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&&Xs&&Xs.getSessionId()!==l){yx?.abort(),o=!1;let m=Xs;Ko=void 0,Xs=void 0,m.close({reason:"forceSessionReload"})}else if(p&&r.isLocal&&l&&!Xs&&Ko){yx?.abort(),o=!1;let m=Ko;Ko=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=Go();!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}})}ymt.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 Dmt(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(FQe),c.push(NQe)),d&&(c.push(Xh),c.push(rQe),c.push(oQe)),r.branchType==="setup-project"&&(c.push(Xh),c.push(YQe)),r.branchType==="org-agent"&&(c.push(WQe),c.push(eDe)),r.branchType==="design-system-indexing"&&(c.push(uQe),c.push(dQe),c.push(CQe),c.push(yQe),c.push(bQe)),r.branchType||(c.push(Xh),c.push(ix),c.push(_Qe),c.push(KQe));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 yDe();if(f)throw en(f),f}r.branchType==="design-system-indexing"&&r.figmaDecodeJobId&&await Rye({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=nDe({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;sDe(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 Ko||Promise.resolve(void 0)}function rm(t,e,r,n,i,s,o,a){if(!Ko){yx=new AbortController;let A=Dmt(t,e,r,n,i,s,yx.signal,o,a);Ko=A,A.then(c=>{Ko===A&&(Xs=c)}).catch(()=>{})}return Ko}function wmt(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 gDe(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,pDe,dDe,Dx,t4,fDe,hDe,mDe,MB,xe,fmt,Ko,Xs,yx,Rl,Ix,Ex,ymt,vmt,n4=L(()=>{"use strict";h();PB=z(JG(),1),pDe=z(require("node:http"),1),dDe=z(require("node:https"),1),Dx=z(require("net"),1),t4=z(require("node:fs"),1),fDe=z(require("node:os"),1),hDe=z(require("node:path"),1),mDe=z(require("@amplitude/analytics-node"),1),MB=z(Er(),1);Rr();Ms();_s();ihe();Zh();rr();Bt();i4();TB();Js();NB();OH();kB();s4();Qr();hr();Tye();Ic();KH();Xr();jye();t8();$ye();Ov();Wye();HH();Zye();nQe();aQe();lQe();fQe();IQe();QQe();vQe();kQe();MQe();UQe();HQe();QH();yH();qQe();zQe();tDe();iDe();WH();e4();lH();Fi();pI();Fo();cDe();xe=ve("Launch"),fmt=48752;Rl=null;ymt=["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"];vmt=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 QDe,DDe,wDe,bDe,o4,Smt,Tl,Nl,xmt,EDe,Fmt,i4=L(()=>{"use strict";h();QDe=z(JG(),1),DDe=z(mde(),1),wDe=require("node:child_process"),bDe=require("node:util"),o4=z(require("node:path"),1);Ap();$G();oh();n4();Smt=(0,bDe.promisify)(wDe.execFile),Tl="/_builder.io",Nl=Tl+"/api",xmt={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"},EDe=({sys:t,app:e,validBuilderPrivateKey:r,authenticateProxy:n,isLocal:i,sharedState:s,fusionConfig:o,launchLogger:a})=>{e.set("etag",!1),e.use((0,DDe.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(Fmt({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",QDe.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 Smt("git",["fsck","--connectivity-only"],{cwd:g,timeout:15e3})}catch{c.status(200).json({healthy:!1});return}}c.status(200).json({healthy:!0})})},Fmt=({validBuilderPrivateKey:t,authenticateProxy:e})=>(r,n,i)=>{let s=r.path.startsWith(Tl);if(Object.values(xmt).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,_n,BDe,wx,kmt,Rmt,Tmt,vDe,SDe,Nmt,Qx,s4=L(()=>{"use strict";h();a4=z(Mae(),1);i4();kB();Bt();Xc=()=>!!process.env.DEBUG_FUSION_PROXY,_n=ve("Proxy",{debug:Xc}),BDe=()=>{let t=(0,a4.createProxyServer)({changeOrigin:!0,ws:!0});return t.on("proxyReqWs",(e,r,n)=>{Xc()&&_n.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(r.headers,null,2));let i=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),_n.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("proxyReq",(e,r,n)=>{Xc()&&(_n.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(r.headers,null,2)),_n.debug("proxyReq: removing headers. Initial host:",e.host));let i=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(e.getHeaders(),null,2)),_n.debug("proxyReq: removing headers. Final host:",e.host))}),t.on("error",e=>{_n.error(`Proxy error: ${e.message}`)}),t},wx=(t,e)=>{let r=(0,a4.createProxyServer)(Nmt(t));return r.on("proxyReqWs",(o,a,A)=>{Xc()&&_n.debug("proxyReqWs: removing headers. Initial headers:",JSON.stringify(a.headers,null,2));let c=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),_n.debug("proxyReq: removing headers. Final host:",o.host))}),r.on("proxyReq",(o,a,A)=>{Xc()&&(_n.debug("proxyReq: removing headers. Initial headers:",JSON.stringify(a.headers,null,2)),_n.debug("proxyReq: removing headers. Initial host:",o.host));let c=vs(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()&&(_n.debug("proxyReq: removing headers. Final headers:",JSON.stringify(o.getHeaders(),null,2)),_n.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(SDe(f))return;let m=o.headers[f]||"";A.setHeader(f,m)}),A.statusCode=c},p=kmt(a);if(u&&u.includes("text/html")&&c===200&&!p){let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{vDe(f,o,A,c)});return}else if(p||c!==200||l>d||u&&!u.includes("text/html")){g(),_n.debug("proxyRes: piping to response"),o.pipe(A);return}else{let f="";o.on("data",m=>{f+=m.toString()}),o.on("end",()=>{Rmt({body:f})?vDe(f,o,A,c):(g(),_n.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}`),_n.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})},kmt=t=>t.headers["x-builder-source"]==="desktop-app",Rmt=({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)},Tmt=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}},vDe=(t,e,r,n)=>{try{Object.keys(e.headers).forEach(a=>{if(!SDe(a)&&a.toLowerCase()!=="content-length"){let A=e.headers[a]||"";_n.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 lmt(t,e){bs.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&&!Tmt(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"))}},SDe=t=>(t=t.toLowerCase(),t==="content-security-policy"||t==="x-frame-options"),Nmt=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 Mmt(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 Pmt(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 Lmt(t,e,r){if(t!=="npm install")return t;if(Mmt("ni"))return"ni";{let n=t,i=Pmt(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 _mt(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 Umt(t){try{if(t&&(0,FDe.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 vs(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&&!Tmt(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"))}},SDe=t=>(t=t.toLowerCase(),t==="content-security-policy"||t==="x-frame-options"),Nmt=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 Mmt(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 Pmt(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 Lmt(t,e,r){if(t!=="npm install")return t;if(Mmt("ni"))return"ni";{let n=t,i=Pmt(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 _mt(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 Umt(t){try{if(t&&(0,FDe.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 vs(t){if(t){if(typeof t=="string")try{return new URL(t)}catch{return}if(t instanceof URL)return t}}function r4(t,e,r){let n=new Mi(500),i=new Mi(200),s=new Mi(500),o=new Mi(500),a=new Mi(1e3),A,c=e.autoDetectDevServer??!1,u=e.autoDetectDevServerPatterns,l=0,d=e.autoSuggestPort??!1,g,p=c?void 0:vs(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,x,w,P=!1,G=[],J=new xDe.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=Umt(e.miseLocationPath??process.env.MISE_INSTALL_PATH);function de(){G.push({all:new Mi(300),out:new Mi(300),err:new Mi(300)})}function ke(){if(!e.autoConfigureHosts||!p)return!1;let k=p.hostname;if(!CA(k)){if(Uoe([{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 O=j0(I,R,t.Sentry);if(O.success){for(let q of O.appliedFiles)M(` Applied: ${q.path} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);return!0}else{for(let q of O.failedFiles)M(` Failed: ${q.path}: ${q.error} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);for(let q of O.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,O=e.nativeApp?1e4:3e3;return k=k??M,R=R??O,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,Vr=async()=>{let k=f?.getPid();return k?Gmt(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 sn(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 O=performance.now(),q=!P,re=k.state==="ok-2xx";P=!0;let se=[];x!==void 0&&(se.push({key:"dev_server_dev_command_time",ms:O-x,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),x=void 0),w!==void 0&&(se.push({key:"dev_server_total_setup_time",ms:O-w,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),w=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 O=e.https??!1?["https","http"]:["http","https"];for(let q of O)try{if(y!=="running"||k.aborted)return null;let re=new URL(`${q}://localhost:${R}`),se=q==="https"?
|
|
4172
|
+
======== Apply file overrides ========`);let O=j0(I,R,t.Sentry);if(O.success){for(let q of O.appliedFiles)M(` Applied: ${q.path} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);return!0}else{for(let q of O.failedFiles)M(` Failed: ${q.path}: ${q.error} (${q.size} bytes, md5: ${q.md5.slice(0,8)})`);for(let q of O.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,O=e.nativeApp?1e4:3e3;return k=k??M,R=R??O,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,Vr=async()=>{let k=f?.getPid();return k?Gmt(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 sn(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 O=performance.now(),q=!P,re=k.state==="ok-2xx";P=!0;let se=[];x!==void 0&&(se.push({key:"dev_server_dev_command_time",ms:O-x,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),x=void 0),w!==void 0&&(se.push({key:"dev_server_total_setup_time",ms:O-w,attributes:{success:re.toString(),first_time:q.toString(),...At()}}),w=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 O=e.https??!1?["https","http"]:["http","https"];for(let q of O)try{if(y!=="running"||k.aborted)return null;let re=new URL(`${q}://localhost:${R}`),se=q==="https"?A4.default:c4.default,Ie=await new Promise((Pe,Te)=>{let Ve=()=>{ut.destroy(),Te(nn(k.reason))};if(k.aborted){Te(nn(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,O=[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()&&O.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(O),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:"?A4.default:c4.default,O=p.href,q=await new Promise((re,se)=>{let Ie=()=>{Pe.destroy(),se(nn(k.reason))};if(k.aborted){se(nn(k.reason));return}k.addEventListener("abort",Ie);let Pe=M.get(O,{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",Vo=>{ur+=Vo.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:O,value:q})=>(M[O]=q,M),{});return k?{...C,...R}:R}function te(k){let R={...e.environmentVariables?.reduce((M,{key:O,value:q})=>(M[O]=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??"."),O=process.platform==="win32"?";":":",q=R.MISE_TRUSTED_CONFIG_PATHS||"";R.MISE_TRUSTED_CONFIG_PATHS=q?`${q}${O}${M}`:M}if(process.platform==="win32"&&be){let O=`${process.env.MISE_DATA_DIR||`${process.env.LOCALAPPDATA}\\mise`}\\shims`,q=R.PATH||R.Path||"";if(q.toLowerCase().includes(O.toLowerCase())||(q=`${O};${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 O of k){if(O.type!=="mise")continue;O.tool==="maven"&&(M+=`mise plugin install maven
|
|
4174
4174
|
`);let q=O.tool,re,se=O.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,Vo=!1;ut.onSpawn(()=>{k.aborted||(ur=!0,ge=performance.now(),sn("starting"),rt().then(()=>{ur&&!k.aborted&&(ge=performance.now(),sn("running"),le?.abort(),Ie({status:"success"}))}))}),ut.onError(on=>{k.aborted||(ur=!1,sn("failed"),t.Sentry?.captureException(on),Ie({status:"failure",code:null,output:on.message}))}),ut.onClose(on=>{k.aborted||(ur=!1,sn("failed"),typeof on=="number"&&!k.aborted&&zp(Buffer.from(`
|
|
4231
4231
|
|
|
4232
4232
|
exited with code ${on}
|
|
4233
|
-
`)),J.emit("close",on),Ie({status:"failure",code:on,output:F(1,"all")}))});let vn=on=>{if(c&&!A){let an=Moe(on,u);an&&(p=vs(an.url),p&&(A="terminal",Ht("auto-detected"),le?.abort(),$.info(`URL auto-detected: ${p.href}`),J.emit("urlDetected",p.href),nt()))}},cu=()=>{if(!Vo){Vo=!0,s.write(Ss),a.write(Ss);let on=G[G.length-1];on&&(on.out.write(Ss),on.all.write(Ss)),J.emit("stdout",Ss)}},Qy=on=>{if(f!==ut)return;cu();let an=on.toString();s.write(an),a.write(an),ge=performance.now();let Wr=G[G.length-1];Wr&&(Wr.out.write(an),Wr.all.write(an)),vn(an),J.emit("stdout",an)},zp=on=>{if(f!==ut)return;cu();let an=on.toString();o.write(an),a.write(an),ge=performance.now();let Wr=G[G.length-1];Wr&&(Wr.err.write(an),Wr.all.write(an)),vn(an),J.emit("stderr",an)};ut.stdout.on("data",Qy),ut.stderr.on("data",zp)}))}function ce({command:k,shell:R,cwd:M,env:O,shouldLogin:q}){let re=mA(R,k,{stdio:["inherit","pipe","pipe"],cwd:M,env:{...O,NODE_ENV:"development",TERM:O.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:O,pty:q,shouldLogin:re}){let se=O.TERM||"xterm-color",Ie=q.spawn(R,yL(k,R,re),{name:se,cols:80,rows:30,cwd:M,env:{...O,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 O=m.findIndex(re=>re.key===k),q=O>=0?m[O]:void 0;if(q?.value===R)return!1;if(q&&R===void 0)m.splice(O,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=Lmt(R??"",t,e.workingDirectory));let O=!1;if(k.forceRestart&&(O=!0),he!==R&&(O=!0),JSON.stringify(M)!==JSON.stringify(Je)&&(O=!0),!O)return null;if(Je=M,he=R,y==="running")try{let q=f;f=void 0,await Ks(t,q,k.signal),le?.abort(),sn(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:Vr,async setProxyServer(k){let R=vs(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),O=M>=0?R.map((q,re)=>re===M?k:q):[...R,k];return I=O,{fileOverrides:O,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 O,q,re,se;try{if(await Sl(),k?.aborted)throw nn(k.reason);return await new Promise((Ie,Pe)=>{O=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(nn(k?.reason))},J.on("httpServerState",q),J.on("devState",re),k&&k.addEventListener("abort",se),re(y),q(B.state)})}finally{O!==void 0&&clearTimeout(O),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 Ks(t,k),n.clear(),i.clear(),G=[],s.clear(),o.clear(),a.clear(),Wne()}catch(k){t.Sentry?.captureException(k)}}}}var xDe,_B,
|
|
4233
|
+
`)),J.emit("close",on),Ie({status:"failure",code:on,output:F(1,"all")}))});let vn=on=>{if(c&&!A){let an=Moe(on,u);an&&(p=vs(an.url),p&&(A="terminal",Ht("auto-detected"),le?.abort(),$.info(`URL auto-detected: ${p.href}`),J.emit("urlDetected",p.href),nt()))}},cu=()=>{if(!Vo){Vo=!0,s.write(Ss),a.write(Ss);let on=G[G.length-1];on&&(on.out.write(Ss),on.all.write(Ss)),J.emit("stdout",Ss)}},Qy=on=>{if(f!==ut)return;cu();let an=on.toString();s.write(an),a.write(an),ge=performance.now();let Wr=G[G.length-1];Wr&&(Wr.out.write(an),Wr.all.write(an)),vn(an),J.emit("stdout",an)},zp=on=>{if(f!==ut)return;cu();let an=on.toString();o.write(an),a.write(an),ge=performance.now();let Wr=G[G.length-1];Wr&&(Wr.err.write(an),Wr.all.write(an)),vn(an),J.emit("stderr",an)};ut.stdout.on("data",Qy),ut.stderr.on("data",zp)}))}function ce({command:k,shell:R,cwd:M,env:O,shouldLogin:q}){let re=mA(R,k,{stdio:["inherit","pipe","pipe"],cwd:M,env:{...O,NODE_ENV:"development",TERM:O.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:O,pty:q,shouldLogin:re}){let se=O.TERM||"xterm-color",Ie=q.spawn(R,yL(k,R,re),{name:se,cols:80,rows:30,cwd:M,env:{...O,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=xH(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 G.slice(-k).map(O=>R==="all"?O.all.getCompactContent({maxLines:M}):R==="out"?O.out.getCompactContent({maxLines:M}):R==="err"?O.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 O=m.findIndex(re=>re.key===k),q=O>=0?m[O]:void 0;if(q?.value===R)return!1;if(q&&R===void 0)m.splice(O,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=Lmt(R??"",t,e.workingDirectory));let O=!1;if(k.forceRestart&&(O=!0),he!==R&&(O=!0),JSON.stringify(M)!==JSON.stringify(Je)&&(O=!0),!O)return null;if(Je=M,he=R,y==="running")try{let q=f;f=void 0,await Ks(t,q,k.signal),le?.abort(),sn(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:Vr,async setProxyServer(k){let R=vs(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),O=M>=0?R.map((q,re)=>re===M?k:q):[...R,k];return I=O,{fileOverrides:O,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 O,q,re,se;try{if(await Sl(),k?.aborted)throw nn(k.reason);return await new Promise((Ie,Pe)=>{O=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(nn(k?.reason))},J.on("httpServerState",q),J.on("devState",re),k&&k.addEventListener("abort",se),re(y),q(B.state)})}finally{O!==void 0&&clearTimeout(O),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 Ks(t,k),n.clear(),i.clear(),G=[],s.clear(),o.clear(),a.clear(),Wne()}catch(k){t.Sentry?.captureException(k)}}}}var xDe,_B,A4,c4,FDe,nm,Ss,HA,xH,Gmt,kB=L(()=>{"use strict";h();fa();Foe();xDe=z(require("node:events"),1),_B=require("node:child_process");K0();JI();Poe();rr();A4=z(require("node:https"),1),c4=z(require("node:http"),1);Goe();aU();FDe=require("node:fs");$oe();Ic();s4();Ap();pI();nm=z(require("node:path"),1),Ss="\x1B[2J\x1B[H",HA="[BUILDER.IO]";xH=t=>{let e,r;_mt(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};Gmt=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 ${on}
|
|
|
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 kDe(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 kDe(t){return t instanceof Error?t.message:String(t)}function UB(t,e){if(u4(e).test(t))return!0;if(e.toLowerCase().includes("localhost")){let n=e.replace(/localhost/gi,"127.0.0.1");if(u4(n).test(t))return!0}else if(e.includes("127.0.0.1")){let n=e.replace(/127\.0\.0\.1/g,"localhost");if(u4(n).test(t))return!0}return!1}function u4(t){return t=String(t).replace(/\./g,"\\.").replace(/\?/g,".").replace(/\*/g,".*"),new RegExp(`^${t}$`,"i")}var vx,RDe=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: ${kDe(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: ${kDe(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 TDe,Omt,l4,NDe=L(()=>{"use strict";h();TDe=z(require("node:os"),1);Bt();Omt=ve("Priority"),l4=(t,e)=>{try{TDe.default.setPriority(t,e)}catch(r){Omt.error(`Failed to set priority to ${e}: ${r}`)}}});async function*Kmt(t){for await(let e of of(t.body))if(e.length)try{yield JSON.parse(e)}catch{}}function Hmt(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 Jmt(t,e){return e??("builderUserId"in t.user?t.user.builderUserId:t.user.source==="builder.io"?t.user.userId:t.credentials.userId)}function MDe(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=Jmt(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 Kmt(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)}`),Hmt({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 PDe=L(()=>{"use strict";h();Js();Jv();hr();Qr();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 PDe=L(()=>{"use strict";h();Js();Jv();hr();Qr();lw();e4();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`)}`)}In("bye \u{1F44B}")}var ie,GB=L(()=>{"use strict";h();rr();ie=z(Er(),1);xt();_s();Xr()});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`)}`)}In("bye \u{1F44B}")}var ie,GB=L(()=>{"use strict";h();rr();ie=z(Er(),1);xt();_s();Xr()});function OB(){let{env:t}=g4.default,{TERM:e,TERM_PROGRAM:r}=t;return g4.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 g4,p4=L(()=>{h();g4=z(require("node:process"),1)});var d4,im,KB,jmt,yi,f4,Sx,Ymt,qmt,$mt,Vmt,Ml=L(()=>{"use strict";h();p4();d4=z(Er(),1),im=z(xy(),1);Bt();KB=z(Er(),1),jmt=ve("Spinner"),yi=()=>{let t=f4?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],e=f4?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)=>{jmt.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(`${d4.default.gray(Ymt)}
|
|
4484
|
+
`);let C=0,I=0;u(),process.env.CI||(r=setInterval(()=>{let y=d4.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)(Vmt):C===1?(0,KB.red)(qmt):(0,KB.red)($mt);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}}},f4=OB(),Sx=(t,e)=>f4?t:e,Ymt=Sx("\u2502","|"),qmt=Sx("\u25A0","x"),$mt=Sx("\u25B2","x"),Vmt=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 h4,LDe,m4,C4,sm,HB,xx,I4,Wmt,zmt,Xmt,E4,_De,xs,Ho,Zmt,UDe,GDe,ODe,B4,KDe,JA=L(()=>{"use strict";h();vi();Zh();h4=z(require("@sentry/node"),1);Bt();Rr();Qr();hr();Fi();rr();LDe=require("node:path"),m4=ve("RepoIndexing"),C4="AGENTS.md",sm="icons.mdx",HB="tokens.mdx",xx="installation.md",I4="repo-indexing",Wmt=[{value:"space",label:"Space",hint:"Available to all applications in your current space"}],zmt=[{value:"organization",label:"Organization",hint:"Available to all applications in your organization"}],Xmt=[{value:"global",label:"Global",hint:"Available to all applications in the Builder platform"}],E4=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=[...Wmt];if((i||s)&&o.push(...zmt),s&&o.push(...Xmt),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 bi({message:"What is your design system scope?",options:o});if(!je(a))return a},_De=async(t,e)=>{try{let r=t.getAppRootDir(),n=await Xo(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 m4.error("Error parsing design system",r,{loggerOptions:{debug:!0}}),{name:void 0,version:void 0}}},xs=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 m4.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}},Ho=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:Zmt(d,g),workingDirectory:t.cwd(),...o&&{workspace:o}};s&&!(0,LDe.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"&&m4.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){h4.captureException(D,{extra:{expectedFile:l,expectedFilePath:Q}})}}}if(!m){let Q=h4.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 Ho(t,e,r,n,i,s,o,{...a,retriesAllowed:u-1},A)}},Zmt=(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 Ho(t,e,r,n,i,s,o,{...a,retriesAllowed:u-1},A)}},Zmt=(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:C4,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}};UDe=(t,e)=>e.find(r=>r.designSystemName===t)||null,GDe=(t,e,r,n)=>n&&n.find(i=>i.designSystemName===e&&i.scope===r)||null,ODe=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},B4=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()},KDe=async t=>{let e=t.join(t.getAppRootDir(),I4);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 eCt(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 bi({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 JDe(t){return t.replace(YDe,"").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 JDe(t){return t.replace(YDe,"").length}function y4(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(JDe(p)>o){let f=0,m=0;for(;m<o-3&&f<p.length;)p.substring(f).match(YDe)?.[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-JDe(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 tCt(t,e){let r="https://docs.google.com/forms/d/e/1FAIpQLSdHUIxeN
|
|
|
4509
4509
|
${a}${A}`}function sCt(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 D4(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 Xo(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 br({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 qDe(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 oCt(){return process.stdout.isTTY||process.env.FORCE_TTY==="1"}function aCt(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var ot,Fx,Q4,jDe,kx,HDe,YDe,Rx=L(()=>{"use strict";h();ot=z(Er(),1);Cp();rr();Rr();_s();GB();vi();Fx=z(require("node:os"),1);Xr();Js();Zh();Tx();Ic();Ml();Q4=z(require("node:readline"),1);Ms();TB();NB();JA();jDe=async(t,e,r)=>{r.prototype?await $De(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)),!oCt()&&!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 D4(t,!e.prompt);let r=await Wt(t,e,{forceSpaceId:e.spaceId,builderPrivateKey:!0,builderPublicKey:!0}),n,i;if(e.workspace){let I=await WDe(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 br({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 br({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 br({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 br({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 _H(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=Q4.default.createInterface({input:process.stdin,output:process.stdout}),process.stdin.isTTY&&process.stdin.setRawMode(!0),Q4.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(),rCt(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=VDe(),pu.message(p[0],{symbol:(0,ot.magenta)("~")})):(g=yi(),g.start(I.title),g.extra(HDe));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
|
+
`:"")+y4(f,ot.magenta," ",-15)+`
|
|
4520
4520
|
`+HDe));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 eCt(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)} (${aCt(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
|
+
${y4(QL(I.result.content).trim(),ot.red,"")}`):$.info(`${I.result.title?I.result.title:`Tool: ${I.result.tool_name}`}
|
|
4529
4529
|
|
|
4530
|
-
${
|
|
4530
|
+
${y4(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 br({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 br({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(iCt(I.usage.total,I.usage.limits.aiGeneration)),I.applyResults.length>0&&$.success(sCt(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 nCt(a),await Me(0)};HDe=`
|
|
4532
|
-
`+(0,ot.dim)("ESC to interrupt"),YDe=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g});function ACt(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=ACt(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 gCt(t){let e=t.split("/");for(let i of e)if(cCt.has(i))return!1;let r=e[e.length-1];if(uCt.has(r))return!1;let n=r.includes(".")?"."+r.split(".").pop():"";return lCt.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=wn(Ma.default.join(
|
|
4532
|
+
`+(0,ot.dim)("ESC to interrupt"),YDe=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g});function ACt(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=ACt(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 gCt(t){let e=t.split("/");for(let i of e)if(cCt.has(i))return!1;let r=e[e.length-1];if(uCt.has(r))return!1;let n=r.includes(".")?"."+r.split(".").pop():"";return lCt.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=wn(Ma.default.join(w4.default.homedir(),".builder","prototypes")),c=wn(Ma.default.join(A,`${e}__${a}`)),u=wn(Ma.default.join(c,"code")),l;o&&(l=ss()),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 w=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:w}}),o&&(l.stop("Failed to get bundle URL"),$.error(w));return}if(!g.ok){let w=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:w}}),o&&(l.stop("Failed to resolve branch"),$.error(w));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(w){Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"bundle-download"},extra:{projectId:e,branchName:r,partial:f,error:w instanceof Error?w.message:String(w)}}),o&&(l.stop("Failed to download bundle"),$.error(`Bundle download failed: ${w instanceof Error?w.message:String(w)}`));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(w4.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:w}=await jB("git",["-C",Q,"bundle","unbundle",E],{cwd:B}),P=w.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(w){Lp.captureException(new Error("pullPrototypeError"),{tags:{operation:"pull-prototype",step:"git-extract"},extra:{projectId:e,branchName:r,partial:f,checkoutBranch:S,error:w instanceof Error?w.message:String(w)}}),o&&(l.stop("Failed to extract bundle"),$.error(`Could not extract git bundle: ${w}`)),tu.default.rmSync(B,{recursive:!0,force:!0});return}let{stdout:x}=await jB("git",["ls-files"],{cwd:Q});tu.default.mkdirSync(u,{recursive:!0});for(let w of x.trim().split(`
|
|
4533
4533
|
`).filter(Boolean))if(gCt(w))try{let P=Ma.default.join(Q,w),G=Ma.default.join(u,w);tu.default.mkdirSync(Ma.default.dirname(G),{recursive:!0}),tu.default.copyFileSync(P,G)}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 $De(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 dCt();if(!l)return;let d=Ma.default.relative(process.cwd(),c.projectDir);e.prompt=pCt(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 dCt();if(!l)return;let d=Ma.default.relative(process.cwd(),c.projectDir);e.prompt=pCt(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 b4(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 pCt(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
|
+
${b4(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 dCt(){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 zDe,tu,
|
|
4553
|
+
${r}`}async function dCt(){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 zDe,tu,w4,Ma,XDe,Pl,Lp,jB,cCt,uCt,lCt,Tx=L(()=>{"use strict";h();zDe=require("node:child_process"),tu=z(require("node:fs"),1),w4=z(require("node:os"),1),Ma=z(require("node:path"),1),XDe=require("node:util");rr();Pl=z(Er(),1),Lp=z(require("@sentry/node"),1);Qr();Rr();hr();xv();Xr();Rx();JB();jB=(0,XDe.promisify)(zDe.execFile),cCt=new Set(["node_modules","dist","build",".git",".next",".nuxt",".svelte-kit",".output","__pycache__",".turbo",".cache","coverage",".vite","storybook-static"]),uCt=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"]),lCt=new Set([".ts",".tsx",".js",".jsx",".vue",".svelte",".css",".scss",".less",".html",".astro"])});function ZDe(t){let e=t.tokenCategories??fCt,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
|
-
${AIt(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 _Ct(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=Dn([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=Fs.dirname(process.execPath),n=Fs.join(r,"bin",e);if(t.existsSync(n))return n}}catch{}try{let r=Fs.dirname(process.execPath),n=Fs.join(r,e);if(t.existsSync(n))return n}catch{}try{let r=process.platform==="win32"?"win32-x64":`${process.platform}-${process.arch}`,n=Fs.join(__dirname,"..","vendors",r,e);if(t.existsSync(n))return n}catch{}return"rg"}async function OCt(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}`)),UCt.forEach(p=>{c.push("--glob",p)}),l+=d,GCt(e.query)&&c.push("--fixed-strings"),c.push("--",e.query);let g=await KCt(A,c,u,r,e.query,d,l);if(!g.isError&&g.toolResult)try{let p=await hoe(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 swe(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 KCt(t,e,r,n,i,s,o){return new Promise(a=>{let A=new Mi(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
|
+
${AIt(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 _Ct(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=Dn([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=Fs.dirname(process.execPath),n=Fs.join(r,"bin",e);if(t.existsSync(n))return n}}catch{}try{let r=Fs.dirname(process.execPath),n=Fs.join(r,e);if(t.existsSync(n))return n}catch{}try{let r=process.platform==="win32"?"win32-x64":`${process.platform}-${process.arch}`,n=Fs.join(__dirname,"..","vendors",r,e);if(t.existsSync(n))return n}catch{}return"rg"}async function OCt(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}`)),UCt.forEach(p=>{c.push("--glob",p)}),l+=d,GCt(e.query)&&c.push("--fixed-strings"),c.push("--",e.query);let g=await KCt(A,c,u,r,e.query,d,l);if(!g.isError&&g.toolResult)try{let p=await hoe(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 swe(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 KCt(t,e,r,n,i,s,o){return new Promise(a=>{let A=new Mi(1e4),c=Cc({command:t,args:e,options:{env:process.env,cwd:r,stdio:["ignore","pipe","pipe"],signal:n}});c.on("spawn",()=>{c.pid&&l4(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 HCt(t){return t.includes("npm i")||t==="yarn"||t.includes("pnpm i")}function JCt(t){return fI(t).some(r=>r.startsWith("git ")||r.startsWith("gh "))}async function owe(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(G)}`),B({isError:!0,toolResult:P,title:`${g} command "${e}"`})};D.on("spawn",()=>{D.pid&&
|
|
4742
|
+
${l(G)}`),B({isError:!0,toolResult:P,title:`${g} command "${e}"`})};D.on("spawn",()=>{D.pid&&l4(D.pid,10),C.aborted?x():C.addEventListener("abort",x,{once:!0})}),D.on("error",w=>{B({isError:!0,toolResult:l(S.getContent().slice(0,5e3))+`
|
|
4743
4743
|
`+String(w),title:`${g} command "${e}"`})}),D.on("exit",w=>{let P=l(S.getContent().slice(0,5e3)),G=w!==0;G&&(P+=`
|
|
4744
4744
|
exited with code ${w}`,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 cIt(t){let{sys:e,bashWorkingDirectory:r}=t,n=r;try{let i=Fs.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=Fs.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=Fs.join(n,".builder","output","tokens","components"),g=await e.readdir(d);for(let p of g)if(p.endsWith(".css")){let f=Fs.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=Fs.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 Fs,Pa,rwe,nwe,UCt,GCt,
|
|
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 x=1;x<S.length;x++)Q.add(S.slice(0,x).join("/")+"/")}let v=[...C,...Q].sort();p(v);return}p(C)})})}async function gIt(t,e,r){let n=await qw("**/*",{cwd:t,ignoreFiles:Am,ignore:VB}),i=[];for(let s of n){let o=(0,Oi.resolve)(t,s);try{let a=(0,ts.readFileSync)(o,"utf-8");if(a.includes("This code was generated by Builder.io")){let A=uwe(a);if(e&&r&&(A.contentId!==e||A.sessionKey!==r))continue;i.push({path:s,code:Nx(a),name:s.split("/").pop()||"",timestamp:(0,ts.statSync)(o).mtime.getTime(),snippetId:A.snippetId})}}catch(a){am.error(`Error reading file ${o}:`,a)}}return i}function pIt(t,e){let r=uwe(t);return r.contentId===e.contentId&&r.sessionKey===e.sessionKey}function oye(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,Oi.resolve)(t,n);if((0,ts.existsSync)(i)){let s=(0,ts.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(Oi.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(Oi.sep).join("/");return r.ignores(s)}}function awe(t,e,r){let n=k4(t),i=cwe.default.watch(t,{ignored:n,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:600},ignorePermissionErrors:!0,followSymlinks:!1,atomic:600}),s=async a=>{let A=(0,Oi.relative)(t,a);try{let c=(0,ts.readFileSync)(a,"utf-8");if(pIt(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,Oi.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,Oi.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,Oi.relative)(t,c.oldPath):void 0,l=A?(0,Oi.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 lwe(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=awe(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=awe(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 gIt(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:Awe(o.map(d=>d.path)),timeStamp:l}}let a=hL(i,r.framework||"react"),A=t.path||Awe(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,Oi.resolve)(i,l.path);try{(0,ts.unlinkSync)(d),$.info(`Deleted old file: ${d}`);let g=(0,Oi.dirname)(d);(0,ts.readdirSync)(g).length===0&&((0,ts.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 Awe(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 Oi,ts,Ll,cwe,vH,am,uIt,Am,VB,Cp=L(()=>{"use strict";h();Oi=require("node:path");Bt();ts=require("node:fs"),Ll=z(Er(),1);one();pQ();dL();mL();rr();cwe=z(require("chokidar"),1),vH=z(require("ignore"),1);Ms();GC();Xr();fa();F4();am=ve("Sync");uIt=!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,pwe.homedir)();if(p)try{for(let C of dIt){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){gwe.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){gwe.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 pwe,gwe,dIt,T4=L(()=>{"use strict";h();pwe=require("node:os");SZ();Cp();TO();Bt();gwe=ve("RulesDiscovery");dIt=[".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 Aye(t){return FB(t)??N4(t)}function cye(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 uye(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 lye(t){for(let e=t.length-1;e>=0;e--)t[e].state!=="done"&&t.splice(e,1)}async function gye(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 dwe(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*pye(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:Dn([n,s.signal])},i);if(!p.ok){let m=await p.text(),C=`Bad Status: ${p.status}: ${m}`;if(p.status===413){let y=dwe(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 cIt(t){let{sys:e,bashWorkingDirectory:r}=t,n=r;try{let i=Fs.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=Fs.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=Fs.join(n,".builder","output","tokens","components"),g=await e.readdir(d);for(let p of g)if(p.endsWith(".css")){let f=Fs.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=Fs.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 Fs,Pa,rwe,nwe,UCt,GCt,FH=L(()=>{"use strict";h();Js();pI();PL();mI();z_();mI();HI();moe();O0();fa();Fs=z(require("node:path"),1);Tu();K0();kB();Zh();Pa=z(require("@sentry/node"),1);JI();Fi();RDe();Qr();NDe();PDe();Tx();ewe();JB();NO();aU();rwe=5e4;nwe=new Set(["mcp__chrome__click","mcp__chrome__hover","mcp__chrome__fill","mcp__chrome__type","mcp__chrome__select_option","mcp__chrome__press_key"]);UCt=["!**/.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"],GCt=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 uwe(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&&uIt)try{return await lIt(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 lIt({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,Oi.resolve)(t,p);(0,ts.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 x=1;x<S.length;x++)Q.add(S.slice(0,x).join("/")+"/")}let v=[...C,...Q].sort();p(v);return}p(C)})})}async function gIt(t,e,r){let n=await qw("**/*",{cwd:t,ignoreFiles:Am,ignore:VB}),i=[];for(let s of n){let o=(0,Oi.resolve)(t,s);try{let a=(0,ts.readFileSync)(o,"utf-8");if(a.includes("This code was generated by Builder.io")){let A=uwe(a);if(e&&r&&(A.contentId!==e||A.sessionKey!==r))continue;i.push({path:s,code:Nx(a),name:s.split("/").pop()||"",timestamp:(0,ts.statSync)(o).mtime.getTime(),snippetId:A.snippetId})}}catch(a){am.error(`Error reading file ${o}:`,a)}}return i}function pIt(t,e){let r=uwe(t);return r.contentId===e.contentId&&r.sessionKey===e.sessionKey}function oye(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,Oi.resolve)(t,n);if((0,ts.existsSync)(i)){let s=(0,ts.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(Oi.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(Oi.sep).join("/");return r.ignores(s)}}function awe(t,e,r){let n=kH(t),i=cwe.default.watch(t,{ignored:n,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:600},ignorePermissionErrors:!0,followSymlinks:!1,atomic:600}),s=async a=>{let A=(0,Oi.relative)(t,a);try{let c=(0,ts.readFileSync)(a,"utf-8");if(pIt(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,Oi.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,Oi.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,Oi.relative)(t,c.oldPath):void 0,l=A?(0,Oi.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 lwe(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=awe(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=awe(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 gIt(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:Awe(o.map(d=>d.path)),timeStamp:l}}let a=hL(i,r.framework||"react"),A=t.path||Awe(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,Oi.resolve)(i,l.path);try{(0,ts.unlinkSync)(d),$.info(`Deleted old file: ${d}`);let g=(0,Oi.dirname)(d);(0,ts.readdirSync)(g).length===0&&((0,ts.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 Awe(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 Oi,ts,Ll,cwe,v4,am,uIt,Am,VB,Cp=L(()=>{"use strict";h();Oi=require("node:path");Bt();ts=require("node:fs"),Ll=z(Er(),1);one();pQ();dL();mL();rr();cwe=z(require("chokidar"),1),v4=z(require("ignore"),1);Ms();GC();Xr();fa();FH();am=ve("Sync");uIt=!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,pwe.homedir)();if(p)try{for(let C of dIt){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){gwe.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){gwe.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 pwe,gwe,dIt,TH=L(()=>{"use strict";h();pwe=require("node:os");SZ();Cp();TO();Bt();gwe=ve("RulesDiscovery");dIt=[".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 Aye(t){return FB(t)??NH(t)}function cye(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 uye(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 lye(t){for(let e=t.length-1;e>=0;e--)t[e].state!=="done"&&t.splice(e,1)}async function gye(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 dwe(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*pye(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:Dn([n,s.signal])},i);if(!p.ok){let m=await p.text(),C=`Bad Status: ${p.status}: ${m}`;if(p.status===413){let y=dwe(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 ai){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=dwe(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&&en(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?Dn([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&&en(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:Dn([o,AbortSignal.timeout(1e4)])},i)).json()}catch(a){return a instanceof qe&&en(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 fye(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 VDe(){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 hwe(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 ai){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=dwe(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&&en(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?Dn([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&&en(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:Dn([o,AbortSignal.timeout(1e4)])},i)).json()}catch(a){return a instanceof qe&&en(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 fye(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 VDe(){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 hwe(t,e){return t.split(e).length-1}function MH(t){return t=t.toLowerCase(),t.endsWith("claude.md")||t.endsWith("agent.md")||t.endsWith("agents.md")}function hye(t,e){if(!t.startsWith(e))return!1;t=t.slice(e.length);let n=hwe(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 mye(t,e){return MH(t)?(t.startsWith(e)&&(t=t.slice(e.length)),hwe(t,"/")===0):!1}function Cye(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 WDe(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 fIt.error(`Error loading workspace: ${r instanceof Error?r.message:String(r)}`),r}}function bH(t){let e=t[0];for(let r=1;r<t.length;r++)e=PH(e,t[r]);return e}function PH(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 Iye(){let t=setInterval(()=>{},1073741824);return()=>clearInterval(t)}function
|
|
4844
|
+
`+e.userPrompt,files:Array.from(new Set([...t.files??[],...e.files??[]])),includeBaseFiles:t.includeBaseFiles}}function Iye(){let t=setInterval(()=>{},1073741824);return()=>clearInterval(t)}function vH(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 Eye(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 Bye(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(nn(e?.reason))};if(e.addEventListener("abort",i),e.aborted){e.removeEventListener("abort",i),n(nn(e.reason));return}t.then(s=>{e.removeEventListener("abort",i),r(s)},s=>{e.removeEventListener("abort",i),n(s)})})}function yye(t,e){return Promise.race([t.then(()=>!1,()=>!1),new Promise(r=>setTimeout(()=>r(!0),e))])}function nn(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,fwe,fIt,ux,aye,dye,Oo,Tp,Ic=L(()=>{"use strict";h();Rr();Qr();hr();Lx=z(require("node:os"),1),fwe=require("node:path/posix");yZ();uw();Bt();Fi();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(nn(e?.reason))};if(e.addEventListener("abort",i),e.aborted){e.removeEventListener("abort",i),n(nn(e.reason));return}t.then(s=>{e.removeEventListener("abort",i),r(s)},s=>{e.removeEventListener("abort",i),n(s)})})}function yye(t,e){return Promise.race([t.then(()=>!1,()=>!1),new Promise(r=>setTimeout(()=>r(!0),e))])}function nn(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 SH(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 Qye(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 hIt(t){return t?.folders?.length===1||!t?.folders?.length}function Dye(t){let e=t?.folders.find(i=>i.enableGit);if(!e?.name)return"";let r=hIt(t)?"":`${e.name}/`,n=e.recommendedRoot;return n?uP((0,fwe.join)(r,uP(n))):r}function lx(t){return`GH_TOKEN_${t.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`}function mIt(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 CIt(t){return t==="gitlab"?{full:"Merge Request",short:"MR"}:{full:"Pull Request",short:"PR"}}function wye(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=mIt(A),l=CIt(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,fwe,fIt,ux,aye,dye,Oo,Tp,Ic=L(()=>{"use strict";h();Rr();Qr();hr();Lx=z(require("node:os"),1),fwe=require("node:path/posix");yZ();uw();Bt();Fi();lw();TH();JI();Tu();Tu();fIt=ve("CodegenUtils"),ux=100,aye=200;dye=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}};Oo=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 IIt(t){return t.replace(/(https?:\/\/)([^@\s]+@)?([^\/\s]+)/g,(e,r,n,i)=>n?`${r}***@${i}`:e)}async function zs(t,e,r){let n=Math.max(r.retry??0,0)+1,i;for(let s=0;s<n;s++)try{return await EIt(t,e,r)}catch(o){i=o,s<n-1&&await Rg(s)}throw i}function Go(){let t=mwe;return mwe++,t.toString()}function EIt(t,e,r){let n=`${t} ${e.join(" ")}`,i=performance.now(),s=Go();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 IIt(t){return t.replace(/(https?:\/\/)([^@\s]+@)?([^\/\s]+)/g,(e,r,n,i)=>n?`${r}***@${i}`:e)}async function zs(t,e,r){let n=Math.max(r.retry??0,0)+1,i;for(let s=0;s<n;s++)try{return await EIt(t,e,r)}catch(o){i=o,s<n-1&&await Rg(s)}throw i}function Go(){let t=mwe;return mwe++,t.toString()}function EIt(t,e,r){let n=`${t} ${e.join(" ")}`,i=performance.now(),s=Go();r.skipLogging||x4.debug(`(id=${s}): starting (cwd: ${r.cwd||"NOT SET"}): ${IIt(n)}`);let o=new Promise((a,A)=>{let c="",u="",l=(0,Cwe.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(()=>{Ks(r.sys,l).then(()=>{A(new Oo(n,void 0,c,u,{cause:new Error(`${t} command timed out`)}))})},r.timeout):void 0;l.on("error",g=>{clearTimeout(d),A(new Oo(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&&BIt(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&&yIt(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 Oo(n,g,c,u)}));return}A(new Oo(n,g??void 0,c,u))}})});return r.skipLogging?o:o.then(a=>{let A=Math.round(performance.now()-i);return x4.debug(`(id=${s}): success (code: 0) [${A}ms] ${a.replaceAll(`
|
|
4851
4851
|
`," ").trim()}`),a}).catch(a=>{let A=a instanceof Oo?a:a?.cause instanceof Oo?a.cause:null;if(A){let c=Math.round(performance.now()-i),u=`${A.stdout.trim()} ${A.stderr.trim()}`.replaceAll(`
|
|
4852
|
-
`," ").trim();
|
|
4852
|
+
`," ").trim();x4.debug(`[GIT](id=${s}): error (code: ${A.code}) [${c}ms] ${u}`)}throw a})}async function Gc(t,e){try{return(await zs("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 Cwe,x4,mwe,BIt,yIt,Fo=L(()=>{"use strict";h();Ic();fa();Cwe=require("node:child_process");Qr();hr();uw();Bt();x4=ve("Git");mwe=0;BIt=(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))},yIt=(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 ywe(){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}},vIt="https://api.figma.com/v1/",ru=async(t,e,r,{auth:n,params:i})=>{let s=new URL(`${vIt}${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()},SIt=async(t,e,r,n,i,s)=>(await ru(t,e,`files/${n}/nodes`,{auth:r,params:{ids:i,depth:s}})).nodes;xIt=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 ywe(){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&&R4.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);R4.warn(`Error detecting PAC URL: ${e}`),Ul=null}return Ul=null,null}async function QIt(t){if(um===void 0){let e=ywe();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,Ewe.getQuickJS)();um=await(0,Iwe.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){R4.info(`PAC resolution failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}async function DIt(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 QIt(t);if(n)return new YA.ProxyAgent({uri:n,connect:{rejectUnauthorized:e},requestTls:{rejectUnauthorized:e}})}return cm||ywe()||(cm=new YA.Agent({connect:{rejectUnauthorized:e}})),cm||new YA.Agent({connect:{rejectUnauthorized:e}})}function wIt(){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 yDe(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,Iwe,Ewe,_x,jA,Bwe,R4,F4,cm,Ul,um,k4,Fe,hr=L(()=>{"use strict";h();YA=require("undici"),Iwe=z(qX(),1),Ewe=z(eP(),1),_x=require("node:child_process");hZ();jA=z(require("node:process"),1),Bwe=z(require("@sentry/node"),1);Fi();Bt();Tu();Qr();Fo();R4=ve("Proxy"),F4=ve("Fetch");Fe=async(t,e,r)=>{let n=new URL(t),i=n.hostname,s=n.port?parseInt(n.port):void 0,o=Go(),a=performance.now(),A="";try{let c=Bwe.getTraceData(),u=await DIt(n.toString());r&&F4.info(`(${o}): ${n.href}`);let l=n.hostname==="api.builder.io",d=await(0,YA.fetch)(n,{...e,dispatcher:u,headers:{...e?.headers,...wIt(),...c,...k4&&l?{Cookie:k4.join("; ")}:{}}});if(l&&(k4=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 ai(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 ai(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 ai||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)?F4.warn(`(${o}): ${e?.method??"GET"} ${n.pathname} ${A} [${c}ms]`):r&&F4.info(`(${o}): ${A} [${c}ms]`)}}});async function Qwe(t,e,r,n,i){if(i.length>0){let s=await xIt(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,T4,vIt,ru,SIt,xIt,N4=L(()=>{"use strict";h();rr();hr();Ms();bIt=z(require("@sentry/node"),1);Qr();Rr();kf();T4=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}},vIt="https://api.figma.com/v1/",ru=async(t,e,r,{auth:n,params:i})=>{let s=new URL(`${vIt}${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()},SIt=async(t,e,r,n,i,s)=>(await ru(t,e,`files/${n}/nodes`,{auth:r,params:{ids:i,depth:s}})).nodes;xIt=async(t,e,r,n)=>{if(!r)return{};let i=new Map,s={};return n.forEach(o=>{let a=T4(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 SIt(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 M4(t){return!(t.category!==Jo.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 Jo,Dwe=L(()=>{"use strict";h();Jo=z(require("typescript"),1)});async function FIt(t,e,r){let n=[],i=[e],s=t.relative(t.getAppRootDir(),e.fileName);for(;i.length>0;){let o=i.shift();if(MIt(o,e)){let a=RIt(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 RIt(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=wwe(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 x of S.properties)yt.default.isPropertyAssignment(x)&&yt.default.isIdentifier(x.name)&&x.name.text==="imports"&&yt.default.isArrayLiteralExpression(x.initializer)&&(m.imports=x.initializer.elements.map(P=>{if(yt.default.isStringLiteral(P))return P.text;if(yt.default.isObjectLiteralExpression(P)){let G={};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)&&(G[_]=J.initializer.text)}return G}return null}).filter(Boolean))}break}case"mapper":if(yt.default.isMethodDeclaration(v)){let S=function(w){let G=n.getSymbolAtLocation(w)?.getDeclarations()?.[0];if(G){let J=NIt(G);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},x=function(w){if((yt.default.isJsxOpeningElement(w)||yt.default.isJsxSelfClosingElement(w))&&yt.default.isIdentifier(w.tagName)){u=w.tagName.getText(r),S(w.tagName);return}else if(yt.default.isTaggedTemplateExpression(w)&&yt.default.isIdentifier(w.tag)&&(w.tag.escapedText==="html"||w.tag.escapedText==="tmpl")){if(yt.default.isTemplateExpression(w.template)){let G=w.template.templateSpans.find(J=>yt.default.isIdentifier(J.expression)&&TIt(J.expression.text)&&S(J.expression));if(G&&yt.default.isIdentifier(G.expression)){u=G.expression.text;return}}let P=w.template.getText(r).match(/^`\s*<([^\s]+)/);if(P){u=P[1];return}if(P=w.template.getText(r).match(/^`\s*([^\s]+)/),P){u=P[1];return}}else yt.default.forEachChild(w,x)};var E=S,Q=x;if(v.parameters&&v.parameters.length>0&&v.parameters[0]&&v.parameters[0].type){let w=v.parameters[0].type.getText(r),P=wwe(w);P&&(l=P)}yt.default.forEachChild(v,x),c=v.getText(r).replace(/^mapper/,"function Mapper"),A=P4(c);break}case"designTokenMapper":if(yt.default.isMethodDeclaration(v)){c=v.getText(r).replace(/^designTokenMapper/,"function Mapper"),A=P4(c),o="design-tokens";break}case"genericMapper":if(yt.default.isMethodDeclaration(v)){c=v.getText(r).replace(/^genericMapper/,"function Mapper"),A=P4(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=GIt(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 TIt(t){return t.charAt(0)===t.charAt(0).toUpperCase()}function P4(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 NIt(t){let e=t;for(;e;){if(yt.default.isImportDeclaration(e))return e;e=e.parent}}function MIt(t,e){return yt.default.isCallExpression(t)&&t.expression.getText(e)===kIt}async function AI(t){let e=["node_modules","dist","build","public"];return(await t.readdirRecursive(t.getAppRootDir(),e)).filter(n=>to(n))}function wwe(t){let e=t.match(/^Figma(\w+)Props$/);if(e&&typeof e[1]=="string")return e[1]}async function L4(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 _It(t){return yt.default.formatDiagnosticsWithColorAndContext(t,LIt)}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 Sn(t,e),a=o.getTypeChecker(),A=o.getSyntacticDiagnostics().filter(M4).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
|
-
${_It(A)}`),Me(1);let c=[...r?o.getSemanticDiagnostics():[]].filter(
|
|
4857
|
+
${_It(A)}`),Me(1);let c=[...r?o.getSemanticDiagnostics():[]].filter(M4);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 FIt(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 UIt(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 "+Io(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 "+Io(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 GIt(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,bwe,kIt,PIt,LIt,cI=L(()=>{"use strict";h();yt=z(require("typescript"),1);Rr();rr();mt=z(Er(),1);no();pQ();yV();Ms();Qr();xt();_s();hr();Xr();kf();
|
|
4862
|
+
`);$.error(i)}return{filteredLinks:r,skippedLinks:n}}function GIt(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,bwe,kIt,PIt,LIt,cI=L(()=>{"use strict";h();yt=z(require("typescript"),1);Rr();rr();mt=z(Er(),1);no();pQ();yV();Ms();Qr();xt();_s();hr();Xr();kf();N4();Rx();Dwe();bwe=async(t,e)=>{let r=await qDe(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 D4(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:x}=UIt(o);c=S,u=x}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 Qwe(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 br({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 x of c)if(x.imports&&x.imports.length>0){let w=x.imports.filter(P=>P.importPath?.startsWith("."));w.length>0&&(D=!0,$.warn(`${(0,mt.dim)(`Found relative imports in ${x.loc}:`)}
|
|
4865
4865
|
${w.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 bi({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=ss(),y=await t.getRepoInfo(),B;if(e.dryrun||(I.start("Publishing Figma Mappings"),B=await PIt(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 bi({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=ss(),y=await t.getRepoInfo(),B;if(e.dryrun||(I.start("Publishing Figma Mappings"),B=await PIt(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 L4(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";In((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})};kIt="figmaMapping";PIt=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")},LIt={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})};kIt="figmaMapping";PIt=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")},LIt={getCanonicalFileName:t=>t,getCurrentDirectory:()=>yt.default.sys.getCurrentDirectory(),getNewLine:()=>yt.default.sys.newLine}});function U4(){return(0,mn.join)((0,Gx.homedir)(),".builder","config","data.json")}async function JIt(t,e){let r=(0,Swe.randomUUID)();return kwe({sys:t,name:"Figma",initialPort:OIt,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=HIt,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=xwe(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=xwe(t,r);if(e=Object.assign(n,e),r==="user"){let s=U4();try{(0,rs.mkdirSync)((0,mn.dirname)(s),{recursive:!0}),(0,rs.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,mn.join)(t.getAppRootDir(),"node_modules",".builder","data.json"),shouldTry:()=>(0,rs.existsSync)((0,mn.join)(t.getAppRootDir(),"node_modules")),ensureGitignore:!1},{path:(0,mn.join)(t.getAppRootDir(),".builder","config","data.json"),shouldTry:()=>!0,ensureGitignore:!0},{path:(0,mn.join)(t.getAppRootDir(),".config","builderio","data.json"),shouldTry:()=>!0,ensureGitignore:!0}];for(let s of i)if(s.shouldTry())try{(0,rs.mkdirSync)((0,mn.dirname)(s.path),{recursive:!0}),(0,rs.writeFileSync)(s.path,JSON.stringify({credentials:e},null,2)),s.ensureGitignore&&YIt(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 YIt(t,e){let r=(0,mn.join)(t.getAppRootDir(),".gitignore"),n=(0,mn.relative)(t.getAppRootDir(),e).replace(/\\/g,"/");try{let i="";if((0,rs.existsSync)(r)&&(i=(0,rs.readFileSync)(r,"utf8")),!i.split(`
|
|
5095
5095
|
`).some(a=>{let A=a.trim();return A===n||A===(0,mn.dirname)(n)+"/"})){let a=n;(0,rs.writeFileSync)(r,i+`
|
|
5096
5096
|
`+a+`
|
|
5097
|
-
`)}}catch(i){t.Sentry?.captureException(i,{level:"info"})}}function xwe(t,e="user"){let r=e==="user"?[
|
|
5098
|
-
OPEN: ${(0,Gl.dim)(d)}`),n=yi(),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 vwe,Gx,mn,rs,Gl,Swe,OIt,KIt,
|
|
5097
|
+
`)}}catch(i){t.Sentry?.captureException(i,{level:"info"})}}function xwe(t,e="user"){let r=e==="user"?[U4()]:[(0,mn.join)(t.getAppRootDir(),"node_modules",".builder","data.json"),(0,mn.join)(t.getAppRootDir(),".builder","config","data.json"),(0,mn.join)(t.getAppRootDir(),".config","builderio","data.json"),(0,mn.join)(t.getRepoRootDir(),".git",".builder.json")];for(let n of r)if((0,rs.existsSync)(n)){let i;try{i=(0,rs.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 Fwe(t,e="user"){let r=e==="user"?[U4()]:[(0,mn.join)(t.getAppRootDir(),"node_modules",".builder","data.json"),(0,mn.join)(t.getAppRootDir(),".builder","config","data.json"),(0,mn.join)(t.getAppRootDir(),".config","builderio","data.json"),(0,mn.join)(t.getRepoRootDir(),".git",".builder.json")],n=!1;for(let i of r)if((0,rs.existsSync)(i))try{t.unlinkSync(i),n=!0}catch(s){t.Sentry?.captureException(s,{level:"warning"})}return n}async function kwe(t){let e,r,n,i=new Promise((l,d)=>{e=l,r=d}),s=t.initialPort,o=0,a=(0,vwe.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<_4?(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<_4;)l=await u();if(l===0)throw new Error(`Failed to find an available port after ${_4} 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=yi(),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 vwe,Gx,mn,rs,Gl,Swe,OIt,KIt,_4,Ux,jo,Wt,HIt,Rr=L(()=>{"use strict";h();vwe=require("node:http");ed();Gx=require("node:os"),mn=require("node:path"),rs=require("node:fs");rr();Gl=z(Er(),1);cI();_s();Swe=require("node:crypto");hr();Ml();GB();vi();TB();Ms();OIt=5294,KIt=5284,_4=4,Ux=t=>!!(process.env.CI||t.ci);jo=(t,e,r="user")=>{let n=Ux(e)?{}:xwe(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 bi({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 JIt(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 jIt(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 Xo(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)}};Kwe.exports=KH});var Jwe=N((Ffr,JH)=>{"use strict";h();var Hwe=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=Hwe;JH.exports.default=Hwe});var Ywe=N((Rfr,jwe)=>{"use strict";h();jwe.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 $we=N((Nfr,jH)=>{"use strict";h();var fEt=sU(),hEt=Jwe(),mEt=Ywe(),qwe=t=>{if(typeof t!="string"||t.length===0||(t=fEt(t),t.length===0))return 0;t=t.replace(mEt()," ");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+=hEt(n)?2:1)}return e};jH.exports=qwe;jH.exports.default=qwe});var YH=N((Pfr,Vwe)=>{h();Vwe.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((_fr,Wwe)=>{h();Wwe.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((Gfr,zwe)=>{h();zwe.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((Kfr,Xwe)=>{h();var CEt=$we(),IEt=YH(),EEt=qH(),BEt=$H();Xwe.exports=function(e,r,n){let i=e.format,s=e.formatTime||BEt,o=e.formatValue||IEt,a=e.formatBar||EEt,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-CEt(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((Jfr,Zwe)=>{h();function Ir(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/Ir(i.fps,10),n.stream=Ir(i.stream,process.stderr),n.terminal=Ir(i.terminal,null),n.clearOnComplete=Ir(i.clearOnComplete,!1),n.stopOnComplete=Ir(i.stopOnComplete,!1),n.barsize=Ir(i.barsize,40),n.align=Ir(i.align,"left"),n.hideCursor=Ir(i.hideCursor,!1),n.linewrap=Ir(i.linewrap,!1),n.barGlue=Ir(i.barGlue,""),n.barCompleteChar=Ir(i.barCompleteChar,"="),n.barIncompleteChar=Ir(i.barIncompleteChar,"-"),n.format=Ir(i.format,"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}"),n.formatTime=Ir(i.formatTime,null),n.formatValue=Ir(i.formatValue,null),n.formatBar=Ir(i.formatBar,null),n.etaBufferLength=Ir(i.etaBuffer,10),n.etaAsynchronousUpdate=Ir(i.etaAsynchronousUpdate,!1),n.progressCalculationRelative=Ir(i.progressCalculationRelative,!1),n.synchronousUpdate=Ir(i.synchronousUpdate,!0),n.noTTYOutput=Ir(i.noTTYOutput,!1),n.notTTYSchedule=Ir(i.notTTYSchedule,2e3),n.emptyOnZero=Ir(i.emptyOnZero,!1),n.forceRedraw=Ir(i.forceRedraw,!1),n.autopadding=Ir(i.autopadding,!1),n.gracefulExit=Ir(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?Ir(e.autopaddingChar," "):"",e}}});var WH=N((qfr,t0e)=>{h();var e0e=Owe(),yEt=HH(),QEt=VH(),DEt=Kx(),wEt=require("events");t0e.exports=class extends wEt{constructor(e){super(),this.options=DEt.assignDerivedOptions(e),this.terminal=this.options.terminal?this.options.terminal:new yEt(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 e0e(this.options.etaBufferLength,0,0),this.payload={},this.isActive=!1,this.formatter=typeof this.options.format=="function"?this.options.format:QEt}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 e0e(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 n0e=N((Wfr,r0e)=>{h();var bEt=WH(),vEt=Kx();r0e.exports=class extends bEt{constructor(e,r){super(vEt.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 s0e=N((Zfr,i0e)=>{h();var SEt=HH(),xEt=WH(),FEt=Kx(),kEt=require("events");i0e.exports=class extends kEt{constructor(e,r){super(),this.bars=[],this.options=FEt.parse(e,r),this.options.synchronousUpdate=!1,this.terminal=this.options.terminal?this.options.terminal:new SEt(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 xEt(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 a0e=N((thr,o0e)=>{h();o0e.exports={format:"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"=",barIncompleteChar:"-"}});var c0e=N((nhr,A0e)=>{h();A0e.exports={format:" {bar} {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var l0e=N((shr,u0e)=>{h();u0e.exports={format:" \x1B[90m{bar}\x1B[0m {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var p0e=N((ahr,g0e)=>{h();g0e.exports={format:" {bar}\u25A0 {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u25A0",barIncompleteChar:" "}});var f0e=N((chr,d0e)=>{h();var REt=a0e(),TEt=c0e(),NEt=l0e(),MEt=p0e();d0e.exports={legacy:REt,shades_classic:TEt,shades_grey:NEt,rect:MEt}});var C0e=N((lhr,m0e)=>{h();var h0e=n0e(),PEt=s0e(),LEt=f0e(),_Et=VH(),UEt=YH(),GEt=qH(),OEt=$H();m0e.exports={Bar:h0e,SingleBar:h0e,MultiBar:PEt,Presets:LEt,Format:{Formatter:_Et,BarFormat:GEt,ValueFormat:UEt,TimeFormat:OEt}}});var w0e=N((Nhr,D0e)=>{h();D0e.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 Wbt={};wy(Wbt,{default:()=>Vbt});module.exports=zr(Wbt);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]="4569f432-96c7-4234-94ac-8a401fe35826",t._sentryDebugIdIdentifier="sentry-dbid-4569f432-96c7-4234-94ac-8a401fe35826")}catch{}})();h();Bt();var rRe=require("../core/index.cjs"),nRe=require("../node/index.cjs"),iRe=require("../server/index.cjs"),sRe=z(cY(),1);h();h();var Ox=require("fs/promises");xk();Rr();cI();rr();var Hr=z(Er(),1),lm=require("node:path");Ms();_s();hr();Xr();kf();var qIt="https://cdn.builder.io",Twe=async(t,e)=>{console.log(""),sr((0,Hr.bgCyan)((0,Hr.bold)((0,Hr.white)(" figma migrate ")))+" "+(0,Hr.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,Hr.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 JIt(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 jIt(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 Xo(t,t.getAppRootDir())&&!await L4(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}},HIt="RHr2ed743waC2g2ZHMEJSn6O0NQ08L"});var Owe=N((bfr,Gwe)=>{h();var O4=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"}};Gwe.exports=O4});var H4=N((Sfr,Kwe)=>{h();var _p=require("readline"),K4=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)}};Kwe.exports=K4});var Jwe=N((Ffr,J4)=>{"use strict";h();var Hwe=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=Hwe;J4.exports.default=Hwe});var Ywe=N((Rfr,jwe)=>{"use strict";h();jwe.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 $we=N((Nfr,j4)=>{"use strict";h();var fEt=sU(),hEt=Jwe(),mEt=Ywe(),qwe=t=>{if(typeof t!="string"||t.length===0||(t=fEt(t),t.length===0))return 0;t=t.replace(mEt()," ");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+=hEt(n)?2:1)}return e};j4.exports=qwe;j4.exports.default=qwe});var Y4=N((Pfr,Vwe)=>{h();Vwe.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((_fr,Wwe)=>{h();Wwe.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((Gfr,zwe)=>{h();zwe.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((Kfr,Xwe)=>{h();var CEt=$we(),IEt=Y4(),EEt=q4(),BEt=$4();Xwe.exports=function(e,r,n){let i=e.format,s=e.formatTime||BEt,o=e.formatValue||IEt,a=e.formatBar||EEt,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-CEt(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((Jfr,Zwe)=>{h();function Ir(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/Ir(i.fps,10),n.stream=Ir(i.stream,process.stderr),n.terminal=Ir(i.terminal,null),n.clearOnComplete=Ir(i.clearOnComplete,!1),n.stopOnComplete=Ir(i.stopOnComplete,!1),n.barsize=Ir(i.barsize,40),n.align=Ir(i.align,"left"),n.hideCursor=Ir(i.hideCursor,!1),n.linewrap=Ir(i.linewrap,!1),n.barGlue=Ir(i.barGlue,""),n.barCompleteChar=Ir(i.barCompleteChar,"="),n.barIncompleteChar=Ir(i.barIncompleteChar,"-"),n.format=Ir(i.format,"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}"),n.formatTime=Ir(i.formatTime,null),n.formatValue=Ir(i.formatValue,null),n.formatBar=Ir(i.formatBar,null),n.etaBufferLength=Ir(i.etaBuffer,10),n.etaAsynchronousUpdate=Ir(i.etaAsynchronousUpdate,!1),n.progressCalculationRelative=Ir(i.progressCalculationRelative,!1),n.synchronousUpdate=Ir(i.synchronousUpdate,!0),n.noTTYOutput=Ir(i.noTTYOutput,!1),n.notTTYSchedule=Ir(i.notTTYSchedule,2e3),n.emptyOnZero=Ir(i.emptyOnZero,!1),n.forceRedraw=Ir(i.forceRedraw,!1),n.autopadding=Ir(i.autopadding,!1),n.gracefulExit=Ir(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?Ir(e.autopaddingChar," "):"",e}}});var W4=N((qfr,t0e)=>{h();var e0e=Owe(),yEt=H4(),QEt=V4(),DEt=Kx(),wEt=require("events");t0e.exports=class extends wEt{constructor(e){super(),this.options=DEt.assignDerivedOptions(e),this.terminal=this.options.terminal?this.options.terminal:new yEt(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 e0e(this.options.etaBufferLength,0,0),this.payload={},this.isActive=!1,this.formatter=typeof this.options.format=="function"?this.options.format:QEt}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 e0e(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 n0e=N((Wfr,r0e)=>{h();var bEt=W4(),vEt=Kx();r0e.exports=class extends bEt{constructor(e,r){super(vEt.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 s0e=N((Zfr,i0e)=>{h();var SEt=H4(),xEt=W4(),FEt=Kx(),kEt=require("events");i0e.exports=class extends kEt{constructor(e,r){super(),this.bars=[],this.options=FEt.parse(e,r),this.options.synchronousUpdate=!1,this.terminal=this.options.terminal?this.options.terminal:new SEt(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 xEt(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 a0e=N((thr,o0e)=>{h();o0e.exports={format:"progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"=",barIncompleteChar:"-"}});var c0e=N((nhr,A0e)=>{h();A0e.exports={format:" {bar} {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var l0e=N((shr,u0e)=>{h();u0e.exports={format:" \x1B[90m{bar}\x1B[0m {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u2588",barIncompleteChar:"\u2591"}});var p0e=N((ahr,g0e)=>{h();g0e.exports={format:" {bar}\u25A0 {percentage}% | ETA: {eta}s | {value}/{total}",barCompleteChar:"\u25A0",barIncompleteChar:" "}});var f0e=N((chr,d0e)=>{h();var REt=a0e(),TEt=c0e(),NEt=l0e(),MEt=p0e();d0e.exports={legacy:REt,shades_classic:TEt,shades_grey:NEt,rect:MEt}});var C0e=N((lhr,m0e)=>{h();var h0e=n0e(),PEt=s0e(),LEt=f0e(),_Et=V4(),UEt=Y4(),GEt=q4(),OEt=$4();m0e.exports={Bar:h0e,SingleBar:h0e,MultiBar:PEt,Presets:LEt,Format:{Formatter:_Et,BarFormat:GEt,ValueFormat:UEt,TimeFormat:OEt}}});var w0e=N((Nhr,D0e)=>{h();D0e.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 Wbt={};wy(Wbt,{default:()=>Vbt});module.exports=zr(Wbt);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]="0b67bf7f-ce37-4f2a-b2d7-fc82b6636d2a",t._sentryDebugIdIdentifier="sentry-dbid-0b67bf7f-ce37-4f2a-b2d7-fc82b6636d2a")}catch{}})();h();Bt();var rRe=require("../core/index.cjs"),nRe=require("../node/index.cjs"),iRe=require("../server/index.cjs"),sRe=z(cY(),1);h();h();var Ox=require("fs/promises");xk();Rr();cI();rr();var Hr=z(Er(),1),lm=require("node:path");Ms();_s();hr();Xr();kf();var qIt="https://cdn.builder.io",Twe=async(t,e)=>{console.log(""),sr((0,Hr.bgCyan)((0,Hr.bold)((0,Hr.white)(" figma migrate ")))+" "+(0,Hr.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,Hr.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 br({m
|
|
|
5117
5117
|
`):Rwe(e);return ZA(t.getAppRootDir(),`import { figmaMapping } from '@builder.io/dev-tools/figma';
|
|
5118
5118
|
${o}
|
|
5119
5119
|
|
|
5120
|
-
${s}`,"typescript",void 0)}function Rwe(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();Rr();GB();var Yo=z(Er(),1);rr();rr();Ms();vi();_s();Xr();h();kf();Rr();
|
|
5120
|
+
${s}`,"typescript",void 0)}function Rwe(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();Rr();GB();var Yo=z(Er(),1);rr();rr();Ms();vi();_s();Xr();h();kf();Rr();N4();var is=z(require("fs/promises"),1),ns=z(require("node:path"),1);var Nwe=`# 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();Xr();var Ol=z(Er(),1);Ml();xt();function eEt(t){let e=t.match(/team\/(\d+)/),r=
|
|
6743
|
+
`;rr();Xr();var Ol=z(Er(),1);Ml();xt();function eEt(t){let e=t.match(/team\/(\d+)/),r=T4(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 tEt(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 rEt(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 nEt(t,e,r){let{sys:n,args:i,figmaAuth:s,debug:o}=t,a,A;if(r){A=`files/${e}/nodes`;let x=await ru(n,i,A,{auth:s,params:{ids:r}});a=Object.assign({name:x.name,thumbnailUrl:x.thumbnailUrl,role:x.role,lastModified:x.lastModified},x.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[x,w]of Object.entries(c))l.set(w,x);for(let[x,w]of Object.entries(u))l.set(w,x);let d=0,g=0,p=new Set;for(let[x,w]of Object.entries(a.componentSets))p.add(x),w.remote&&g++;let f=[],m=new Map;for(let[x,w]of Object.entries(a.components))w.componentSetId?p.has(w.componentSetId)&&m.set(w.key,w.componentSetId):(f.push(w),w.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 pEt(t){return t.name.startsWith("_")||t.name.startsWith(".")}function dEt(t){return t?t.inputs.length===0&&t.jsx==="":!0}var Uwe=async(t,e,r)=>{if(e==="migrate")await Twe(t,r);else if(e==="publish"||e==="p")await bwe(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 _we(t,r);else if(e==="auth"){console.log(""),sr((0,Yo.bgCyan)((0,Yo.bold)((0,Yo.white)(" figma auth ")))+" "+(0,Yo.dim)(ht));let{builderPublicKey:n}=await Wt(t,r,{requireFigmaAuth:"always",builderPrivateKey:!0,builderPublicKey:!0,force:!0});await Pt("figma auth",{spaceId:n}),In((0,Yo.bgGreen)((0,Yo.bold)((0,Yo.white)(" Done! \u{1F389} "))))}else e==="help"&&Zc(r._[2]||"figma")}};rr();Fi();xt();mL();h();function
|
|
6804
|
+
See: https://www.builder.io/c/docs/mapping-functions`),await Me(1);if(e==="report")await _we(t,r);else if(e==="auth"){console.log(""),sr((0,Yo.bgCyan)((0,Yo.bold)((0,Yo.white)(" figma auth ")))+" "+(0,Yo.dim)(ht));let{builderPublicKey:n}=await Wt(t,r,{requireFigmaAuth:"always",builderPrivateKey:!0,builderPublicKey:!0,force:!0});await Pt("figma auth",{spaceId:n}),In((0,Yo.bgGreen)((0,Yo.bold)((0,Yo.white)(" Done! \u{1F389} "))))}else e==="help"&&Zc(r._[2]||"figma")}};rr();Fi();xt();mL();h();function G4(t,e){return{cwd:t,command:e[0],snippetId:e[1],path:e[2]}}Cp();Ms();_s();GB();Rx();n4();var Wl=z(Er(),1);Xr();Rr();h();var Op=z(require("@sentry/node"),1);Bt();var La=z(Er(),1);rr();Rr();Qr();var Xx=z(require("node:crypto"),1);hr();Xr();Js();Js();var sJ=z(C0e(),1);h();h();h();h();function z4({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 KEt=z4();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(KEt,"")}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],X4=[8361,8361,65377,65470,65474,65479,65482,65487,65490,65495,65498,65500,65512,65518],Z4=[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 HEt=Hx[0],JEt=Hx.at(-1),jEt=Jx[0],YEt=Jx.at(-1),Dhr=X4[0],whr=X4.at(-1),bhr=Z4[0],vhr=Z4.at(-1),qEt=zB[0],$Et=zB.at(-1),I0e=19968,[VEt,WEt]=zEt(zB);function zEt(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(I0e>=i&&I0e<=s)return[i,s];s-i>r-e&&(e=i,r=s)}return[e,r]}var E0e=t=>t<HEt||t>JEt?!1:jx(Hx,t),B0e=t=>t<jEt||t>YEt?!1:jx(Jx,t);var y0e=t=>t>=VEt&&t<=WEt?!0:t<qEt||t>$Et?!1:jx(zB,t);function XEt(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function Q0e(t,{ambiguousAsWide:e=!1}={}){return XEt(t),B0e(t)||y0e(t)||e&&E0e(t)?2:1}var b0e=z(w0e(),1),ZEt=new Intl.Segmenter,eBt=/^\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 ZEt.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)&&!eBt.test(o)){if((0,b0e.default)().test(o)){i+=2;continue}i+=Q0e(a,s)}}return i}h();var v0e=(t=0)=>e=>`\x1B[${e+t}m`,S0e=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,x0e=(t=0)=>(e,r,n)=>`\x1B[${38+t};2;${e};${r};${n}m`,Jr={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]}},Ghr=Object.keys(Jr.modifier),tBt=Object.keys(Jr.color),rBt=Object.keys(Jr.bgColor),Ohr=[...tBt,...rBt];function nBt(){let t=new Map;for(let[e,r]of Object.entries(Jr)){for(let[n,i]of Object.entries(r))Jr[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},r[n]=Jr[n],t.set(i[0],i[1]);Object.defineProperty(Jr,e,{value:r,enumerable:!1})}return Object.defineProperty(Jr,"codes",{value:t,enumerable:!1}),Jr.color.close="\x1B[39m",Jr.bgColor.close="\x1B[49m",Jr.color.ansi=v0e(),Jr.color.ansi256=S0e(),Jr.color.ansi16m=x0e(),Jr.bgColor.ansi=v0e(10),Jr.bgColor.ansi256=S0e(10),Jr.bgColor.ansi16m=x0e(10),Object.defineProperties(Jr,{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=>Jr.rgbToAnsi256(...Jr.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)=>Jr.ansi256ToAnsi(Jr.rgbToAnsi256(e,r,n)),enumerable:!1},hexToAnsi:{value:e=>Jr.ansi256ToAnsi(Jr.hexToAnsi256(e)),enumerable:!1}}),Jr}var iBt=nBt(),F0e=iBt;var qx=new Set(["\x1B","\x9B"]),sBt=39,tJ="\x07",T0e="[",oBt="]",N0e="m",Yx=`${oBt}8;;`,k0e=t=>`${qx.values().next().value}${T0e}${t}${N0e}`,R0e=t=>`${qx.values().next().value}${Yx}${t}${tJ}`,aBt=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===N0e&&(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())},ABt=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("")},cBt=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",i,s,o=aBt(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=>ABt(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(`(?:\\${T0e}(?<code>\\d+)m|\\${Yx}(?<uri>.*)${tJ})`).exec(A.slice(u))||{groups:{}};if(p.code!==void 0){let f=Number.parseFloat(p.code);i=f===sBt?void 0:f}else p.uri!==void 0&&(s=p.uri.length===0?void 0:p.uri)}let g=F0e.codes.get(Number(i));c[l+1]===`
|
|
6806
6806
|
`?(s&&(n+=R0e("")),i&&g&&(n+=k0e(g))):d===`
|
|
6807
6807
|
`&&(i&&g&&(n+=k0e(i)),s&&(n+=R0e(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=W0e.replaceAll("{{COMPONENTS}}",o).replaceAll("{{ICONS}}",n.hasIcons?a:"").replaceAll("{{TOKENS}}",n.hasDesignTokens?A:"");try{let u={type:"agent",name:
|
|
7252
|
+
`,c=W0e.replaceAll("{{COMPONENTS}}",o).replaceAll("{{ICONS}}",n.hasIcons?a:"").replaceAll("{{TOKENS}}",n.hasDesignTokens?A:"");try{let u={type:"agent",name:C4,description:"Repository agent documentation",content:c,designSystemId:n.designSystemId,rawComponents:s.map(l=>({name:l.name,description:l.description})),rawTokenGroups:n.discoveredTokenGroups};await xs(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 IBt(t,i.map(s=>s.id))},IBt=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 CBt.error("API request failed:",n.status,i),new Error(`Failed to mark component as deprecated: ${n.status} ${i}`)}};JA();var abe=require("node:path");Fi();_s();h();var tbe=require("node:child_process"),rbe=require("util"),nbe=require("node:path"),ebe=(0,rbe.promisify)(tbe.exec);async function gm(t){let e=t.cwd(),r;try{let{stdout:a}=await ebe("git rev-parse --show-toplevel",{cwd:e});r=a.trim()}catch{return}let n=(0,nbe.relative)(r,e),i=n?`./${n}`:"./",s;try{let{stdout:a}=await ebe("git remote get-url origin",{cwd:e});s=a.trim()}catch{return}let o=EBt(s);return{gitRoot:r,recommendedRoot:i==="./"?void 0:i,originUrl:s,...o}}function EBt(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 ibe(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 sbe(t,e,r){let n=ss();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 M0e(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 bi({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 sbe(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){en(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 _De(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 bi({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 M0e(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 bi({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 sbe(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){en(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 _De(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 bi({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 E4(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=GDe(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 br({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=UDe(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 br({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 E4(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 x=ss();if(r)if((0,abe.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 w=D?.id||"",P=!D&&d;if(P){let J=await gm(t);w=await ODe(f,{designSystemName:d,designSystemVersion:E,designSystemPackage:r,status:"in-progress",scope:S,gitOriginUrl:J?.originUrl,gitRelativePath:J?.recommendedRoot,cliArgs:process.argv.slice(2)})}let G=null;try{if(l){x.start("Processing custom documentation"),await t.exists(l)||($.error(`${l} does not exist`),process.exit(1));let{validDocs:J,invalidFiles:_}=await DBt(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 br({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:w||"none",userId:f.userId,spaceId:f.builderPublicKey,source:"custom"}),x.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 wBt(t,f,X,{designSystemId:w,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){x.message("Creating agent documentation");try{await iJ(t,f,j,{designSystemId:w,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 obe(f,w,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})}),x.stop("Custom documentation collected"),await Pt("repo indexing completed",{sessionId:I,commandString:process.argv.slice(2).join(" "),forceBoolean:e.force,designSystemPackage:r||"none",designSystemId:w||"none",userId:f.userId,spaceId:f.builderPublicKey,source:"custom"});let he=[..._,...ee];G={componentsToCheck:ge,storedComponentDocs:ue,source:"custom",summaryData:{indexedComponents:j,discoveredComponents:K,failedComponents:he,failedTokens:H,numIconsIndexed:Z,discoveredTokenGroups:U,tokenGroupsToIndex:Y}}}else{if(await KDe(t)){if($.warn(XB(`\u26A0\uFE0F Warning: Existing ${I4} 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 br({message:"Continue with existing files?"});if(typeof Ce=="symbol"||!Ce){$.info("Repository indexing canceled.");return}}x=ss()}x.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:w||"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",_),x.message("Looking for components");let K=await obe(f,w,e.debug),j=K.find(Ce=>Qf(Ce)),ee=K.filter(Ce=>Ku(Ce)),U=K.filter(Ce=>Ug(Ce)),Y=BBt(a),H=Y.length>0,[Z,ue,ge,he]=await Promise.all([U0e(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}),$0e(t,f,`${I}-installation-discovery`,{designSystemId:w,designSystemPackage:r,designSystemVersion:E,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode}),!H&&K0e(t,f,`${I}-icon-discovery`,{designSystemPackage:r,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode})||void 0,!H&&j0e(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(x.stop(`${X} new and ${Ce} existing component docs found`),Ce>0){let V=await br({message:"Using --force will remove existing component documents. Continue?"});if(typeof V=="symbol"||!V){x.stop("Canceled");return}}x.start("")}let rt=0,nt=[];x.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 Vr=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,Vr.update(rt)},sn=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 Y0e(t,f,`${I}-${wt.name}-doc`,wt,{designSystemId:w,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 X0e(t,f,`${I}-${wt.name}-doc`,wt,{designSystemId:w,designSystemPackage:r,designSystemVersion:E,workspaceConfig:y,debug:e.debug,include:A,exclude:c,instructions:u,privacyMode:m?.privacyMode}),x.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?(x.message("Summarizing component library"),await iJ(t,f,Je,{designSystemId:w,debug:e.debug,hasIcons:!H&&(ge?.icons.length||0)>0,hasDesignTokens:!H&&be.length>0,discoveredTokenGroups:be.map(Ce=>Ce.name)}),x.message("Agent docs stored"),{success:!0}):{success:!0})(),ge&&H0e(f,ge,{designSystemId:w,debug:e.debug,sessionId:`${I}-icon-discovery`,previousHash:j?.hash,force:i}),sn(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}),G={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:w||"none",userId:f.userId,spaceId:f.builderPublicKey}),e.createFusionExample&&await sbe(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}}),w&&await
|
|
7283
|
-
`))),{validDocs:A,invalidFiles:a}},wBt=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 xs(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 xs(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 xs(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 xs(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}}),w&&await B4(f,{id:w,designSystemName:d,designSystemPackage:r,designSystemVersion:E,status:"failed",scope:S,source:l?"custom":"auto"}),J}if(G&&G.summaryData){let J=G.storedComponentDocs.filter(_=>RL(_)?!1:G.specificComponentNames&&G.specificComponentNames.length>0?G.specificComponentNames.includes(_.name):!0);await Z0e(f,G.componentsToCheck,J),yBt(G.summaryData.discoveredComponents,G.summaryData.indexedComponents,p,G.summaryData.failedComponents,i,d,w,G.summaryData.numIconsIndexed,G.summaryData.discoveredTokenGroups,G.summaryData.tokenGroupsToIndex,G.summaryData.failedTokens),w&&await B4(f,{id:w,designSystemName:d,designSystemPackage:r,designSystemVersion:E,status:"completed",scope:S,source:G.source})}},obe=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)},QBt=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},DBt=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:QBt(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}},wBt=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 xs(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 xs(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 xs(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 xs(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}};KH();h();h();Rr();var Zx=z(Er(),1);rr();Fi();var Abe=(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}`)}};Rr();rr();var Un=z(Er(),1);Xr();_s();var cbe=async(t,e,r)=>{if(e==="status"){Abe(t,r);return}if(r.reset){console.log(""),sr((0,Un.bgCyan)((0,Un.bold)((0,Un.white)(" auth reset ")))+" "+(0,Un.dim)(ht)),Fwe(t)?($.success("Credentials have been cleared successfully"),await Pt("auth reset",{})):$.info("No credentials found to clear"),In((0,Un.bgGreen)((0,Un.bold)((0,Un.white)(" Done! \u{1F389} "))));return}console.log(""),sr((0,Un.bgCyan)((0,Un.bold)((0,Un.white)(" auth ")))+" "+(0,Un.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}),In((0,Un.bgGreen)((0,Un.bold)((0,Un.white)(" Done! \u{1F389} "))))};h();rr();var Gn=z(Er(),1);Xr();Ml();Rr();hr();Qr();TB();var Sbe=require("node:child_process"),xbe=require("util");h();var ube=require("node:child_process"),lbe=require("util"),pm=(0,lbe.promisify)(ube.exec);async function gbe(){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 pbe(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 dbe(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 Cbe=z(aH(),1),Ibe=require("node:path"),Ebe=require("node:fs"),vBt=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"]),SBt=[/^npm_config_/,/^npm_command$/,/^npm_execpath$/,/^npm_lifecycle_/,/^npm_node_execpath$/,/^npm_package_/];function fbe(t){return vBt.has(t)?!0:SBt.some(e=>e.test(t))}var hbe={"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:[]},mbe=[/TOKEN/i,/KEY/i,/SECRET/i,/PASSWORD/i,/PASS/i,/AUTH/i,/PRIVATE/i,/CREDENTIAL/i],xBt=new Set(["NODE_ENV","CI","PORT","HOST","ENVIRONMENT"]);async function FBt(t,e){let r=[".env",".env.local",".env.development",".env.development.local"],n={};for(let i of r){let s=(0,Ibe.join)(e,i);if((0,Ebe.existsSync)(s))try{let o=(0,Cbe.config)({path:s});o.parsed&&Object.assign(n,o.parsed)}catch{}}return n}function kBt(t){let e=[];if(t)for(let[n,i]of Object.entries(t)){if(!i||fbe(n))continue;let s="Custom";for(let[a,A]of Object.entries(hbe))if(A.some(c=>c.test(n))){s=a;break}let o=mbe.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)||fbe(n)||i===void 0)continue;let s="Custom";for(let[A,c]of Object.entries(hbe))if(c.some(u=>u.test(n))){s=A;break}let o=mbe.some(A=>A.test(n)),a=xBt.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 Bbe(t,e){let r=await FBt(t,e),n=kBt(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 ybe(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"),Qbe=require("node:os");rr();async function Dbe(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,Qbe.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 wbe(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 bbe=require("node:child_process");rr();var Kp=z(Er(),1);async function vbe(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 RBt(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 bi({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 bi({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 RBt(t,e){return new Promise(r=>{let n=t.trim().split(/\s+/),i=n[0],s=n.slice(1),o=(0,bbe.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 TBt=(0,xbe.promisify)(Sbe.exec);function NBt(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 Fbe(t,e){console.log(""),sr((0,Gn.bgCyan)((0,Gn.bold)((0,Gn.white)(" connect-repo ")))+" "+(0,Gn.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=ibe(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 vbe(r.gitRoot,e.installCommand);if(!o.success&&!o.skipped){Ke("Installation failed. Cannot continue.");return}$.step("Collecting environment variables...");let a=await Bbe(t,r.gitRoot);if(a===null){Ke("Environment variable selection cancelled");return}let A=ybe(a);$.info(`\u2713 Selected ${A.total} variables (${A.secrets} secret, ${A.public} public)`),$.step("Collecting configuration files...");let c=await Dbe(t,r.gitRoot),u=await wbe(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=yi();l.start("Checking installed tools");let d=await gbe(),g=pbe(d);l.stop(),$.info(`\u2713 Detected: ${dbe(d)}`),await MBt(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 MBt(t,e,r,n,i,s,o,a){$.step("Creating Fusion project...");let A=[`Project: ${(0,Gn.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=yi();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 bi({message:`Create project "${(0,Gn.bold)(n)}" in space "${(0,Gn.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 TBt("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=NBt(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"),In((0,Gn.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(qo.includes(t))return qo.indexOf(t);let e=zBt.exec(t);if(e!==null)return Number(e[1])},zBt=/^fd(\d+)$/,XBt=(t,e)=>t.map(r=>r===void 0?eyt[e]:r),ZBt=(0,Jbe.debuglog)("execa").enabled?"full":"none",eyt={lines:!1,buffer:!0,maxBuffer:1e3*1e3*100,verbose:ZBt,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)),Ybe=({verbose:t},e)=>{let r=fJ(t,e);return AF(r)?r:void 0},fJ=(t,e)=>e===void 0?tyt(t):su(t,e),tyt=t=>t.find(e=>AF(e))??cF.findLast(e=>t.includes(e)),AF=t=>typeof t=="function",cF=["none","short","full"];h();var ave=require("node:util");h();var qbe=require("node:process"),$be=require("node:util"),Vbe=(t,e)=>{let r=[t,...e],n=r.join(" "),i=r.map(s=>ayt(Wbe(s))).join(" ");return{command:n,escapedCommand:i}},ty=t=>(0,$be.stripVTControlCharacters)(t).split(`
|
|
7295
7295
|
`).map(e=>Wbe(e)).join(`
|
|
7296
|
-
`),Wbe=t=>t.replaceAll(iyt,e=>ryt(e)),ryt=t=>{let e=syt[t];if(e!==void 0)return e;let r=t.codePointAt(0),n=r.toString(16);return r<=oyt?`\\u${n.padStart(4,"0")}`:`\\U${n}`},nyt=()=>{try{return new RegExp("\\p{Separator}|\\p{Other}","gu")}catch{return/[\s\u0000-\u001F\u007F-\u009F\u00AD]/g}},iyt=nyt(),syt={" ":" ","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},oyt=65535,ayt=t=>Ayt.test(t)?t:qbe.platform==="win32"?`"${t.replaceAll('"','""')}"`:`'${t.replaceAll("'","'\\''")}'`,Ayt=/^[\w./-]+$/;h();h();
|
|
7296
|
+
`),Wbe=t=>t.replaceAll(iyt,e=>ryt(e)),ryt=t=>{let e=syt[t];if(e!==void 0)return e;let r=t.codePointAt(0),n=r.toString(16);return r<=oyt?`\\u${n.padStart(4,"0")}`:`\\U${n}`},nyt=()=>{try{return new RegExp("\\p{Separator}|\\p{Other}","gu")}catch{return/[\s\u0000-\u001F\u007F-\u009F\u00AD]/g}},iyt=nyt(),syt={" ":" ","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},oyt=65535,ayt=t=>Ayt.test(t)?t:qbe.platform==="win32"?`"${t.replaceAll('"','""')}"`:`'${t.replaceAll("'","'\\''")}'`,Ayt=/^[\w./-]+$/;h();h();p4();var zbe={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"},Xbe={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"},cyt={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"},uyt={...zbe,...Xbe},lyt={...zbe,...cyt},gyt=OB(),pyt=gyt?uyt:lyt,uF=pyt,RIr=Object.entries(Xbe);h();var Zbe=z(require("node:tty"),1),dyt=Zbe.default?.WriteStream?.prototype?.hasColors?.()??!1,Dt=(t,e)=>{if(!dyt)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}},MIr=Dt(0,0),eve=Dt(1,22),PIr=Dt(2,22),LIr=Dt(3,23),_Ir=Dt(4,24),UIr=Dt(53,55),GIr=Dt(7,27),OIr=Dt(8,28),KIr=Dt(9,29),HIr=Dt(30,39),JIr=Dt(31,39),jIr=Dt(32,39),YIr=Dt(33,39),qIr=Dt(34,39),$Ir=Dt(35,39),VIr=Dt(36,39),WIr=Dt(37,39),lF=Dt(90,39),zIr=Dt(40,49),XIr=Dt(41,49),ZIr=Dt(42,49),eEr=Dt(43,49),tEr=Dt(44,49),rEr=Dt(45,49),nEr=Dt(46,49),iEr=Dt(47,49),sEr=Dt(100,49),tve=Dt(91,39),oEr=Dt(92,39),rve=Dt(93,39),aEr=Dt(94,39),AEr=Dt(95,39),cEr=Dt(96,39),uEr=Dt(97,39),lEr=Dt(101,49),gEr=Dt(102,49),pEr=Dt(103,49),dEr=Dt(104,49),fEr=Dt(105,49),hEr=Dt(106,49),mEr=Dt(107,49);var sve=({type:t,message:e,timestamp:r,piped:n,commandId:i,result:{failed:s=!1}={},options:{reject:o=!0}})=>{let a=fyt(r),A=hyt[t]({failed:s,reject:o,piped:n}),c=myt[t]({reject:o});return`${lF(`[${a}]`)} ${lF(`[${i}]`)} ${c(A)} ${c(e)}`},fyt=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"),nve=({failed:t,reject:e})=>t?e?uF.cross:uF.warning:uF.tick,hyt={command:({piped:t})=>t?"|":"$",output:()=>" ",ipc:()=>"*",error:nve,duration:nve},ive=t=>t,myt={command:()=>eve,output:()=>ive,ipc:()=>ive,error:({reject:t})=>t?tve:rve,duration:()=>lF};h();var ove=(t,e,r)=>{let n=Ybe(e,r);return t.map(({verboseLine:i,verboseObject:s})=>Cyt(i,s,n)).filter(i=>i!==void 0).map(i=>Iyt(i)).join("")},Cyt=(t,e,r)=>{if(r===void 0)return t;let n=r(t,e);if(typeof n=="string")return n},Iyt=t=>t.endsWith(`
|
|
7297
7297
|
`)?t:`${t}
|
|
7298
7298
|
`;var qA=({type:t,verboseMessage:e,fdNumber:r,verboseInfo:n,result:i})=>{let s=Eyt({type:t,result:i,verboseInfo:n}),o=Byt(e,s),a=ove(o,n,r);a!==""&&console.warn(a.slice(0,-1))},Eyt=({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}),Byt=(t,e)=>t.split(`
|
|
7299
7299
|
`).map(r=>yyt({...e,message:r})),yyt=t=>({verboseLine:sve(t),verboseObject:t}),pF=t=>{let e=typeof t=="string"?t:(0,ave.inspect)(t);return ty(e).replaceAll(" "," ".repeat(Qyt))},Qyt=2;var Ave=(t,e)=>{fm(e)&&qA({type:"command",verboseMessage:t,verboseInfo:e})};h();var cve=(t,e,r)=>{byt(t);let n=Dyt(t);return{verbose:t,escapedCommand:e,commandId:n,rawOptions:r}},Dyt=t=>fm({verbose:t})?wyt++:void 0,wyt=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}=Vbe(t,e),o=gJ(r,"verbose"),a=cve(o,s,{...r});return Ave(s,a),{command:i,escapedCommand:s,startTime:n,verboseInfo:a}};h();var RSe=z(require("node:path"),1),FJ=z(require("node:process"),1),TSe=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 vyt=({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&&Syt(o,a,s),i&&xyt(o,a,n,s),e===""||e===Kl.default.delimiter?`${o.join(Kl.default.delimiter)}${e}`:[...o,e].join(Kl.default.delimiter)},Syt=(t,e,r)=>{for(let n of Tre(r)){let i=Kl.default.join(n,"node_modules/.bin");e.includes(i)||t.push(i)}},xyt=(t,e,r,n)=>{let i=Kl.default.resolve(n,mc(r),"..");e.includes(i)||t.push(i)},uve=({env:t=ry.default.env,...e}={})=>{t={...t};let r=hF({env:t});return e.path=t[r],t[r]=vyt(e),t};h();var bve=require("node:timers/promises");h();var lve=(t,e,r)=>{let n=r?iy:ny,i=t instanceof Ua?{}:{cause:t};return new n(e,i)},Ua=class extends Error{},gve=(t,e)=>{Object.defineProperty(t.prototype,"name",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,dve,{value:!0,writable:!1,enumerable:!1,configurable:!1})},pve=t=>mF(t)&&dve in t,dve=Symbol("isExecaError"),mF=t=>Object.prototype.toString.call(t)==="[object Error]",ny=class extends Error{};gve(ny,ny.name);var iy=class extends Error{};gve(iy,iy.name);h();var mm=require("node:os");h();var Eve=require("node:os");h();var fve=()=>{let t=mve-hve+1;return Array.from({length:t},Fyt)},Fyt=(t,e)=>({name:`SIGRT${e+1}`,number:hve+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),hve=34,mve=64;h();var Ive=require("node:os");h();var Cve=[{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=fve();return[...Cve,...t].map(kyt)},kyt=({name:t,number:e,description:r,action:n,forced:i=!1,standard:s})=>{let{signals:{[t]:o}}=Ive.constants,a=o!==void 0;return{name:t,number:a?o:e,description:r,supported:a,action:n,forced:i,standard:s}};var Ryt=()=>{let t=CJ();return Object.fromEntries(t.map(Tyt))},Tyt=({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}],Bve=Ryt(),Nyt=()=>{let t=CJ(),e=65,r=Array.from({length:e},(n,i)=>Myt(i,t));return Object.assign({},...r)},Myt=(t,e)=>{let r=Pyt(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}}},Pyt=(t,e)=>{let r=e.find(({name:n})=>Eve.constants.signals[n]===t);return r!==void 0?r:e.find(n=>n.number===t)},lBr=Nyt();var Qve=t=>{let e="option `killSignal`";if(t===0)throw new TypeError(`Invalid ${e}: 0 cannot be used.`);return wve(t,e)},Dve=t=>t===0?t:wve(t,"`subprocess.kill()`'s argument"),wve=(t,e)=>{if(Number.isInteger(t))return Lyt(t,e);if(typeof t=="string")return Uyt(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(!Di||!ks)return{content:[{type:"text",text:"System and args must be initialized before calling pullPrototype"}],isError:!0};let{builderPublicKey:n,builderPrivateKey:i,userId:s}=jo(Di,ks);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=b4(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 jbt(t){let e=await Kbt("gh",["pr","diff",t]),r=Hbt(e);Obt(r);let n=Jbt(r.join(`
|
|
7415
7415
|
`))+`
|
|
7416
7416
|
`,i=(0,Zj.join)(process.cwd(),".builder","tmp");(0,wk.mkdirSync)(i,{recursive:!0});let s=(0,Wke.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 zke(t,e,r){if(e==="diff"){let n=r._[2];if(!n)throw new Error("Usage: builderio agent diff <pr_number>");await jbt(String(n))}else throw new Error(`Unknown agent subcommand: ${e??"(none)"}. Available: diff`)}h();Rr();
|
|
7417
|
+
`)}async function zke(t,e,r){if(e==="diff"){let n=r._[2];if(!n)throw new Error("Usage: builderio agent diff <pr_number>");await jbt(String(n))}else throw new Error(`Unknown agent subcommand: ${e??"(none)"}. Available: diff`)}h();Rr();WH();rr();async function Xke(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=ss();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();Rr();Ml();rr();var Zke=z(require("prompts"),1),bk=z(Er(),1);Fo();Ms();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 eRe(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 Qi("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 br({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 Qi("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=yi();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 Ybt(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 qbt(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,rRe.createDevTools)(t,e.nativeApp);await(0,iRe.createDevToolsServer)({...r,getClientId:()=>"builder-dev-tools-cli",closeAppServer:async()=>{},restartAppServer:async()=>{t.debug("restart server")},enableAppWatch:async n=>n,...t})}Pye();async function $bt(){let t=(0,sRe.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,nRe.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 Ybt(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 Uwe(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(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 jDe(n,o,t)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(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&&(en(o),Ke()),await Me(1)}else if(i==="launch"||i==="fusion")try{await IDe({sys:n,args:t})}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(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 qbt(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,rRe.createDevTools)(t,e.nativeApp);await(0,iRe.createDevToolsServer)({...r,getClientId:()=>"builder-dev-tools-cli",closeAppServer:async()=>{},restartAppServer:async()=>{t.debug("restart server")},enableAppWatch:async n=>n,...t})}Pye();async function $bt(){let t=(0,sRe.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,nRe.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 Ybt(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 Uwe(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(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 jDe(n,o,t)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(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&&(en(o),Ke()),await Me(1)}else if(i==="launch"||i==="fusion")try{await IDe({sys:n,args:t})}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(o),Ke()),await Me(1)}else if(i==="add"){let o=G4(n.getAppRootDir(),process.argv.slice(2));return await Une(o),await Me(0)}else if(i==="sync"){let o=G4(n.getAppRootDir(),process.argv.slice(2)),a=await S4(o);await lwe(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 cbe(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(a),Ke()),await Me(1)}}else if(i==="doctor"){let o=t._[1];try{return await Oke(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(a),Ke()),await Me(1)}}else if(i==="connect-repo"||i==="repo-connect")try{return await Fbe(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(o),Ke()),await Me(1)}else if(i==="agent"){let o=t._[1];try{return await zke(n,o,t),await Me(0)}catch(a){return n.Sentry?.captureException(a),a instanceof qe&&(en(a),Ke()),await Me(1)}}else if(i==="space-sync")try{return await Xke(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(o),Ke()),await Me(1)}else if(i==="push")try{return await eRe(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(o),Ke()),await Me(1)}else if(i==="pull")try{return await tRe(n,t),await Me(0)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(o),Ke()),await Me(1)}else if(i==="dsi-mcp"||i==="mcp")try{await $ke(n,t)}catch(o){return n.Sentry?.captureException(o),o instanceof qe&&(en(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);qbt(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&&(en(n),Ke("Cannot start builder dev tools due to network error")),await Me(1)}})}$bt().catch(t=>{process.stderr.write((t instanceof Error?t.stack??t.message:String(t))+`
|
|
7440
7440
|
`),process.exit(1)});var Vbt=void 0;
|
|
7441
7441
|
/*! Bundled license information:
|
|
7442
7442
|
|