@alexgorbatchev/dotfiles 0.0.1 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +107 -107
- package/cli.js.map +8 -8
- package/package.json +2 -3
- package/skill/references/shell-and-hooks.md +7 -0
package/cli.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{i as
|
|
4
|
-
`),J=M.filter((
|
|
5
|
-
`).trim()}function
|
|
6
|
-
`).map((Z)=>
|
|
7
|
-
`),
|
|
8
|
-
`)}function j$($){if(!$)return $;return $.replace(/[/\\]/g,"-").replace(/[:]/g,"-").replace(/[<>"|?*]/g,"_").trim()}async function
|
|
3
|
+
import{i as vG}from"./cli-fj2hdbnx.js";function s($,M){if(M.startsWith($)){let J=M.slice($.length);return J.startsWith("/")||J===""?`~${J}`:M}return M}function c($){let M=$.split(`
|
|
4
|
+
`),J=M.filter((Y)=>Y.trim().length>0);if(J.length===0)return $;let Q=Math.min(...J.map((Y)=>Y.match(/^ */)?.[0].length??0));return M.map((Y)=>Y.slice(Q)).join(`
|
|
5
|
+
`).trim()}function L7($,M,J){let Q=M[1];if(Q&&Q in J){let Y=J[Q];if(Y!==void 0){let G=$.match(/^(\s*)/)?.[1]??"";return Y.split(`
|
|
6
|
+
`).map((Z)=>G+Z)}}return[$]}function x7($,M){let J=$,Q=/{(\w+)}/g,Y;Y=Q.exec(J);while(Y!==null){let G=Y[0],X=Y[1];if(X&&X in M){let Z=M[X];if(Z!==void 0)J=J.replace(G,Z),Q.lastIndex=0}Y=Q.exec(J)}return J}function oJ($,M){let Q=c($).split(`
|
|
7
|
+
`),Y=[];for(let G of Q){let Z=G.trim().match(/^{(\w+)}$/);if(Z){let q=L7(G,Z,M);Y.push(...q)}else{let q=x7(G,M);Y.push(q)}}return Y.join(`
|
|
8
|
+
`)}function j$($){if(!$)return $;return $.replace(/[/\\]/g,"-").replace(/[:]/g,"-").replace(/[<>"|?*]/g,"_").trim()}async function A$($){let{binaryPath:M,args:J=["--version"],regex:Q,env:Y,shellExecutor:G}=$;try{let X=await G`${M} ${J}`.env({...process.env,...Y}).quiet().noThrow(),Z=(X.stdout.toString()+X.stderr.toString()).trim();if(Q){let U=typeof Q==="string"?new RegExp(Q):Q,K=Z.match(U);if(K?.[1])return j$(K[1]);throw Error(`Version detection failed: regex ${U} did not match output: ${Z}`)}let q=/v?(\d+\.\d+\.\d+(?:-[\w.]+)?(?:\+[\w.]+)?)/i,I=Z.match(q);if(I?.[1])return j$(I[1]);return}catch(X){if(X instanceof Error&&X.message.startsWith("Version detection failed"))throw X;return}}var x={SUCCESS:0,ERROR:1};function N($){throw process.exit($),Error(`MOCK_EXIT_CLI_CALLED_WITH_${$}`)}function n($,M){if(M==="~"||M.startsWith("~/")||M.startsWith("~\\"))return M.replace(/^~(?=$|\/|\\)/,$);return M}import f0 from"path";function RM($,M,J,Q){let Y=T7(M,J);if(Y=n(J.paths.homeDir,Y),!f0.isAbsolute(Y))if($){let G=f0.dirname($);Y=f0.resolve(G,Y)}else Y=f0.resolve(J.paths.dotfilesDir,Y);return Y}function T7($,M){return $.replace(/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g,(J,Q)=>{if(Q.includes(".")){let Y=Q.split("."),G=M;for(let X of Y)if(G&&typeof G==="object"&&X in G)G=G[X];else return J;return typeof G==="string"?G:J}return J})}function H0($){let J=(typeof $==="string"?parseInt($,8):$)&511,Q=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"],Y=Q[J>>6&7]??"---",G=Q[J>>3&7]??"---",X=Q[J&7]??"---";return Y+G+X}function i6($=new Date){let M=$.getFullYear(),J=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0"),Y=String($.getHours()).padStart(2,"0"),G=String($.getMinutes()).padStart(2,"0"),X=String($.getSeconds()).padStart(2,"0");return`${M}-${J}-${Q}-${Y}-${G}-${X}`}import k7 from"path";function p0($){let M=$?.DOTFILES_BUILT_PACKAGE_NAME??"@alexgorbatchev/dotfiles";if(M!==void 0){let J=M.trim();if(J!=="")return J}return"@alexgorbatchev/dotfiles"}var S7=`/**
|
|
9
9
|
* Type-safe binary names for tool dependencies.
|
|
10
10
|
*
|
|
11
11
|
* This file is automatically generated by the build system and the \`generate\` command.
|
|
12
12
|
* It extracts binary names from loaded tool configurations to provide autocomplete
|
|
13
13
|
* for the \`dependsOn()\` method.
|
|
14
|
-
*/`;function
|
|
15
|
-
`),Z=
|
|
16
|
-
${
|
|
14
|
+
*/`;function w7($){let M=new Set;for(let[J,Q]of Object.entries($))if(Q.binaries&&Q.binaries.length>0)for(let Y of Q.binaries)if(typeof Y==="string")M.add(Y);else{let G=Y;M.add(G.name)}else M.add(J);return M}function b7($){if($.size===0)return"string";return Array.from($).toSorted().map((Q)=>`'${Q}'`).join(" | ")}function N7($,M){let J=w7($),G=(b7(J)==="string"?[]:Array.from(J).toSorted()).map((H)=>` '${H}': never;`).join(`
|
|
15
|
+
`),Z=G.length>0?` interface IKnownBinNameRegistry {
|
|
16
|
+
${G}
|
|
17
17
|
}`:" interface IKnownBinNameRegistry {}",I=`declare module '${M??p0()}' {
|
|
18
18
|
${Z}
|
|
19
|
-
}`;return[
|
|
19
|
+
}`;return[S7,I,"export {};",""].join(`
|
|
20
20
|
|
|
21
|
-
`)}async function
|
|
22
|
-
`),J=[];for(let Q of M)if(
|
|
21
|
+
`)}async function l6($,M,J,Q){let Y=N7($,Q);await J.ensureDir(k7.dirname(M)),await J.writeFile(M,Y,"utf8")}import a6 from"path";async function wM($,M,J){let Q=[],Y=J!==void 0,G=J??M,X=await $.readdir(M);for(let Z of X){let q=a6.join(M,Z);if((await $.stat(q)).isDirectory()){let U=await wM($,q,Y?G:void 0);Q.push(...U)}else{let U=Y?a6.relative(G,q):q;Q.push(U)}}return Q}function sM(){if(typeof CLI_BIN_PATH>"u")return process.argv.slice(0,2).join(" ");return CLI_BIN_PATH}async function s6($,M,J){let Q=$ instanceof Request?$.url:$.toString(),Y=J?.enabled?`http://localhost:${J.port}/${Q}`:Q;if($ instanceof Request)return fetch(Y,{method:$.method,headers:$.headers,body:$.body,mode:$.mode,credentials:$.credentials,cache:$.cache,redirect:$.redirect,referrer:$.referrer,integrity:$.integrity,...M});return fetch(Y,M)}async function t$($,M){if(typeof M==="function")return await M($);return M}async function c0($,M,J,Q,Y){let G=Y?.mode??"file",X=v7(J),Z=await $.readFile(M,"utf8"),q=G==="line"?await y7(Z,X,Q):await r6(Z,X,Q),I=q!==Z;if(I)await $.writeFile(M,q,"utf8");return I}function v7($){if(typeof $==="string"){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(Q,"g")}let M=$.flags.includes("g")?$.flags:`${$.flags}g`;return new RegExp($.source,M)}async function r6($,M,J){let Q=Array.from($.matchAll(M)),Y=$,G=0;for(let X of Q){let Z=X[0]??"",q=X.index??0,I=X.slice(1),U=X.groups,H=await t$({substring:Z,captures:I,offset:q,input:$,groups:U},J),_=q+G,O=_+Z.length;Y=Y.slice(0,_)+H+Y.slice(O),G+=H.length-Z.length}return Y}async function y7($,M,J){let Q=$.split(/(\r\n|\n)/),Y="";for(let G=0;G<Q.length;G+=2){let X=Q[G]??"",Z=Q[G+1]??"",q=await r6(X,M,J);Y+=q+Z}return Y}import{z as t6}from"zod";var E$;((X)=>{X[X.None=0]="None";X[X.Linux=1]="Linux";X[X.MacOS=2]="MacOS";X[X.Windows=4]="Windows";X[X.Unix=3]="Unix";X[X.All=7]="All"})(E$||={});var OM;((Y)=>{Y[Y.None=0]="None";Y[Y.X86_64=1]="X86_64";Y[Y.Arm64=2]="Arm64";Y[Y.All=3]="All"})(OM||={});var o6=t6.number().int().min(0).max(7).refine(($)=>{return($&-8)===0},{message:"Must be a valid Platform value. Use `Platform.None`, `Platform.Linux`, `Platform.MacOS`, `Platform.Windows`, `Platform.Unix`, or `Platform.All`. You can combine values with a bitwise OR (e.g., `Platform.Linux | Platform.MacOS`)."}),e6=t6.number().int().min(0).max(3).refine(($)=>{return($&-4)===0},{message:"Must be a valid Architecture value. Use `Architecture.None`, `Architecture.X86_64`, `Architecture.Arm64`, or `Architecture.All`. You can combine values with a bitwise OR (e.g., `Architecture.X86_64 | Architecture.Arm64`)."});function rM($,M){if(M===0)return $===0;return($&M)===M}function tM($,M){if(M===0)return $===0;return($&M)===M}function $Y($){switch($){case"darwin":return 2;case"linux":return 1;case"win32":return 4;default:return 0}}function MY($){switch($){case"x64":return 1;case"arm64":return 2;default:return 0}}function o$($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";case 0:return"none";default:return"unknown"}}function e$($){switch($){case 1:return"x86_64";case 2:return"arm64";case 0:return"none";default:return"unknown"}}import{z as F}from"zod";function P7($){let M=$?.enabled??!0,J=$?.ttl??86400000;return F.object({enabled:F.boolean().default(M),ttl:F.number().default(J)}).strict()}var h0=P7();function n0($){let{defaultHost:M,includeToken:J,includeUserAgent:Q,defaultUserAgent:Y="dotfiles-generator",tokenDefault:G=""}=$;return F.object({host:F.string().default(M),cache:h0.default(h0.parse({})),token:F.string().default(J?G:""),userAgent:F.string().default(Q?Y:"dotfiles-generator")}).strict()}var eJ=F.object({homeDir:F.string().default("{HOME}"),dotfilesDir:F.string().default("{configFileDir}"),targetDir:F.string().default("{paths.generatedDir}/bin-default"),generatedDir:F.string().default("{paths.dotfilesDir}/.generated"),toolConfigsDir:F.string().default("{paths.dotfilesDir}/tools"),shellScriptsDir:F.string().default("{paths.generatedDir}/shell-scripts"),binariesDir:F.string().default("{paths.generatedDir}/binaries")}).strict(),$Q=F.object({sudoPrompt:F.string().default("Please enter your password to continue:")}).strict(),MQ=F.object({debug:F.string().default("")}).strict(),JQ=F.object({checkOnRun:F.boolean().default(!0),checkInterval:F.number().default(86400)}).strict(),QQ=n0({defaultHost:"https://api.github.com",includeToken:!0,includeUserAgent:!0}),JY=n0({defaultHost:"https://crates.io"}),QY=n0({defaultHost:"https://raw.githubusercontent.com"}),YY=n0({defaultHost:"https://github.com"}),YQ=F.object({cratesIo:JY.default(JY.parse({})),githubRaw:QY.default(QY.parse({})),githubRelease:YY.default(YY.parse({})),userAgent:F.string().default("dotfiles-generator")}).strict(),GQ=F.object({timeout:F.number().default(300000),retryCount:F.number().default(3),retryDelay:F.number().default(1000),cache:h0.default(h0.parse({}))}).strict(),XQ=F.object({catalog:F.object({generate:F.boolean().default(!0),filePath:F.string().default("{paths.dotfilesDir}/CATALOG.md")}).strict().default({generate:!0,filePath:"{paths.dotfilesDir}/CATALOG.md"}),shellInstall:F.object({zsh:F.string().optional(),bash:F.string().optional(),powershell:F.string().optional()}).strict().optional()}).strict(),m0=["macos","linux","windows"],g0=["x86_64","arm64"],C7=F.union([F.object({os:F.enum(m0),arch:F.enum(g0).optional()}).strict(),F.object({os:F.enum(m0).optional(),arch:F.enum(g0)}).strict()]),d7=F.object({paths:eJ.required().default(eJ.parse({})),system:$Q.required().default($Q.parse({})),logging:MQ.required().default(MQ.parse({})),updates:JQ.required().default(JQ.parse({})),github:QQ.required().default(QQ.parse({})),cargo:YQ.required().default(YQ.parse({})),downloader:GQ.required().default(GQ.parse({})),features:XQ.default(XQ.parse({}))}).strict(),u7=F.object({paths:eJ.partial().optional(),system:$Q.partial().optional(),logging:MQ.partial().optional(),updates:JQ.partial().optional(),github:QQ.partial().optional(),cargo:YQ.partial().optional(),downloader:GQ.partial().optional(),features:XQ.partial().optional()}).strict(),f7=F.object({match:F.array(C7).nonempty(),get config(){return u7.partial()}}).strict(),ZQ=d7.extend({platform:F.array(f7).optional()}).strict(),GY=F.object({configFilePath:F.string(),configFileDir:F.string()});var{Glob:i7}=globalThis.Bun;import VM from"path";function W($){return $}var jM={VERBOSE:1,DEFAULT:3,QUIET:5},WQ=["verbose","default","quiet"],XY={verbose:jM.VERBOSE,default:jM.DEFAULT,quiet:jM.QUIET};function ZY($){let M=$.toLowerCase();if(!(M in XY))throw Error(`Invalid log level: ${$}. Valid levels are: ${WQ.join(", ")}`);return XY[M]}import{Logger as n7}from"tslog";var p7=/\.tool\.(ts|js)/,c7=/([^/\\]+\.tool\.(?:ts|js)):(\d+)/;function h7($){return p7.test($)}function m7($){let M=c7.exec($);if(!M)return null;return`${M[1]}:${M[2]}`}function g7($){if(!$)return[];let M=$.split(`
|
|
22
|
+
`),J=[];for(let Q of M)if(h7(Q)){let Y=m7(Q);if(Y)J.push(Y)}return J}function WY($){let M=typeof $.stack==="string"?$.stack:void 0,J=g7(M);if(J.length===0)return null;return`(${J.join(", ")})`}function qY($){return $ instanceof Error}function IY($){let M=[],J=[...$.issues].toSorted((Q,Y)=>(Q.path??[]).length-(Y.path??[]).length);for(let Q of J)if(M.push(`\u2716 ${Q.message}`),Q.path?.length){let Y=Q.path.map(String).join(".");M.push(` \u2192 at ${Y}`)}return M}function UY($){return`[${$}]`}class _0 extends n7{_trace;constructor($){let J=($?.prefix??[]).map((Q)=>String(Q));if($?.context)J.push(UY($.context));super({...$,prefix:J});this._trace=$?.trace===!0}isTracingEnabled(){return this._trace}filterErrorArgs($){if(this.isTracingEnabled())return $;let M=[];for(let J of $)if(qY(J)){let Q=WY(J);if(Q)M.push(Q)}else M.push(J);return M}trace($,...M){return super.trace($,...M)}debug($,...M){return super.debug($,...M)}info($,...M){let J=this.filterErrorArgs(M);return super.info($,...J)}warn($,...M){let J=this.filterErrorArgs(M);return super.warn($,...J)}error($,...M){let J=this.filterErrorArgs(M);return super.error($,...J)}fatal($,...M){let J=this.filterErrorArgs(M);return super.fatal($,...J)}getSubLogger($){let M=[...this.settings.parentNames??[]];if(this.settings.name&&$?.name)M.push(this.settings.name);return new _0({...this.settings,...$,parentNames:M})}zodErrors($){let M=IY($);for(let J of M)this.error(J)}setPrefix($){return this.settings.prefix=[UY($)],this}}function qQ($){let M={};if(typeof $==="string")M.name=$;else M={...$};M.level=M.level??jM.DEFAULT;let J=M.trace?"{{logLevelName}}\t{{filePathWithLine}} - ":"{{logLevelName}}\t",Q=process.env.NO_COLOR==="1"||process.env.TERM==="dumb";return new _0({name:M.name,minLevel:M.level,trace:M.trace,prettyLogTemplate:J,stylePrettyLogs:!Q,hideLogPositionForProduction:!1,prettyErrorTemplate:`
|
|
23
23
|
{{errorName}} {{errorMessage}}
|
|
24
24
|
error stack:
|
|
25
|
-
{{errorStack}}`,prettyLogStyles:{logLevelName:{FATAL:["bold","red"],ERROR:["bold","red"],WARN:["bold","yellow"],INFO:["bold","blue"],DEBUG:["bold","white"],TRACE:["bold","white"]}},prettyInspectOptions:{breakLength:1/0,compact:!0}})}function
|
|
26
|
-
${J}`}}function W$($={}){return(J,...Q)=>{let
|
|
27
|
-
`)},async bytes(){let Z=await
|
|
28
|
-
`);
|
|
25
|
+
{{errorStack}}`,prettyLogStyles:{logLevelName:{FATAL:["bold","red"],ERROR:["bold","red"],WARN:["bold","yellow"],INFO:["bold","blue"],DEBUG:["bold","white"],TRACE:["bold","white"]}},prettyInspectOptions:{breakLength:1/0,compact:!0}})}function KY($,M,J){if(M)return jM.QUIET;if(J)return jM.VERBOSE;return ZY($)}var M$={pluginAlreadyRegistered:($)=>W(`Plugin ${$} is already registered, replacing...`),pluginRegistered:($,M,J)=>W(`Registered installer plugin: ${$} (${M} v${J})`),pluginRegistrationFailed:($)=>W(`Failed to register plugin ${$}`),schemasComposed:($,M)=>W(`Composed schemas from ${$} plugins: ${M}`),noPluginForMethod:($,M)=>W(`No plugin registered for installation method: ${$}. Available methods: ${M}`),pluginValidationFailed:($)=>W(`Plugin validation failed: ${$}`),validationFailed:($,M)=>W(`Plugin validation failed for ${$}: ${M}`),validationWarning:($,M)=>W(`Validation warning for ${$}: ${M}`),delegatingToPlugin:($)=>W(`Delegating installation to plugin: ${$}`),validationCacheCleared:()=>W("Validation cache cleared"),cleaningUpPlugins:()=>W("Cleaning up plugins..."),pluginCleanedUp:($)=>W(`Cleaned up plugin: ${$}`),pluginCleanupFailed:($)=>W(`Failed to cleanup plugin ${$}`),pluginCleanupComplete:()=>W("Plugin cleanup complete"),replaceInFileNoMatch:($,M)=>W(`Could not find '${$}' in ${M}`),resolveNoMatches:($)=>W(`No matches found for pattern: ${$}`),resolveMultipleMatches:($,M,J)=>W(`Pattern '${$}' matched ${M} paths (expected exactly 1): ${J}`)};class i0 extends Error{constructor($){super($);this.name="ResolveError"}}function IQ($,M){let J=$.getSubLogger({context:M});return{trace:(Y)=>{J.trace(Y)},debug:(Y)=>{J.debug(Y)},info:(Y)=>{J.info(Y)},warn:(Y)=>{J.warn(Y)},error:(Y,G)=>{if(G!==void 0)J.error(Y,G);else J.error(Y)}}}function R0($,M,J,Q,Y,G){let X=VM.join($.paths.binariesDir,J,"current"),Z={platform:M.platform,arch:M.arch,homeDir:$.paths.homeDir,hostname:M.hostname},q=async(H,_,O,B)=>{let j=await c0(Y,H,_,O,B);if(!j&&B?.errorMessage){let V=_ instanceof RegExp?_.source:_;G.error(M$.replaceInFileNoMatch(V,H))}return j},I=(H)=>{let _=VM.isAbsolute(H),O,B;if(_){let A=VM.dirname(H),T=VM.basename(H);if(/[*?[\]{]/.test(A)){let w=H.split(VM.sep),u=[],i=[],E=!1;for(let g of w)if(!E&&!/[*?[\]{]/.test(g))u.push(g);else E=!0,i.push(g);O=u.join(VM.sep)||"/",B=i.join(VM.sep)}else O=A,B=T}else O=Q,B=H;let j=new i7(B),V=[];for(let A of j.scanSync({cwd:O,onlyFiles:!1}))V.push(VM.join(O,A));if(V.length===0)throw G.error(M$.resolveNoMatches(H)),new i0(`No matches found for pattern: ${H}`);if(V.length>1){let A=V.slice(0,5).join(", ")+(V.length>5?", ...":"");throw G.error(M$.resolveMultipleMatches(H,V.length,A)),new i0(`Pattern '${H}' matched ${V.length} paths (expected exactly 1)`)}let D=V[0];if(D===void 0)throw G.error(M$.resolveNoMatches(H)),new i0(`No matches found for pattern: ${H}`);return D},U=IQ(G,J);return{toolName:J,toolDir:Q,currentDir:X,projectConfig:$,systemInfo:Z,replaceInFile:q,resolve:I,log:U}}import{z as HY}from"zod";class UQ{plugins=new Map;validationCache=new Map;composedToolConfigSchema;composedInstallParamsSchema;logger;schemasComposed=!1;eventHandlers=[];constructor($){this.logger=$.getSubLogger({name:"InstallerPluginRegistry"})}onEvent($){this.eventHandlers.push($)}async emitEvent($){for(let M of this.eventHandlers)await M($)}async register($){let{method:M}=$;try{if(!M||typeof M!=="string")throw Error("Plugin must have a valid method name");if(this.schemasComposed)throw Error("Cannot register plugins after schemas have been composed");if(this.plugins.has(M))this.logger.warn(M$.pluginAlreadyRegistered(M));if($.initialize)await $.initialize();this.plugins.set(M,$),this.logger.debug(M$.pluginRegistered(M,$.displayName,$.version))}catch(J){throw this.logger.error(M$.pluginRegistrationFailed(M),J),Error(`Plugin registration failed: ${M}`,{cause:J})}}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getAll(){return Array.from(this.plugins.values())}getMethods(){return Array.from(this.plugins.keys())}getExternallyManagedMethods(){let $=new Set;for(let[M,J]of this.plugins)if(J.externallyManaged)$.add(M);return $}getMissingBinaryMessagesByMethod(){let $=new Map;for(let[M,J]of this.plugins)if(J.missingBinaryMessage)$.set(M,J.missingBinaryMessage);return $}composeSchemas(){let $=this.getAll();if($.length===0)throw Error("No plugins registered");let M=$.map((Q)=>Q.toolConfigSchema);if(M.length===1)this.composedToolConfigSchema=M[0];else{let[Q,...Y]=M;this.composedToolConfigSchema=HY.discriminatedUnion("installationMethod",[Q,...Y])}let J=$.map((Q)=>Q.paramsSchema);if(J.length===1)this.composedInstallParamsSchema=J[0];else{let[Q,Y,...G]=J;this.composedInstallParamsSchema=HY.union([Q,Y,...G])}this.schemasComposed=!0,this.logger.info(M$.schemasComposed($.length,this.getMethods().join(", ")))}getToolConfigSchema(){if(!this.composedToolConfigSchema)throw Error("Schemas not composed. Call composeSchemas() after registering all plugins.");return this.composedToolConfigSchema}getInstallParamsSchema(){if(!this.composedInstallParamsSchema)throw Error("Schemas not composed. Call composeSchemas() after registering all plugins.");return this.composedInstallParamsSchema}async validatePlugin($,M,J){if(!$.validate)return null;let Q=this.validationCache.get($.method);if(!Q){if(Q=await $.validate(M),$.staticValidation)this.validationCache.set($.method,Q)}if(!Q.valid){let Y=`Plugin validation failed: ${Q.errors?.join(", ")}`;return J.error(M$.validationFailed($.method,Q.errors?.join(", ")??"Unknown error")),{success:!1,error:Y}}if(Q.warnings&&Q.warnings.length>0)for(let Y of Q.warnings)J.warn(M$.validationWarning($.method,Y));return null}async install($,M,J,Q,Y,G){let X=$.getSubLogger({name:"InstallerPluginRegistry"}).getSubLogger({name:"install"}),Z=this.get(M);if(!Z){let I=`No plugin registered for installation method: ${M}. Available methods: ${this.getMethods().join(", ")}`;return X.error(M$.noPluginForMethod(M,this.getMethods().join(", "))),{success:!1,error:I}}let q=await this.validatePlugin(Z,Y,X);if(q)return q;return X.debug(M$.delegatingToPlugin(M)),await Z.install(J,Q,Y,G,X)}clearValidationCache(){this.validationCache.clear(),this.logger.debug(M$.validationCacheCleared())}async cleanup(){let $=this.logger.getSubLogger({name:"cleanup"});$.info(M$.cleaningUpPlugins());let M=this.getAll();for(let J of M)if(J.cleanup)try{await J.cleanup(),$.debug(M$.pluginCleanedUp(J.method))}catch(Q){$.error(M$.pluginCleanupFailed(J.method),Q)}$.info(M$.pluginCleanupComplete())}}import{z as AY}from"zod";import{z as zM}from"zod";import{z as l7}from"zod";var O0=l7.custom(($)=>typeof $==="function","Must be a function");var r=zM.object({auto:zM.boolean().optional(),env:zM.custom().optional(),hooks:zM.object({"before-install":zM.array(O0).optional(),"after-download":zM.array(O0).optional(),"after-extract":zM.array(O0).optional(),"after-install":zM.array(O0).optional()}).partial().optional()}).strict();import{z as jQ}from"zod";import{z as d$}from"zod";import{z as a7}from"zod";import{z as V$}from"zod";import{z as KQ}from"zod";var _Y=KQ.object({kind:KQ.enum(["once","always"]),value:KQ.string()});var l0=V$.object({scripts:V$.array(_Y).optional(),aliases:V$.record(V$.string(),V$.string()).optional(),env:V$.record(V$.string(),V$.string()).optional(),functions:V$.record(V$.string(),V$.string()).optional(),paths:V$.array(V$.unknown()).optional(),completions:V$.unknown().optional()}).strict();var RY=a7.object({zsh:l0.optional(),bash:l0.optional(),powershell:l0.optional()}).strict();import{z as HQ}from"zod";var OY=HQ.object({enabled:HQ.boolean().optional(),constraint:HQ.string().optional()}).strict();import{z as _Q}from"zod";var Z$=_Q.object({name:_Q.string().min(1),pattern:_Q.string().min(1)}).strict();import{z as RQ}from"zod";var jY=RQ.object({source:RQ.string().min(1),target:RQ.string().min(1)}).strict();import{z as OQ}from"zod";var VY=OQ.object({source:OQ.string().min(1),target:OQ.string().min(1)}).strict();var a0=d$.object({binaries:d$.array(d$.union([d$.string().min(1),Z$])).optional(),dependencies:d$.array(d$.string().min(1)).optional(),disabled:d$.boolean().optional(),hostname:d$.string().optional(),version:d$.string().optional(),shellConfigs:RY.optional(),symlinks:d$.array(VY).optional(),copies:d$.array(jY).optional(),updateCheck:OY.optional()}).strict();var zY=a0.extend({name:jQ.string().min(1),version:jQ.string(),configFilePath:jQ.string().optional()}).strict();import{z as s7}from"zod";import{z as BY}from"zod";var DY=BY.object({platforms:o6,architectures:e6.optional(),config:BY.unknown()}).strict();var t=zY.extend({platformConfigs:s7.array(DY).optional()});import{z as j0}from"zod";var fZ=j0.object({source:j0.string().min(1).optional(),url:j0.string().url().optional(),cmd:j0.string().min(1).optional(),bin:j0.string().optional()}).strict().refine(($)=>{let M=Boolean($.source),J=Boolean($.cmd),Q=Boolean($.url);if(J&&Q)return!1;if(J&&M)return!1;if(!M&&!J&&!Q)return!1;return!0},{message:"Invalid completion config: use 'source' alone, 'cmd' alone, 'url' alone, or 'url' with 'source'. Cannot combine 'cmd' with 'url' or 'source'."});var JW=a0.extend({installationMethod:AY.string().optional(),installParams:AY.unknown().optional()}).strict();var oM=Symbol("loggingShellBrand");function FY($,M){let J=(Q,...Y)=>{let G=Q[0]||"";for(let X=0;X<Y.length;X++){let Z=Y[X];if(Array.isArray(Z))G+=Z.map((q)=>EY(String(q))).join(" ");else G+=EY(String(Z));G+=Q[X+1]||""}return M.info(W(`$ ${G}`)),$(Q,...Y)};return Object.assign(J,$),Object.defineProperty(J,oM,{value:!0,enumerable:!1}),J}function EY($){if($===""||/[\s"'`$\\]/.test($))return`'${$.replace(/'/g,"'\\''")}'`;return $}class VQ extends Error{code;stdout;stderr;name="ShellError";constructor($,M,J,Q){super(`Exited with code: ${$}`);this.code=$;this.stdout=M;this.stderr=J;if(J)this.message+=`
|
|
26
|
+
${J}`}}function W$($={}){return(J,...Q)=>{let Y=typeof J==="string"?J:o7(J,Q);return r7(Y,$)}}function r7($,M){let J={...M},Q=!1,Y=null,G=async()=>{if(Y)return Y;return Q=!0,Y=t7($,J),Y},X={cwd(Z){if(Q)throw Error("Cannot modify command after execution");return J={...J,cwd:Z},X},env(Z){if(Q)throw Error("Cannot modify command after execution");return J={...J,env:{...J.env,...Z}},X},quiet(){if(Q)throw Error("Cannot modify command after execution");return J={...J,quiet:!0},X},noThrow(){if(Q)throw Error("Cannot modify command after execution");return J={...J,noThrow:!0},X},async text(){return(await G()).stdout.replace(/\r?\n$/,"")},async json(){let Z=await G();return JSON.parse(Z.stdout)},async lines(){return(await G()).stdout.replace(/\r?\n$/,"").split(`
|
|
27
|
+
`)},async bytes(){let Z=await G();return new TextEncoder().encode(Z.stdout)},then(Z,q){return G().then(Z,q)}};return X}async function t7($,M){let{cwd:J,env:Q,logger:Y,noThrow:G,skipCommandLog:X}=M;if(Y&&!X)Y.info(W(`$ ${$}`));let Z={...process.env};if(Q)for(let[H,_]of Object.entries(Q))if(_===void 0)delete Z[H];else Z[H]=_;let q=Bun.spawn(["sh","-c",$],{cwd:J,env:Z,stdout:"pipe",stderr:"pipe"}),[I,U]=await Promise.all([LY(q.stdout,Y?(H)=>Y.info(W(`| ${H}`)):void 0),LY(q.stderr,Y?(H)=>Y.info(W(`| ${H}`)):void 0)]),K=await q.exited;if(K!==0&&!G)throw new VQ(K,I,U,$);return{code:K,stdout:I,stderr:U}}async function LY($,M){let J=$.getReader(),Q=new TextDecoder,Y=[],G="";while(!0){let{done:X,value:Z}=await J.read();if(X)break;let q=Q.decode(Z,{stream:!0});if(Y.push(q),M){G+=q;let I=G.split(`
|
|
28
|
+
`);G=I.pop()??"";for(let U of I)if(U)M(U)}}if(M&&G)M(G);return Y.join("")}function o7($,M){let J=$[0]||"";for(let Q=0;Q<M.length;Q++){let Y=M[Q];if(Array.isArray(Y))J+=Y.map(xY).join(" ");else J+=xY(Y);J+=$[Q+1]||""}return J}function xY($){let M=String($);if(/^[a-zA-Z0-9_\-./=:@]+$/.test(M))return M;return`'${M.replace(/'/g,"'\\''")}'`}function s0($){return typeof $==="function"&&oM in $}function TY($){return{kind:"once",value:$}}function kY($){return{kind:"always",value:$}}function n$($){return{kind:"raw",value:$}}function r0($){return $.kind==="once"}function t0($){return $.kind==="always"}function o0($){return $.kind==="raw"}function e0($){return $.value}import{randomUUID as CX}from"crypto";import J0 from"path";import bX from"path";var l={directoryDeletionError:()=>W("Error tracking directory deletion %s: %s"),rmdirTracked:()=>W("Tracked rmdir operation: %s"),operationRecorded:()=>W("Recorded %s operation for %s: %s"),operationsRetrieved:()=>W("Retrieved %d operations with filter: %o"),fileStatesComputed:()=>W("Computed %d file states for tool: %s"),fileStateComputed:()=>W("Computed file state for %s: %s"),noOperationsFound:()=>W("No operations found for file: %s"),toolsFound:()=>W("Found %d registered tools"),operationsRemoved:()=>W("Removed %d operations for tool: %s"),compactionComplete:()=>W("Compaction complete: %d -> %d operations"),validationComplete:()=>W("Validation complete: %d issues found, %d repaired"),registryClosed:()=>W("Closed SQLite file registry"),schemaInitialized:()=>W("Schema initialization complete"),fileCreated:($)=>W(`write ${$}`),fileUpdated:($)=>W(`write ${$}`),fileRemoved:($)=>W(`rm ${$}`),fileMoved:($,M)=>W(`mv ${$} ${M}`),fileCopied:($,M)=>W(`cp ${$} ${M}`),symlinkCreated:($,M)=>W(`ln -s ${M} ${$}`),permissionsChanged:($,M)=>W(`chmod ${M} ${$}`),directoryCreated:($)=>W(`mkdir ${$}`)};class zQ{db;logger;constructor($,M){this.logger=$.getSubLogger({name:"SqliteFileRegistry"}),this.db=M,this.initializeSchema()}async recordOperation($){let M=this.logger.getSubLogger({name:"recordOperation"}),J=this.db.prepare(`
|
|
29
29
|
INSERT INTO file_operations (
|
|
30
30
|
tool_name, operation_type, file_path, target_path, file_type,
|
|
31
31
|
metadata, size_bytes, permissions, created_at, operation_id
|
|
32
32
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
33
|
-
`),Q=Date.now(),
|
|
33
|
+
`),Q=Date.now(),Y=$.metadata?JSON.stringify($.metadata):null;J.run($.toolName,$.operationType,$.filePath,$.targetPath||null,$.fileType,Y,$.sizeBytes||null,$.permissions||null,Q,$.operationId),M.debug(l.operationRecorded(),$.operationType,$.toolName,$.filePath)}async getOperations($={}){let M=this.logger.getSubLogger({name:"getOperations"}),J="SELECT * FROM file_operations WHERE 1=1",Q=[];if($.toolName)J+=" AND tool_name = ?",Q.push($.toolName);if($.operationType)J+=" AND operation_type = ?",Q.push($.operationType);if($.fileType)J+=" AND file_type = ?",Q.push($.fileType);if($.filePath)J+=" AND file_path = ?",Q.push($.filePath);if($.createdAfter)J+=" AND created_at > ?",Q.push($.createdAfter);if($.createdBefore)J+=" AND created_at < ?",Q.push($.createdBefore);if($.operationId)J+=" AND operation_id = ?",Q.push($.operationId);J+=" ORDER BY created_at DESC, id DESC";let Y=this.db.prepare(J),G=Q.length>0?Y.all(...Q):Y.all();return M.debug(l.operationsRetrieved(),G.length,$),G.map((X)=>({id:X.id,toolName:X.tool_name,operationType:X.operation_type,filePath:X.file_path,targetPath:X.target_path??void 0,fileType:X.file_type,metadata:X.metadata?JSON.parse(X.metadata):void 0,sizeBytes:X.size_bytes??void 0,permissions:X.permissions?parseInt(X.permissions,10):void 0,createdAt:parseInt(X.created_at,10),operationId:X.operation_id}))}async getFileStatesForTool($){let M=this.logger.getSubLogger({name:"getFileStatesForTool"}),J=await this.getOperations({toolName:$}),Q=new Map;for(let G of[...J].toReversed())if(G.operationType==="rm")Q.delete(G.filePath);else Q.set(G.filePath,{filePath:G.filePath,toolName:G.toolName,fileType:G.fileType,lastOperation:G.operationType,targetPath:G.targetPath,lastModified:G.createdAt,metadata:G.metadata,sizeBytes:G.sizeBytes,permissions:G.permissions});let Y=Array.from(Q.values());return M.debug(l.fileStatesComputed(),Y.length,$),Y}async getFileState($){let M=this.logger.getSubLogger({name:"getFileState"}),J=await this.getOperations({filePath:$});if(J.length===0)return M.debug(l.noOperationsFound(),$),null;let Q=null;for(let Y of[...J].toReversed())if(Y.operationType==="rm")Q=null;else Q={filePath:Y.filePath,toolName:Y.toolName,fileType:Y.fileType,lastOperation:Y.operationType,targetPath:Y.targetPath,lastModified:Y.createdAt,metadata:Y.metadata,sizeBytes:Y.sizeBytes,permissions:Y.permissions};return M.debug(l.fileStateComputed(),$,Q?"active":"deleted"),Q}async getRegisteredTools(){let $=this.logger.getSubLogger({name:"getRegisteredTools"}),M=await this.getOperations(),J=new Map;for(let Y of M)if(!J.has(Y.filePath))J.set(Y.filePath,Y);let Q=Array.from(new Set(Array.from(J.values()).filter((Y)=>Y.operationType!=="rm").map((Y)=>Y.toolName))).toSorted();return $.debug(l.toolsFound(),Q.length),Q}async removeToolOperations($){let M=this.logger.getSubLogger({name:"removeToolOperations"}),Q=this.db.prepare("DELETE FROM file_operations WHERE tool_name = ?").run($);M.debug(l.operationsRemoved(),Q.changes,$)}async compact(){let $=this.logger.getSubLogger({name:"compact"}),M=await this.getStats(),J=await this.getOperations({operationType:"rm"});for(let Y of J)if(!await this.getFileState(Y.filePath))this.db.prepare("DELETE FROM file_operations WHERE file_path = ?").run(Y.filePath);let Q=await this.getStats();$.debug(l.compactionComplete(),M.totalOperations,Q.totalOperations)}async validate(){let $=this.logger.getSubLogger({name:"validate"}),M=[],J=[],Q=this.db.prepare(`
|
|
34
34
|
SELECT operation_id, COUNT(*) as count
|
|
35
35
|
FROM file_operations
|
|
36
36
|
GROUP BY operation_id
|
|
37
37
|
HAVING count > 1
|
|
38
|
-
`).all();if(Q.length>0)M.push(`Found ${Q.length} duplicate operation IDs`);let
|
|
38
|
+
`).all();if(Q.length>0)M.push(`Found ${Q.length} duplicate operation IDs`);let Y=await this.getOperations({operationType:"symlink"});for(let G of Y)if(G.targetPath){if(!await this.getFileState(G.targetPath))M.push(`Symlink ${G.filePath} points to missing target ${G.targetPath}`)}return $.debug(l.validationComplete(),M.length,J.length),{valid:M.length===0,issues:M,repaired:J}}async getStats(){let $=this.db.prepare("SELECT COUNT(*) as count FROM file_operations").get(),M=this.db.prepare("SELECT COUNT(DISTINCT file_path) as count FROM file_operations").get(),J=this.db.prepare("SELECT COUNT(DISTINCT tool_name) as count FROM file_operations").get(),Q=this.db.prepare("SELECT MIN(created_at) as oldest, MAX(created_at) as newest FROM file_operations").get();return{totalOperations:$.count,totalFiles:M.count,totalTools:J.count,oldestOperation:Q.oldest||0,newestOperation:Q.newest||0}}async close(){this.db.close(),this.logger.debug(l.registryClosed())}initializeSchema(){let $=this.logger.getSubLogger({name:"initializeSchema"});this.db.run(`
|
|
39
39
|
CREATE TABLE IF NOT EXISTS file_operations (
|
|
40
40
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
41
|
tool_name TEXT NOT NULL,
|
|
@@ -55,29 +55,29 @@ ${J}`}}function W$($={}){return(J,...Q)=>{let G=typeof J==="string"?J:t7(J,Q);re
|
|
|
55
55
|
CREATE INDEX IF NOT EXISTS idx_operation_type ON file_operations(operation_type);
|
|
56
56
|
CREATE INDEX IF NOT EXISTS idx_created_at ON file_operations(created_at);
|
|
57
57
|
CREATE INDEX IF NOT EXISTS idx_operation_id ON file_operations(operation_id);
|
|
58
|
-
`),$.debug(l.schemaInitialized())}}var V0=Symbol("resolvedFileSystemBrand");import{Volume as
|
|
59
|
-
${M}`),cleaningFailedInstall:($)=>W(`No binaries found, cleaning up installation directory: ${$}`),fallbackCleanup:($)=>W(`Directory still exists after rm(), trying rmdir: ${$}`),searchingWithPattern:($,M)=>W(`Searching for binary using pattern ${$} in directory ${M}`),fallbackPattern:($,M)=>W(`Trying fallback binary pattern ${$} in directory ${M}`),patternPathMissing:($)=>W(`Pattern path does not exist: ${$}`),noPatternMatch:($,M)=>W(`No matches found for pattern ${$} in directory ${M}`),directDownloadSingleBinary:($,M)=>W(`Direct download only provides one binary, but ${$} were configured. Only ${M} will be available.`),patternDebug:($,M,J)=>W(`Pattern: ${$}, Parts: [${M.join(", ")}], ExtractDir: ${J}`),processingPart:($,M)=>W(`Processing part: "${$}", currentDir: ${M}`),wildcardMatchResult:($)=>W(`Wildcard match result: ${$??"null"}`),directPath:($)=>W(`Direct path: ${$}`),finalResult:($)=>W(`Final result: ${$}`)},binarySymlink:{targetBinaryMissing:($,M,J)=>W(`Cannot create entrypoint for ${$}/${M}: target binary missing at ${J}`),removingExisting:($)=>W(`Removing old entrypoint: ${$}`),removeExistingFailed:($)=>W(`Failed to remove old entrypoint ${$}`),creating:($,M)=>W(`Creating entrypoint: ${$} <- ${M}`),creationFailed:($,M)=>W(`Failed to create entrypoint ${$} <- ${M}`),verificationMismatch:($,M,J)=>W(`Entrypoint ${$} is ${J}, expected ${M}`),verificationFailed:($)=>W(`Failed to verify entrypoint ${$}`),createdAndVerified:($,M)=>W(`Successfully created and verified entrypoint: ${$} <- ${M}`)},lifecycle:{startingInstallation:($)=>W(`Starting installation for ${$}`),hookExecution:($)=>W(`install: Running ${$} hook`),directoryCreated:($)=>W(`install: Created installation directory: ${$}`),directoryRenamed:($,M)=>W(`install: Renamed installation directory from ${$} to ${M}`),cleaningFailedInstallDir:($)=>W(`install: Cleaning up failed installation directory: ${$}`),versionResolved:($)=>W(`install: Resolved version: ${$}`),versionFallbackToTimestamp:()=>W("install: Version resolution returned null, using timestamp"),versionResolutionFailed:($)=>W(`install: Version resolution failed, using timestamp: ${String($)}`),externalBinaryMissing:($,M,J)=>W(`Cannot create symlink for ${$}/${M}: external binary missing at ${J}`),removingExistingSymlink:($)=>W(`Removing existing symlink: ${$}`),creatingExternalSymlink:($,M)=>W(`Creating external symlink: ${$} -> ${M}`),symlinkVerificationFailed:($)=>W(`Symlink verification failed: ${$}`),externalSymlinkCreated:($,M)=>W(`External symlink created: ${$} -> ${M}`)},outcome:{installSuccess:($,M,J)=>W(`Tool "${$}" \`${M}\` installed successfully using ${J}`),outdatedVersion:($,M,J)=>W(`Tool "${$}" version ${M} is outdated (latest: ${J})`),installFailed:($)=>W(`Installation failed via ${$}`),hookFailed:($)=>W(`Hook failed: ${$}`),unsupportedOperation:($,M)=>W(`${$} not yet supported (${M})`)},archive:{extracting:($)=>W(`Extracting archive: ${$}`),extracted:()=>W("Archive extracted: %o"),cleaning:($)=>W(`Cleaning up downloaded archive: ${$}`)},binaryMovement:{moving:($,M)=>W(`Moving binary from ${$} to ${M}`)},completion:{noCompletionsConfigured:()=>W("install: no completions configured"),generatingCompletions:($)=>W(`install: generating ${$} completion files`),generatedCompletion:($,M)=>W(`install: generated completion: ${$} -> ${M}`),symlinking:($,M,J)=>W(`Symlinking completion for ${$} from ${M} to ${J}`),notFound:($)=>W(`Completion file not found: ${$}`),directoryListing:($)=>W(` ${$}`)},hookExecutor:{executingHook:($,M)=>W(`Executing ${$} hook with ${M}ms timeout`),hookCompleted:($,M)=>W(`Hook ${$} completed successfully in ${M}ms`),continuingDespiteFailure:($)=>W(`Continuing installation despite ${$} hook failure`),stoppingDueToFailure:($)=>W(`Stopping hook execution due to failure in ${$} hook`),timeoutExceeded:($,M)=>W(`Hook ${$} timed out after ${M}ms`)}};async function JJ($,M,J,Q,G,Y,X){let Z=X.getSubLogger({name:"createBinaryEntrypoint"}),q=B0.join(Y,M),I=B0.join(q,Q),U=B0.join(I,J),K=B0.join(I,G);if(K===U)return;if(!await $.exists(K)){let _=`Cannot create entrypoint: target binary does not exist at ${K}`;throw Z.error(L.binarySymlink.targetBinaryMissing(M,J,K)),Error(_)}await $.ensureDir(I);try{if(await $.exists(U))Z.debug(L.binarySymlink.removingExisting(U)),await $.rm(U,{force:!0})}catch(_){Z.error(L.binarySymlink.removeExistingFailed(U),_);let O=_ instanceof Error?_.message:String(_);throw Error(`Failed to remove old entrypoint ${U}: ${O}`,{cause:_})}try{let _=B0.relative(I,K);if(Z.debug(L.binarySymlink.creating(U,_)),await($ instanceof f?$.withFileType("symlink"):$).symlink(_,U),!(await $.lstat(U)).isSymbolicLink())throw Error("Entrypoint unexpectedly created as regular file instead of symlink")}catch(_){let O=_ instanceof Error?_.message:String(_);throw Z.error(L.binarySymlink.creationFailed(U,K),_),Error(`Failed to create entrypoint at ${U}: ${O}`,{cause:_})}if(!await $.exists(U))throw Z.error(L.binarySymlink.verificationFailed(U)),Error(`Entrypoint creation appeared to succeed but file does not exist at ${U}`);Z.debug(L.binarySymlink.createdAndVerified(U,K))}function e$($,M){let J=(Q,...G)=>{if(typeof Q==="string")return $(Q).env(M);return $(Q,...G).env(M)};if(Object.assign(J,$),s0($))Object.defineProperty(J,tM,{value:!0,enumerable:!1});return J}function q$($,M){return $ instanceof f?$.withToolName(M):$}import QJ from"crypto";import i$ from"path";var T={initialized:($,M,J,Q)=>W(`Cache directory: ${$}, TTL: ${M} ms, Strategy: ${J}, Enabled: ${Q}`),cachingDisabled:($,M)=>W(`Cache disabled, ${$} for key: ${M}`),entryMissing:($)=>W(`No cache entry found for key: ${$}`),entryExpired:($)=>W(`Cache entry expired for key: ${$}`),cacheHit:($,M,J)=>{let Q=J!==void 0?`, size: ${J} bytes`:"";return W(`Cache hit for key: ${$} (${M})${Q}`)},cacheStored:($,M,J,Q)=>{let G=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${G}, expires: ${J}`)},cacheEntryRemoved:($)=>W(`Removed cache entry for key: ${$}`),cacheCleared:()=>W("Removed entire cache directory"),expiredEntriesCleared:($)=>W(`Removed ${$} expired cache entries`),cacheEntryExists:($)=>W(`Valid cache entry exists for key: ${$}`),noEntryToDelete:($)=>W(`No cache entry to delete for key: ${$}`),cacheDirectoryMissing:()=>W("Cache directory does not exist, nothing to clear"),binaryFileMissing:($,M)=>W(`Binary file missing for key: ${$}, path: ${M}`),contentHashMismatch:($,M,J)=>W(`Content hash mismatch for key: ${$}, expected: ${M}, actual: ${J}`),metadataProcessingWarning:($,M)=>W(`Error processing cache file ${$}: ${M}`),retrievalFailed:($,M)=>W(`Error retrieving cache for key: ${$}, error: ${M}`),storageFailed:($,M)=>W(`Error caching data for key: ${$}, error: ${M}`),checkFailed:($,M)=>W(`Error checking cache for key: ${$}, error: ${M}`),deleteFailed:($,M)=>W(`Error deleting cache entry for key: ${$}, error: ${M}`),clearExpiredFailed:($)=>W(`Error clearing expired cache entries: ${$}`),clearFailed:($)=>W(`Error clearing cache: ${$}`),directoryCreationFailed:($)=>W(`Error ensuring cache directories exist: ${$}`),binaryDirectoryNotConfigured:()=>W("Binary directory not configured for binary strategy"),binaryDataRequired:()=>W("Binary storage strategy requires Buffer data")};class $M{config;fileSystem;logger;metadataDir;binariesDir;constructor($,M,J){if(this.logger=$.getSubLogger({name:"FileCache"}),this.fileSystem=M,this.config=J,J.storageStrategy==="json")this.metadataDir=J.cacheDir;else this.metadataDir=i$.join(J.cacheDir,"metadata"),this.binariesDir=i$.join(J.cacheDir,"binaries");this.logger.debug(T.initialized(J.cacheDir,J.defaultTtl,J.storageStrategy,J.enabled))}async get($){let M=this.logger.getSubLogger({name:"get"});if(!this.config.enabled)return M.debug(T.cachingDisabled("returning null",$)),null;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(T.entryMissing($)),null;let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);if(this.isExpired(G))return M.debug(T.entryExpired($)),await this.deleteEntry($,G),null;if(G.type==="json")return M.debug(T.cacheHit($,"JSON")),G.data;else{if(!this.binariesDir)throw Error(T.binaryDirectoryNotConfigured());let Y=i$.join(this.binariesDir,G.binaryFileName);if(!await this.fileSystem.exists(Y))return M.warn(T.binaryFileMissing($,Y)),await this.fileSystem.rm(J).catch(()=>{}),null;let X=await this.fileSystem.readFile(Y),Z=Buffer.isBuffer(X)?X:Buffer.from(X),q=QJ.createHash("sha256").update(Z).digest("hex"),I=G.contentHash;if(q!==I)return M.warn(T.contentHashMismatch($,I,q)),await this.deleteEntry($,G),null;return M.debug(T.cacheHit($,"binary",Z.length)),Z}}catch(J){return M.warn(T.retrievalFailed($,this.getErrorMessage(J))),null}}async set($,M,J){let Q=this.logger.getSubLogger({name:"set"});if(!this.config.enabled){Q.debug(T.cachingDisabled("skipping set",$));return}try{await this.ensureCacheDirectories();let G=J??this.config.defaultTtl,Y=Date.now();if(this.config.storageStrategy==="json"){let X={type:"json",data:M,timestamp:Y,expiresAt:Y+G},Z=this.getMetadataFilePath($);await this.fileSystem.writeFile(Z,JSON.stringify(X,null,2),"utf8"),Q.debug(T.cacheStored($,"JSON",new Date(X.expiresAt).toISOString()))}else{if(!Buffer.isBuffer(M))throw Error(T.binaryDataRequired());if(!this.binariesDir)throw Error(T.binaryDirectoryNotConfigured());let X=M,Z=QJ.createHash("sha256").update(X).digest("hex"),q=`${Z}.bin`,I=i$.join(this.binariesDir,q);await this.fileSystem.writeFile(I,X);let U={type:"binary",binaryFileName:q,contentHash:Z,size:X.length,timestamp:Y,expiresAt:Y+G},K=this.getMetadataFilePath($);await this.fileSystem.writeFile(K,JSON.stringify(U,null,2),"utf8"),Q.debug(T.cacheStored($,"binary",new Date(U.expiresAt).toISOString(),X.length))}}catch(G){let Y=this.getErrorMessage(G);throw Q.warn(T.storageFailed($,Y)),Error(`Failed to cache data: ${Y}`,{cause:G})}}async setDownload($,M,J,Q,G){let Y=this.logger.getSubLogger({name:"setDownload"});if(!this.config.enabled){Y.debug(T.cachingDisabled("skipping setDownload",$));return}try{await this.ensureCacheDirectories();let X=J??this.config.defaultTtl,Z=Date.now();if(this.config.storageStrategy==="json")throw Error("Download caching requires binary storage strategy");if(!this.binariesDir)throw Error(T.binaryDirectoryNotConfigured());let q=QJ.createHash("sha256").update(M).digest("hex"),I=`${q}.bin`,U=i$.join(this.binariesDir,I);await this.fileSystem.writeFile(U,M);let K={type:"binary",binaryFileName:I,contentHash:q,size:M.length,url:Q,contentType:G,timestamp:Z,expiresAt:Z+X},H=this.getMetadataFilePath($);await this.fileSystem.writeFile(H,JSON.stringify(K,null,2),"utf8"),Y.debug(T.cacheStored($,"download",new Date(K.expiresAt).toISOString(),M.length))}catch(X){let Z=this.getErrorMessage(X);throw Y.warn(T.storageFailed($,Z)),Error(`Failed to cache download: ${Z}`,{cause:X})}}async has($){let M=this.logger.getSubLogger({name:"has"});if(!this.config.enabled)return M.debug(T.cachingDisabled("returning false",$)),!1;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(T.entryMissing($)),!1;let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);if(this.isExpired(G))return M.debug(T.entryExpired($)),!1;if(G.type==="binary"&&this.binariesDir){let Y=i$.join(this.binariesDir,G.binaryFileName);if(!await this.fileSystem.exists(Y))return M.debug(T.binaryFileMissing($,Y)),!1}return M.debug(T.cacheEntryExists($)),!0}catch(J){return M.warn(T.checkFailed($,this.getErrorMessage(J))),!1}}async delete($){let M=this.logger.getSubLogger({name:"delete"});if(!this.config.enabled){M.debug(T.cachingDisabled("skipping delete",$));return}try{let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J)){let Q=await this.fileSystem.readFile(J,"utf8"),G=JSON.parse(Q);await this.deleteEntry($,G),M.debug(T.cacheEntryRemoved($))}else M.debug(T.noEntryToDelete($))}catch(J){let Q=this.getErrorMessage(J);throw M.warn(T.deleteFailed($,Q)),Error(`Failed to delete cache entry: ${Q}`,{cause:J})}}async clearExpired(){let $=this.logger.getSubLogger({name:"clearExpired"});if(!this.config.enabled){$.debug(T.cachingDisabled("skipping clearExpired","N/A"));return}try{if(!await this.fileSystem.exists(this.metadataDir)){$.debug(T.cacheDirectoryMissing());return}let M=await this.fileSystem.readdir(this.metadataDir),J=0;for(let Q of M){if(!Q.endsWith(".json"))continue;let G=i$.join(this.metadataDir,Q);try{let Y=await this.fileSystem.readFile(G,"utf8"),X=JSON.parse(Y);if(this.isExpired(X)){let Z=i$.basename(Q,".json");await this.deleteEntry(Z,X),J++}}catch(Y){$.warn(T.metadataProcessingWarning(Q,this.getErrorMessage(Y))),await this.fileSystem.rm(G).catch(()=>{}),J++}}$.debug(T.expiredEntriesCleared(J))}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.clearExpiredFailed(J)),Error(`Failed to clear expired cache entries: ${J}`,{cause:M})}}async clear(){let $=this.logger.getSubLogger({name:"clear"});if(!this.config.enabled){$.debug(T.cachingDisabled("skipping clear","N/A"));return}try{if(await this.fileSystem.exists(this.config.cacheDir))await this.fileSystem.rm(this.config.cacheDir,{recursive:!0,force:!0}),$.debug(T.cacheCleared());else $.debug(T.cacheDirectoryMissing());await this.ensureCacheDirectories()}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.clearFailed(J)),Error(`Failed to clear cache: ${J}`,{cause:M})}}getMetadataFilePath($){let M=QJ.createHash("md5").update($).digest("hex");return i$.join(this.metadataDir,`${M}.json`)}async ensureCacheDirectories(){let $=this.logger.getSubLogger({name:"ensureCacheDirectories"});try{if(await this.fileSystem.ensureDir(this.metadataDir),this.binariesDir)await this.fileSystem.ensureDir(this.binariesDir)}catch(M){let J=this.getErrorMessage(M);throw $.warn(T.directoryCreationFailed(J)),Error(`Failed to create cache directories: ${J}`,{cause:M})}}getErrorMessage($){if($ instanceof Error)return $.message;return String($)}isExpired($){return Date.now()>$.expiresAt}async deleteEntry($,M){let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J))await this.fileSystem.rm(J);if(M.type==="binary"&&this.binariesDir){let Q=i$.join(this.binariesDir,M.binaryFileName);if(await this.fileSystem.exists(Q))await this.fileSystem.rm(Q)}}}import JX from"crypto";function k6($,M={}){let J={headers:M.headers||{}},Q={url:$,options:J};return`download:${JX.createHash("sha256").update(JSON.stringify(Q)).digest("hex")}`}import QX from"path";var D0={strategyCreated:($,M)=>W(`Created ${$}${M}`),downloadStarted:($)=>W(`Downloading URL: ${$}`),downloadToFileStarted:($,M)=>W(`Downloading URL ${$} to file: ${M}`)};var B$={strategyWrapped:($,M)=>W(`Wrapping strategy ${$} with cache, TTL: ${M} ms`),cachingDisabled:($,M,J)=>W(`Cache disabled, ${$} for key: ${M} (${J})`),cacheHit:($,M,J)=>{let Q=J!==void 0?`, size: ${J} bytes`:"";return W(`Cache hit for key: ${$} (${M})${Q}`)},cacheStored:($,M,J,Q)=>{let G=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${G}, expires: ${J}`)},cacheStorageFailed:($)=>W(`Error caching data for key: ${$}`),cacheCheckFailed:($)=>W(`Error checking cache for key: ${$}`),cacheMiss:($)=>W(`No cache entry found for key: ${$}`),cacheDisabledForProgress:($)=>W(`Cache disabled, caching for key: ${$} (reason: progress callback)`),readFileForCaching:($)=>W(`read file for caching: ${$}`),downloadedFileExists:($,M)=>W(`Downloaded file exists (${$}): ${M}`),downloadedFileCached:($,M)=>W(`Successfully read file for caching from ${$}, size: ${M} bytes`),downloadedFileMissing:($)=>W(`Downloaded file not found: ${$}`),downloadedFileReadFailed:($)=>W(`Failed to read ${$}`),downloadFromStrategy:($)=>W(`download from ${$}`),cachedFileWritten:($)=>W(`[CachedDownloadStrategy] write ${$}`)},k$={constructed:($)=>W(`NodeFetchStrategy constructed (fileSystem ${$})`),downloadTimeout:($)=>W(`Download timeout for ${$}`),responseBodyReadFailed:($,M)=>W(`Failed to read response body for ${$}: ${String(M)}`),downloadFailed:($,M,J,Q)=>W(`Download failed: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${Q??"N/A"}`),downloadAttempt:($,M)=>W(`Attempt ${$}: Downloading ${M}`),downloadSuccessful:($,M)=>W(`Download successful for ${$}, size: ${M} bytes`),savingToDestination:($)=>W(`Saving to destination: ${$}`),savedSuccessfully:($)=>W(`Successfully wrote to ${$} using IFileSystem`),downloadAttemptError:($,M,J)=>W(`Error during download attempt ${$} for ${M}: ${String(J)}`),retryingDownload:($,M,J,Q)=>W(`Retrying download for ${$}, attempt ${M}/${J} after ${Q}ms`),exhaustedRetries:($)=>W(`Exhausted retries for ${$}`)},MM={errorCreated:($,M,J)=>W(`${$} created: message=${M}, url=${J}`),networkErrorCreated:($,M,J)=>W(`NetworkError created: message=${$}, url=${M}, originalError=${String(J)}`),httpErrorCreated:($,M,J,Q,G,Y)=>W(`HttpError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(Y??{})}`),notFoundErrorCreated:($,M,J)=>W(`NotFoundError created: url=${$}, responseBody=${String(M)}, responseHeaders=${JSON.stringify(J??{})}`),forbiddenErrorCreated:($,M,J)=>W(`ForbiddenError created: url=${$}, responseBody=${String(M)}, responseHeaders=${JSON.stringify(J??{})}`),rateLimitErrorCreated:($,M,J,Q,G,Y,X)=>W(`RateLimitError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(G)}, responseHeaders=${JSON.stringify(Y??{})}, resetTimestamp=${String(X)}`),clientErrorCreated:($,M,J,Q,G)=>W(`ClientError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(G??{})}`),serverErrorCreated:($,M,J,Q,G)=>W(`ServerError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(G??{})}`)};class zQ{name;cache;underlyingStrategy;logger;cacheTtl;fileSystem;constructor($,M,J,Q,G=86400000){this.logger=$.getSubLogger({name:"CachedDownloadStrategy"}),this.fileSystem=M,this.cache=J,this.underlyingStrategy=Q,this.cacheTtl=G,this.name=`cached-${Q.name}`,this.logger.debug(B$.strategyWrapped(Q.name,G))}async isAvailable(){return await this.underlyingStrategy.isAvailable()}async handleCacheHit($,M,J,Q,G){if($.trace(B$.cacheHit(J,"binary",M.length),{url:Q}),G.onProgress)G.onProgress(0,M.length);if(G.destinationPath){if(await this.fileSystem.ensureDir(QX.dirname(G.destinationPath)),await this.fileSystem.writeFile(G.destinationPath,M),$.trace(B$.cachedFileWritten(G.destinationPath)),G.onProgress)G.onProgress(M.length,M.length);return}if(G.onProgress)G.onProgress(M.length,M.length);return M}async readFileForCaching($,M){$.trace(B$.readFileForCaching(M));try{let J=await this.fileSystem.exists(M);if($.trace(B$.downloadedFileExists(M,J)),J){let Q=await this.fileSystem.readFileBuffer(M);return $.trace(B$.downloadedFileCached(M,Q.length),{path:M,size:Q.length}),Q}else return $.trace(B$.downloadedFileMissing(M)),null}catch(J){return $.trace(B$.downloadedFileReadFailed(M),J),null}}async determineBufferToCache($,M,J){if(M instanceof Buffer)return M;else if(J.destinationPath&&M===void 0)return await this.readFileForCaching($,J.destinationPath);return null}async cacheResult($,M,J,Q,G){try{await this.cache.setDownload(J,M,this.cacheTtl,Q,this.extractContentTypeFromHeaders(G.headers)),$.trace(B$.cacheStored(J,"binary","TTL-based",M.length),{url:Q})}catch(Y){$.trace(B$.cacheStorageFailed(J),Y)}}async download($,M={}){let J=this.logger.getSubLogger({name:"download"}),Q=k6($,M);try{let X=await this.cache.get(Q);if(X)return await this.handleCacheHit(J,X,Q,$,M);J.trace(B$.cacheMiss(Q),{url:$})}catch(X){J.trace(B$.cacheCheckFailed(Q),X)}J.trace(B$.downloadFromStrategy(this.underlyingStrategy.name),{url:$});let G=await this.underlyingStrategy.download($,M),Y=await this.determineBufferToCache(J,G,M);if(Y)await this.cacheResult(J,Y,Q,$,M);return G}extractContentTypeFromHeaders($){if(!$)return;return $.Accept||$.accept}}class BQ extends Error{url;constructor($,M,J){super(M);let Q=$.getSubLogger({name:"DownloaderError"});this.name="DownloaderError",this.url=J,Q.debug(MM.errorCreated("DownloaderError",M,J))}}class I$ extends BQ{originalError;constructor($,M,J,Q){super($,M,J);let G=$.getSubLogger({name:"NetworkError"});this.name="NetworkError",this.originalError=Q,G.debug(MM.networkErrorCreated(M,J,Q),Q)}}class E$ extends BQ{statusCode;statusText;responseBody;responseHeaders;constructor($,M,J,Q,G,Y,X){super($,M,J);let Z=$.getSubLogger({name:"HttpError"});this.name="HttpError",this.statusCode=Q,this.statusText=G,this.responseBody=Y,this.responseHeaders=X,Z.debug(MM.httpErrorCreated(M,J,Q,G,Y,X),{url:J,statusCode:Q,statusText:G,responseBody:Y,responseHeaders:X})}}class S$ extends E${constructor($,M,J,Q){super($,"Resource not found",M,404,"Not Found",J,Q);let G=$.getSubLogger({name:"NotFoundError"});this.name="NotFoundError",G.debug(MM.notFoundErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class bM extends E${constructor($,M,J,Q){super($,"Access forbidden",M,403,"Forbidden",J,Q);let G=$.getSubLogger({name:"ForbiddenError"});this.name="ForbiddenError",G.debug(MM.forbiddenErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class zM extends E${resetTimestamp;constructor($,M,J,Q,G,Y,X,Z){super($,M,J,Q,G,Y,X);let q=$.getSubLogger({name:"RateLimitError"});this.name="RateLimitError",this.resetTimestamp=Z,q.debug(MM.rateLimitErrorCreated(M,J,Q,G,Y,X,Z),{url:J,statusCode:Q,statusText:G,responseBody:Y,responseHeaders:X,resetTimestamp:Z})}}class vM extends E${constructor($,M,J,Q,G,Y){super($,`Client error: ${Q}`,M,J,Q,G,Y);let X=$.getSubLogger({name:"ClientError"});this.name="ClientError",X.debug(MM.clientErrorCreated(M,J,Q,G,Y),{url:M,statusCode:J,statusText:Q,responseBody:G,responseHeaders:Y})}}class NM extends E${constructor($,M,J,Q,G,Y){super($,`Server error: ${Q}`,M,J,Q,G,Y);let X=$.getSubLogger({name:"ServerError"});this.name="ServerError",X.debug(MM.serverErrorCreated(M,J,Q,G,Y),{url:M,statusCode:J,statusText:Q,responseBody:G,responseHeaders:Y})}}class DQ{name="node-fetch";logger;fileSystem;proxyConfig;constructor($,M,J){this.logger=$.getSubLogger({name:"NodeFetchStrategy"}),this.logger.debug(k$.constructed(M?"provided":"undefined")),this.fileSystem=M,this.proxyConfig=J}async isAvailable(){return typeof fetch==="function"}getResponseHeaders($){let M={};return $.forEach((J,Q)=>{M[Q]=J}),M}parseRateLimitReset($){let M=$.get("X-RateLimit-Reset");if(M){let Q=parseInt(M,10);if(!Number.isNaN(Q))return Q*1000}let J=$.get("Retry-After");if(J){let Q=parseInt(J,10);if(!Number.isNaN(Q))return Date.now()+Q*1000;let G=Date.parse(J);if(!Number.isNaN(G))return G}return}async setupDownloadRequest($,M,J){let Q=new AbortController,G;if(J)G=setTimeout(()=>{this.logger.debug(k$.downloadTimeout($)),Q.abort()},J);return{response:await aG($,{headers:M,signal:Q.signal},this.proxyConfig),timeoutId:G}}async handleErrorResponse($,M){let J;try{J=await $.text()}catch(Z){this.logger.debug(k$.responseBodyReadFailed(M,Z))}let Q=this.getResponseHeaders($.headers),G=$.status,Y=$.statusText;if(this.logger.debug(k$.downloadFailed(M,G,Y,J?.substring(0,100))),G===404)throw new S$(this.logger,M,J,Q);let X=this.parseRateLimitReset($.headers);if(G===403){if(X)throw new zM(this.logger,"Forbidden: Rate limit likely exceeded",M,G,Y,J,Q,X);throw new bM(this.logger,M,J,Q)}if(G===429)throw new zM(this.logger,"Too Many Requests",M,G,Y,J,Q,X);if(G>=400&&G<500)throw new vM(this.logger,M,G,Y,J,Q);if(G>=500&&G<600)throw new NM(this.logger,M,G,Y,J,Q);throw new E$(this.logger,`HTTP error ${G}`,M,G,Y,J,Q)}async processResponseStream($,M,J){let Q=$.headers.get("content-length"),G=null;if(Q){let q=parseInt(Q,10);if(!Number.isNaN(q))G=q}let Y=0;if(J)J(Y,G);let X=[],Z=$.body?.getReader();if(!Z)throw new I$(this.logger,"Response body is not readable.",M);while(!0){let{done:q,value:I}=await Z.read();if(q)break;if(I){if(X.push(Buffer.from(I)),Y+=I.length,J)J(Y,G)}}return Buffer.concat(X)}async handleDownloadAttempt($,M,J){let{headers:Q,timeout:G,onProgress:Y,destinationPath:X}=M;this.logger.debug(k$.downloadAttempt(J+1,$));let{response:Z,timeoutId:q}=await this.setupDownloadRequest($,Q,G);if(q)clearTimeout(q);if(!Z.ok)await this.handleErrorResponse(Z,$);let I=await this.processResponseStream(Z,$,Y);if(this.logger.debug(k$.downloadSuccessful($,I.length)),X){this.logger.debug(k$.savingToDestination(X)),await this.fileSystem.writeFile(X,I),this.logger.debug(k$.savedSuccessfully(X));return}else return I}handleDownloadError($,M,J,Q,G){if(this.logger.debug(k$.downloadAttemptError(J+1,M,$)),J>=Q){if($ instanceof E$||$ instanceof I$)throw $;let Y=`Failed to download ${M}`;if($ instanceof Error&&$.name==="AbortError")Y=`Download timed out for ${M}`;else if($ instanceof Error)Y=$.message;throw new I$(this.logger,Y,M,$ instanceof Error?$:void 0)}}async retryDownload($,M,J,Q,G){this.logger.debug(k$.retryingDownload($,M+2,J+1,Q)),await new Promise((Y)=>setTimeout(Y,Q))}async download($,M){let{retryCount:J=0,retryDelay:Q=1000,onProgress:G}=M,Y=0;while(Y<=J)try{return await this.handleDownloadAttempt($,M,Y)}catch(X){if(this.handleDownloadError(X,$,Y,J,G),Y<J)await this.retryDownload($,Y,J,Q,G),Y++}throw this.logger.debug(k$.exhaustedRetries($)),new I$(this.logger,`Download failed for ${$} after ${J} retries.`,$)}}class AQ{strategies=[];fs;logger;constructor($,M,J,Q,G){if(this.logger=$.getSubLogger({name:"Downloader"}),this.fs=M,typeof J<"u")this.strategies=J;else{let Y=new DQ(this.logger,this.fs,G),X=G?.enabled?` (proxy port ${G.port})`:"";if(Q)this.logger.debug(D0.strategyCreated("CachedDownloadStrategy",` wrapping NodeFetchStrategy${X}`)),this.strategies.push(new zQ(this.logger,this.fs,Q,Y));else this.logger.debug(D0.strategyCreated("NodeFetchStrategy",X||" (no cache)")),this.strategies.push(Y)}}registerStrategy($){this.strategies.unshift($)}async tryDownloadWithStrategy($,M,J){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};return{success:!0,buffer:await $.download(M,J)}}async download($,M,J={}){if($.getSubLogger({name:"Downloader"}).getSubLogger({name:"download"}).debug(D0.downloadStarted(M)),this.strategies.length===0)throw Error("No download strategies registered.");let G;for(let Y of this.strategies)try{let X=await this.tryDownloadWithStrategy(Y,M,J);if(X.success)return X.buffer}catch(X){G=this.normalizeError(X)}if(G)throw G;throw Error(`No available download strategy succeeded for ${M}.`)}async tryDownloadToFileWithStrategy($,M,J){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};if(await $.download(M,J)===void 0)return{success:!0};throw Error("Strategy returned Buffer instead of void for downloadToFile method")}normalizeError($){if($ instanceof Error)return $;else if(typeof $==="string")return Error($);else return Error(`An unknown error occurred during download: ${JSON.stringify($)}`)}async downloadToFile($,M,J,Q={}){$.getSubLogger({name:"Downloader"}).getSubLogger({name:"downloadToFile"}).debug(D0.downloadToFileStarted(M,J));let Y={...Q,destinationPath:J};if(this.strategies.length===0)throw Error("No download strategies registered.");let X;for(let Z of this.strategies)try{if((await this.tryDownloadToFileWithStrategy(Z,M,Y)).success)return}catch(q){X=this.normalizeError(q)}if(X)throw X;throw Error(`No available download strategy succeeded for ${M}.`)}}import*as oM from"cli-progress";class EQ{filename;progressBar=null;enabled;startTime=0;constructor($,M={}){this.filename=$;this.enabled=M.enabled??!0}createCallback(){if(!this.enabled)return;return($,M)=>{if(this.startTime===0)if(this.startTime=Date.now(),M)this.progressBar=new oM.SingleBar({format:`Downloading ${this.filename} |{bar}| {percentage}% | {value}/{total} | {speed} | ETA: {eta_formatted}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},oM.Presets.shades_classic),this.progressBar.start(M,0,{speed:"0 B/s"});else this.progressBar=new oM.SingleBar({format:`Downloading ${this.filename} |{bar}| {value} | {speed}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},oM.Presets.shades_classic),this.progressBar.start(100,0,{speed:"0 B/s"});if(this.progressBar){let J=(Date.now()-this.startTime)/1000,Q=J>0?`${this.formatBytes($/J)}/s`:"0 B/s";if(M){if(this.progressBar.update($,{speed:Q}),$>=M)this.progressBar.stop()}else{let G=Math.floor(Date.now()/100)%100;this.progressBar.update(G,{speed:Q,value:this.formatBytes($)})}}}}clear(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}finish(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}formatBytes($){let M=["B","KB","MB","GB"],J=$,Q=0;while(J>=1024&&Q<M.length-1)J/=1024,Q++;return`${J.toFixed(J>=10?0:1)} ${M[Q]}`}}function S6($=!1){if($)return!1;if(!process.stderr.isTTY)return!1;if(process.env.CI==="true"||process.env.CI==="1")return!1;if(process.env.NO_COLOR)return!1;return!0}async function U$($,M,J,Q,G,Y){let X=S6(Y?.quiet),Z=new EQ(Q,{enabled:X});try{await G.download($,M,{destinationPath:J,onProgress:Z.createCallback()})}finally{Z.finish()}}function w6($){return $.installParams?.hooks}async function w$($,M,J,Q,G){let X=w6($)?.["after-download"];if(!X)return{success:!0};G.debug(L.lifecycle.hookExecution("after-download"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(G,"after-download",q,Z);if(!I.success)return{success:!1,error:`afterDownload hook failed: ${I.error}`}}return{success:!0}}async function eM($,M,J,Q,G){let X=w6($)?.["after-extract"];if(!X)return{success:!0};G.debug(L.lifecycle.hookExecution("after-extract"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(G,"after-extract",q,Z);if(!I.success)return{success:!1,error:`afterExtract hook failed: ${I.error}`}}return{success:!0}}function GX($){return typeof $==="object"&&$!==null}function YX($){if(!GX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function b6($){if(typeof $==="string")return $.trim();if($ instanceof Uint8Array)return Buffer.from($).toString("utf8").trim();return""}function v6($){if(YX($)){let M=b6($.stderr);if(M.length>0)return M;let J=b6($.stdout);if(J.length>0)return J;if($.message)return $.message;return`exit code ${$.exitCode??"unknown"}`}if($ instanceof Error)return $.message;return String($)}function l$($){if(!$||$.length===0)return[];return $.map((M)=>typeof M==="string"?{name:M,pattern:`{,*/}${M}`}:M)}function GJ($){return l$($).map((J)=>J.name)}import{join as XX}from"path";function e($,M){return l$($).map((Q)=>XX(M,Q.name))}import u6 from"path";import{codeFrameColumns as ZX}from"@babel/code-frame";function WX($){return typeof $==="object"&&$!==null}function P6($){if(!WX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function qX($){return $.isTracingEnabled()}function IX($){return $.endsWith(`
|
|
58
|
+
`),$.debug(l.schemaInitialized())}}var V0=Symbol("resolvedFileSystemBrand");import{Volume as e7}from"memfs";class $J{vol;constructor($){if(this.vol=new e7,$)this.vol.fromJSON($)}async readFile($,M="utf8"){return(await this.vol.promises.readFile($,{encoding:M})).toString()}async readFileBuffer($){let M=await this.vol.promises.readFile($);return Buffer.from(M)}async writeFile($,M,J="utf8"){let Q=typeof M==="string"?M:Buffer.isBuffer(M)?M:Buffer.from(M.buffer,M.byteOffset,M.byteLength);await this.vol.promises.writeFile($,Q,{encoding:J})}async exists($){try{return await this.vol.promises.stat($),!0}catch{return!1}}async mkdir($,M){await this.vol.promises.mkdir($,M)}async readdir($){return(await this.vol.promises.readdir($)).map((J)=>J.toString())}async rm($,M){try{if((await this.vol.promises.lstat($)).isSymbolicLink()){await this.vol.promises.unlink($);return}}catch(J){let Q=J;if(M?.force&&Q?.code==="ENOENT")return}try{await this.vol.promises.rm($,M)}catch(J){let Q=J;if(M?.force&&Q?.code==="ENOENT")return;throw J}}async rmdir($,M){await this.vol.promises.rmdir($,M)}async stat($){return await this.vol.promises.stat($)}async lstat($){return await this.vol.promises.lstat($)}async symlink($,M,J){await this.vol.promises.symlink($,M,J)}async readlink($){return(await this.vol.promises.readlink($)).toString()}async chmod($,M){await this.vol.promises.chmod($,typeof M==="string"?parseInt(M,8):M)}async copyFile($,M,J){await this.vol.promises.copyFile($,M,J)}async rename($,M){await this.vol.promises.rename($,M)}async ensureDir($){await this.vol.promises.mkdir($,{recursive:!0})}getVolume(){return this.vol}}import{constants as $X,promises as MX}from"fs";class z${fs;constants;constructor($=MX,M=$X){this.fs=$,this.constants=M}async readFile($,M="utf8"){return this.fs.readFile($,{encoding:M})}async readFileBuffer($){return this.fs.readFile($)}async writeFile($,M,J="utf8"){return this.fs.writeFile($,M,{encoding:J})}async exists($){try{return await this.fs.access($,this.constants.F_OK),!0}catch{return!1}}async mkdir($,M){await this.fs.mkdir($,M)}async readdir($){return this.fs.readdir($)}async rm($,M){return this.fs.rm($,M)}async rmdir($,M){if(M?.recursive)return this.fs.rm($,{recursive:!0,force:!0});return this.fs.rmdir($)}async stat($){return this.fs.stat($)}async lstat($){return this.fs.lstat($)}async symlink($,M,J){return this.fs.symlink($,M,J)}async readlink($){return this.fs.readlink($)}async chmod($,M){return this.fs.chmod($,M)}async copyFile($,M,J){return this.fs.copyFile($,M,J)}async rename($,M){return this.fs.rename($,M)}async ensureDir($){await this.fs.mkdir($,{recursive:!0})}}class MJ{[V0];inner;homeDir;constructor($,M){this.inner=$,this.homeDir=M,this[V0]=!0}async readFile($,M){return this.inner.readFile(n(this.homeDir,$),M)}async readFileBuffer($){return this.inner.readFileBuffer(n(this.homeDir,$))}async writeFile($,M,J){await this.inner.writeFile(n(this.homeDir,$),M,J)}async exists($){return this.inner.exists(n(this.homeDir,$))}async mkdir($,M){await this.inner.mkdir(n(this.homeDir,$),M)}async readdir($){return this.inner.readdir(n(this.homeDir,$))}async rm($,M){await this.inner.rm(n(this.homeDir,$),M)}async rmdir($,M){await this.inner.rmdir(n(this.homeDir,$),M)}async stat($){return this.inner.stat(n(this.homeDir,$))}async lstat($){return this.inner.lstat(n(this.homeDir,$))}async symlink($,M,J){await this.inner.symlink(n(this.homeDir,$),n(this.homeDir,M),J)}async readlink($){return this.inner.readlink(n(this.homeDir,$))}async chmod($,M){await this.inner.chmod(n(this.homeDir,$),M)}async copyFile($,M,J){await this.inner.copyFile(n(this.homeDir,$),n(this.homeDir,M),J)}async rename($,M){await this.inner.rename(n(this.homeDir,$),n(this.homeDir,M))}async ensureDir($){await this.inner.ensureDir(n(this.homeDir,$))}}import{randomUUID as JX}from"crypto";import z0 from"path";class f{[V0]=!0;fs;registry;logger;parentLogger;context;projectConfig;suppressLogging=!1;constructor($,M,J,Q,Y){this.parentLogger=$,this.logger=$.getSubLogger({name:"TrackedFileSystem",context:Q.toolName}),this.fs=M,this.registry=J,this.context=Q,this.projectConfig=Y}static createContext($,M,J){return{toolName:$,fileType:M,operationId:JX(),metadata:J}}withContext($){let M={...this.context,...$},J=new f(this.parentLogger,this.fs,this.registry,M,this.projectConfig);return J.setSuppressLogging(this.suppressLogging),J}setSuppressLogging($){this.suppressLogging=$}logInfo($){if(!this.suppressLogging)this.logger.info($)}withToolName($){return this.withContext({toolName:$})}withFileType($){return this.withContext({fileType:$})}async readFile($,M){return this.fs.readFile($,M)}async readFileBuffer($){return this.fs.readFileBuffer($)}async writeFile($,M,J){let Q=await this.fs.exists($),Y=!0;if(Q)try{let X=await this.fs.readFile($,J||"utf8"),Z=typeof M==="string"?M:M.toString();Y=X!==Z}catch{Y=!0}if(!Y)return;await this.fs.writeFile($,M,J);let G=await this.getFileStats($);if(await this.recordOperation("writeFile",$,{sizeBytes:G?.sizeBytes,permissions:G?.permissions}),!Q)this.logInfo(l.fileCreated(s(this.projectConfig.paths.homeDir,$)));else this.logInfo(l.fileUpdated(s(this.projectConfig.paths.homeDir,$)))}async copyFile($,M,J){await this.fs.copyFile($,M,J);let Q=await this.getFileStats(M);await this.recordOperation("cp",M,{targetPath:$,sizeBytes:Q?.sizeBytes,permissions:Q?.permissions}),this.logInfo(l.fileCopied(s(this.projectConfig.paths.homeDir,$),s(this.projectConfig.paths.homeDir,M)))}async rename($,M){await this.fs.rename($,M);let J=await this.getFileStats(M);await this.recordOperation("rename",M,{targetPath:$,sizeBytes:J?.sizeBytes,permissions:J?.permissions}),this.logInfo(l.fileMoved(s(this.projectConfig.paths.homeDir,$),s(this.projectConfig.paths.homeDir,M)))}async symlink($,M,J){await this.fs.symlink($,M,J),await this.recordOperation("symlink",M,{targetPath:$}),this.logInfo(l.symlinkCreated(s(this.projectConfig.paths.homeDir,M),s(this.projectConfig.paths.homeDir,$)))}async recordExistingSymlink($,M){let J=z0.resolve(M),Q=z0.resolve($),Y=await this.registry.getFileState(J);if(Y&&Y.targetPath===Q)return;await this.recordOperation("symlink",M,{targetPath:$})}async rm($,M){if(M?.recursive&&await this.fs.exists($))if((await this.fs.stat($)).isDirectory())await this.trackDirectoryDeletion($);else await this.trackFileDeletion($);else if(await this.fs.exists($))await this.trackFileDeletion($);await this.fs.rm($,M),this.logInfo(l.fileRemoved(s(this.projectConfig.paths.homeDir,$)))}async chmod($,M){await this.fs.chmod($,M);let J=await this.getFileStats($);await this.recordOperation("chmod",$,{permissions:J?.permissions}),this.logInfo(l.permissionsChanged(s(this.projectConfig.paths.homeDir,$),H0(M)))}async exists($){return this.fs.exists($)}async stat($){return this.fs.stat($)}async lstat($){return this.fs.lstat($)}async readlink($){return this.fs.readlink($)}async readdir($){return this.fs.readdir($)}async mkdir($,M){let J=await this.fs.exists($);if(await this.fs.mkdir($,M),!J)await this.recordOperation("mkdir",$),this.logInfo(l.directoryCreated(s(this.projectConfig.paths.homeDir,$)))}async rmdir($,M){let J=this.logger.getSubLogger({name:"rmdir"});if(await this.fs.exists($))if(M?.recursive)await this.trackDirectoryDeletion($);else await this.trackFileDeletion($);await this.fs.rmdir($,M),J.debug(l.rmdirTracked(),$)}async ensureDir($){let M=await this.fs.exists($);if(await this.fs.ensureDir($),!M)await this.recordOperation("mkdir",$),this.logInfo(l.directoryCreated(s(this.projectConfig.paths.homeDir,$)))}async getFileStats($){try{let M=await this.fs.stat($);return{sizeBytes:M.size,permissions:M.mode&511}}catch{return null}}async recordOperation($,M,J){await this.registry.recordOperation({toolName:this.context.toolName,operationType:$,filePath:z0.resolve(M),fileType:this.context.fileType,operationId:this.context.operationId,metadata:this.context.metadata,targetPath:J?.targetPath?z0.resolve(J.targetPath):void 0,sizeBytes:J?.sizeBytes,permissions:J?.permissions})}async trackFileDeletion($){await this.recordOperation("rm",$)}async trackDirectoryDeletion($){try{let M=await this.fs.readdir($);for(let J of M){let Q=z0.join($,J);if((await this.fs.stat(Q)).isDirectory())await this.trackDirectoryDeletion(Q);else await this.trackFileDeletion(Q)}await this.trackFileDeletion($)}catch(M){this.logger.debug(l.directoryDeletionError(),$,M instanceof Error?M.message:String(M))}}}import B0 from"path";var L={binarySetupService:{binaryNotFound:($,M)=>W(`Binary ${$} not found at ${M}, skipping`),extractedFilesTree:($,M)=>W(`Extracted files in ${$}:
|
|
59
|
+
${M}`),cleaningFailedInstall:($)=>W(`No binaries found, cleaning up installation directory: ${$}`),fallbackCleanup:($)=>W(`Directory still exists after rm(), trying rmdir: ${$}`),searchingWithPattern:($,M)=>W(`Searching for binary using pattern ${$} in directory ${M}`),fallbackPattern:($,M)=>W(`Trying fallback binary pattern ${$} in directory ${M}`),patternPathMissing:($)=>W(`Pattern path does not exist: ${$}`),noPatternMatch:($,M)=>W(`No matches found for pattern ${$} in directory ${M}`),directDownloadSingleBinary:($,M)=>W(`Direct download only provides one binary, but ${$} were configured. Only ${M} will be available.`),patternDebug:($,M,J)=>W(`Pattern: ${$}, Parts: [${M.join(", ")}], ExtractDir: ${J}`),processingPart:($,M)=>W(`Processing part: "${$}", currentDir: ${M}`),wildcardMatchResult:($)=>W(`Wildcard match result: ${$??"null"}`),directPath:($)=>W(`Direct path: ${$}`),finalResult:($)=>W(`Final result: ${$}`)},binarySymlink:{targetBinaryMissing:($,M,J)=>W(`Cannot create entrypoint for ${$}/${M}: target binary missing at ${J}`),removingExisting:($)=>W(`Removing old entrypoint: ${$}`),removeExistingFailed:($)=>W(`Failed to remove old entrypoint ${$}`),creating:($,M)=>W(`Creating entrypoint: ${$} <- ${M}`),creationFailed:($,M)=>W(`Failed to create entrypoint ${$} <- ${M}`),verificationMismatch:($,M,J)=>W(`Entrypoint ${$} is ${J}, expected ${M}`),verificationFailed:($)=>W(`Failed to verify entrypoint ${$}`),createdAndVerified:($,M)=>W(`Successfully created and verified entrypoint: ${$} <- ${M}`)},lifecycle:{startingInstallation:($)=>W(`Starting installation for ${$}`),hookExecution:($)=>W(`install: Running ${$} hook`),directoryCreated:($)=>W(`install: Created installation directory: ${$}`),directoryRenamed:($,M)=>W(`install: Renamed installation directory from ${$} to ${M}`),cleaningFailedInstallDir:($)=>W(`install: Cleaning up failed installation directory: ${$}`),versionResolved:($)=>W(`install: Resolved version: ${$}`),versionFallbackToTimestamp:()=>W("install: Version resolution returned null, using timestamp"),versionResolutionFailed:($)=>W(`install: Version resolution failed, using timestamp: ${String($)}`),externalBinaryMissing:($,M,J)=>W(`Cannot create symlink for ${$}/${M}: external binary missing at ${J}`),removingExistingSymlink:($)=>W(`Removing existing symlink: ${$}`),creatingExternalSymlink:($,M)=>W(`Creating external symlink: ${$} -> ${M}`),symlinkVerificationFailed:($)=>W(`Symlink verification failed: ${$}`),externalSymlinkCreated:($,M)=>W(`External symlink created: ${$} -> ${M}`)},outcome:{installSuccess:($,M,J)=>W(`Tool "${$}" \`${M}\` installed successfully using ${J}`),outdatedVersion:($,M,J)=>W(`Tool "${$}" version ${M} is outdated (latest: ${J})`),installFailed:($)=>W(`Installation failed via ${$}`),hookFailed:($)=>W(`Hook failed: ${$}`),unsupportedOperation:($,M)=>W(`${$} not yet supported (${M})`)},archive:{extracting:($)=>W(`Extracting archive: ${$}`),extracted:()=>W("Archive extracted: %o"),cleaning:($)=>W(`Cleaning up downloaded archive: ${$}`)},binaryMovement:{moving:($,M)=>W(`Moving binary from ${$} to ${M}`)},completion:{noCompletionsConfigured:()=>W("install: no completions configured"),generatingCompletions:($)=>W(`install: generating ${$} completion files`),generatedCompletion:($,M)=>W(`install: generated completion: ${$} -> ${M}`),symlinking:($,M,J)=>W(`Symlinking completion for ${$} from ${M} to ${J}`),notFound:($)=>W(`Completion file not found: ${$}`),directoryListing:($)=>W(` ${$}`),preparedFromUrl:($,M)=>W(`install: prepared ${$} completion source at ${M}`),prepareFailed:($)=>W(`install: failed to prepare ${$} completion`)},hookExecutor:{executingHook:($,M)=>W(`Executing ${$} hook with ${M}ms timeout`),hookCompleted:($,M)=>W(`Hook ${$} completed successfully in ${M}ms`),continuingDespiteFailure:($)=>W(`Continuing installation despite ${$} hook failure`),stoppingDueToFailure:($)=>W(`Stopping hook execution due to failure in ${$} hook`),timeoutExceeded:($,M)=>W(`Hook ${$} timed out after ${M}ms`)}};async function JJ($,M,J,Q,Y,G,X){let Z=X.getSubLogger({name:"createBinaryEntrypoint"}),q=B0.join(G,M),I=B0.join(q,Q),U=B0.join(I,J),K=B0.join(I,Y);if(K===U)return;if(!await $.exists(K)){let _=`Cannot create entrypoint: target binary does not exist at ${K}`;throw Z.error(L.binarySymlink.targetBinaryMissing(M,J,K)),Error(_)}await $.ensureDir(I);try{if(await $.exists(U))Z.debug(L.binarySymlink.removingExisting(U)),await $.rm(U,{force:!0})}catch(_){Z.error(L.binarySymlink.removeExistingFailed(U),_);let O=_ instanceof Error?_.message:String(_);throw Error(`Failed to remove old entrypoint ${U}: ${O}`,{cause:_})}try{let _=B0.relative(I,K);if(Z.debug(L.binarySymlink.creating(U,_)),await($ instanceof f?$.withFileType("symlink"):$).symlink(_,U),!(await $.lstat(U)).isSymbolicLink())throw Error("Entrypoint unexpectedly created as regular file instead of symlink")}catch(_){let O=_ instanceof Error?_.message:String(_);throw Z.error(L.binarySymlink.creationFailed(U,K),_),Error(`Failed to create entrypoint at ${U}: ${O}`,{cause:_})}if(!await $.exists(U))throw Z.error(L.binarySymlink.verificationFailed(U)),Error(`Entrypoint creation appeared to succeed but file does not exist at ${U}`);Z.debug(L.binarySymlink.createdAndVerified(U,K))}function $M($,M){let J=(Q,...Y)=>{if(typeof Q==="string")return $(Q).env(M);return $(Q,...Y).env(M)};if(Object.assign(J,$),s0($))Object.defineProperty(J,oM,{value:!0,enumerable:!1});return J}function q$($,M){return $ instanceof f?$.withToolName(M):$}import QJ from"crypto";import i$ from"path";var k={initialized:($,M,J,Q)=>W(`Cache directory: ${$}, TTL: ${M} ms, Strategy: ${J}, Enabled: ${Q}`),cachingDisabled:($,M)=>W(`Cache disabled, ${$} for key: ${M}`),entryMissing:($)=>W(`No cache entry found for key: ${$}`),entryExpired:($)=>W(`Cache entry expired for key: ${$}`),cacheHit:($,M,J)=>{let Q=J!==void 0?`, size: ${J} bytes`:"";return W(`Cache hit for key: ${$} (${M})${Q}`)},cacheStored:($,M,J,Q)=>{let Y=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${Y}, expires: ${J}`)},cacheEntryRemoved:($)=>W(`Removed cache entry for key: ${$}`),cacheCleared:()=>W("Removed entire cache directory"),expiredEntriesCleared:($)=>W(`Removed ${$} expired cache entries`),cacheEntryExists:($)=>W(`Valid cache entry exists for key: ${$}`),noEntryToDelete:($)=>W(`No cache entry to delete for key: ${$}`),cacheDirectoryMissing:()=>W("Cache directory does not exist, nothing to clear"),binaryFileMissing:($,M)=>W(`Binary file missing for key: ${$}, path: ${M}`),contentHashMismatch:($,M,J)=>W(`Content hash mismatch for key: ${$}, expected: ${M}, actual: ${J}`),metadataProcessingWarning:($,M)=>W(`Error processing cache file ${$}: ${M}`),retrievalFailed:($,M)=>W(`Error retrieving cache for key: ${$}, error: ${M}`),storageFailed:($,M)=>W(`Error caching data for key: ${$}, error: ${M}`),checkFailed:($,M)=>W(`Error checking cache for key: ${$}, error: ${M}`),deleteFailed:($,M)=>W(`Error deleting cache entry for key: ${$}, error: ${M}`),clearExpiredFailed:($)=>W(`Error clearing expired cache entries: ${$}`),clearFailed:($)=>W(`Error clearing cache: ${$}`),directoryCreationFailed:($)=>W(`Error ensuring cache directories exist: ${$}`),binaryDirectoryNotConfigured:()=>W("Binary directory not configured for binary strategy"),binaryDataRequired:()=>W("Binary storage strategy requires Buffer data")};class MM{config;fileSystem;logger;metadataDir;binariesDir;constructor($,M,J){if(this.logger=$.getSubLogger({name:"FileCache"}),this.fileSystem=M,this.config=J,J.storageStrategy==="json")this.metadataDir=J.cacheDir;else this.metadataDir=i$.join(J.cacheDir,"metadata"),this.binariesDir=i$.join(J.cacheDir,"binaries");this.logger.debug(k.initialized(J.cacheDir,J.defaultTtl,J.storageStrategy,J.enabled))}async get($){let M=this.logger.getSubLogger({name:"get"});if(!this.config.enabled)return M.debug(k.cachingDisabled("returning null",$)),null;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(k.entryMissing($)),null;let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);if(this.isExpired(Y))return M.debug(k.entryExpired($)),await this.deleteEntry($,Y),null;if(Y.type==="json")return M.debug(k.cacheHit($,"JSON")),Y.data;else{if(!this.binariesDir)throw Error(k.binaryDirectoryNotConfigured());let G=i$.join(this.binariesDir,Y.binaryFileName);if(!await this.fileSystem.exists(G))return M.warn(k.binaryFileMissing($,G)),await this.fileSystem.rm(J).catch(()=>{}),null;let X=await this.fileSystem.readFile(G),Z=Buffer.isBuffer(X)?X:Buffer.from(X),q=QJ.createHash("sha256").update(Z).digest("hex"),I=Y.contentHash;if(q!==I)return M.warn(k.contentHashMismatch($,I,q)),await this.deleteEntry($,Y),null;return M.debug(k.cacheHit($,"binary",Z.length)),Z}}catch(J){return M.warn(k.retrievalFailed($,this.getErrorMessage(J))),null}}async set($,M,J){let Q=this.logger.getSubLogger({name:"set"});if(!this.config.enabled){Q.debug(k.cachingDisabled("skipping set",$));return}try{await this.ensureCacheDirectories();let Y=J??this.config.defaultTtl,G=Date.now();if(this.config.storageStrategy==="json"){let X={type:"json",data:M,timestamp:G,expiresAt:G+Y},Z=this.getMetadataFilePath($);await this.fileSystem.writeFile(Z,JSON.stringify(X,null,2),"utf8"),Q.debug(k.cacheStored($,"JSON",new Date(X.expiresAt).toISOString()))}else{if(!Buffer.isBuffer(M))throw Error(k.binaryDataRequired());if(!this.binariesDir)throw Error(k.binaryDirectoryNotConfigured());let X=M,Z=QJ.createHash("sha256").update(X).digest("hex"),q=`${Z}.bin`,I=i$.join(this.binariesDir,q);await this.fileSystem.writeFile(I,X);let U={type:"binary",binaryFileName:q,contentHash:Z,size:X.length,timestamp:G,expiresAt:G+Y},K=this.getMetadataFilePath($);await this.fileSystem.writeFile(K,JSON.stringify(U,null,2),"utf8"),Q.debug(k.cacheStored($,"binary",new Date(U.expiresAt).toISOString(),X.length))}}catch(Y){let G=this.getErrorMessage(Y);throw Q.warn(k.storageFailed($,G)),Error(`Failed to cache data: ${G}`,{cause:Y})}}async setDownload($,M,J,Q,Y){let G=this.logger.getSubLogger({name:"setDownload"});if(!this.config.enabled){G.debug(k.cachingDisabled("skipping setDownload",$));return}try{await this.ensureCacheDirectories();let X=J??this.config.defaultTtl,Z=Date.now();if(this.config.storageStrategy==="json")throw Error("Download caching requires binary storage strategy");if(!this.binariesDir)throw Error(k.binaryDirectoryNotConfigured());let q=QJ.createHash("sha256").update(M).digest("hex"),I=`${q}.bin`,U=i$.join(this.binariesDir,I);await this.fileSystem.writeFile(U,M);let K={type:"binary",binaryFileName:I,contentHash:q,size:M.length,url:Q,contentType:Y,timestamp:Z,expiresAt:Z+X},H=this.getMetadataFilePath($);await this.fileSystem.writeFile(H,JSON.stringify(K,null,2),"utf8"),G.debug(k.cacheStored($,"download",new Date(K.expiresAt).toISOString(),M.length))}catch(X){let Z=this.getErrorMessage(X);throw G.warn(k.storageFailed($,Z)),Error(`Failed to cache download: ${Z}`,{cause:X})}}async has($){let M=this.logger.getSubLogger({name:"has"});if(!this.config.enabled)return M.debug(k.cachingDisabled("returning false",$)),!1;try{let J=this.getMetadataFilePath($);if(!await this.fileSystem.exists(J))return M.debug(k.entryMissing($)),!1;let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);if(this.isExpired(Y))return M.debug(k.entryExpired($)),!1;if(Y.type==="binary"&&this.binariesDir){let G=i$.join(this.binariesDir,Y.binaryFileName);if(!await this.fileSystem.exists(G))return M.debug(k.binaryFileMissing($,G)),!1}return M.debug(k.cacheEntryExists($)),!0}catch(J){return M.warn(k.checkFailed($,this.getErrorMessage(J))),!1}}async delete($){let M=this.logger.getSubLogger({name:"delete"});if(!this.config.enabled){M.debug(k.cachingDisabled("skipping delete",$));return}try{let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J)){let Q=await this.fileSystem.readFile(J,"utf8"),Y=JSON.parse(Q);await this.deleteEntry($,Y),M.debug(k.cacheEntryRemoved($))}else M.debug(k.noEntryToDelete($))}catch(J){let Q=this.getErrorMessage(J);throw M.warn(k.deleteFailed($,Q)),Error(`Failed to delete cache entry: ${Q}`,{cause:J})}}async clearExpired(){let $=this.logger.getSubLogger({name:"clearExpired"});if(!this.config.enabled){$.debug(k.cachingDisabled("skipping clearExpired","N/A"));return}try{if(!await this.fileSystem.exists(this.metadataDir)){$.debug(k.cacheDirectoryMissing());return}let M=await this.fileSystem.readdir(this.metadataDir),J=0;for(let Q of M){if(!Q.endsWith(".json"))continue;let Y=i$.join(this.metadataDir,Q);try{let G=await this.fileSystem.readFile(Y,"utf8"),X=JSON.parse(G);if(this.isExpired(X)){let Z=i$.basename(Q,".json");await this.deleteEntry(Z,X),J++}}catch(G){$.warn(k.metadataProcessingWarning(Q,this.getErrorMessage(G))),await this.fileSystem.rm(Y).catch(()=>{}),J++}}$.debug(k.expiredEntriesCleared(J))}catch(M){let J=this.getErrorMessage(M);throw $.warn(k.clearExpiredFailed(J)),Error(`Failed to clear expired cache entries: ${J}`,{cause:M})}}async clear(){let $=this.logger.getSubLogger({name:"clear"});if(!this.config.enabled){$.debug(k.cachingDisabled("skipping clear","N/A"));return}try{if(await this.fileSystem.exists(this.config.cacheDir))await this.fileSystem.rm(this.config.cacheDir,{recursive:!0,force:!0}),$.debug(k.cacheCleared());else $.debug(k.cacheDirectoryMissing());await this.ensureCacheDirectories()}catch(M){let J=this.getErrorMessage(M);throw $.warn(k.clearFailed(J)),Error(`Failed to clear cache: ${J}`,{cause:M})}}getMetadataFilePath($){let M=QJ.createHash("md5").update($).digest("hex");return i$.join(this.metadataDir,`${M}.json`)}async ensureCacheDirectories(){let $=this.logger.getSubLogger({name:"ensureCacheDirectories"});try{if(await this.fileSystem.ensureDir(this.metadataDir),this.binariesDir)await this.fileSystem.ensureDir(this.binariesDir)}catch(M){let J=this.getErrorMessage(M);throw $.warn(k.directoryCreationFailed(J)),Error(`Failed to create cache directories: ${J}`,{cause:M})}}getErrorMessage($){if($ instanceof Error)return $.message;return String($)}isExpired($){return Date.now()>$.expiresAt}async deleteEntry($,M){let J=this.getMetadataFilePath($);if(await this.fileSystem.exists(J))await this.fileSystem.rm(J);if(M.type==="binary"&&this.binariesDir){let Q=i$.join(this.binariesDir,M.binaryFileName);if(await this.fileSystem.exists(Q))await this.fileSystem.rm(Q)}}}import QX from"crypto";function SY($,M={}){let J={headers:M.headers||{}},Q={url:$,options:J};return`download:${QX.createHash("sha256").update(JSON.stringify(Q)).digest("hex")}`}import YX from"path";var D0={strategyCreated:($,M)=>W(`Created ${$}${M}`),downloadStarted:($)=>W(`Downloading URL: ${$}`),downloadToFileStarted:($,M)=>W(`Downloading URL ${$} to file: ${M}`)};var B$={strategyWrapped:($,M)=>W(`Wrapping strategy ${$} with cache, TTL: ${M} ms`),cachingDisabled:($,M,J)=>W(`Cache disabled, ${$} for key: ${M} (${J})`),cacheHit:($,M,J)=>{let Q=J!==void 0?`, size: ${J} bytes`:"";return W(`Cache hit for key: ${$} (${M})${Q}`)},cacheStored:($,M,J,Q)=>{let Y=Q!==void 0?`, size: ${Q} bytes`:"";return W(`Cached data for key: ${$} (${M})${Y}, expires: ${J}`)},cacheStorageFailed:($)=>W(`Error caching data for key: ${$}`),cacheCheckFailed:($)=>W(`Error checking cache for key: ${$}`),cacheMiss:($)=>W(`No cache entry found for key: ${$}`),cacheDisabledForProgress:($)=>W(`Cache disabled, caching for key: ${$} (reason: progress callback)`),readFileForCaching:($)=>W(`read file for caching: ${$}`),downloadedFileExists:($,M)=>W(`Downloaded file exists (${$}): ${M}`),downloadedFileCached:($,M)=>W(`Successfully read file for caching from ${$}, size: ${M} bytes`),downloadedFileMissing:($)=>W(`Downloaded file not found: ${$}`),downloadedFileReadFailed:($)=>W(`Failed to read ${$}`),downloadFromStrategy:($)=>W(`download from ${$}`),cachedFileWritten:($)=>W(`[CachedDownloadStrategy] write ${$}`)},k$={constructed:($)=>W(`NodeFetchStrategy constructed (fileSystem ${$})`),downloadTimeout:($)=>W(`Download timeout for ${$}`),responseBodyReadFailed:($,M)=>W(`Failed to read response body for ${$}: ${String(M)}`),downloadFailed:($,M,J,Q)=>W(`Download failed: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${Q??"N/A"}`),downloadAttempt:($,M)=>W(`Attempt ${$}: Downloading ${M}`),downloadSuccessful:($,M)=>W(`Download successful for ${$}, size: ${M} bytes`),savingToDestination:($)=>W(`Saving to destination: ${$}`),savedSuccessfully:($)=>W(`Successfully wrote to ${$} using IFileSystem`),downloadAttemptError:($,M,J)=>W(`Error during download attempt ${$} for ${M}: ${String(J)}`),retryingDownload:($,M,J,Q)=>W(`Retrying download for ${$}, attempt ${M}/${J} after ${Q}ms`),exhaustedRetries:($)=>W(`Exhausted retries for ${$}`)},JM={errorCreated:($,M,J)=>W(`${$} created: message=${M}, url=${J}`),networkErrorCreated:($,M,J)=>W(`NetworkError created: message=${$}, url=${M}, originalError=${String(J)}`),httpErrorCreated:($,M,J,Q,Y,G)=>W(`HttpError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(Y)}, responseHeaders=${JSON.stringify(G??{})}`),notFoundErrorCreated:($,M,J)=>W(`NotFoundError created: url=${$}, responseBody=${String(M)}, responseHeaders=${JSON.stringify(J??{})}`),forbiddenErrorCreated:($,M,J)=>W(`ForbiddenError created: url=${$}, responseBody=${String(M)}, responseHeaders=${JSON.stringify(J??{})}`),rateLimitErrorCreated:($,M,J,Q,Y,G,X)=>W(`RateLimitError created: message=${$}, url=${M}, statusCode=${J}, statusText=${Q}, responseBody=${String(Y)}, responseHeaders=${JSON.stringify(G??{})}, resetTimestamp=${String(X)}`),clientErrorCreated:($,M,J,Q,Y)=>W(`ClientError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(Y??{})}`),serverErrorCreated:($,M,J,Q,Y)=>W(`ServerError created: url=${$}, statusCode=${M}, statusText=${J}, responseBody=${String(Q)}, responseHeaders=${JSON.stringify(Y??{})}`)};class BQ{name;cache;underlyingStrategy;logger;cacheTtl;fileSystem;constructor($,M,J,Q,Y=86400000){this.logger=$.getSubLogger({name:"CachedDownloadStrategy"}),this.fileSystem=M,this.cache=J,this.underlyingStrategy=Q,this.cacheTtl=Y,this.name=`cached-${Q.name}`,this.logger.debug(B$.strategyWrapped(Q.name,Y))}async isAvailable(){return await this.underlyingStrategy.isAvailable()}async handleCacheHit($,M,J,Q,Y){if($.trace(B$.cacheHit(J,"binary",M.length),{url:Q}),Y.onProgress)Y.onProgress(0,M.length);if(Y.destinationPath){if(await this.fileSystem.ensureDir(YX.dirname(Y.destinationPath)),await this.fileSystem.writeFile(Y.destinationPath,M),$.trace(B$.cachedFileWritten(Y.destinationPath)),Y.onProgress)Y.onProgress(M.length,M.length);return}if(Y.onProgress)Y.onProgress(M.length,M.length);return M}async readFileForCaching($,M){$.trace(B$.readFileForCaching(M));try{let J=await this.fileSystem.exists(M);if($.trace(B$.downloadedFileExists(M,J)),J){let Q=await this.fileSystem.readFileBuffer(M);return $.trace(B$.downloadedFileCached(M,Q.length),{path:M,size:Q.length}),Q}else return $.trace(B$.downloadedFileMissing(M)),null}catch(J){return $.trace(B$.downloadedFileReadFailed(M),J),null}}async determineBufferToCache($,M,J){if(M instanceof Buffer)return M;else if(J.destinationPath&&M===void 0)return await this.readFileForCaching($,J.destinationPath);return null}async cacheResult($,M,J,Q,Y){try{await this.cache.setDownload(J,M,this.cacheTtl,Q,this.extractContentTypeFromHeaders(Y.headers)),$.trace(B$.cacheStored(J,"binary","TTL-based",M.length),{url:Q})}catch(G){$.trace(B$.cacheStorageFailed(J),G)}}async download($,M={}){let J=this.logger.getSubLogger({name:"download"}),Q=SY($,M);try{let X=await this.cache.get(Q);if(X)return await this.handleCacheHit(J,X,Q,$,M);J.trace(B$.cacheMiss(Q),{url:$})}catch(X){J.trace(B$.cacheCheckFailed(Q),X)}J.trace(B$.downloadFromStrategy(this.underlyingStrategy.name),{url:$});let Y=await this.underlyingStrategy.download($,M),G=await this.determineBufferToCache(J,Y,M);if(G)await this.cacheResult(J,G,Q,$,M);return Y}extractContentTypeFromHeaders($){if(!$)return;return $.Accept||$.accept}}class DQ extends Error{url;constructor($,M,J){super(M);let Q=$.getSubLogger({name:"DownloaderError"});this.name="DownloaderError",this.url=J,Q.debug(JM.errorCreated("DownloaderError",M,J))}}class U$ extends DQ{originalError;constructor($,M,J,Q){super($,M,J);let Y=$.getSubLogger({name:"NetworkError"});this.name="NetworkError",this.originalError=Q,Y.debug(JM.networkErrorCreated(M,J,Q),Q)}}class F$ extends DQ{statusCode;statusText;responseBody;responseHeaders;constructor($,M,J,Q,Y,G,X){super($,M,J);let Z=$.getSubLogger({name:"HttpError"});this.name="HttpError",this.statusCode=Q,this.statusText=Y,this.responseBody=G,this.responseHeaders=X,Z.debug(JM.httpErrorCreated(M,J,Q,Y,G,X),{url:J,statusCode:Q,statusText:Y,responseBody:G,responseHeaders:X})}}class S$ extends F${constructor($,M,J,Q){super($,"Resource not found",M,404,"Not Found",J,Q);let Y=$.getSubLogger({name:"NotFoundError"});this.name="NotFoundError",Y.debug(JM.notFoundErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class bM extends F${constructor($,M,J,Q){super($,"Access forbidden",M,403,"Forbidden",J,Q);let Y=$.getSubLogger({name:"ForbiddenError"});this.name="ForbiddenError",Y.debug(JM.forbiddenErrorCreated(M,J,Q),{url:M,responseBody:J,responseHeaders:Q})}}class BM extends F${resetTimestamp;constructor($,M,J,Q,Y,G,X,Z){super($,M,J,Q,Y,G,X);let q=$.getSubLogger({name:"RateLimitError"});this.name="RateLimitError",this.resetTimestamp=Z,q.debug(JM.rateLimitErrorCreated(M,J,Q,Y,G,X,Z),{url:J,statusCode:Q,statusText:Y,responseBody:G,responseHeaders:X,resetTimestamp:Z})}}class NM extends F${constructor($,M,J,Q,Y,G){super($,`Client error: ${Q}`,M,J,Q,Y,G);let X=$.getSubLogger({name:"ClientError"});this.name="ClientError",X.debug(JM.clientErrorCreated(M,J,Q,Y,G),{url:M,statusCode:J,statusText:Q,responseBody:Y,responseHeaders:G})}}class vM extends F${constructor($,M,J,Q,Y,G){super($,`Server error: ${Q}`,M,J,Q,Y,G);let X=$.getSubLogger({name:"ServerError"});this.name="ServerError",X.debug(JM.serverErrorCreated(M,J,Q,Y,G),{url:M,statusCode:J,statusText:Q,responseBody:Y,responseHeaders:G})}}class AQ{name="node-fetch";logger;fileSystem;proxyConfig;constructor($,M,J){this.logger=$.getSubLogger({name:"NodeFetchStrategy"}),this.logger.debug(k$.constructed(M?"provided":"undefined")),this.fileSystem=M,this.proxyConfig=J}async isAvailable(){return typeof fetch==="function"}getResponseHeaders($){let M={};return $.forEach((J,Q)=>{M[Q]=J}),M}parseRateLimitReset($){let M=$.get("X-RateLimit-Reset");if(M){let Q=parseInt(M,10);if(!Number.isNaN(Q))return Q*1000}let J=$.get("Retry-After");if(J){let Q=parseInt(J,10);if(!Number.isNaN(Q))return Date.now()+Q*1000;let Y=Date.parse(J);if(!Number.isNaN(Y))return Y}return}async setupDownloadRequest($,M,J){let Q=new AbortController,Y;if(J)Y=setTimeout(()=>{this.logger.debug(k$.downloadTimeout($)),Q.abort()},J);return{response:await s6($,{headers:M,signal:Q.signal},this.proxyConfig),timeoutId:Y}}async handleErrorResponse($,M){let J;try{J=await $.text()}catch(Z){this.logger.debug(k$.responseBodyReadFailed(M,Z))}let Q=this.getResponseHeaders($.headers),Y=$.status,G=$.statusText;if(this.logger.debug(k$.downloadFailed(M,Y,G,J?.substring(0,100))),Y===404)throw new S$(this.logger,M,J,Q);let X=this.parseRateLimitReset($.headers);if(Y===403){if(X)throw new BM(this.logger,"Forbidden: Rate limit likely exceeded",M,Y,G,J,Q,X);throw new bM(this.logger,M,J,Q)}if(Y===429)throw new BM(this.logger,"Too Many Requests",M,Y,G,J,Q,X);if(Y>=400&&Y<500)throw new NM(this.logger,M,Y,G,J,Q);if(Y>=500&&Y<600)throw new vM(this.logger,M,Y,G,J,Q);throw new F$(this.logger,`HTTP error ${Y}`,M,Y,G,J,Q)}async processResponseStream($,M,J){let Q=$.headers.get("content-length"),Y=null;if(Q){let q=parseInt(Q,10);if(!Number.isNaN(q))Y=q}let G=0;if(J)J(G,Y);let X=[],Z=$.body?.getReader();if(!Z)throw new U$(this.logger,"Response body is not readable.",M);while(!0){let{done:q,value:I}=await Z.read();if(q)break;if(I){if(X.push(Buffer.from(I)),G+=I.length,J)J(G,Y)}}return Buffer.concat(X)}async handleDownloadAttempt($,M,J){let{headers:Q,timeout:Y,onProgress:G,destinationPath:X}=M;this.logger.debug(k$.downloadAttempt(J+1,$));let{response:Z,timeoutId:q}=await this.setupDownloadRequest($,Q,Y);if(q)clearTimeout(q);if(!Z.ok)await this.handleErrorResponse(Z,$);let I=await this.processResponseStream(Z,$,G);if(this.logger.debug(k$.downloadSuccessful($,I.length)),X){this.logger.debug(k$.savingToDestination(X)),await this.fileSystem.writeFile(X,I),this.logger.debug(k$.savedSuccessfully(X));return}else return I}handleDownloadError($,M,J,Q,Y){if(this.logger.debug(k$.downloadAttemptError(J+1,M,$)),J>=Q){if($ instanceof F$||$ instanceof U$)throw $;let G=`Failed to download ${M}`;if($ instanceof Error&&$.name==="AbortError")G=`Download timed out for ${M}`;else if($ instanceof Error)G=$.message;throw new U$(this.logger,G,M,$ instanceof Error?$:void 0)}}async retryDownload($,M,J,Q,Y){this.logger.debug(k$.retryingDownload($,M+2,J+1,Q)),await new Promise((G)=>setTimeout(G,Q))}async download($,M){let{retryCount:J=0,retryDelay:Q=1000,onProgress:Y}=M,G=0;while(G<=J)try{return await this.handleDownloadAttempt($,M,G)}catch(X){if(this.handleDownloadError(X,$,G,J,Y),G<J)await this.retryDownload($,G,J,Q,Y),G++}throw this.logger.debug(k$.exhaustedRetries($)),new U$(this.logger,`Download failed for ${$} after ${J} retries.`,$)}}class EQ{strategies=[];fs;logger;constructor($,M,J,Q,Y){if(this.logger=$.getSubLogger({name:"Downloader"}),this.fs=M,typeof J<"u")this.strategies=J;else{let G=new AQ(this.logger,this.fs,Y),X=Y?.enabled?` (proxy port ${Y.port})`:"";if(Q)this.logger.debug(D0.strategyCreated("CachedDownloadStrategy",` wrapping NodeFetchStrategy${X}`)),this.strategies.push(new BQ(this.logger,this.fs,Q,G));else this.logger.debug(D0.strategyCreated("NodeFetchStrategy",X||" (no cache)")),this.strategies.push(G)}}registerStrategy($){this.strategies.unshift($)}async tryDownloadWithStrategy($,M,J){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};return{success:!0,buffer:await $.download(M,J)}}async download($,M,J={}){if($.getSubLogger({name:"Downloader"}).getSubLogger({name:"download"}).debug(D0.downloadStarted(M)),this.strategies.length===0)throw Error("No download strategies registered.");let Y;for(let G of this.strategies)try{let X=await this.tryDownloadWithStrategy(G,M,J);if(X.success)return X.buffer}catch(X){Y=this.normalizeError(X)}if(Y)throw Y;throw Error(`No available download strategy succeeded for ${M}.`)}async tryDownloadToFileWithStrategy($,M,J){if(!await $.isAvailable())return{success:!1,error:"Strategy not available"};if(await $.download(M,J)===void 0)return{success:!0};throw Error("Strategy returned Buffer instead of void for downloadToFile method")}normalizeError($){if($ instanceof Error)return $;else if(typeof $==="string")return Error($);else return Error(`An unknown error occurred during download: ${JSON.stringify($)}`)}async downloadToFile($,M,J,Q={}){$.getSubLogger({name:"Downloader"}).getSubLogger({name:"downloadToFile"}).debug(D0.downloadToFileStarted(M,J));let G={...Q,destinationPath:J};if(this.strategies.length===0)throw Error("No download strategies registered.");let X;for(let Z of this.strategies)try{if((await this.tryDownloadToFileWithStrategy(Z,M,G)).success)return}catch(q){X=this.normalizeError(q)}if(X)throw X;throw Error(`No available download strategy succeeded for ${M}.`)}}import*as eM from"cli-progress";class FQ{filename;progressBar=null;enabled;startTime=0;constructor($,M={}){this.filename=$;this.enabled=M.enabled??!0}createCallback(){if(!this.enabled)return;return($,M)=>{if(this.startTime===0)if(this.startTime=Date.now(),M)this.progressBar=new eM.SingleBar({format:`Downloading ${this.filename} |{bar}| {percentage}% | {value}/{total} | {speed} | ETA: {eta_formatted}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},eM.Presets.shades_classic),this.progressBar.start(M,0,{speed:"0 B/s"});else this.progressBar=new eM.SingleBar({format:`Downloading ${this.filename} |{bar}| {value} | {speed}`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,stream:process.stderr},eM.Presets.shades_classic),this.progressBar.start(100,0,{speed:"0 B/s"});if(this.progressBar){let J=(Date.now()-this.startTime)/1000,Q=J>0?`${this.formatBytes($/J)}/s`:"0 B/s";if(M){if(this.progressBar.update($,{speed:Q}),$>=M)this.progressBar.stop()}else{let Y=Math.floor(Date.now()/100)%100;this.progressBar.update(Y,{speed:Q,value:this.formatBytes($)})}}}}clear(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}finish(){if(this.progressBar)this.progressBar.stop(),this.progressBar=null}formatBytes($){let M=["B","KB","MB","GB"],J=$,Q=0;while(J>=1024&&Q<M.length-1)J/=1024,Q++;return`${J.toFixed(J>=10?0:1)} ${M[Q]}`}}function wY($=!1){if($)return!1;if(!process.stderr.isTTY)return!1;if(process.env.NO_COLOR)return!1;return!0}async function K$($,M,J,Q,Y,G){let X=wY(G?.quiet),Z=new FQ(Q,{enabled:X});try{await Y.download($,M,{destinationPath:J,onProgress:Z.createCallback()})}finally{Z.finish()}}function bY($){return $.installParams?.hooks}async function w$($,M,J,Q,Y){let X=bY($)?.["after-download"];if(!X)return{success:!0};Y.debug(L.lifecycle.hookExecution("after-download"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(Y,"after-download",q,Z);if(!I.success)return{success:!1,error:`afterDownload hook failed: ${I.error}`}}return{success:!0}}async function $0($,M,J,Q,Y){let X=bY($)?.["after-extract"];if(!X)return{success:!0};Y.debug(L.lifecycle.hookExecution("after-extract"));let Z=J.createEnhancedContext(M,Q);for(let q of X){let I=await J.executeHook(Y,"after-extract",q,Z);if(!I.success)return{success:!1,error:`afterExtract hook failed: ${I.error}`}}return{success:!0}}function GX($){return typeof $==="object"&&$!==null}function XX($){if(!GX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function NY($){if(typeof $==="string")return $.trim();if($ instanceof Uint8Array)return Buffer.from($).toString("utf8").trim();return""}function vY($){if(XX($)){let M=NY($.stderr);if(M.length>0)return M;let J=NY($.stdout);if(J.length>0)return J;if($.message)return $.message;return`exit code ${$.exitCode??"unknown"}`}if($ instanceof Error)return $.message;return String($)}function l$($){if(!$||$.length===0)return[];return $.map((M)=>typeof M==="string"?{name:M,pattern:`{,*/}${M}`}:M)}function YJ($){return l$($).map((J)=>J.name)}import{join as ZX}from"path";function e($,M){return l$($).map((Q)=>ZX(M,Q.name))}import fY from"path";import{codeFrameColumns as WX}from"@babel/code-frame";function qX($){return typeof $==="object"&&$!==null}function CY($){if(!qX($))return!1;let M=$.name;if(typeof M!=="string")return!1;return M==="ShellError"}function IX($){return $.isTracingEnabled()}function UX($){return $.endsWith(`
|
|
60
60
|
`)?$:`${$}
|
|
61
|
-
`}function
|
|
62
|
-
`);for(let J of M){if(!J.includes(".tool.ts"))continue;let Q=
|
|
63
|
-
${
|
|
64
|
-
`}function
|
|
65
|
-
`)}function
|
|
61
|
+
`}function dY($,M,J){return{filePath:$,line:M,column:J}}function yY($,M){let J=M.exec($);if(!J)return null;let Q=J[1],Y=Number(J[2]),G=Number(J[3]);if(!Q||Number.isNaN(Y)||Number.isNaN(G))return null;return dY(Q,Y,G)}function KX($){let M=/([^\s]+\.tool\.ts):(\d+)\s*$/.exec($);if(!M)return null;let J=M[1],Q=Number(M[2]);if(!J||Number.isNaN(Q))return null;return dY(J,Q,1)}function HX($){let M=$.split(`
|
|
62
|
+
`);for(let J of M){if(!J.includes(".tool.ts"))continue;let Q=yY(J,/\(([^)]+\.tool\.ts):(\d+):(\d+)\)\s*$/);if(Q)return Q;let Y=yY(J,/\s+at\s+([^\s]+\.tool\.ts):(\d+):(\d+)\s*$/);if(Y)return Y;let G=KX(J);if(G)return G}return null}async function _X($,M){if(!await $.exists(M.filePath))return null;let Q=await $.readFile(M.filePath,"utf8"),Y=WX(Q,{start:{line:M.line,column:M.column}},{linesAbove:2,linesBelow:2,highlightCode:!0,forceColor:!0});return`${M.filePath}:${M.line}:${M.column}
|
|
63
|
+
${Y}
|
|
64
|
+
`}function RX($){let M=[],J=typeof $.exitCode==="number"?String($.exitCode):"unknown";M.push(`exit code: ${J}`);let Q=PY($.stderr);if(Q.length>0)M.push("stderr:"),M.push(Q);let Y=PY($.stdout);if(Y.length>0)M.push("stdout:"),M.push(Y);return M.join(`
|
|
65
|
+
`)}function PY($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");return""}function OX($,M){let J=[];if($ instanceof Error){if(J.push(`${$.name}: ${$.message}`),M&&typeof $.stack==="string"&&$.stack.length>0)J.push("stack:"),J.push($.stack);return J.join(`
|
|
66
66
|
`)}return J.push(String($)),J.join(`
|
|
67
|
-
`)}async function
|
|
68
|
-
`))}function
|
|
69
|
-
`);Z.error(L.binarySetupService.extractedFilesTree(G,B))}continue}let _=BM.relative(G,H);await JJ($,M,U,Q,_,Y,Z),q=!0}return q}async function f6($,M,J="",Q=3,G=0){let Y=[];if(G>=Q)return Y;let X=[];try{X=await $.readdir(M)}catch{return Y}let Z=X.toSorted();for(let q=0;q<Z.length;q++){let I=Z[q];if(!I)continue;let U=q===Z.length-1,K=BM.join(M,I),H=U?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",_=J+(U?" ":"\u2502 "),O=await TX($,K,I,J,H,_,Q,G);Y.push(...O)}return Y}async function TX($,M,J,Q,G,Y,X,Z){let q=[];try{let I=await $.stat(M),U=I.isDirectory()?`${J}/`:J;if(q.push(`${Q}${G}${U}`),I.isDirectory()&&Z<X-1){let K=await f6($,M,Y,X,Z+1);q.push(...K)}}catch{q.push(`${Q}${G}${J} (inaccessible)`)}return q}async function kX($,M){return((await $.stat(M)).mode&73)!==0}async function SX($,M,J,Q,G){G.getSubLogger({name:"findBinaryUsingPattern"}).debug(L.binarySetupService.searchingWithPattern(J,M));let Z=(await SM($,M,M)).filter((K)=>LX(K,J));if(Z.length===0)return null;let q=[];for(let K of Z){let H=BM.join(M,K);if(await kX($,H))q.push(K)}if(q.length===0)return null;let I=q.find((K)=>BM.basename(K)===Q);if(I)return BM.join(M,I);let U=q[0];if(U)return BM.join(M,U);return null}import LQ from"path";async function $0($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"setupBinariesFromDirectDownload"}),Z=l$(J.binaries),q=Z[0]?.name||M;await $.chmod(G,493);let I=LQ.join(Q.projectConfig.paths.generatedDir,"binaries"),U=LQ.basename(G),K=LQ.basename(Q.stagingDir);if(await JJ($,M,q,K,U,I,X),Z.length>1)X.debug(L.binarySetupService.directDownloadSingleBinary(Z.length,q))}async function Q$($,M,J,Q){try{return await Q()}catch(G){return J.error(L.outcome.installFailed($),G),{success:!1,error:G instanceof Error?G.message:String(G)}}}class xQ{projectConfig;systemInfo;resolvedFileSystem;fileSystem;$shell;emitInstallEvent;constructor($){this.projectConfig=$.projectConfig,this.systemInfo=$.systemInfo,this.resolvedFileSystem=$.resolvedFileSystem,this.fileSystem=$.fileSystem,this.$shell=$.$shell,this.emitInstallEvent=$.emitInstallEvent}createMinimalContext($){let M=this.getToolDirectory($.toolConfig),J=$.parentLogger.getSubLogger({name:"minimalContext"});return{...R0(this.projectConfig,this.systemInfo,$.toolName,M,this.resolvedFileSystem,J),stagingDir:"",timestamp:"",toolConfig:$.toolConfig,$:$.$shell??e$(this.$shell,process.env),fileSystem:this.fileSystem}}createBaseInstallContext($){let M=this.getToolDirectory($.toolConfig),J=$.parentLogger.getSubLogger({name:`install-${$.toolName}`}),Q=R0(this.projectConfig,this.systemInfo,$.toolName,M,this.resolvedFileSystem,J),G=$.$shell??e$(this.$shell,process.env),Y=(I={})=>({...Q,stagingDir:$.stagingDir,timestamp:$.timestamp,toolConfig:$.toolConfig,$:G,fileSystem:this.fileSystem,installEnv:$.installEnv,...I}),X=Y(),Z=async(I,U)=>{await this.emitInstallEvent({type:I,toolName:$.toolName,context:{...Y(U),emitEvent:Z,logger:J}})};return X.emitEvent=Z,{context:X,logger:J}}getToolDirectory($){return $.configFilePath?wX.dirname($.configFilePath):this.projectConfig.paths.toolConfigsDir}}function YJ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function bX($){return Array.isArray($)&&$.every((M)=>typeof M==="function")}function vX($){if(!YJ($))return!1;return typeof $.getSubLogger==="function"}function TQ($){if(!YJ($))return;let M=$.installParams;if(!YJ(M))return;let J=M.hooks;if(!YJ(J))return;let Q=Object.entries(J);if(Q.length===0)return;let G={};for(let[Y,X]of Q){if(!bX(X))return;G[Y]=X}return G}class kQ{hookExecutor;constructor($){this.hookExecutor=$}async handleInstallEvent($,M,J){if(!M)return;let Q=TQ(M);if(!Q)return;let G=Q[$.type];if(!G)return;let Y=$.context.logger,X=vX(Y)?Y:J,Z=$.context.fileSystem,q=this.hookExecutor.createEnhancedContext($.context,Z,X);for(let I of G){let U=await this.hookExecutor.executeHook(X,$.type,I,q);if(!U.success){let K=U.error?`${$.type} hook failed: ${U.error}`:`Hook ${$.type} failed`;throw Error(K)}}}async executeBeforeInstallHook($,M,J,Q){let G=Q.getSubLogger({name:"executeBeforeInstallHook"}),X=TQ($)?.["before-install"];if(!X)return null;G.debug(L.lifecycle.hookExecution("before-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,G);for(let q of X){let I=await this.hookExecutor.executeHook(G,"before-install",q,Z);if(!I.success)return{success:!1,error:`beforeInstall hook failed: ${I.error}`}}return null}async executeAfterInstallHook($,M,J,Q){let G=Q.getSubLogger({name:"executeAfterInstallHook"}),X=TQ($)?.["after-install"];if(!X)return;G.debug(L.lifecycle.hookExecution("after-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,G);for(let q of X)await this.hookExecutor.executeHook(G,"after-install",q,Z,{continueOnError:!0})}}import JM from"path";function NX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function yX($){let M={};if(!$.success)return M;if(!("metadata"in $))return M;let J=$.metadata;if(!NX(J))return M;let{method:Q,...G}=J;if(typeof Q==="string")return{...G,installMethod:Q};return J}class SQ{projectConfig;toolInstallationRegistry;symlinkGenerator;constructor($){this.projectConfig=$.projectConfig,this.toolInstallationRegistry=$.toolInstallationRegistry,this.symlinkGenerator=$.symlinkGenerator}async recordInstallation($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"recordInstallation"});if(!G.success)return;try{let Z="version"in G&&G.version?G.version:Q.timestamp,q=M.installParams,I=q&&typeof q==="object"&&"version"in q&&typeof q.version==="string"?q.version:void 0,U="originalTag"in G&&typeof G.originalTag==="string"?G.originalTag:void 0;await this.toolInstallationRegistry.recordToolInstallation({toolName:$,version:Z,installPath:J,timestamp:Q.timestamp,binaryPaths:G.binaryPaths,configuredVersion:I,originalTag:U,...yX(G)}),X.debug(L.outcome.installSuccess($,Z,"registry-recorded"))}catch(Z){X.error(L.outcome.installFailed("registry-record"),Z)}}async createBinaryEntrypoints($,M,J,Q,G,Y){let X=Q.getSubLogger({name:"createBinaryEntrypoints"}),Z=JM.join(this.projectConfig.paths.binariesDir,$);if(await J.ensureDir(Z),Y){let q=JM.join(Z,"external");await J.ensureDir(q);for(let I of M){let U=JM.basename(I),K=JM.join(q,U);try{await this.symlinkGenerator.createBinarySymlink(X,I,K)}catch(H){throw X.error(L.lifecycle.externalBinaryMissing($,U,I)),H}}return}for(let q of M){let I=JM.basename(q),U=JM.join(G,I);if(q===U)continue;try{if(await J.exists(U))await J.rm(U,{force:!0})}catch(K){throw X.error(L.binarySymlink.removeExistingFailed(U),K),K}try{await J.copyFile(q,U);let H=(await J.stat(q)).mode&511;await J.chmod(U,H)}catch(K){throw X.error(L.binarySymlink.creationFailed(U,q),K),K}}}async updateCurrentSymlink($,M,J,Q,G){let Y=J.getSubLogger({name:"updateCurrentSymlink"}),X=JM.join(this.projectConfig.paths.binariesDir,$),Z=JM.join(X,"current");await M.ensureDir(X);let q=G?"external":JM.basename(Q);try{if(await M.exists(Z))await M.rm(Z,{force:!0,recursive:!0})}catch(I){throw Y.error(L.lifecycle.removingExistingSymlink(Z),I),I}try{await M.withFileType("symlink").symlink(q,Z,"dir")}catch(I){throw Y.error(L.lifecycle.creatingExternalSymlink(Z,q),I),I}try{let I=await M.readlink(Z);if(I!==q)throw Y.error(L.lifecycle.symlinkVerificationFailed(Z)),Error(`Symlink verification failed: ${Z} points to ${I}, expected ${q}`)}catch(I){throw Y.error(L.lifecycle.symlinkVerificationFailed(Z),I),I}}}class wQ{logger;fs;resolvedFs;projectConfig;hookExecutor;hookLifecycle;toolInstallationRegistry;systemInfo;registry;installationStateWriter;$;installContextFactory;currentToolConfig;constructor($,M,J,Q,G,Y,X,Z,q,I){this.logger=$.getSubLogger({name:"Installer"}),this.fs=M,this.resolvedFs=J,this.projectConfig=Q,this.hookExecutor=I,this.hookLifecycle=new kQ(I),this.toolInstallationRegistry=G,this.systemInfo=Y,this.registry=X,this.installationStateWriter=new SQ({projectConfig:this.projectConfig,toolInstallationRegistry:this.toolInstallationRegistry,symlinkGenerator:Z}),this.$=q,this.installContextFactory=new xQ({projectConfig:this.projectConfig,systemInfo:this.systemInfo,resolvedFileSystem:this.resolvedFs,fileSystem:this.fs,$shell:this.$,emitInstallEvent:async(U)=>{await this.registry.emitEvent(U)}}),this.registry.onEvent(async(U)=>{await this.hookLifecycle.handleInstallEvent(U,this.currentToolConfig,this.logger)})}async shouldSkipInstallation($,M,J,Q){let G=Q.getSubLogger({name:"shouldSkipInstallation"});if(J?.force||J?.skipVersionCheck)return null;let Y=await this.toolInstallationRegistry.getToolInstallation($);if(!Y)return null;let X=M0.join(this.projectConfig.paths.binariesDir,$,"current"),Z=e(M.binaries,X),I=this.registry.get(M.installationMethod)?.getShellInit?.($,M,X),U=await this.getTargetVersion($,M);if(U){if(Y.version===U)return G.debug(L.outcome.installSuccess($,U,"already-installed")),{success:!0,version:Y.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I};return G.debug(L.outcome.outdatedVersion($,Y.version,U)),null}return G.debug(L.outcome.installSuccess($,Y.version,"already-installed-latest")),{success:!0,version:Y.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I}}async executeInstallationMethod($,M,J,Q,G){return await this.registry.install(G,M.installationMethod,$,M,J,Q)}async install($,M,J){let Q=this.logger.getSubLogger({name:"install",context:$}),G=this.getSystemInfo(),Y=G$(M,G);this.currentToolConfig=Y;let X=this.fs.withToolName($);if(J?.shimMode)X.setSuppressLogging(!0);try{let Z=await this.shouldSkipInstallation($,Y,J,Q);if(Z)return Z;let q=this.registry.get(Y.installationMethod),I=q?.externallyManaged===!0,U=this.projectConfig.paths.binariesDir,K=M0.join(U,$);await X.ensureDir(K);let H=nG(),_=H;if(Y.version&&Y.version!=="latest")_=Y.version;if(!I&&q?.resolveVersion){let m=this.createMinimalContext($,Y,Q);try{let $$=await q.resolveVersion($,Y,m,Q);if($$)_=$$,Q.debug(L.lifecycle.versionResolved($$));else Q.debug(L.lifecycle.versionFallbackToTimestamp())}catch($$){Q.debug(L.lifecycle.versionResolutionFailed($$))}}let O=PX(),B=M0.join(K,O);if(!I)await X.ensureDir(B),Q.debug(L.lifecycle.directoryCreated(B));let j=`DOTFILES_INSTALLING_${$.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`,V="/Users/alex/development/projects/dotfiles-installer/packages/build:/Users/alex/development/projects/dotfiles-installer/packages/build/src/build/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/build/src/build/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/build/src/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/build/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/packages/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/node_modules/.bin:/Users/alex/development/node_modules/.bin:/Users/alex/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/node_modules/.bin:/Users/alex/development/node_modules/.bin:/Users/alex/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/dotfiles-installer/node_modules/.bin:/Users/alex/development/projects/node_modules/.bin:/Users/alex/development/node_modules/.bin:/Users/alex/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/Users/alex/go/bin:/Users/alex/Applications/cmux.app/Contents/Resources/bin:/Users/alex/.local/state/fnm_multishells/7266_1772222045270/bin:/Users/alex/.fly/bin:/Users/alex/.cache/.bun/bin:node_modules/.bin:/Users/alex/.orbstack/bin:/Users/alex/.cargo/bin:/Users/alex/.dotfiles/.generated/bin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/local/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/bin:/var/run/com.apple.security.cryptexd/codex.system/bootstrap/usr/appleinternal/bin:/opt/pmk/env/global/bin:/Library/Apple/usr/bin:/opt/homebrew/bin:/Users/alex/.local/bin:/Users/alex/.dotfiles/bin:/Users/alex/.local/bin",D=G.platform===4?";":":",A=I?V:`${B}${D}${V}`,b={...process.env,[j]:"true",PATH:A},k=e$(this.$,b),{context:S,logger:u}=this.createBaseInstallContext($,B,H,Y,Q,k,b),i=await this.hookLifecycle.executeBeforeInstallHook(Y,S,X,u);if(i)return i;let E;try{E=await this.executeInstallationMethod($,Y,S,J,u),E.installationMethod=Y.installationMethod;let m=E.success&&"version"in E?E.version:void 0,$$=_===H&&m&&m!==H?m:_,g=I?M0.join(K,"external"):M0.join(K,$$);if(E.success&&!I){if(await X.exists(g))await X.rm(g,{recursive:!0,force:!0});if(await X.rename(B,g),Q.debug(L.lifecycle.directoryRenamed(B,g)),E.success&&"binaryPaths"in E&&E.binaryPaths)E.binaryPaths=E.binaryPaths.map((y)=>y.startsWith(B)?y.replace(B,g):y)}if(E.success&&I)await X.ensureDir(g);let o=E.success&&"binaryPaths"in E?E.binaryPaths:void 0;if(E.success&&o){let y=[];for(let O$ of o)if(await X.exists(O$))y.push(O$);if(y.length>0)await this.installationStateWriter.createBinaryEntrypoints($,y,X,Q,g,I)}if(E.success)await this.installationStateWriter.updateCurrentSymlink($,X,Q,g,I);if(!I&&!E.success&&await X.exists(B)){Q.debug(L.lifecycle.cleaningFailedInstallDir(B)),await X.rm(B,{recursive:!0,force:!0});let y=M0.dirname(B);try{if((await X.readdir(y)).length===0)await X.rmdir(y)}catch{}}if(!E.success&&E.error)Q.error(W(E.error));if(E.success){let y="binaryPaths"in E&&Array.isArray(E.binaryPaths)?E.binaryPaths:[],O$="version"in E?E.version:void 0,r$=I?V:`${g}${D}${V}`,d0={...process.env,[j]:"true",PATH:r$},T$=e$(this.$,d0),sJ={...S,$:T$,installedDir:g,binaryPaths:y,version:O$,installEnv:d0};await this.hookLifecycle.executeAfterInstallHook(Y,sJ,X,u),await this.installationStateWriter.recordInstallation($,Y,g,S,E,u)}return E}catch(m){return E={success:!1,error:m instanceof Error?m.message:String(m),installationMethod:Y.installationMethod},Q.error(W(E.error)),E}}catch(Z){let q={success:!1,error:Z instanceof Error?Z.message:String(Z),installationMethod:Y.installationMethod};return Q.error(W(q.error)),q}}async getTargetVersion($,M){if(M.version&&M.version!=="latest")return M.version;return null}createMinimalContext($,M,J){return this.installContextFactory.createMinimalContext({toolName:$,toolConfig:M,parentLogger:J})}createBaseInstallContext($,M,J,Q,G,Y=e$(this.$,process.env),X){let Z=G.getSubLogger({name:"createBaseInstallContext"});return this.installContextFactory.createBaseInstallContext({toolName:$,stagingDir:M,timestamp:J,toolConfig:Q,parentLogger:Z,$shell:Y,installEnv:X})}getSystemInfo(){return this.systemInfo}}import{z as yM}from"zod";var d$={installing:($)=>W(`Installing from brew: toolName=${$}`),executingCommand:($)=>W(`installFromBrew: Executing command: ${$}`),fetchingVersion:($)=>W(`Fetching version info for formula: ${$}`),versionFetched:($,M)=>W(`Fetched version ${M} for formula ${$}`),versionNotFound:($)=>W(`No stable version found for formula ${$}`),versionFetchFailed:($)=>W(`Failed to fetch version for formula ${$}`),prefixFetched:($,M)=>W(`Formula ${$} installed at prefix: ${M}`),prefixFetchFailed:($)=>W(`Failed to fetch prefix for formula ${$}`),prefixFallback:($,M)=>W(`Using fallback prefix for formula ${$}: ${M}`)};var CX=yM.object({name:yM.string(),versions:yM.object({stable:yM.string(),head:yM.string().optional(),bottle:yM.boolean().optional()})});async function p6($,M,J,Q,G,Y,X){let Z=G.getSubLogger({name:"installFromBrew"});if(Z.debug(d$.installing($),M.installParams),!M.installParams)return{success:!1,error:"Install parameters not specified"};let q=M.installParams,I=q.formula||$,U=q.cask||!1,K=q.tap;return Q$("brew",$,Z,async()=>{let _=X??W$({logger:Z,skipCommandLog:!0});await fX(I,U,K,Q?.force,Z,Y,_);let O=await uX(I,Z,Y),B=e(M.binaries,`${O}/bin`),j,V=B[0];if(q.versionArgs&&q.versionRegex&&V)j=await D$({binaryPath:V,args:q.versionArgs,regex:q.versionRegex,shellExecutor:Y});else j=await dX(I,Z,Y);return{success:!0,binaryPaths:B,version:j||void 0,metadata:{method:"brew",formula:I,isCask:U,tap:K}}})}async function dX($,M,J){try{M.debug(d$.fetchingVersion($));let G=(await J`brew info --json ${$}`.quiet().noThrow()).stdout.toString(),Y=JSON.parse(G),X=yM.array(CX).parse(Y);if(X.length>0&&X[0]?.versions.stable){let Z=X[0].versions.stable,q=j$(Z);return M.debug(d$.versionFetched($,q)),q}M.debug(d$.versionNotFound($));return}catch(Q){M.debug(d$.versionFetchFailed($),Q);return}}async function uX($,M,J){try{let G=(await J`brew --prefix ${$}`.quiet()).stdout.toString().trim();return M.debug(d$.prefixFetched($,G)),G}catch(Q){M.debug(d$.prefixFetchFailed($),Q);let Y=`${(await J`brew --prefix`.quiet()).stdout.toString().trim()}/opt/${$}`;return M.debug(d$.prefixFallback($,Y)),Y}}async function fX($,M,J,Q,G,Y,X){if(J){let q=Array.isArray(J)?J:[J];for(let I of q)G.debug(d$.executingCommand(`brew tap ${I}`)),await Y`brew tap ${I}`.quiet()}let Z=["install"];if(M)Z.push("--cask");if(Q)Z.push("--force");Z.push($),G.info(d$.executingCommand(`brew ${Z.join(" ")}`)),await X`brew ${Z}`}import{z as QM}from"zod";var XJ=r.extend({formula:QM.string().optional(),cask:QM.boolean().optional(),tap:QM.union([QM.string(),QM.array(QM.string())]).optional(),versionArgs:QM.array(QM.string()).optional(),versionRegex:QM.string().optional()});import{z as pX}from"zod";var c6=t.extend({installationMethod:pX.literal("brew"),installParams:XJ});var cX="1.0.0";class bQ{shell;method="brew";displayName="Homebrew Installer";version=cX;paramsSchema=XJ;toolConfigSchema=c6;constructor($){this.shell=$}externallyManaged=!0;async install($,M,J,Q,G){let Y=await p6($,M,J,Q,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import{parse as hX}from"smol-toml";import{z as u$}from"zod";class J0 extends Error{statusCode;cause;constructor($,M,J){super($);if(this.name="CargoClientError",this.statusCode=M,this.cause=J,Error.captureStackTrace)Error.captureStackTrace(this,J0)}}var b$={constructor:{initialized:($,M)=>W(`Initializing ${$} with user agent: ${M}`)},request:{makingRequest:($,M)=>W(`Making ${$} request to ${M}`)},errors:{emptyResponse:($)=>W(`Empty response received from ${$}`),jsonParseError:($)=>W(`JSON parse error for ${$}`)},cratesIo:{querying:($)=>W(`Querying crates.io for crate ${$}`),notFound:($)=>W(`Crate not found: ${$}`),metadataError:($)=>W(`Error fetching crate metadata for ${$}`)},parsing:{parsingCrateMetadata:($)=>W(`Parsing Cargo.toml from ${$}`),cargoTomlParseError:($)=>W(`Error parsing Cargo.toml from ${$}`)}};var mX=u$.object({package:u$.object({name:u$.string(),version:u$.string(),edition:u$.string().optional(),description:u$.string().optional(),authors:u$.array(u$.string()).optional(),license:u$.string().optional(),repository:u$.string().optional(),homepage:u$.string().optional()})});class vQ{downloader;logger;cargoConfig;cratesIoCache;githubRawCache;cratesIoCacheEnabled;cratesIoCacheTtl;githubRawCacheEnabled;githubRawCacheTtl;constructor($,M,J,Q,G){this.logger=$.getSubLogger({name:"CargoClient"}),this.downloader=J,this.cratesIoCache=Q,this.githubRawCache=G,this.cargoConfig=M.cargo,this.cratesIoCacheEnabled=this.cargoConfig.cratesIo.cache.enabled&&Boolean(this.cratesIoCache),this.cratesIoCacheTtl=this.cargoConfig.cratesIo.cache.ttl,this.githubRawCacheEnabled=this.cargoConfig.githubRaw.cache.enabled&&Boolean(this.githubRawCache),this.githubRawCacheTtl=this.cargoConfig.githubRaw.cache.ttl,this.logger.getSubLogger({name:"constructor"}).debug(b$.constructor.initialized("CargoClient",this.cargoConfig.userAgent))}async request($,M){this.logger.getSubLogger({name:"request"}).debug(b$.request.makingRequest("GET",$));let Q=this.buildRequestHeaders(),{useCache:G,cacheKey:Y,cacheTtl:X}=this.resolveCacheOptions($,M),Z=await this.tryReadCache(Y,G);if(Z)return Z;let q=await this.performDownload($,Q),I=this.parseJson(q,$);return await this.tryStoreCache(Y,I,X,G),I}resolveCacheOptions($,M){if(!M)return{useCache:!1,cacheTtl:0};let J=M.kind,Q=J==="cratesIo"?this.cratesIoCacheEnabled:this.githubRawCacheEnabled,G=J==="cratesIo"?this.cratesIoCacheTtl:this.githubRawCacheTtl,Y=Q?`cargo:${J}:${$}`:void 0;return{useCache:Q,cacheKey:Y,cacheTtl:G}}async tryReadCache($,M){let J=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!M||!$||!J)return null;try{let Q=await J.get($);if(Q)return Q}catch{}return null}async tryStoreCache($,M,J,Q){let G=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!Q||!$||!G)return;try{await G.set($,M,J)}catch{}}parseJson($,M){let J=this.logger.getSubLogger({name:"parseJson"});if(!$||$.length===0)throw J.error(b$.errors.emptyResponse(M)),new I$(J,"Empty response received from API",M);try{return JSON.parse($.toString("utf-8"))}catch(Q){if(Q instanceof SyntaxError)throw J.error(b$.errors.jsonParseError(M),Q),new J0(`Invalid JSON response from ${M}: ${Q.message}`,void 0,Q);throw Q}}async performDownload($,M){let J=this.logger.getSubLogger({name:"performDownload"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q)throw J.error(b$.errors.emptyResponse($)),new I$(J,"Empty response received from API",$);return Q}buildRequestHeaders(){return{Accept:"application/json","User-Agent":this.cargoConfig.userAgent}}async getCrateMetadata($){let M=this.logger.getSubLogger({name:"getCrateMetadata"});M.debug(b$.cratesIo.querying($));let J=`${this.cargoConfig.cratesIo.host}/api/v1/crates/${$}`;try{return await this.request(J,{kind:"cratesIo"})}catch(Q){if(Q instanceof S$)return M.error(b$.cratesIo.notFound($)),null;throw M.error(b$.cratesIo.metadataError($),Q),Q}}buildCargoTomlUrl($,M="main"){return`${this.cargoConfig.githubRaw.host}/${$}/${M}/Cargo.toml`}async getCargoTomlPackage($){let M=this.logger.getSubLogger({name:"getCargoTomlPackage"});M.debug(b$.parsing.parsingCrateMetadata($));let{useCache:J,cacheKey:Q}=this.resolveCacheOptions($,{kind:"githubRaw"});if(J){let G=await this.tryReadCache(Q,J);if(G)return G}try{let G=await this.downloader.download(M,$,{headers:this.buildRequestHeaders()});if(!G||G.length===0)return M.error(b$.errors.emptyResponse($)),null;let Y=this.parseCargoToml(G);return await this.tryStoreCache(Q,Y,this.githubRawCacheTtl,J),Y}catch(G){if(G instanceof J0)throw G;if(G instanceof S$)return null;throw M.error(b$.parsing.cargoTomlParseError($),G),G}}parseCargoToml($){let M=this.logger.getSubLogger({name:"parseCargoToml"}),J=$.toString("utf-8"),Q=hX(J),G=mX.safeParse(Q);if(!G.success)throw M.zodErrors(G.error),new J0("Could not parse version from Cargo.toml [package] section",void 0);return G.data.package}async getLatestVersion($){return(await this.getCrateMetadata($))?.crate.newest_version||null}}import gX from"path";var K$={installing:($)=>W(`Installing from cargo: ${$}`),foundVersion:($,M)=>W(`Found crate ${$} version ${M}`),downloadingAsset:($,M)=>W(`Downloading asset ${$} from ${M}`),archiveExtracted:()=>W("Archive extracted: %o"),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),parsingMetadata:($)=>W(`Parsing crate metadata from: ${$}`),queryingCratesIo:($)=>W(`Querying crates.io API for crate: ${$}`),queryingGitHubReleases:($)=>W(`Querying GitHub releases for ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($,M)=>W(`Exception while resolving version for ${$}: ${String(M)}`),updateCheckFailed:($)=>W(`Failed to check update for cargo tool: ${$}`)};async function h6($,M,J,Q,G,Y,X,Z,q,I,U){let K=I.getSubLogger({name:"installFromCargo"});if(K.debug(K$.installing($)),!M.installParams)return{success:!1,error:"Install parameters not specified"};let H=M.installParams,_=H.crateName||$;return Q$("cargo",$,K,async()=>{let B=q$(G,$),j=await lX(_,H,X,K);K.debug(K$.foundVersion(_,j.version));let V=await sX(_,j.version,H,J,U);K.debug(K$.downloadingAsset(`${_}-${j.version}`,V));let D=`${_}-${j.version}.tar.gz`,A=gX.join(J.stagingDir,D);await U$(K,V,A,D,Y,Q);let b={...J,version:j.version},k=await nX(M,q,b,A,B,K);if(!k.success)return k;let S=await Z.extract(K,A,{targetDir:J.stagingDir});K.debug(K$.archiveExtracted(),S),await DM(G,$,M,J,J.stagingDir,K);let u=await iX(M,q,b,S,B,K);if(!u.success)return u;if(await G.exists(A))await G.rm(A),K.debug(K$.cleaningArchive(A));let i=e(M.binaries,J.stagingDir),E={method:"cargo",crateName:_,binarySource:H.binarySource||"cargo-quickinstall",downloadUrl:V};return{success:!0,binaryPaths:i,version:j.version,originalTag:j.originalTag,metadata:E}})}async function nX($,M,J,Q,G,Y){let X=$.installParams?.hooks?.["after-download"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,downloadPath:Q},G);for(let q of X){let I=await M.executeHook(Y,"afterDownload",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function iX($,M,J,Q,G,Y){let X=$.installParams?.hooks?.["after-install"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,extractResult:Q},G);for(let q of X){let I=await M.executeHook(Y,"afterInstall",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function lX($,M,J,Q){let G=M.versionSource||"cargo-toml";switch(G){case"cargo-toml":{let Y=M.cargoTomlUrl||J.buildCargoTomlUrl(M.githubRepo||`${$}-community/${$}`);Q.debug(K$.parsingMetadata(Y));let X=await J.getCargoTomlPackage(Y);if(!X)throw Error(`Failed to fetch or parse Cargo.toml from ${Y}`);return{version:j$(X.version)}}case"crates-io":{Q.debug(K$.queryingCratesIo($));let Y=await J.getLatestVersion($);if(!Y)throw Error(`Failed to get latest version for crate ${$} from crates.io`);return{version:j$(Y)}}case"github-releases":{if(!M.githubRepo)throw Error("githubRepo is required when using github-releases version source");return aX(M.githubRepo,Q)}default:throw Error(`Unknown version source: ${G}`)}}async function aX($,M){throw M.debug(K$.queryingGitHubReleases($)),Error("GitHub releases version source not yet implemented")}async function sX($,M,J,Q,G){let Y=J.binarySource||"cargo-quickinstall",X=rX(Q.systemInfo.platform),Z=tX(Q.systemInfo.arch);switch(Y){case"cargo-quickinstall":return`${G}/cargo-bins/cargo-quickinstall/releases/download/${$}-${M}/${$}-${M}-${Z}-${X}.tar.gz`;case"github-releases":{if(!J.githubRepo)throw Error("githubRepo is required when using github-releases binary source");let I=(J.assetPattern||"{crateName}-{version}-{platform}-{arch}.tar.gz").replace("{crateName}",$).replace("{version}",M).replace("{platform}",X).replace("{arch}",Z);return`${G}/${J.githubRepo}/releases/download/v${M}/${I}`}default:throw Error(`Unknown binary source: ${Y}`)}}function rX($){switch($){case 2:return"apple-darwin";case 1:return"unknown-linux-gnu";case 4:return"pc-windows-msvc";default:return"unknown"}}function tX($){switch($){case 2:return"aarch64";case 1:return"x86_64";default:return"unknown"}}import{z as Q0}from"zod";var ZJ=r.extend({crateName:Q0.string(),binarySource:Q0.enum(["cargo-quickinstall","github-releases"]).optional(),githubRepo:Q0.string().optional(),assetPattern:Q0.string().optional(),versionSource:Q0.enum(["cargo-toml","crates-io","github-releases"]).optional(),cargoTomlUrl:Q0.string().optional()});import{z as oX}from"zod";var m6=t.extend({installationMethod:oX.literal("cargo"),installParams:ZJ});var eX="1.0.0";class NQ{fs;downloader;cargoClient;archiveExtractor;hookExecutor;githubHost;method="cargo";displayName="Cargo Installer";version=eX;paramsSchema=ZJ;toolConfigSchema=m6;constructor($,M,J,Q,G,Y){this.fs=$;this.downloader=M;this.cargoClient=J;this.archiveExtractor=Q;this.hookExecutor=G;this.githubHost=Y}async install($,M,J,Q,G){let Y=await h6($,M,J,Q,this.fs,this.downloader,this.cargoClient,this.archiveExtractor,this.hookExecutor,G,this.githubHost);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}async resolveVersion($,M,J,Q){let G=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.crateName;if(!X)return G.debug(K$.versionResolutionFailed($,"Missing crateName in install params")),null;let Z=await this.cargoClient.getLatestVersion(X);if(!Z)return G.debug(K$.versionResolutionFailed($,`Could not fetch version for crate: ${X}`)),null;let q=AM(Z);return G.debug(K$.versionResolutionResolved($,q)),q}catch(Y){return G.debug(K$.versionResolutionException($,Y)),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let Y=M.installParams?.crateName;if(!Y)return{success:!1,error:"Missing crateName in install params"};let X=await this.cargoClient.getLatestVersion(Y);if(!X)return{success:!1,error:`Could not fetch latest version for crate: ${Y}`};let Z=M.version||"latest";if(Z==="latest")return{success:!0,hasUpdate:!1,currentVersion:X,latestVersion:X};return{success:!0,hasUpdate:Z!==X,currentVersion:Z,latestVersion:X}}catch(G){return Q.error(K$.updateCheckFailed($),G),{success:!1,error:G instanceof Error?G.message:"Unknown error"}}}supportsReadme(){return!1}}import WJ from"path";var GM={installing:($)=>W(`Installing from curl-script: toolName=${$}`),downloadingScript:($)=>W(`Downloading install script from: ${$}`),executingScript:($)=>W(`Executing install script using: ${$}`),movingBinary:($,M)=>W(`Moving binary from ${$} to ${M}`),binaryFoundInInstallDir:($)=>W(`Binary found in install directory: ${$}`),binaryNotFound:($,M)=>W(`Binary ${$} not found in search paths: ${M}`),detectedVersion:($)=>W(`Detected version: ${$}`),versionDetectionFailed:($)=>W(`Failed to detect version: ${$}`),noBinariesInstalled:($)=>W(`No binaries were installed. Expected at: ${$}`),scriptOutput:()=>W("Install script output:")};async function $8($,M,J,Q){let G=GJ($.binaries);for(let Y of G){let X=WJ.join(M.stagingDir,Y);if(await J.exists(X)){Q.debug(GM.binaryFoundInInstallDir(X));continue}let Z=["/usr/local/bin",WJ.join(M.systemInfo.homeDir,".local","bin"),"/usr/bin"],q=!1;for(let I of Z){let U=WJ.join(I,Y);if(await J.exists(U)){Q.debug(GM.movingBinary(U,X)),await J.copyFile(U,X),await J.chmod(X,493),q=!0;break}}if(!q)Q.warn(GM.binaryNotFound(Y,`${M.stagingDir}, ${Z.join(", ")}`))}}async function g6($,M,J,Q,G,Y,X,Z,q,I){let U=q$(G,$),K=Z.getSubLogger({name:"installFromCurlScript"});if(K.debug(GM.installing($)),!M.installParams||!("url"in M.installParams)||!("shell"in M.installParams))return{success:!1,error:"URL or shell not specified in installParams"};let H=M.installParams,_=H.url,O=H.shell;return Q$("curl-script",$,K,async()=>{K.debug(GM.downloadingScript(_));let j=WJ.join(J.stagingDir,`${$}-install.sh`);await U$(K,_,j,`${$}-install.sh`,Y,Q),await U.chmod(j,493);let V={...J,downloadPath:j},D=await w$(M,V,X,G,K);if(!D.success)return D;K.debug(GM.executingScript(O));let A={projectConfig:J.projectConfig,scriptPath:j,stagingDir:J.stagingDir},b=H.args?await wM(A,H.args):[],k=H.env?await wM(A,H.env):{},S={...process.env,...k},u=I??W$({logger:K,skipCommandLog:!0}),i="";if(O==="bash"){let y=await u`bash ${j} ${b}`.env(S);i=[y.stdout,y.stderr].filter(Boolean).join(`
|
|
70
|
-
`)}else{let y=await u`sh ${j} ${
|
|
71
|
-
`)}await
|
|
72
|
-
`))K.error(W(O$))}return{success:!1,error:`Installation script completed but no binaries were found at expected locations: ${y}`}}let $$,g=E[0];if(g)$$=await D$({shellExecutor:q,binaryPath:g,args:H.versionArgs,regex:H.versionRegex});return{success:!0,binaryPaths:E,metadata:{method:"curl-script",scriptUrl:_,shell:O},version:$$||(M.version!=="latest"?M.version:void 0)}})}import{z as PM}from"zod";var qJ=r.extend({url:PM.string().url(),shell:PM.enum(["bash","sh"]),args:PM.custom().optional(),env:PM.custom().optional(),versionArgs:PM.array(PM.string()).optional(),versionRegex:PM.string().optional()});import{z as IJ}from"zod";var n6=t.extend({installationMethod:IJ.literal("curl-script"),installParams:qJ,binaries:IJ.array(IJ.union([IJ.string().min(1),Z$])).min(1)});var M8="1.0.0";class yQ{fs;downloader;hookExecutor;shell;method="curl-script";displayName="Curl Script Installer";version=M8;paramsSchema=qJ;toolConfigSchema=n6;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,G){let Y=await g6($,M,J,Q,this.fs,this.downloader,this.hookExecutor,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,metadata:Y.metadata,version:Y.version}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import J8 from"path";var G0={installing:($)=>W(`Installing from curl-tar: toolName=${$}`),downloadingArchive:($)=>W(`Downloading archive from: ${$}`),downloadingTarball:($)=>W(`Downloading tarball from: ${$}`),extractingTarball:()=>W("Extracting tarball"),tarballExtracted:()=>W("Tarball extracted successfully"),archiveExtracted:()=>W("Archive extracted: %o"),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`)};async function i6($,M,J,Q,G,Y,X,Z,q,I){let U=q$(G,$),K=q.getSubLogger({name:"installFromCurlTar"});K.debug(G0.installing($));let H,_;if(!M.installParams||!("url"in M.installParams))return{success:!1,error:"URL not specified in installParams"};let O=M.installParams,B=O.url;return Q$("curl-tar",$,K,async()=>{K.debug(G0.downloadingTarball(B));let V=J8.join(J.stagingDir,`${$}.tar.gz`);await U$(K,B,V,`${$}.tar.gz`,Y,Q),H={...J,downloadPath:V};let D=await w$(M,H,Z,G,K);if(!D.success)return{success:!1,error:D.error};K.debug(G0.extractingTarball());let A=await X.extract(K,V,{targetDir:J.stagingDir});K.debug(G0.tarballExtracted(),A),_={...H,extractDir:J.stagingDir,extractResult:A};let b=await eM(M,_,Z,G,K);if(!b.success)return{success:!1,error:b.error};if(await DM(U,$,M,J,J.stagingDir,K),await U.exists(V))K.debug(G0.cleaningArchive(V)),await U.rm(V);let k=e(M.binaries,J.stagingDir),S,u=k[0];if(u)S=await D$({binaryPath:u,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});return{success:!0,binaryPaths:k,metadata:{method:"curl-tar",downloadUrl:B,tarballUrl:B},version:S||(M.version!=="latest"?M.version:void 0)}})}import{z as UJ}from"zod";var KJ=r.extend({url:UJ.string().url(),versionArgs:UJ.array(UJ.string()).optional(),versionRegex:UJ.string().optional()});import{z as HJ}from"zod";var l6=t.extend({installationMethod:HJ.literal("curl-tar"),installParams:KJ,binaries:HJ.array(HJ.union([HJ.string().min(1),Z$])).min(1)});var Q8="1.0.0";class PQ{fs;downloader;archiveExtractor;hookExecutor;shell;method="curl-tar";displayName="Curl Tar Installer";version=Q8;paramsSchema=KJ;toolConfigSchema=l6;constructor($,M,J,Q,G){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=G}async install($,M,J,Q,G){let Y=await i6($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function a6($){let M=/\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?/,J=$.match(M);if(!J||J.index===void 0)return"";return $.slice(0,J.index)}function s6($){let M=/(\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?)/,J=$.match(M);if(!J)return $;let Q=J[1];if(!Q)return $;return Q}function r6($,M){let J=a6($),Q=s6(M);return`${J}${Q}`}import G8 from"crypto";import CQ from"semver";class a extends Error{originalError;statusCode;constructor($,M,J){super($);this.name="GitHubApiClientError",this.statusCode=M,this.originalError=J,Object.setPrototypeOf(this,a.prototype)}}var z={constructor:{initialized:($,M)=>W(`GitHub API client initialized with base URL ${$} and User-Agent ${M}`),authTokenPresent:()=>W("GitHub token authentication enabled"),authTokenMissing:()=>W("No GitHub token provided; requests will be unauthenticated")},ghCli:{initialized:($)=>W(`GitHub CLI API client initialized for hostname ${$}`),executing:($)=>W(`Executing gh api request for ${$}`),cacheHit:($)=>W(`Cache hit for gh api ${$}`),cacheMiss:($)=>W(`Cache miss for gh api ${$}`),commandFailed:($)=>W(`gh cli command failed with exit code ${$}`),parseError:($)=>W(`Failed to parse gh api response for ${$}`),notAvailable:()=>W("gh cli is not available or not authenticated"),downloadingAsset:($,M,J)=>W(`Downloading ${$} from ${M}@${J} via gh release download`),downloadComplete:($)=>W(`Downloaded ${$} via gh cli`),downloadFailed:($,M)=>W(`gh release download failed for ${$} with exit code ${M}`)},cache:{enabled:($)=>W(`GitHub API cache enabled with TTL ${$} ms`),disabled:()=>W("GitHub API cache provided but disabled by configuration"),missing:()=>W("No GitHub API cache provided; responses will not be cached")},request:{performing:($,M)=>W(`GitHub API ${$} request to ${M}`),emptyResponse:($)=>W(`GitHub API returned an empty response buffer for ${$}`)},errors:{requestFailure:($)=>W(`GitHub API request failure for ${$}`),notFound:($)=>W(`GitHub resource not found for ${$}`),rateLimit:($,M)=>W(`GitHub API rate limit exceeded for ${$}, resets at ${M}`),forbidden:($)=>W(`GitHub API request forbidden for ${$}`),client:($,M)=>W(`GitHub API client error for ${$} with status ${M}`),server:($,M)=>W(`GitHub API server error for ${$} with status ${M}`),http:($,M)=>W(`GitHub API HTTP error for ${$} with status ${M}`),network:($)=>W(`GitHub API network error for ${$}`),unknown:($)=>W(`Unknown GitHub API error for ${$}`),constraintLatestError:()=>W("GitHub API latest constraint lookup failed"),constraintError:($,M,J)=>W(`GitHub API error while evaluating constraint ${$} for ${M}/${J}`)},releases:{fetchingLatest:($,M)=>W(`Fetching latest GitHub release for ${$}/${M}`),latestNotFound:($,M)=>W(`Latest GitHub release not found for ${$}/${M}`),latestError:($,M)=>W(`Error fetching latest GitHub release for ${$}/${M}`),fetchingByTag:($,M,J)=>W(`Fetching GitHub release ${$} for ${M}/${J}`),tagNotFound:($,M,J)=>W(`GitHub release ${$} not found for ${M}/${J}`),tagError:($,M,J)=>W(`Error fetching GitHub release ${$} for ${M}/${J}`),fetchingAll:($,M)=>W(`Fetching all GitHub releases for ${$}/${M}`),fetchingPage:($,M)=>W(`Fetching GitHub releases page ${$} via ${M}`),totalFetched:($,M,J)=>W(`Fetched ${$} GitHub releases for ${M}/${J}`),filteredPrereleases:($)=>W(`Filtered prereleases leaving ${$} GitHub releases`),fetchingLatestTags:($,M,J)=>W(`Fetching ${J} latest release tags for ${$}/${M}`),fetchedTags:($)=>W(`Fetched ${$} release tags`),fetchTagsError:($,M)=>W(`Error fetching release tags for ${$}/${M}`)},constraints:{searching:($,M,J)=>W(`Searching for GitHub release matching constraint ${$} in ${M}/${J}`),pageFetch:($)=>W(`Iterating GitHub releases pages for constraint ${$}`),pageRequest:($,M,J)=>W(`Fetching GitHub releases page ${$} for ${M}/${J}`),bestCandidate:($,M)=>W(`Best GitHub release candidate so far ${$} (version ${M})`),resultFound:($,M)=>W(`Found GitHub release ${M} for constraint ${$}`),resultMissing:($)=>W(`No GitHub release found for constraint ${$}`)},rateLimit:{fetching:()=>W("Fetching GitHub API rate limit status")},tagPattern:{probing:($,M)=>W(`Probing release tag pattern for ${$}/${M}`),detected:($)=>W(`Detected latest release tag: ${$}`),noRedirect:($,M)=>W(`No redirect found for ${$}/${M} latest release`),probeFailed:($,M)=>W(`Failed to probe tag pattern for ${$}/${M}`)}};class _J{hostname;shell;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q){this.logger=$.getSubLogger({name:"GhCliApiClient"}),this.hostname=this.extractHostname(M.github.host),this.shell=J,this.cache=Q,this.cacheEnabled=M.github.cache.enabled,this.cacheTtlMs=M.github.cache.ttl;let G=this.logger.getSubLogger({name:"constructor"});if(G.debug(z.ghCli.initialized(this.hostname)),this.cache&&this.cacheEnabled)G.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)G.debug(z.cache.disabled());else G.debug(z.cache.missing())}extractHostname($){try{let M=new URL($);if(M.hostname==="api.github.com")return"github.com";return M.hostname.replace(/^api\./,"")}catch{return"github.com"}}generateCacheKey($,M){let J=`${M}:${$}`,Q=G8.createHash("sha256").update("gh-cli").digest("hex").substring(0,8);return J+=`:${Q}`,J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=this.generateCacheKey($,M),G=await this.tryGetFromCache(Q,M,$);if(G)return G;J.debug(z.ghCli.executing($));let Y=this.buildGhApiArgs($,M);try{let X=await this.executeGhCommand($,Y);return await this.tryCacheResponse(Q,X,M),X}catch(X){return this.handleRequestError(X,$)}}buildGhApiArgs($,M){let J=["api"];if(this.hostname!=="github.com")J.push("--hostname",this.hostname);if(M!=="GET")J.push("--method",M);let Q=$.startsWith("/")?$.substring(1):$;return J.push(Q),J}async executeGhCommand($,M){let J=this.logger.getSubLogger({name:"executeGhCommand"}),Q=["gh",...M].join(" "),G=await this.shell(Q).quiet().noThrow();if(G.code!==0)throw J.debug(z.ghCli.commandFailed(G.code)),this.parseGhError(G.stderr,G.code,$);try{return JSON.parse(G.stdout)}catch{throw J.debug(z.ghCli.parseError($)),new a(`Failed to parse gh api response for ${$}`,void 0)}}parseGhError($,M,J){let Q=$.toLowerCase();if(Q.includes("not found")||Q.includes("404"))return new a(`GitHub resource not found: ${J}. Status: 404`,404);if(Q.includes("rate limit")||Q.includes("403"))return new a(`GitHub API rate limit exceeded for ${J}. Status: 403`,403);if(Q.includes("unauthorized")||Q.includes("401"))return new a(`GitHub API unauthorized for ${J}. Status: 401`,401);if(Q.includes("forbidden"))return new a(`GitHub API forbidden for ${J}. Status: 403`,403);return new a(`gh api command failed for ${J} with exit code ${M}: ${$}`,void 0)}async tryGetFromCache($,M,J){let Q=this.logger.getSubLogger({name:"tryGetFromCache"});if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let G=await this.cache.get($);if(G)return Q.debug(z.ghCli.cacheHit(J)),G;Q.debug(z.ghCli.cacheMiss(J))}catch{}return null}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){if(this.logger.getSubLogger({name:"handleRequestError"}).debug(z.errors.requestFailure(M),$),$ instanceof a)throw $;if($ instanceof Error)throw new a(`Error during gh api request to ${M}: ${$.message}`,void 0,$);throw new a(`Unknown error during gh api request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(z.releases.fetchingLatest($,M));try{return await this.request(`/repos/${$}/${M}/releases/latest`)}catch(Q){if(Q instanceof a&&Q.statusCode===404)return J.debug(z.releases.latestNotFound($,M)),null;throw J.debug(z.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(z.releases.fetchingByTag(J,$,M));try{return await this.request(`/repos/${$}/${M}/releases/tags/${J}`)}catch(G){if(G instanceof a&&G.statusCode===404)return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),G),G}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let G=J?.perPage||30,Y=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${G}&page=${X}`;Q.debug(z.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{if(Z=Z.concat(U),X++,U.length<G)q=!1;if(Y!==void 0&&Z.length>=Y)Z=Z.slice(0,Y),q=!1}}if(Q.debug(z.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(z.releases.filteredPrereleases(I.length)),I}return Z}async getReleaseByConstraint($,M,J){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(J,$,M)),J==="latest")return await this.handleLatestConstraint($,M);return await this.findReleaseByVersionConstraint($,M,J)}async handleLatestConstraint($,M){try{return await this.getLatestRelease($,M)}catch(J){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),J),null}}async findReleaseByVersionConstraint($,M,J){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(J));let G=null,Y=null,X=1,Z=30,q=100;while(X<=q){let I=await this.fetchReleasesPage($,M,X,Z,J);if(!I)break;if(I.length===0)break;let U=this.findBestReleaseFromPage(I,J,G,Y);if(U.release)G=U.release,Y=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,G),G}async fetchReleasesPage($,M,J,Q,G){let Y=`/repos/${$}/${M}/releases?per_page=${Q}&page=${J}`,X=this.logger.getSubLogger({name:"fetchReleasesPage"});X.debug(z.constraints.pageRequest(J,$,M));try{return await this.request(Y)}catch(Z){return X.debug(z.errors.constraintError(G,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let G=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),Y=J,X=Q;for(let Z of $){if(!Z.tag_name)continue;let q=Z.tag_name.startsWith("v")?Z.tag_name.substring(1):Z.tag_name;if(this.isVersionSatisfying(q,M)){if(this.isBetterVersion(q,X))Y=Z,X=q,G.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:Y,version:X}}isVersionSatisfying($,M){return Boolean(CQ.valid($))&&CQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||CQ.gt($,M)}logConstraintResult($,M){let J=this.logger.getSubLogger({name:"logConstraintResult"});if(M)J.debug(z.constraints.resultFound($,M.tag_name));else J.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(z.releases.fetchingLatestTags($,M,J));try{let Y=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(Y.length)),Y}catch(G){return Q.debug(z.releases.fetchTagsError($,M),G),[]}}async probeLatestTag($,M){let J=this.logger.getSubLogger({name:"probeLatestTag"});J.debug(z.tagPattern.probing($,M));try{let Q=await this.getLatestRelease($,M);if(Q)return J.debug(z.tagPattern.detected(Q.tag_name)),Q.tag_name;return null}catch{return J.debug(z.tagPattern.probeFailed($,M)),null}}async downloadAsset($,M,J,Q,G){let Y=this.logger.getSubLogger({name:"downloadAsset"});Y.debug(z.ghCli.downloadingAsset(Q,`${$}/${M}`,J));let X=G.substring(0,G.lastIndexOf("/")),Z=["release","download",J];if(Z.push("--repo",`${$}/${M}`),Z.push("--pattern",Q),Z.push("--dir",X),Z.push("--clobber"),this.hostname!=="github.com");let q=["gh",...Z].join(" "),I=await this.shell(q).quiet().noThrow();if(I.code!==0)throw Y.debug(z.ghCli.downloadFailed(Q,I.code)),new a(`gh release download failed for ${Q}: ${I.stderr.trim()||`exit code ${I.code}`}`,void 0);Y.debug(z.ghCli.downloadComplete(Q))}}import Y8 from"crypto";import dQ from"semver";class RJ{baseUrl;githubToken;downloader;userAgent;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q){this.logger=$.getSubLogger({name:"GitHubApiClient"}),this.baseUrl=M.github.host,this.githubToken=M.github.token,this.downloader=J,this.userAgent=M.github.userAgent,this.cache=Q,this.cacheEnabled=M.github.cache.enabled,this.cacheTtlMs=M.github.cache.ttl;let G=this.logger.getSubLogger({name:"constructor"});if(G.debug(z.constructor.initialized(this.baseUrl,this.userAgent)),this.githubToken)G.debug(z.constructor.authTokenPresent());else G.debug(z.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)G.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)G.debug(z.cache.disabled());else G.debug(z.cache.missing())}generateCacheKey($,M){let J=`${M}:${$}`;if(this.githubToken&&typeof this.githubToken==="string"&&this.githubToken.length>0){let Q=Y8.createHash("sha256").update(this.githubToken).digest("hex").substring(0,8);J+=`:${Q}`}return J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=`${this.baseUrl}${$}`,G=this.generateCacheKey($,M),Y=await this.tryGetFromCache(G,M);if(Y)return Y;J.debug(z.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(G,Z,M),Z}catch(Z){return this.handleRequestError(Z,Q)}}async tryGetFromCache($,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let J=await this.cache.get($);if(J)return J}catch{}return null}buildRequestHeaders(){let $={Accept:"application/vnd.github.v3+json","User-Agent":this.userAgent};if(this.githubToken)$.Authorization=`token ${this.githubToken}`;return $}async performRequest($,M){let J=this.logger.getSubLogger({name:"performRequest"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q||Q.length===0)throw J.debug(z.request.emptyResponse($)),new I$(this.logger,"Empty response received from API",$);let G=Q.toString("utf-8");return JSON.parse(G)}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){let J=this.logger.getSubLogger({name:"handleRequestError"});if(J.debug(z.errors.requestFailure(M),$),$ instanceof S$)throw J.debug(z.errors.notFound(M),$.responseBody),Error(`GitHub resource not found: ${M}. Status: ${$.statusCode}`);if($ instanceof zM)return this.handleRateLimitError($,M);if($ instanceof bM)return this.handleForbiddenError($,M);if($ instanceof vM)return this.handleClientError($,M);if($ instanceof NM)return this.handleServerError($,M);if($ instanceof E$)return this.handleHttpError($,M);if($ instanceof I$)return this.handleNetworkError($,M);return this.handleUnknownError($,M)}handleRateLimitError($,M){let J=this.logger.getSubLogger({name:"handleRateLimitError"}),Q=$.resetTimestamp?new Date($.resetTimestamp).toISOString():"N/A";throw J.debug(z.errors.rateLimit(M,Q),$.responseBody),new a(`GitHub API rate limit exceeded for ${M}. Status: ${$.statusCode}. Resets at ${Q}.`,$.statusCode,$)}handleForbiddenError($,M){throw this.logger.getSubLogger({name:"handleForbiddenError"}).debug(z.errors.forbidden(M),$.responseBody),new a(`GitHub API request forbidden for ${M}. Status: ${$.statusCode}.`,$.statusCode,$)}handleClientError($,M){throw this.logger.getSubLogger({name:"handleClientError"}).debug(z.errors.client(M,$.statusCode),$.responseBody),new a(`GitHub API client error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleServerError($,M){throw this.logger.getSubLogger({name:"handleServerError"}).debug(z.errors.server(M,$.statusCode),$.responseBody),new a(`GitHub API server error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleHttpError($,M){throw this.logger.getSubLogger({name:"handleHttpError"}).debug(z.errors.http(M,$.statusCode),$),new a(`GitHub API HTTP error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleNetworkError($,M){throw this.logger.getSubLogger({name:"handleNetworkError"}).debug(z.errors.network(M),$),new a(`Network error while requesting ${M}: ${$.message}`,void 0,$)}handleUnknownError($,M){if(this.logger.getSubLogger({name:"handleUnknownError"}).debug(z.errors.unknown(M),$),$ instanceof Error)throw new a(`Unknown error during GitHub API request to ${M}: ${$.message}`,void 0,$);throw new a(`Unknown error during GitHub API request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(z.releases.fetchingLatest($,M));try{return await this.request(`/repos/${$}/${M}/releases/latest`)}catch(Q){if(Q instanceof Error&&Q.message.includes("GitHub resource not found"))return J.debug(z.releases.latestNotFound($,M)),null;throw J.debug(z.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(z.releases.fetchingByTag(J,$,M));try{return await this.request(`/repos/${$}/${M}/releases/tags/${J}`)}catch(G){if(G instanceof Error&&G.message.includes("GitHub resource not found"))return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),G),G}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let G=J?.perPage||30,Y=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${G}&page=${X}`;Q.debug(z.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{if(Z=Z.concat(U),X++,U.length<G)q=!1;if(Y!==void 0&&Z.length>=Y)Z=Z.slice(0,Y),q=!1}}if(Q.debug(z.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(z.releases.filteredPrereleases(I.length)),I}return Z}async getReleaseByConstraint($,M,J){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(J,$,M)),J==="latest")return await this.handleLatestConstraint($,M);return await this.findReleaseByVersionConstraint($,M,J)}async handleLatestConstraint($,M){try{return await this.getLatestRelease($,M)}catch(J){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),J),null}}async findReleaseByVersionConstraint($,M,J){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(J));let G=null,Y=null,X=1,Z=30,q=100;while(X<=q){let I=await this.fetchReleasesPage($,M,X,Z,J);if(!I)break;if(I.length===0)break;let U=this.findBestReleaseFromPage(I,J,G,Y);if(U.release)G=U.release,Y=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,G),G}async fetchReleasesPage($,M,J,Q,G){let Y=`/repos/${$}/${M}/releases?per_page=${Q}&page=${J}`,X=this.logger.getSubLogger({name:"fetchReleasesPage"});X.debug(z.constraints.pageRequest(J,$,M));try{return await this.request(Y)}catch(Z){return X.debug(z.errors.constraintError(G,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let G=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),Y=J,X=Q;for(let Z of $){if(!Z.tag_name)continue;let q=Z.tag_name.startsWith("v")?Z.tag_name.substring(1):Z.tag_name;if(this.isVersionSatisfying(q,M)){if(this.isBetterVersion(q,X))Y=Z,X=q,G.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:Y,version:X}}isVersionSatisfying($,M){return Boolean(dQ.valid($))&&dQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||dQ.gt($,M)}logConstraintResult($,M){let J=this.logger.getSubLogger({name:"logConstraintResult"});if(M)J.debug(z.constraints.resultFound($,M.tag_name));else J.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(z.releases.fetchingLatestTags($,M,J));try{let Y=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(Y.length)),Y}catch(G){return Q.debug(z.releases.fetchTagsError($,M),G),[]}}async probeLatestTag($,M){let J=this.logger.getSubLogger({name:"probeLatestTag"});J.debug(z.tagPattern.probing($,M));let Q=`https://github.com/${$}/${M}/releases/latest`;try{let Y=(await fetch(Q,{method:"HEAD",redirect:"manual"})).headers.get("location");if(!Y)return J.debug(z.tagPattern.noRedirect($,M)),null;let Z=Y.match(/\/releases\/tag\/(.+)$/)?.[1];if(!Z)return J.debug(z.tagPattern.noRedirect($,M)),null;let q=decodeURIComponent(Z);return J.debug(z.tagPattern.detected(q)),q}catch(G){return J.debug(z.tagPattern.probeFailed($,M),G),null}}}function uQ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function t6($){let M=$.system.length>0?`(${$.system.map(uQ).join("|")})`:"",J=$.cpu.length>0?`(${$.cpu.map(uQ).join("|")})`:"",Q=$.variants.length>0?`(${$.variants.map(uQ).join("|")})`:"";return{systemPattern:M,cpuPattern:J,variantPattern:Q}}function OJ($){let M={system:[],cpu:[],variants:[]};switch($.platform){case 2:M.system=["apple","darwin","apple-darwin","dmg","mac","macos","mac-os","osx","os-x","os64x"],M.variants=["darwin"];break;case 1:M.system=["linux"],M.variants=["musl","gnu","unknown-linux"];break;case 4:M.system=["windows","win32","win64","pc-windows-gnu"],M.variants=["mingw","msys","cygwin","pc-windows"];break;default:M.system=[],M.variants=[];break}switch($.arch){case 2:M.cpu=["arm64","aarch64","aarch"];break;case 1:M.cpu=["amd64","x86_64","x64","x86-64"];break;default:M.cpu=[];break}return M}function o6($){let M=OJ($);return t6(M)}var X8=[/\.sha\d+(sum)?$/i,/\.md5(sum)?$/i,/\.sum$/i,/^shasums/i,/\.sig$/i,/\.asc$/i,/\.pem$/i,/\.json$/i,/\.txt$/i,/\.sbom$/i,/\.deb$/i,/\.rpm$/i,/\.apk$/i,/\.pkg$/i,/buildable-artifact/i,/\.vsix$/i,/\.b3$/i,/\.zst$/i];function Z8($){let M=$.filter((J)=>!X8.some((Q)=>Q.test(J)));return M.length>0?M:$}function W8($,M){let J=new RegExp(M,"i"),Q=$.filter((G)=>J.test(G.toLowerCase()));return Q.length>0?Q:$}function jJ($,M){let J=o6(M),Q=OJ(M),G=Z8($),Y;if(J.systemPattern){let Z=new RegExp(J.systemPattern,"i");Y=G.filter((q)=>Z.test(q.toLowerCase()))}else Y=[...G];if(Y.length===0)return;let X=[];if(J.cpuPattern)X.push(J.cpuPattern);X.push(...Q.variants);for(let Z of X){if(Y.length<=1)break;Y=W8(Y,Z)}return Y[0]}import U8 from"path";var P={startingInstallation:($)=>W(`Starting installation: ${$}`),fetchLatest:($)=>W(`Getting latest release for ${$}`),fetchByTag:($,M)=>W(`Fetching release ${$} for ${M}`),assetSelectorCustom:()=>W("Using custom asset selector"),assetPatternMatch:($)=>W(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,M)=>W(`Selecting asset for platform ${$} and architecture ${M}`),determiningDownloadUrl:($,M)=>W(`Determining download URL. rawBrowserDownloadUrl="${$}", hasCustomHost=${M}`),usingAbsoluteUrl:($)=>W(`Using absolute browser_download_url directly: "${$}"`),invalidRelativeUrl:($)=>W(`Invalid asset download URL format: ${$}`),resolvedRelativeUrl:($,M,J)=>W(`Resolved relative URL. Base: "${$}", Relative Path: "${M}", Result: "${J}"`),finalDownloadUrl:($,M,J)=>W(`Final download URL determined. Raw: "${$}", Result: "${M}", hasCustomHost=${J}`),downloadUrlError:($,M)=>W(`Download URL construction failed: Raw: "${$}", hasCustomHost=${M}`),downloadingAsset:($)=>W(`Downloading asset: ${$}`),downloadingViaGhCli:($)=>W(`Downloading ${$} via gh release download (authenticated)`),downloadingViaHttp:($)=>W(`Downloading ${$} via HTTP`),extractingArchive:($)=>W(`Extracting archive: ${$}`),archiveExtracted:($,M)=>W(`Archive extracted. fileCount=${$}, executableCount=${M}`),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),invalidUrl:($)=>W(`Invalid URL: ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($)=>W(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>W(`Failed to check update for ${$}`),detectingTagPattern:()=>W("Detecting tag pattern from latest release"),tagPatternDetectionFailed:()=>W("Failed to detect tag pattern"),tryingCorrectedTag:($,M)=>W(`Trying corrected tag '${$}' (original: '${M}')`),usingCorrectedTag:($,M)=>W(`Found release with corrected tag '${$}' (you specified: '${M}')`),availableReleaseTags:()=>W("Available release tags:"),releaseTagItem:($)=>W(` - ${$}`),noReleaseTagsAvailable:()=>W("No release tags available for this repository")};import{minimatch as q8}from"minimatch";function I8($){return/^[dgimsuvy]*$/.test($)}function e6($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function $Y($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!I8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function MY($){if(!e6($))return!0;try{return $Y($),!0}catch{return!1}}function JY($){if(typeof $==="string")return $;return $.toString()}function QY($,M){if(typeof M==="string"){if(e6(M))return $Y(M).test($);return q8($,M)}return M.test($)}async function YY($,M,J,Q,G,Y,X,Z,q,I,U){let K=U.getSubLogger({name:"installFromGitHubRelease"});if(K.debug(P.startingInstallation($)),!M.installParams||!("repo"in M.installParams))return{success:!1,error:"GitHub repository not specified in installParams"};let H=M.installParams,_=H.repo,O=H.version||"latest",[B,j]=_.split("/");if(!B||!j)return{success:!1,error:`Invalid GitHub repository format: ${_}. Expected format: owner/repo`};try{let V=await A0(_,O,H.prerelease??!1,X,K);if(!V.success)return V;let D=await fQ(V.data,H,J,K);if(!D.success)return D;let A=O8(D.data.browser_download_url,q,K);if(!A.success)return A;let b=U8.join(J.stagingDir,D.data.name),k=await B8(A.data,D.data,Y,X,B,j,V.data.tag_name,b,Q,K);if(!k.success)return k;let S={...J,downloadPath:k.data.downloadPath},u=await D8(M,S,I,G,K);if(!u.success)return u;let i=j$(V.data.tag_name),E=await A8(D.data,k.data.downloadPath,$,M,J,S,G,Z,I,G,K);if(!E.success)return E;let m=e(M.binaries,J.stagingDir),$$={method:"github-release",releaseUrl:V.data.html_url,publishedAt:V.data.published_at,releaseName:V.data.name,downloadUrl:A.data,assetName:D.data.name};return{success:!0,binaryPaths:m,version:i,originalTag:V.data.tag_name,metadata:$$}}catch(V){return{success:!1,error:V instanceof Error?V.message:String(V)}}}var K8=5;async function A0($,M,J,Q,G){let Y=G.getSubLogger({name:"fetchGitHubRelease"}),[X,Z]=$.split("/");if(!X||!Z)return{success:!1,error:`Invalid GitHub repository format: ${$}. Expected format: owner/repo`};if(M==="latest"){if(Y.debug(P.fetchLatest($)),J){let O=(await Q.getAllReleases(X,Z,{perPage:1,includePrerelease:!0,limit:1}))[0];if(!O)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:O}}let K=await Q.getLatestRelease(X,Z);if(!K)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:K}}Y.debug(P.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};let I=await H8(X,Z,M,Q,Y);if(I)return{success:!0,data:I};return await _8(X,Z,Q,Y),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function H8($,M,J,Q,G){let Y=G.getSubLogger({name:"fetchWithTagPatternDetection"});Y.debug(P.detectingTagPattern());let X=await Q.probeLatestTag($,M);if(!X)return Y.debug(P.tagPatternDetectionFailed()),null;let Z=r6(X,J);if(Z!==J){Y.debug(P.tryingCorrectedTag(Z,J));let q=await Q.getReleaseByTag($,M,Z);if(q)return Y.info(P.usingCorrectedTag(Z,J)),q}return null}async function _8($,M,J,Q){let G=Q.getSubLogger({name:"showAvailableReleaseTags"}),Y=await J.getLatestReleaseTags($,M,K8);if(Y.length===0){G.error(P.noReleaseTagsAvailable());return}G.info(P.availableReleaseTags());for(let X of Y)G.info(P.releaseTagItem(X))}async function fQ($,M,J,Q){let G;if(M.assetSelector){Q.debug(P.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};G=M.assetSelector(X)}else if(M.assetPattern){Q.debug(P.assetPatternMatch(JY(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>QY(q.name,X));if(G=GY(Z,J.systemInfo),!G&&Z.length>0)G=Z[0]}else Q.debug(P.assetPlatformMatch(t$(J.systemInfo.platform),o$(J.systemInfo.arch))),G=GY($.assets,J.systemInfo);if(!G)return{success:!1,error:R8($,M,J)};return{success:!0,data:G}}function GY($,M){let J=$.map((G)=>G.name),Q=jJ(J,M);if(!Q)return;return $.find((G)=>G.name===Q)}function R8($,M,J){let Q=$.assets.map((q)=>q.name),G=t$(J.systemInfo.platform),Y=o$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${G}/${Y}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${G}/${Y}.`;else X=`for platform "${G}" and architecture "${Y}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
|
|
73
|
-
`)}function O8($,M,J){let Q=M.github.host,G=Boolean(Q);J.debug(P.determiningDownloadUrl($,G));try{let X=j8($)?V8($,J):z8($,Q,J);if(!X.success)return X;return J.debug(P.finalDownloadUrl($,X.data,G)),X}catch(Y){return J.error(P.invalidUrl($)),J.debug(P.downloadUrlError($,G),Y),{success:!1,error:Y instanceof Error?Y.message:String(Y)}}}function j8($){return URL.canParse($)}function V8($,M){return M.debug(P.usingAbsoluteUrl($)),{success:!0,data:$}}function z8($,M,J){if(!$.startsWith("/"))return J.debug(P.invalidRelativeUrl($)),{success:!1,error:`Invalid asset download URL format: ${$}`};let Q=M&&!M.includes("api.github.com")?M:"https://github.com";if(!/^https?:\/\//.test(Q))Q=`https:${Q.startsWith("//")?"":"//"}${Q}`;let Y=new URL($,Q).toString();return J.debug(P.resolvedRelativeUrl(Q,$,Y)),{success:!0,data:Y}}async function B8($,M,J,Q,G,Y,X,Z,q,I){if(Q.downloadAsset){I.debug(P.downloadingViaGhCli(M.name));try{return await Q.downloadAsset(G,Y,X,M.name,Z),{success:!0,data:{downloadPath:Z}}}catch(U){I.debug(P.downloadingAsset($),U instanceof Error?U:Error(String(U)))}}I.debug(P.downloadingViaHttp(M.name));try{return await U$(I,$,Z,M.name,J,q),{success:!0,data:{downloadPath:Z}}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}async function D8($,M,J,Q,G){let Y=await w$($,M,J,Q,G);if(Y.success)return{success:!0,data:void 0};return{success:!1,error:Y.error||"Hook execution failed"}}async function A8($,M,J,Q,G,Y,X,Z,q,I,U){if(CM($.name))return await E8($,M,J,Q,G,Y,X,Z,q,I,U);else return await $0(X,J,Q,G,M,U),{success:!0,data:void 0}}async function E8($,M,J,Q,G,Y,X,Z,q,I,U){U.debug(P.extractingArchive($.name));let K=await Z.extract(U,M,{targetDir:G.stagingDir});U.debug(P.archiveExtracted(K.extractedFiles.length,K.executables.length));let H={...Y,extractDir:G.stagingDir,extractResult:K},_=await F8(Q,H,I,q,U);if(!_.success)return _;if(await DM(X,J,Q,G,G.stagingDir,U),await X.exists(M))U.debug(P.cleaningArchive(M)),await X.rm(M);return{success:!0,data:void 0}}async function F8($,M,J,Q,G){let Y=await eM($,M,Q,J,G);if(Y.success)return{success:!0,data:void 0};return{success:!1,error:Y.error||"Hook execution failed"}}import{z as EM}from"zod";var Y0=r.extend({repo:EM.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:EM.union([EM.string().refine(MY,"assetPattern must be a valid glob or a regex string like /.../"),EM.instanceof(RegExp)]).optional(),version:EM.string().optional(),assetSelector:EM.custom(($)=>typeof $==="function","Must be a function").optional(),ghCli:EM.boolean().optional(),prerelease:EM.boolean().optional()});import{z as VJ}from"zod";var XY=t.extend({installationMethod:VJ.literal("github-release"),installParams:Y0,binaries:VJ.array(VJ.union([VJ.string().min(1),Z$])).min(1)});class pQ{fs;downloader;githubApiClient;ghCliApiClient;archiveExtractor;projectConfig;hookExecutor;method="github-release";displayName="GitHub Release";version="1.0.0";paramsSchema=Y0;toolConfigSchema=XY;constructor($,M,J,Q,G,Y,X){this.fs=$;this.downloader=M;this.githubApiClient=J;this.ghCliApiClient=Q;this.archiveExtractor=G;this.projectConfig=Y;this.hookExecutor=X}getApiClient($){if($.installParams.ghCli&&this.ghCliApiClient)return this.ghCliApiClient;return this.githubApiClient}async install($,M,J,Q,G){let Y=q$(this.fs,$);return await YY($,M,J,Q,Y,this.downloader,this.getApiClient(M),this.archiveExtractor,this.projectConfig,this.hookExecutor,G)}async resolveVersion($,M,J,Q){try{let G=M.installParams,Y=M.version||"latest",X=await A0(G.repo,Y,G.prerelease??!1,this.getApiClient(M),Q);if(!X.success)return Q.debug(P.versionResolutionFailed($,X.error)),null;let Z=AM(X.data.tag_name);return Q.debug(P.versionResolutionResolved($,Z)),Z}catch(G){return Q.debug(P.versionResolutionException($),G),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let Y=M.installParams.repo,[X,Z]=Y.split("/");if(!X||!Z)return{success:!1,error:`Invalid repo format: ${Y}. Expected owner/repo`};let q=await this.getApiClient(M).getLatestRelease(X,Z);if(!q||!q.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let I=M.version||"latest",U=q.tag_name.replace(/^v/,"");if(I==="latest")return{success:!0,hasUpdate:!1,currentVersion:U,latestVersion:U};return{success:!0,hasUpdate:I!==U,currentVersion:I,latestVersion:U}}catch(G){return Q.error(P.updateCheckFailed($),G),{success:!1,error:G instanceof Error?G.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,M){let Q=M.installParams.repo,[G,Y]=Q.split("/");if(!G||!Y)return null;let X=M.version||"main";return`https://raw.githubusercontent.com/${G}/${Y}/${X}/README.md`}}import dM from"path";var F$={installing:($)=>W(`Installing from dmg: toolName=${$}`),skippingNonMacOS:($)=>W(`Skipping DMG installation for ${$}: not running on macOS`),downloadingDmg:($)=>W(`Downloading DMG from: ${$}`),mountingDmg:($)=>W(`Mounting DMG: ${$}`),dmgMounted:($)=>W(`DMG mounted at: ${$}`),copyingApp:($)=>W(`Copying app bundle: ${$}`),symlinkingBinary:($,M)=>W(`Symlinking binary: ${$} -> ${M}`),unmountingDmg:($)=>W(`Unmounting DMG: ${$}`),appNotFound:($)=>W(`No .app bundle found in DMG at: ${$}`),extractingArchive:()=>W("Extracting archive to find DMG"),archiveExtracted:($)=>W(`Archive extracted: ${$} files`),dmgFoundInArchive:($)=>W(`Found DMG in archive: ${$}`),noDmgInArchive:()=>W("No .dmg file found in archive")};async function ZY($,M,J,Q,G,Y,X,Z,q,I,U,K){let H=q$(G,$),_=q.getSubLogger({name:"installFromDmg"});if(_.debug(F$.installing($)),J.systemInfo.platform!==2)return _.info(F$.skippingNonMacOS($)),{success:!0,binaryPaths:[],metadata:{method:"dmg",dmgUrl:L8(M.installParams.source)}};let O=M.installParams;return Q$("dmg",$,_,async()=>{await G.ensureDir(J.stagingDir);let j=await T8(O.source,J,Q,Y,U,K,_);if(!j.success)return{success:!1,error:j.error};let V={...J,downloadPath:j.data.downloadPath},D=await w$(M,V,Z,G,_);if(!D.success)return{success:!1,error:D.error};let A=j.data.downloadPath;if(CM(j.data.downloadName)){_.debug(F$.extractingArchive());let o=await X.extract(_,j.data.downloadPath,{targetDir:J.stagingDir});_.debug(F$.archiveExtracted(o.extractedFiles.length));let y=o.extractedFiles.find((O$)=>O$.endsWith(".dmg"));if(!y)return _.error(F$.noDmgInArchive()),{success:!1,error:"No .dmg file found in extracted archive"};_.debug(F$.dmgFoundInArchive(y)),A=y}let b=W$({logger:_,skipCommandLog:!0}),k=dM.join(J.stagingDir,".dmg-mount");await G.ensureDir(k),_.debug(F$.mountingDmg(A)),await b`hdiutil attach -nobrowse -noautoopen -mountpoint ${k} ${A}`,_.debug(F$.dmgMounted(k));let S,u;try{let o=await v8(O.appName,k,G,_);if(!o)return{success:!1,error:"No .app bundle found in DMG"};S=o;let y=dM.join(k,S),O$="/Applications";await G.ensureDir(O$);let r$=dM.join(O$,S);if(await G.exists(r$))await G.rm(r$,{recursive:!0,force:!0});_.debug(F$.copyingApp(S)),await I`cp -R ${y} ${r$}`.quiet(),u=r$}finally{_.debug(F$.unmountingDmg(k)),await I`hdiutil detach ${k}`.quiet().noThrow()}if(await H.exists(A))await H.rm(A);if(A!==j.data.downloadPath&&await H.exists(j.data.downloadPath))await H.rm(j.data.downloadPath);if(!u)return{success:!1,error:"App installation path was not resolved"};let E=l$(M.binaries).map((o)=>O.binaryPath?dM.join(u,O.binaryPath):dM.join(u,"Contents","MacOS",o.name)),m,$$=E[0];if($$)m=await D$({binaryPath:$$,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});let g={method:"dmg",downloadUrl:j.data.sourceUrl,dmgUrl:j.data.sourceUrl};return{success:!0,binaryPaths:E,metadata:g,version:m||(M.version!=="latest"?M.version:void 0)}})}function L8($){if($.type==="url")return $.url;return`github-release:${$.repo}`}function x8($,M,J){if($.ghCli&&J)return J;return M}async function T8($,M,J,Q,G,Y,X){if($.type==="url")return await k8($,M,J,Q,X);return await S8($,M,J,Q,G,Y,X)}async function k8($,M,J,Q,G){G.debug(F$.downloadingDmg($.url));let Y=b8($.url,"download.dmg"),X=dM.join(M.stagingDir,Y);try{return await U$(G,$.url,X,Y,Q,J),{success:!0,data:{downloadPath:X,downloadName:Y,sourceUrl:$.url}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:String(Z)}}}async function S8($,M,J,Q,G,Y,X){if(!G)return{success:!1,error:"GitHub API client is not configured for DMG github-release source"};let Z=x8($,G,Y),q=$.version||"latest",I=await A0($.repo,q,$.prerelease??!1,Z,X);if(!I.success)return I;let U=await fQ(I.data,$,M,X);if(!U.success)return U;let K=U.data.name.endsWith(".dmg"),H=CM(U.data.name);if(!K&&!H)return{success:!1,error:`Selected GitHub release asset must be a .dmg or supported archive: ${U.data.name}`};let[_,O]=$.repo.split("/");if(!_||!O)return{success:!1,error:`Invalid GitHub repository format: ${$.repo}. Expected format: owner/repo`};let B=dM.join(M.stagingDir,U.data.name),j=await w8($,U.data,_,O,I.data.tag_name,B,J,Q,Z,X);if(!j.success)return j;return{success:!0,data:{downloadPath:B,downloadName:U.data.name,sourceUrl:U.data.browser_download_url}}}async function w8($,M,J,Q,G,Y,X,Z,q,I){if($.ghCli&&q.downloadAsset)try{return await q.downloadAsset(J,Q,G,M.name,Y),{success:!0,data:void 0}}catch{}try{return await U$(I,M.browser_download_url,Y,M.name,Z,X),{success:!0,data:void 0}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}function b8($,M){try{let Q=new URL($).pathname.split("/").pop();if(!Q)return M;return decodeURIComponent(Q)}catch{return M}}async function v8($,M,J,Q){if($)return $;let Y=(await J.readdir(M)).find((X)=>X.endsWith(".app"));if(!Y)return Q.error(F$.appNotFound(M)),null;return Y}import{z as f$}from"zod";var N8=Y0.pick({repo:!0,version:!0,assetPattern:!0,assetSelector:!0,ghCli:!0,prerelease:!0}),y8=f$.object({type:f$.literal("url"),url:f$.string().url()}),P8=f$.object({type:f$.literal("github-release")}).extend(N8.shape),C8=f$.discriminatedUnion("type",[y8,P8]),zJ=r.extend({source:C8,appName:f$.string().optional(),binaryPath:f$.string().optional(),versionArgs:f$.array(f$.string()).optional(),versionRegex:f$.string().optional()});import{z as d8}from"zod";var WY=t.extend({installationMethod:d8.literal("dmg"),installParams:zJ});var u8="1.0.0";class cQ{fs;downloader;archiveExtractor;hookExecutor;shell;githubApiClient;ghCliApiClient;method="dmg";displayName="DMG Installer";version=u8;paramsSchema=zJ;toolConfigSchema=WY;staticValidation=!0;externallyManaged=!0;missingBinaryMessage="Installation completed. This tool was installed as a macOS app bundle in /Applications. Launch it from Spotlight, Launchpad, or the Applications folder.";constructor($,M,J,Q,G,Y,X){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=G;this.githubApiClient=Y;this.ghCliApiClient=X}async validate($){if($.systemInfo.platform!==2)return{valid:!0,warnings:["DMG installer only works on macOS"]};try{return await this.shell`which hdiutil`.quiet(),{valid:!0}}catch{return{valid:!1,errors:["hdiutil not found \u2014 required for DMG installation"]}}}async install($,M,J,Q,G){return ZY($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,G,this.shell,this.githubApiClient,this.ghCliApiClient)}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import f8 from"crypto";class p$ extends Error{originalError;statusCode;constructor($,M,J){super($);this.name="GiteaApiClientError",this.statusCode=M,this.originalError=J,Object.setPrototypeOf(this,p$.prototype)}}function qY($){return{name:$.name,browser_download_url:$.browser_download_url,size:$.size,content_type:"application/octet-stream",state:"uploaded",download_count:$.download_count,created_at:$.created_at,updated_at:$.created_at}}var d={constructor:{initialized:($)=>W(`Gitea API client initialized. baseUrl=${$}`),authTokenPresent:()=>W("API token is configured"),authTokenMissing:()=>W("No API token configured")},cache:{enabled:($)=>W(`Cache enabled. TTL=${$}ms`),disabled:()=>W("Cache is present but disabled"),missing:()=>W("No cache configured")},request:{performing:($,M)=>W(`Gitea API ${$} request to ${M}`),emptyResponse:($)=>W(`Empty response from ${$}`)},releases:{fetchingLatest:($,M)=>W(`Fetching latest release for ${$}/${M}`),latestNotFound:($,M)=>W(`Latest release not found for ${$}/${M}`),latestError:($,M)=>W(`Error fetching latest release for ${$}/${M}`),fetchingByTag:($,M,J)=>W(`Fetching release by tag ${$} for ${M}/${J}`),tagNotFound:($,M,J)=>W(`Release tag ${$} not found for ${M}/${J}`),tagError:($,M,J)=>W(`Error fetching release ${$} for ${M}/${J}`),fetchingAll:($,M)=>W(`Fetching all releases for ${$}/${M}`),fetchingPage:($,M)=>W(`Fetching page ${$}: ${M}`),totalFetched:($,M,J)=>W(`Fetched ${$} releases for ${M}/${J}`),filteredPrereleases:($)=>W(`After filtering prereleases: ${$} releases`),fetchingLatestTags:($,M,J)=>W(`Fetching ${J} latest release tags for ${$}/${M}`),fetchedTags:($)=>W(`Fetched ${$} release tags`),fetchTagsError:($,M)=>W(`Error fetching release tags for ${$}/${M}`)},errors:{requestFailure:($)=>W(`Request failure: ${$}`),notFound:($)=>W(`Resource not found: ${$}`),rateLimit:($)=>W(`Rate limit exceeded: ${$}`),forbidden:($)=>W(`Forbidden: ${$}`),client:($,M)=>W(`Client error ${M}: ${$}`),server:($,M)=>W(`Server error ${M}: ${$}`),http:($,M)=>W(`HTTP error ${M}: ${$}`),network:($)=>W(`Network error: ${$}`),unknown:($)=>W(`Unknown error: ${$}`)}};function hQ($){let M=$.assets.map(qY);return{id:$.id,tag_name:$.tag_name,name:$.name,draft:$.draft,prerelease:$.prerelease,created_at:$.created_at,published_at:$.published_at,assets:M,body:$.body,html_url:$.html_url}}class mQ{baseUrl;token;downloader;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q,G){this.logger=$.getSubLogger({name:"GiteaApiClient"});let Y=M.replace(/\/+$/,"");this.baseUrl=`${Y}/api/v1`,this.token=G?.token,this.downloader=J,this.cache=Q,this.cacheEnabled=G?.cacheEnabled??!0,this.cacheTtlMs=G?.cacheTtlMs??300000;let X=this.logger.getSubLogger({name:"constructor"});if(X.debug(d.constructor.initialized(this.baseUrl)),this.token)X.debug(d.constructor.authTokenPresent());else X.debug(d.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)X.debug(d.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)X.debug(d.cache.disabled());else X.debug(d.cache.missing())}generateCacheKey($,M){let J=`gitea:${M}:${$}`;if(this.token&&typeof this.token==="string"&&this.token.length>0){let Q=f8.createHash("sha256").update(this.token).digest("hex").substring(0,8);J+=`:${Q}`}return J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=`${this.baseUrl}${$}`,G=this.generateCacheKey($,M),Y=await this.tryGetFromCache(G,M);if(Y)return Y;J.debug(d.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(G,Z,M),Z}catch(Z){return this.handleRequestError(Z,Q)}}async tryGetFromCache($,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let J=await this.cache.get($);if(J)return J}catch{}return null}buildRequestHeaders(){let $={Accept:"application/json"};if(this.token)$.Authorization=`token ${this.token}`;return $}async performRequest($,M){let J=this.logger.getSubLogger({name:"performRequest"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q||Q.length===0)throw J.debug(d.request.emptyResponse($)),new I$(this.logger,"Empty response received from API",$);let G=Q.toString("utf-8");return JSON.parse(G)}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){let J=this.logger.getSubLogger({name:"handleRequestError"});if(J.debug(d.errors.requestFailure(M),$),$ instanceof S$)throw J.debug(d.errors.notFound(M)),Error(`Gitea resource not found: ${M}. Status: ${$.statusCode}`);if($ instanceof zM)throw J.debug(d.errors.rateLimit(M)),new p$(`Gitea API rate limit exceeded for ${M}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof bM)throw J.debug(d.errors.forbidden(M)),new p$(`Gitea API request forbidden for ${M}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof vM)throw J.debug(d.errors.client(M,$.statusCode)),new p$(`Gitea API client error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof NM)throw J.debug(d.errors.server(M,$.statusCode)),new p$(`Gitea API server error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof E$)throw J.debug(d.errors.http(M,$.statusCode)),new p$(`Gitea API HTTP error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof I$)throw J.debug(d.errors.network(M)),new p$(`Network error while requesting ${M}: ${$.message}`,void 0,$);if(J.debug(d.errors.unknown(M),$),$ instanceof Error)throw new p$(`Unknown error during Gitea API request to ${M}: ${$.message}`,void 0,$);throw new p$(`Unknown error during Gitea API request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(d.releases.fetchingLatest($,M));try{let Q=await this.request(`/repos/${$}/${M}/releases/latest`);return hQ(Q)}catch(Q){if(Q instanceof Error&&Q.message.includes("Gitea resource not found"))return J.debug(d.releases.latestNotFound($,M)),null;throw J.debug(d.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(d.releases.fetchingByTag(J,$,M));try{let G=await this.request(`/repos/${$}/${M}/releases/tags/${J}`);return hQ(G)}catch(G){if(G instanceof Error&&G.message.includes("Gitea resource not found"))return Q.debug(d.releases.tagNotFound(J,$,M)),null;throw Q.debug(d.releases.tagError(J,$,M),G),G}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(d.releases.fetchingAll($,M));let G=J?.limit||30,Y=J?.maxResults,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?limit=${G}&page=${X}`;Q.debug(d.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{let K=U.map(hQ);if(Z=Z.concat(K),X++,U.length<G)q=!1;if(Y!==void 0&&Z.length>=Y)Z=Z.slice(0,Y),q=!1}}if(Q.debug(d.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(d.releases.filteredPrereleases(I.length)),I}return Z}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(d.releases.fetchingLatestTags($,M,J));try{let Y=(await this.request(`/repos/${$}/${M}/releases?limit=${J}`)).map((X)=>X.tag_name);return Q.debug(d.releases.fetchedTags(Y.length)),Y}catch(G){return Q.debug(d.releases.fetchTagsError($,M),G),[]}}}import h8 from"path";var J$={startingInstallation:($)=>W(`Starting installation: ${$}`),fetchLatest:($)=>W(`Getting latest release for ${$}`),fetchByTag:($,M)=>W(`Fetching release ${$} for ${M}`),assetSelectorCustom:()=>W("Using custom asset selector"),assetPatternMatch:($)=>W(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,M)=>W(`Selecting asset for platform ${$} and architecture ${M}`),downloadingAsset:($)=>W(`Downloading asset: ${$}`),extractingArchive:($)=>W(`Extracting archive: ${$}`),archiveExtracted:($,M)=>W(`Archive extracted. fileCount=${$}, executableCount=${M}`),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($)=>W(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>W(`Failed to check update for ${$}`),availableReleaseTags:()=>W("Available release tags:"),releaseTagItem:($)=>W(` - ${$}`),noReleaseTagsAvailable:()=>W("No release tags available for this repository")};import{minimatch as p8}from"minimatch";function c8($){return/^[dgimsuvy]*$/.test($)}function IY($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function UY($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!c8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function KY($){if(!IY($))return!0;try{return UY($),!0}catch{return!1}}function HY($){if(typeof $==="string")return $;return $.toString()}function _Y($,M){if(typeof M==="string"){if(IY(M))return UY(M).test($);return p8($,M)}return M.test($)}var m8=5;async function OY($,M,J,Q,G,Y,X,Z,q,I){let U=I.getSubLogger({name:"installFromGiteaRelease"});if(U.debug(J$.startingInstallation($)),!M.installParams||!("repo"in M.installParams))return{success:!1,error:"Repository not specified in installParams"};let K=M.installParams,H=K.repo,_=K.version||"latest",[O,B]=H.split("/");if(!O||!B)return{success:!1,error:`Invalid repository format: ${H}. Expected format: owner/repo`};try{let j=await gQ(H,_,K.prerelease??!1,X,U);if(!j.success)return j;let V=n8(j.data,K,J,U);if(!V.success)return V;let D=V.data.browser_download_url,A=h8.join(J.stagingDir,V.data.name),b=await l8(D,V.data,Y,A,Q,U);if(!b.success)return b;let k={...J,downloadPath:b.data.downloadPath},S=await a8(M,k,q,G,U);if(!S.success)return S;let u=j$(j.data.tag_name),i=await s8(V.data,b.data.downloadPath,$,M,J,k,G,Z,q,G,U);if(!i.success)return i;let E=e(M.binaries,J.stagingDir),m={method:"gitea-release",releaseUrl:j.data.html_url,publishedAt:j.data.published_at,releaseName:j.data.name,instanceUrl:K.instanceUrl,downloadUrl:D,assetName:V.data.name};return{success:!0,binaryPaths:E,version:u,originalTag:j.data.tag_name,metadata:m}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}}async function gQ($,M,J,Q,G){let Y=G.getSubLogger({name:"fetchGiteaRelease"}),[X,Z]=$.split("/");if(!X||!Z)return{success:!1,error:`Invalid repository format: ${$}. Expected format: owner/repo`};if(M==="latest"){if(Y.debug(J$.fetchLatest($)),J){let _=(await Q.getAllReleases(X,Z,{limit:1,includePrerelease:!0,maxResults:1}))[0];if(!_)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:_}}let U=await Q.getLatestRelease(X,Z);if(!U)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:U}}Y.debug(J$.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};return await g8(X,Z,Q,Y),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function g8($,M,J,Q){let G=Q.getSubLogger({name:"showAvailableReleaseTags"}),Y=await J.getLatestReleaseTags($,M,m8);if(Y.length===0){G.error(J$.noReleaseTagsAvailable());return}G.info(J$.availableReleaseTags());for(let X of Y)G.info(J$.releaseTagItem(X))}function n8($,M,J,Q){let G;if(M.assetSelector){Q.debug(J$.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};G=M.assetSelector(X)}else if(M.assetPattern){Q.debug(J$.assetPatternMatch(HY(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>_Y(q.name,X));if(G=RY(Z,J.systemInfo),!G&&Z.length>0)G=Z[0]}else Q.debug(J$.assetPlatformMatch(t$(J.systemInfo.platform),o$(J.systemInfo.arch))),G=RY($.assets,J.systemInfo);if(!G)return{success:!1,error:i8($,M,J)};return{success:!0,data:G}}function RY($,M){let J=$.map((G)=>G.name),Q=jJ(J,M);if(!Q)return;return $.find((G)=>G.name===Q)}function i8($,M,J){let Q=$.assets.map((q)=>q.name),G=t$(J.systemInfo.platform),Y=o$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${G}/${Y}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${G}/${Y}.`;else X=`for platform "${G}" and architecture "${Y}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
|
|
74
|
-
`)}async function l8($,M,J,Q,G,Y){Y.debug(J$.downloadingAsset($));try{return await U$(Y,$,Q,M.name,J,G),{success:!0,data:{downloadPath:Q}}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}async function a8($,M,J,Q,G){let Y=await w$($,M,J,Q,G);if(Y.success)return{success:!0,data:void 0};return{success:!1,error:Y.error||"Hook execution failed"}}async function s8($,M,J,Q,G,Y,X,Z,q,I,U){if(CM($.name))return await r8($,M,J,Q,G,Y,X,Z,q,I,U);return await $0(X,J,Q,G,M,U),{success:!0,data:void 0}}async function r8($,M,J,Q,G,Y,X,Z,q,I,U){U.debug(J$.extractingArchive($.name));let K=await Z.extract(U,M,{targetDir:G.stagingDir});U.debug(J$.archiveExtracted(K.extractedFiles.length,K.executables.length));let H={...Y,extractDir:G.stagingDir,extractResult:K},_=await t8(Q,H,I,q,U);if(!_.success)return _;if(await DM(X,J,Q,G,G.stagingDir,U),await X.exists(M))U.debug(J$.cleaningArchive(M)),await X.rm(M);return{success:!0,data:void 0}}async function t8($,M,J,Q,G){let Y=await eM($,M,Q,J,G);if(Y.success)return{success:!0,data:void 0};return{success:!1,error:Y.error||"Hook execution failed"}}import{z as YM}from"zod";var BJ=r.extend({instanceUrl:YM.string().url("instanceUrl must be a valid URL"),repo:YM.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:YM.union([YM.string().refine(KY,"assetPattern must be a valid glob or a regex string like /.../"),YM.instanceof(RegExp)]).optional(),version:YM.string().optional(),assetSelector:YM.custom(($)=>typeof $==="function","Must be a function").optional(),prerelease:YM.boolean().optional(),token:YM.string().optional()});import{z as DJ}from"zod";var jY=t.extend({installationMethod:DJ.literal("gitea-release"),installParams:BJ,binaries:DJ.array(DJ.union([DJ.string().min(1),Z$])).min(1)});class nQ{fs;downloader;archiveExtractor;hookExecutor;cache;method="gitea-release";displayName="Gitea Release";version="1.0.0";paramsSchema=BJ;toolConfigSchema=jY;constructor($,M,J,Q,G){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.cache=G}createApiClient($,M){let J=$.installParams;return new mQ(M,J.instanceUrl,this.downloader,this.cache,{token:J.token})}async install($,M,J,Q,G){let Y=q$(this.fs,$),X=this.createApiClient(M,G);return await OY($,M,J,Q,Y,this.downloader,X,this.archiveExtractor,this.hookExecutor,G)}async resolveVersion($,M,J,Q){try{let G=M.installParams,Y=M.version||"latest",X=this.createApiClient(M,Q),Z=await gQ(G.repo,Y,G.prerelease??!1,X,Q);if(!Z.success)return Q.debug(J$.versionResolutionFailed($,Z.error)),null;let q=AM(Z.data.tag_name);return Q.debug(J$.versionResolutionResolved($,q)),q}catch(G){return Q.debug(J$.versionResolutionException($),G),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let Y=M.installParams.repo,[X,Z]=Y.split("/");if(!X||!Z)return{success:!1,error:`Invalid repo format: ${Y}. Expected owner/repo`};let I=await this.createApiClient(M,Q).getLatestRelease(X,Z);if(!I||!I.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let U=M.version||"latest",K=I.tag_name.replace(/^v/,"");if(U==="latest")return{success:!0,hasUpdate:!1,currentVersion:K,latestVersion:K};return{success:!0,hasUpdate:U!==K,currentVersion:U,latestVersion:K}}catch(G){return Q.error(J$.updateCheckFailed($),G),{success:!1,error:G instanceof Error?G.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,M){let J=M.installParams,Q=J.repo,[G,Y]=Q.split("/");if(!G||!Y)return null;let X=J.instanceUrl.replace(/\/+$/,""),Z=M.version||"main";return`${X}/${G}/${Y}/raw/branch/${Z}/README.md`}}import VY from"path";var iQ={installing:($)=>W(`Manual installation: toolName=${$}`),manualInstructions:()=>W("Manual installation requires user action"),multipleBinariesNotSupported:()=>W("Manual installation does not support multiple binaries")};async function zY($,M,J,Q,G,Y){let X=q$(G,$),Z=Y.getSubLogger({name:"installManually"});Z.debug(iQ.installing($));let q=M.installParams;return Q$("manual",$,Z,async()=>{let U=[];if(q?.binaryPath){let H=_M(M.configFilePath,q.binaryPath,J.projectConfig,J.systemInfo);if(!await X.exists(H))return{success:!1,error:`Binary not found at ${H}`};await o8(M,$,J,X,H,Z),U=e(M.binaries,J.stagingDir)}return{success:!0,binaryPaths:U,metadata:{method:"manual",manualInstall:!0}}})}async function o8($,M,J,Q,G,Y){let X=Y.getSubLogger({name:"installBinariesManually"}),Z=GJ($.binaries);for(let q of Z){let I=VY.join(J.stagingDir,q);if(q===M||Z.length===1)await Q.ensureDir(VY.dirname(I)),await Q.copyFile(G,I),await Q.chmod(I,493);else X.debug(iQ.multipleBinariesNotSupported())}}import{z as e8}from"zod";var AJ=r.extend({binaryPath:e8.string().min(1).optional()});import{z as EJ}from"zod";var BY=t.extend({installationMethod:EJ.literal("manual"),installParams:AJ.optional(),binaries:EJ.array(EJ.union([EJ.string().min(1),Z$])).optional()});var $1="1.0.0";class lQ{fs;method="manual";displayName="Manual Installer";version=$1;paramsSchema=AJ;toolConfigSchema=BY;constructor($){this.fs=$}async install($,M,J,Q,G){let Y=await zY($,M,J,Q,this.fs,G);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,metadata:Y.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function M1($,M){if(M.platform===0)return!1;if(!sM($.platforms,M.platform))return!1;if($.architectures!==void 0){if(M.arch===0)return!1;if(!rM($.architectures,M.arch))return!1}return!0}function aQ($){return{...$,scripts:$.scripts?[...$.scripts]:void 0,functions:$.functions?{...$.functions}:void 0,paths:$.paths?[...$.paths]:void 0}}function J1($){if(!$)return;return{zsh:$.zsh?aQ($.zsh):void 0,bash:$.bash?aQ($.bash):void 0,powershell:$.powershell?aQ($.powershell):void 0}}function Q1($){if(!$.shellConfigs)$.shellConfigs={zsh:void 0,bash:void 0,powershell:void 0}}function sQ($,M,J){if(!J)return;if(!$[M])$[M]={};let Q=$[M];if(J.scripts)Q.scripts=[...Q.scripts||[],...J.scripts];if(J.completions)Q.completions=J.completions;if(J.aliases)Q.aliases={...Q.aliases,...J.aliases};if(J.env)Q.env={...Q.env,...J.env};if(J.functions)Q.functions={...Q.functions,...J.functions};if(J.paths)Q.paths=[...Q.paths||[],...J.paths]}function G1($,M){if(!M)return;Q1($);let J=$.shellConfigs;sQ(J,"zsh",M.zsh),sQ(J,"bash",M.bash),sQ(J,"powershell",M.powershell)}function Y1($,M){if(M.binaries!==void 0)$.binaries=M.binaries;if(M.dependencies!==void 0)$.dependencies=M.dependencies;if(M.version!==void 0)$.version=M.version;if(M.updateCheck!==void 0)$.updateCheck=M.updateCheck;if(M.installationMethod!==void 0)$.installationMethod=M.installationMethod;if(M.installParams!==void 0)$.installParams=M.installParams}function X1($){let M={...$,shellConfigs:J1($.shellConfigs),dependencies:$.dependencies?[...$.dependencies]:void 0},{platformConfigs:J,...Q}=M;return Q}function G$($,M){if(!$.platformConfigs||$.platformConfigs.length===0)return $;let J=$.platformConfigs.filter((G)=>M1(G,M));if(J.length===0){let{platformConfigs:G,...Y}=$;return Y}let Q=X1($);for(let G of J){let Y=G.config;if(G1(Q,Y.shellConfigs),Y.symlinks)Q.symlinks=[...Q.symlinks||[],...Y.symlinks];if(Y.copies)Q.copies=[...Q.copies||[],...Y.copies];Y1(Q,Y)}return Q}import DY from"path";function FJ($,M){let J=M.trim();if(DY.isAbsolute(J))return J;return DY.resolve($,J)}function AM($){if(!$)return $;if($.startsWith("v")||$.startsWith("V"))return $.slice(1);return $}import{randomUUID as Z1}from"crypto";import{basename as AY,extname as W1,join as E0}from"path";var XM={shellCommandStarted:($)=>W(`Executing shell command: ${$}`),shellCommandFailed:($,M)=>W(`Shell command failed (exit ${M??"unknown"}): ${$}`),fileCommandFallbackFailed:($)=>W(`Failed to detect archive format using file command: ${$}`),extractionRequested:($)=>W(`Extracting archive ${$}`),executableFlagApplied:($)=>W(`Marked file as executable: ${$}`),executableCheckFailed:($)=>W(`Failed to inspect file for executable permissions: ${$}`)};class rQ{fs;logger;shell;constructor($,M,J){this.fs=M,this.logger=$.getSubLogger({name:"ArchiveExtractor"}),this.shell=J}detectFormatByExtension($){let M=$.toLowerCase();if(M.endsWith(".tar.gz")||M.endsWith(".tgz"))return"tar.gz";if(M.endsWith(".gz"))return"gzip";if(M.endsWith(".tar.bz2")||M.endsWith(".tbz2")||M.endsWith(".tbz"))return"tar.bz2";if(M.endsWith(".tar.xz")||M.endsWith(".txz"))return"tar.xz";if(M.endsWith(".tar.lzma"))return"tar.lzma";if(M.endsWith(".tar"))return"tar";if(M.endsWith(".zip"))return"zip";if(M.endsWith(".rar"))return"rar";if(M.endsWith(".7z"))return"7z";if(M.endsWith(".deb"))return"deb";if(M.endsWith(".rpm"))return"rpm";if(M.endsWith(".dmg"))return"dmg";return null}detectFormatByMimeType($){if($.includes("gzip"))return"tar.gz";if($.includes("zip"))return"zip";if($.includes("x-bzip2"))return"tar.bz2";if($.includes("x-xz"))return"tar.xz";if($.includes("x-tar"))return"tar";if($.includes("x-7z-compressed"))return"7z";if($.includes("x-rar-compressed"))return"rar";if($.includes("x-debian-package"))return"deb";if($.includes("x-rpm"))return"rpm";if($.includes("x-apple-diskimage"))return"dmg";return null}async detectFormatUsingFileCommand($,M){try{M.debug(XM.shellCommandStarted("file"));let G=(await this.shell`file -b --mime-type ${$}`.quiet()).stdout.trim();return this.detectFormatByMimeType(G)}catch(J){return M.debug(XM.fileCommandFallbackFailed($),J),null}}async detectFormat($){let M=this.logger.getSubLogger({name:"detectFormat"}),J=AY($),Q=this.detectFormatByExtension(J);if(Q)return Q;let G=await this.detectFormatUsingFileCommand($,M);if(G)return G;throw Error(`Unsupported or undetectable archive format for: ${$}`)}isSupported($){return["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"].includes($)}getTarFlagForFormat($){switch($){case"tar.gz":return"-xzf";case"tar.bz2":return"-xjf";case"tar.xz":return"-xJf";case"tar":return"-xf";default:throw Error(`Unsupported tar format: ${$}`)}}async extractArchiveByFormat($,M,J){switch($){case"tar.gz":case"tar.bz2":case"tar.xz":case"tar":{let Q=this.getTarFlagForFormat($),G="tar";this.logger.debug(XM.shellCommandStarted("tar")),await this.shell`tar ${Q} ${M} -C ${J}`.quiet();break}case"zip":{this.logger.debug(XM.shellCommandStarted("unzip")),await this.shell`unzip -qo ${M} -d ${J}`.quiet();break}case"gzip":{this.logger.debug(XM.shellCommandStarted("gunzip"));let G=AY(M),Y=G.endsWith(".gz")?G.slice(0,-3):G,X=E0(J,Y);await this.shell`gunzip -c ${M} > ${X}`.quiet();break}default:throw Error(`Extraction for format ${$} not implemented.`)}}async extract($,M,J={}){let Q=$.getSubLogger({name:"extract"}),{format:G,targetDir:Y=".",detectExecutables:X=!0}=J;Q.debug(XM.extractionRequested(M),J);let Z=G||await this.detectFormat(M);if(!this.isSupported(Z))throw Error(`Unsupported archive format: ${Z}`);await this.fs.ensureDir(Y);let q=Z1(),I=E0(Y,`.extract-temp-${q}`);await this.fs.ensureDir(I);try{await this.extractArchiveByFormat(Z,M,I);let U=await SM(this.fs,I);for(let _ of U){let O=_.substring(I.length+1),B=E0(Y,O),j=E0(B,"..");await this.fs.ensureDir(j),await this.fs.rename(_,B)}await this.fs.rm(I,{recursive:!0,force:!0});let K=U.map((_)=>{let O=_.substring(I.length+1);return E0(Y,O)}),H={extractedFiles:K,executables:[]};if(X)H.executables=await this.detectAndSetExecutables(K);return H}catch(U){try{await this.fs.rm(I,{recursive:!0,force:!0})}catch{}throw U}}async detectAndSetExecutables($){let M=this.logger.getSubLogger({name:"detectAndSetExecutables"}),J=[];for(let Q of $)try{let G=await this.fs.stat(Q);if(G.isFile()){let Y=W1(Q);if(Y===""||[".sh",".py",".pl",".rb"].includes(Y)){if(!(G.mode&64))M.debug(XM.executableFlagApplied(Q)),await this.fs.chmod(Q,G.mode|64);J.push(Q)}}}catch(G){M.debug(XM.executableCheckFailed(Q),G)}return J}}var q1=["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"];function I1($){let M=$.toLowerCase();if(M.endsWith(".tar.gz")||M.endsWith(".tgz"))return"tar.gz";if(M.endsWith(".tar.bz2")||M.endsWith(".tbz2")||M.endsWith(".tbz"))return"tar.bz2";if(M.endsWith(".tar.xz")||M.endsWith(".txz"))return"tar.xz";if(M.endsWith(".tar.lzma"))return"tar.lzma";if(M.endsWith(".tar"))return"tar";if(M.endsWith(".gz"))return"gzip";if(M.endsWith(".zip"))return"zip";if(M.endsWith(".rar"))return"rar";if(M.endsWith(".7z"))return"7z";if(M.endsWith(".deb"))return"deb";if(M.endsWith(".rpm"))return"rpm";if(M.endsWith(".dmg"))return"dmg";return null}function CM($){let M=I1($);if(!M)return!1;return q1.includes(M)}var ZM={configurationFieldIgnored:($,M)=>W(`Configuration field "${$}" ignored: ${M}`),configurationFieldRequired:($,M)=>W(`Required configuration missing: ${$}${M?`. Example: ${M}`:""}`),configurationFieldInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),invalidFunctionName:($)=>W(`Invalid function name: "${$}"`)};import tQ from"path";var L$={generationStarted:($,M)=>W(`Starting completion generation for "${$}" (shell: ${M})`),generationComplete:($,M,J)=>W(`Generated completion ${$} for ${M} (${J})`),commandExecutionStarted:($,M,J)=>W(`Executing completion command for "${$}" (shell: ${J}): ${M}`),commandExecutionFailed:($,M,J,Q)=>W(`Completion command failed for "${$}" [${M}] exit ${J}: ${Q}`),commandExecutionCompleted:($,M)=>W(`Completion command succeeded for "${$}" (shell: ${M})`),symlinkCreated:($,M)=>W(`Symlinked completion: ${$} -> ${M}`),sourceNotFound:($)=>W(`Completion source file not found: ${$}`),downloadingCompletion:($)=>W(`Downloading completion from: ${$}`),completionDownloaded:($)=>W(`Completion downloaded to: ${$}`),completionAlreadyDownloaded:($)=>W(`Completion already downloaded: ${$}`),extractingCompletionArchive:($)=>W(`Extracting completion archive: ${$}`),completionArchiveExtracted:($)=>W(`Completion archive extracted to: ${$}`)};class F0{logger;shell;constructor($,M){this.logger=$.getSubLogger({name:"CompletionCommandExecutor"}),this.shell=M}async executeCompletionCommand($,M,J,Q,G){let Y=this.logger.getSubLogger({name:"executeCompletionCommand"}).setPrefix(M);Y.debug(L$.commandExecutionStarted(M,$,J));let X=G?.map((I)=>tQ.dirname(I))??[],Z=[...new Set([...X,Q])],q=Z.join(tQ.delimiter);if(G&&G.length>0){let I=[...new Set(G.map((K)=>tQ.basename(K)))];if(!await this.checkAnyBinaryExistsInPath(I,q)){let K=Z.join(", ");throw Error(`None of the expected binaries (${I.join(", ")}) found in: ${K}. Skipping completion generation to prevent infinite loop.`)}}try{let I=`cd ${Q} && PATH=${q}:$PATH ${$}`,U=await this.shell`sh -c ${I}`.quiet();return Y.debug(L$.commandExecutionCompleted(M,J)),U.stdout}catch(I){let U=I&&typeof I==="object"&&"exitCode"in I?I.exitCode:-1,K=I&&typeof I==="object"&&"stderr"in I?I.stderr.toString():"Unknown error",H=`Completion command failed for ${M}: ${$}`;throw Y.error(L$.commandExecutionFailed(M,$,U,K)),Error(`${H}
|
|
67
|
+
`)}async function jX($,M){if(!M)return null;let J=HX(M);if(!J)return null;return await _X($,J)}function VX($,M){if(!M)return[];if(!$||$.length===0)return[];return["stack:",$]}async function zX($,M){let J=[RX($)],Q=typeof $.stack==="string"?$.stack:void 0,Y=VX(Q,M);return J.push(...Y),J}async function BX($,M){return[OX($,M)]}async function DX($){let M=IX($.logger),J=[],Q=AX($.error),Y=await jX($.fileSystem,Q);if(Y)J.push("---"),J.push(Y),J.push("---");if(M)if(CY($.error)){let X=await zX($.error,!0);J.push(...X)}else{let X=await BX($.error,!0);J.push(...X)}if(J.length===0)return"";return UX(J.join(`
|
|
68
|
+
`))}function AX($){if(CY($))return typeof $.stack==="string"?$.stack:void 0;if($ instanceof Error)return $.stack;return}async function uY($){let M=await DX($);if(M.length>0)$.writeOutput(M)}function EX($){if(typeof $!=="object"||$===null)return!1;return $.name==="ShellError"}function FX($,M){return Object.assign((Q,...Y)=>{return $(Q,...Y).cwd(M)},$)}function LX($,M,J,Q){if(M.length===0)return $;let Y=J===4?";":":",G=Q.PATH||"",X=[...M,G].join(Y),Z={...Q,PATH:X};return Object.assign((I,...U)=>{let K=I[0]||"";for(let _=0;_<U.length;_++)K+=String(U[_])+(I[_+1]||"");return $`sh -c ${K}`.env(Z)},$)}class LQ{defaultTimeoutMs=60000;writeOutput;constructor($){this.writeOutput=$}async executeHook($,M,J,Q,Y={}){let G=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHook",context:M}),X=Y.timeoutMs??this.defaultTimeoutMs,Z=Y.continueOnError??!1,q=Date.now();G.debug(L.hookExecutor.executingHook(M,X));let I;try{let U=J(Q),K=new Promise((O,B)=>{I=setTimeout(()=>{B(Error(L.hookExecutor.timeoutExceeded(M,X)))},X)});if(await Promise.race([U,K]),I!==void 0)clearTimeout(I);let H=Date.now()-q;return G.debug(L.hookExecutor.hookCompleted(M,H)),{success:!0,durationMs:H,skipped:!1}}catch(U){if(I!==void 0)clearTimeout(I);let K=Date.now()-q,H=U instanceof Error?U.message:String(U),_=vY(U);if(G.error(L.outcome.hookFailed(_),U),EX(U))await uY({fileSystem:Q.fileSystem,logger:G,hookName:M,toolName:Q.toolName,error:U,writeOutput:this.writeOutput});if(Z)G.debug(L.hookExecutor.continuingDespiteFailure(M));return{success:!1,error:H,durationMs:K,skipped:!1}}}createEnhancedContext($,M,J){let Q=M instanceof f?M.withToolName($.toolName):M,Y=$.toolConfig?.configFilePath,G=Y?fY.dirname(Y):void 0,X="binaryPaths"in $&&Array.isArray($.binaryPaths)?$.binaryPaths:[],Z=[...new Set(X.map((H)=>fY.dirname(H)))],q,I=J&&!s0($.$);if(I&&$.installEnv)q=W$({logger:J,skipCommandLog:!0,env:$.installEnv});else q=$.$;let U=$.installEnv??process.env;if(Z.length>0)q=LX(q,Z,$.systemInfo.platform,U);if(G)q=FX(q,G);if(I)q=FY(q,J);return{...$,$:q,fileSystem:Q}}async executeHooks($,M,J){let Q=$.getSubLogger({name:"HookExecutor"}).getSubLogger({name:"executeHooks"}),Y=[];for(let X of M){let{name:Z,hook:q,options:I}=X,U=await this.executeHook($,Z,q,J,I);if(Y.push(U),!U.success&&!I?.continueOnError){Q.debug(L.hookExecutor.stoppingDueToFailure(Z));break}}return Y}}import{minimatch as xX}from"minimatch";import DM from"path";async function AM($,M,J,Q,Y,G){let X=G.getSubLogger({name:"setupBinariesFromArchive"}),Z=DM.join(Q.projectConfig.paths.generatedDir,"binaries"),q=l$(J.binaries),I=DM.basename(Q.stagingDir);await TX($,M,q,I,Y,Z,X)}async function TX($,M,J,Q,Y,G,X){let Z=X.getSubLogger({name:"setupBinariesUsingPatterns"}),q=!1;for(let I of J){let{name:U,pattern:K}=I,H=await wX($,Y,K,U,Z);if(!H){Z.error(L.binarySetupService.binaryNotFound(U,K));let O=await pY($,Y);if(O.length>0){let B=O.join(`
|
|
69
|
+
`);Z.error(L.binarySetupService.extractedFilesTree(Y,B))}continue}let _=DM.relative(Y,H);await JJ($,M,U,Q,_,G,Z),q=!0}return q}async function pY($,M,J="",Q=3,Y=0){let G=[];if(Y>=Q)return G;let X=[];try{X=await $.readdir(M)}catch{return G}let Z=X.toSorted();for(let q=0;q<Z.length;q++){let I=Z[q];if(!I)continue;let U=q===Z.length-1,K=DM.join(M,I),H=U?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",_=J+(U?" ":"\u2502 "),O=await kX($,K,I,J,H,_,Q,Y);G.push(...O)}return G}async function kX($,M,J,Q,Y,G,X,Z){let q=[];try{let I=await $.stat(M),U=I.isDirectory()?`${J}/`:J;if(q.push(`${Q}${Y}${U}`),I.isDirectory()&&Z<X-1){let K=await pY($,M,G,X,Z+1);q.push(...K)}}catch{q.push(`${Q}${Y}${J} (inaccessible)`)}return q}async function SX($,M){return((await $.stat(M)).mode&73)!==0}async function wX($,M,J,Q,Y){Y.getSubLogger({name:"findBinaryUsingPattern"}).debug(L.binarySetupService.searchingWithPattern(J,M));let Z=(await wM($,M,M)).filter((K)=>xX(K,J));if(Z.length===0)return null;let q=[];for(let K of Z){let H=DM.join(M,K);if(await SX($,H))q.push(K)}if(q.length===0)return null;let I=q.find((K)=>DM.basename(K)===Q);if(I)return DM.join(M,I);let U=q[0];if(U)return DM.join(M,U);return null}import xQ from"path";async function M0($,M,J,Q,Y,G){let X=G.getSubLogger({name:"setupBinariesFromDirectDownload"}),Z=l$(J.binaries),q=Z[0]?.name||M;await $.chmod(Y,493);let I=xQ.join(Q.projectConfig.paths.generatedDir,"binaries"),U=xQ.basename(Y),K=xQ.basename(Q.stagingDir);if(await JJ($,M,q,K,U,I,X),Z.length>1)X.debug(L.binarySetupService.directDownloadSingleBinary(Z.length,q))}async function Q$($,M,J,Q){try{return await Q()}catch(Y){return J.error(L.outcome.installFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:String(Y)}}}class TQ{projectConfig;systemInfo;resolvedFileSystem;fileSystem;$shell;emitInstallEvent;constructor($){this.projectConfig=$.projectConfig,this.systemInfo=$.systemInfo,this.resolvedFileSystem=$.resolvedFileSystem,this.fileSystem=$.fileSystem,this.$shell=$.$shell,this.emitInstallEvent=$.emitInstallEvent}createMinimalContext($){let M=this.getToolDirectory($.toolConfig),J=$.parentLogger.getSubLogger({name:"minimalContext"});return{...R0(this.projectConfig,this.systemInfo,$.toolName,M,this.resolvedFileSystem,J),stagingDir:"",timestamp:"",toolConfig:$.toolConfig,$:$.$shell??$M(this.$shell,process.env),fileSystem:this.fileSystem}}createBaseInstallContext($){let M=this.getToolDirectory($.toolConfig),J=$.parentLogger.getSubLogger({name:`install-${$.toolName}`}),Q=R0(this.projectConfig,this.systemInfo,$.toolName,M,this.resolvedFileSystem,J),Y=$.$shell??$M(this.$shell,process.env),G=(I={})=>({...Q,stagingDir:$.stagingDir,timestamp:$.timestamp,toolConfig:$.toolConfig,$:Y,fileSystem:this.fileSystem,installEnv:$.installEnv,...I}),X=G(),Z=async(I,U)=>{await this.emitInstallEvent({type:I,toolName:$.toolName,context:{...G(U),emitEvent:Z,logger:J}})};return X.emitEvent=Z,{context:X,logger:J}}getToolDirectory($){return $.configFilePath?bX.dirname($.configFilePath):this.projectConfig.paths.toolConfigsDir}}function GJ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function NX($){return Array.isArray($)&&$.every((M)=>typeof M==="function")}function vX($){if(!GJ($))return!1;return typeof $.getSubLogger==="function"}function kQ($){if(!GJ($))return;let M=$.installParams;if(!GJ(M))return;let J=M.hooks;if(!GJ(J))return;let Q=Object.entries(J);if(Q.length===0)return;let Y={};for(let[G,X]of Q){if(!NX(X))return;Y[G]=X}return Y}class SQ{hookExecutor;constructor($){this.hookExecutor=$}async handleInstallEvent($,M,J){if(!M)return;let Q=kQ(M);if(!Q)return;let Y=Q[$.type];if(!Y)return;let G=$.context.logger,X=vX(G)?G:J,Z=$.context.fileSystem,q=this.hookExecutor.createEnhancedContext($.context,Z,X);for(let I of Y){let U=await this.hookExecutor.executeHook(X,$.type,I,q);if(!U.success){let K=U.error?`${$.type} hook failed: ${U.error}`:`Hook ${$.type} failed`;throw Error(K)}}}async executeBeforeInstallHook($,M,J,Q){let Y=Q.getSubLogger({name:"executeBeforeInstallHook"}),X=kQ($)?.["before-install"];if(!X)return null;Y.debug(L.lifecycle.hookExecution("before-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,Y);for(let q of X){let I=await this.hookExecutor.executeHook(Y,"before-install",q,Z);if(!I.success)return{success:!1,error:`beforeInstall hook failed: ${I.error}`}}return null}async executeAfterInstallHook($,M,J,Q){let Y=Q.getSubLogger({name:"executeAfterInstallHook"}),X=kQ($)?.["after-install"];if(!X)return;Y.debug(L.lifecycle.hookExecution("after-install"));let Z=this.hookExecutor.createEnhancedContext(M,J,Y);for(let q of X)await this.hookExecutor.executeHook(Y,"after-install",q,Z,{continueOnError:!0})}}import QM from"path";function yX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function PX($){let M={};if(!$.success)return M;if(!("metadata"in $))return M;let J=$.metadata;if(!yX(J))return M;let{method:Q,...Y}=J;if(typeof Q==="string")return{...Y,installMethod:Q};return J}class wQ{projectConfig;toolInstallationRegistry;symlinkGenerator;constructor($){this.projectConfig=$.projectConfig,this.toolInstallationRegistry=$.toolInstallationRegistry,this.symlinkGenerator=$.symlinkGenerator}async recordInstallation($,M,J,Q,Y,G){let X=G.getSubLogger({name:"recordInstallation"});if(!Y.success)return;try{let Z="version"in Y&&Y.version?Y.version:Q.timestamp,q=M.installParams,I=q&&typeof q==="object"&&"version"in q&&typeof q.version==="string"?q.version:void 0,U="originalTag"in Y&&typeof Y.originalTag==="string"?Y.originalTag:void 0;await this.toolInstallationRegistry.recordToolInstallation({toolName:$,version:Z,installPath:J,timestamp:Q.timestamp,binaryPaths:Y.binaryPaths,configuredVersion:I,originalTag:U,...PX(Y)}),X.debug(L.outcome.installSuccess($,Z,"registry-recorded"))}catch(Z){X.error(L.outcome.installFailed("registry-record"),Z)}}async createBinaryEntrypoints($,M,J,Q,Y,G){let X=Q.getSubLogger({name:"createBinaryEntrypoints"}),Z=QM.join(this.projectConfig.paths.binariesDir,$);if(await J.ensureDir(Z),G){let q=QM.join(Z,"external");await J.ensureDir(q);for(let I of M){let U=QM.basename(I),K=QM.join(q,U);try{await this.symlinkGenerator.createBinarySymlink(X,I,K)}catch(H){throw X.error(L.lifecycle.externalBinaryMissing($,U,I)),H}}return}for(let q of M){let I=QM.basename(q),U=QM.join(Y,I);if(q===U)continue;try{if(await J.exists(U))await J.rm(U,{force:!0})}catch(K){throw X.error(L.binarySymlink.removeExistingFailed(U),K),K}try{await J.copyFile(q,U);let H=(await J.stat(q)).mode&511;await J.chmod(U,H)}catch(K){throw X.error(L.binarySymlink.creationFailed(U,q),K),K}}}async updateCurrentSymlink($,M,J,Q,Y){let G=J.getSubLogger({name:"updateCurrentSymlink"}),X=QM.join(this.projectConfig.paths.binariesDir,$),Z=QM.join(X,"current");await M.ensureDir(X);let q=Y?"external":QM.basename(Q);try{if(await M.exists(Z))await M.rm(Z,{force:!0,recursive:!0})}catch(I){throw G.error(L.lifecycle.removingExistingSymlink(Z),I),I}try{await M.withFileType("symlink").symlink(q,Z,"dir")}catch(I){throw G.error(L.lifecycle.creatingExternalSymlink(Z,q),I),I}try{let I=await M.readlink(Z);if(I!==q)throw G.error(L.lifecycle.symlinkVerificationFailed(Z)),Error(`Symlink verification failed: ${Z} points to ${I}, expected ${q}`)}catch(I){throw G.error(L.lifecycle.symlinkVerificationFailed(Z),I),I}}}class bQ{logger;fs;resolvedFs;projectConfig;hookExecutor;hookLifecycle;toolInstallationRegistry;systemInfo;registry;installationStateWriter;$;completionGenerator;installContextFactory;currentToolConfig;constructor($,M,J,Q,Y,G,X,Z,q,I,U){this.logger=$.getSubLogger({name:"Installer"}),this.fs=M,this.resolvedFs=J,this.projectConfig=Q,this.hookExecutor=I,this.hookLifecycle=new SQ(I),this.toolInstallationRegistry=Y,this.systemInfo=G,this.registry=X,this.installationStateWriter=new wQ({projectConfig:this.projectConfig,toolInstallationRegistry:this.toolInstallationRegistry,symlinkGenerator:Z}),this.$=q,this.completionGenerator=U,this.installContextFactory=new TQ({projectConfig:this.projectConfig,systemInfo:this.systemInfo,resolvedFileSystem:this.resolvedFs,fileSystem:this.fs,$shell:this.$,emitInstallEvent:async(K)=>{await this.registry.emitEvent(K)}}),this.registry.onEvent(async(K)=>{await this.hookLifecycle.handleInstallEvent(K,this.currentToolConfig,this.logger)})}async shouldSkipInstallation($,M,J,Q){let Y=Q.getSubLogger({name:"shouldSkipInstallation"});if(J?.force||J?.skipVersionCheck)return null;let G=await this.toolInstallationRegistry.getToolInstallation($);if(!G)return null;let X=J0.join(this.projectConfig.paths.binariesDir,$,"current"),Z=e(M.binaries,X),I=this.registry.get(M.installationMethod)?.getShellInit?.($,M,X),U=await this.getTargetVersion($,M);if(U){if(G.version===U)return Y.debug(L.outcome.installSuccess($,U,"already-installed")),{success:!0,version:G.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I};return Y.debug(L.outcome.outdatedVersion($,G.version,U)),null}return Y.debug(L.outcome.installSuccess($,G.version,"already-installed-latest")),{success:!0,version:G.version,installationMethod:"already-installed",binaryPaths:Z,shellInit:I}}async executeInstallationMethod($,M,J,Q,Y){return await this.registry.install(Y,M.installationMethod,$,M,J,Q)}isShellCompletionConfigInput($){if(typeof $==="string"||typeof $==="function")return!0;if(typeof $!=="object"||$===null)return!1;return"source"in $||"cmd"in $||"url"in $}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin?{bin:$.bin}:{}};if("url"in $)return{url:$.url,...$.source?{source:$.source}:{},...$.bin?{bin:$.bin}:{}};return{source:$.source,...$.bin?{bin:$.bin}:{}}}async prepareUrlCompletionAssets($,M,J,Q,Y){let G=Y.getSubLogger({name:"prepareUrlCompletionAssets"});if(!this.completionGenerator?.prepareUrlCompletionSource)return;let X=["zsh","bash","powershell"],Z=Q??M.version??"latest";for(let q of X){let I=M.shellConfigs?.[q]?.completions;if(!this.isShellCompletionConfigInput(I))continue;let U={version:Z},K=await t$(U,I),H=this.normalizeCompletionConfig(K);if(!H.url)continue;let _={...U,toolName:$,toolInstallDir:J,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,homeDir:this.projectConfig.paths.homeDir,configFilePath:M.configFilePath};try{let O=await this.completionGenerator.prepareUrlCompletionSource(H,$,_);G.debug(L.completion.preparedFromUrl(q,O))}catch(O){G.warn(L.completion.prepareFailed(q),O)}}}async install($,M,J){let Q=this.logger.getSubLogger({name:"install",context:$}),Y=this.getSystemInfo(),G=Y$(M,Y);this.currentToolConfig=G;let X=this.fs.withToolName($);if(J?.shimMode)X.setSuppressLogging(!0);try{let Z=await this.shouldSkipInstallation($,G,J,Q);if(Z)return Z;let q=this.registry.get(G.installationMethod),I=q?.externallyManaged===!0,U=this.projectConfig.paths.binariesDir,K=J0.join(U,$);await X.ensureDir(K);let H=i6(),_=H;if(G.version&&G.version!=="latest")_=G.version;if(!I&&q?.resolveVersion){let g=this.createMinimalContext($,G,Q);try{let $$=await q.resolveVersion($,G,g,Q);if($$)_=$$,Q.debug(L.lifecycle.versionResolved($$));else Q.debug(L.lifecycle.versionFallbackToTimestamp())}catch($$){Q.debug(L.lifecycle.versionResolutionFailed($$))}}let O=CX(),B=J0.join(K,O);if(!I)await X.ensureDir(B),Q.debug(L.lifecycle.directoryCreated(B));let j=`DOTFILES_INSTALLING_${$.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`,V="/home/runner/work/dotfiles/dotfiles/packages/build:/home/runner/work/dotfiles/dotfiles/packages/build/src/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/src/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/src/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/build/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/packages/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/node_modules/.bin:/home/runner/work/node_modules/.bin:/home/runner/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/dotfiles/node_modules/.bin:/home/runner/work/dotfiles/node_modules/.bin:/home/runner/work/node_modules/.bin:/home/runner/node_modules/.bin:/home/node_modules/.bin:/node_modules/.bin:/opt/hostedtoolcache/node/24.14.1/x64/bin:/home/runner/.bun/bin:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin",D=Y.platform===4?";":":",A=I?V:`${B}${D}${V}`,T={...process.env,[j]:"true",PATH:A},S=$M(this.$,T),{context:w,logger:u}=this.createBaseInstallContext($,B,H,G,Q,S,T),i=await this.hookLifecycle.executeBeforeInstallHook(G,w,X,u);if(i)return i;let E;try{E=await this.executeInstallationMethod($,G,w,J,u),E.installationMethod=G.installationMethod;let g=E.success&&"version"in E?E.version:void 0,$$=_===H&&g&&g!==H?g:_,m=I?J0.join(K,"external"):J0.join(K,$$);if(E.success&&!I){if(await X.exists(m))await X.rm(m,{recursive:!0,force:!0});if(await X.rename(B,m),Q.debug(L.lifecycle.directoryRenamed(B,m)),E.success&&"binaryPaths"in E&&E.binaryPaths)E.binaryPaths=E.binaryPaths.map((y)=>y.startsWith(B)?y.replace(B,m):y)}if(E.success&&I)await X.ensureDir(m);let o=E.success&&"binaryPaths"in E?E.binaryPaths:void 0;if(E.success&&o){let y=[];for(let I$ of o)if(await X.exists(I$))y.push(I$);if(y.length>0)await this.installationStateWriter.createBinaryEntrypoints($,y,X,Q,m,I)}if(E.success)await this.installationStateWriter.updateCurrentSymlink($,X,Q,m,I);if(!I&&!E.success&&await X.exists(B)){Q.debug(L.lifecycle.cleaningFailedInstallDir(B)),await X.rm(B,{recursive:!0,force:!0});let y=J0.dirname(B);try{if((await X.readdir(y)).length===0)await X.rmdir(y)}catch{}}if(!E.success&&E.error)Q.error(W(E.error));if(E.success){let y="binaryPaths"in E&&Array.isArray(E.binaryPaths)?E.binaryPaths:[],I$="version"in E?E.version:void 0;await this.prepareUrlCompletionAssets($,G,m,I$,Q);let r$=I?V:`${m}${D}${V}`,d0={...process.env,[j]:"true",PATH:r$},T$=$M(this.$,d0),sJ={...w,$:T$,installedDir:m,binaryPaths:y,version:I$,installEnv:d0};await this.hookLifecycle.executeAfterInstallHook(G,sJ,X,u),await this.installationStateWriter.recordInstallation($,G,m,w,E,u)}return E}catch(g){return E={success:!1,error:g instanceof Error?g.message:String(g),installationMethod:G.installationMethod},Q.error(W(E.error)),E}}catch(Z){let q={success:!1,error:Z instanceof Error?Z.message:String(Z),installationMethod:G.installationMethod};return Q.error(W(q.error)),q}}async getTargetVersion($,M){if(M.version&&M.version!=="latest")return M.version;return null}createMinimalContext($,M,J){return this.installContextFactory.createMinimalContext({toolName:$,toolConfig:M,parentLogger:J})}createBaseInstallContext($,M,J,Q,Y,G=$M(this.$,process.env),X){let Z=Y.getSubLogger({name:"createBaseInstallContext"});return this.installContextFactory.createBaseInstallContext({toolName:$,stagingDir:M,timestamp:J,toolConfig:Q,parentLogger:Z,$shell:G,installEnv:X})}getSystemInfo(){return this.systemInfo}}import{z as yM}from"zod";var u$={installing:($)=>W(`Installing from brew: toolName=${$}`),executingCommand:($)=>W(`installFromBrew: Executing command: ${$}`),fetchingVersion:($)=>W(`Fetching version info for formula: ${$}`),versionFetched:($,M)=>W(`Fetched version ${M} for formula ${$}`),versionNotFound:($)=>W(`No stable version found for formula ${$}`),versionFetchFailed:($)=>W(`Failed to fetch version for formula ${$}`),prefixFetched:($,M)=>W(`Formula ${$} installed at prefix: ${M}`),prefixFetchFailed:($)=>W(`Failed to fetch prefix for formula ${$}`),prefixFallback:($,M)=>W(`Using fallback prefix for formula ${$}: ${M}`)};var dX=yM.object({name:yM.string(),versions:yM.object({stable:yM.string(),head:yM.string().optional(),bottle:yM.boolean().optional()})});async function cY($,M,J,Q,Y,G,X){let Z=Y.getSubLogger({name:"installFromBrew"});if(Z.debug(u$.installing($),M.installParams),!M.installParams)return{success:!1,error:"Install parameters not specified"};let q=M.installParams,I=q.formula||$,U=q.cask||!1,K=q.tap;return Q$("brew",$,Z,async()=>{let _=X??W$({logger:Z,skipCommandLog:!0});await pX(I,U,K,Q?.force,Z,G,_);let O=await fX(I,Z,G),B=e(M.binaries,`${O}/bin`),j,V=B[0];if(q.versionArgs&&q.versionRegex&&V)j=await A$({binaryPath:V,args:q.versionArgs,regex:q.versionRegex,shellExecutor:G});else j=await uX(I,Z,G);return{success:!0,binaryPaths:B,version:j||void 0,metadata:{method:"brew",formula:I,isCask:U,tap:K}}})}async function uX($,M,J){try{M.debug(u$.fetchingVersion($));let Y=(await J`brew info --json ${$}`.quiet().noThrow()).stdout.toString(),G=JSON.parse(Y),X=yM.array(dX).parse(G);if(X.length>0&&X[0]?.versions.stable){let Z=X[0].versions.stable,q=j$(Z);return M.debug(u$.versionFetched($,q)),q}M.debug(u$.versionNotFound($));return}catch(Q){M.debug(u$.versionFetchFailed($),Q);return}}async function fX($,M,J){try{let Y=(await J`brew --prefix ${$}`.quiet()).stdout.toString().trim();return M.debug(u$.prefixFetched($,Y)),Y}catch(Q){M.debug(u$.prefixFetchFailed($),Q);let G=`${(await J`brew --prefix`.quiet()).stdout.toString().trim()}/opt/${$}`;return M.debug(u$.prefixFallback($,G)),G}}async function pX($,M,J,Q,Y,G,X){if(J){let q=Array.isArray(J)?J:[J];for(let I of q)Y.debug(u$.executingCommand(`brew tap ${I}`)),await G`brew tap ${I}`.quiet()}let Z=["install"];if(M)Z.push("--cask");if(Q)Z.push("--force");Z.push($),Y.info(u$.executingCommand(`brew ${Z.join(" ")}`)),await X`brew ${Z}`}import{z as YM}from"zod";var XJ=r.extend({formula:YM.string().optional(),cask:YM.boolean().optional(),tap:YM.union([YM.string(),YM.array(YM.string())]).optional(),versionArgs:YM.array(YM.string()).optional(),versionRegex:YM.string().optional()});import{z as cX}from"zod";var hY=t.extend({installationMethod:cX.literal("brew"),installParams:XJ});var hX="1.0.0";class NQ{shell;method="brew";displayName="Homebrew Installer";version=hX;paramsSchema=XJ;toolConfigSchema=hY;constructor($){this.shell=$}externallyManaged=!0;async install($,M,J,Q,Y){let G=await cY($,M,J,Q,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import{parse as mX}from"smol-toml";import{z as f$}from"zod";class Q0 extends Error{statusCode;cause;constructor($,M,J){super($);if(this.name="CargoClientError",this.statusCode=M,this.cause=J,Error.captureStackTrace)Error.captureStackTrace(this,Q0)}}var b$={constructor:{initialized:($,M)=>W(`Initializing ${$} with user agent: ${M}`)},request:{makingRequest:($,M)=>W(`Making ${$} request to ${M}`)},errors:{emptyResponse:($)=>W(`Empty response received from ${$}`),jsonParseError:($)=>W(`JSON parse error for ${$}`)},cratesIo:{querying:($)=>W(`Querying crates.io for crate ${$}`),notFound:($)=>W(`Crate not found: ${$}`),metadataError:($)=>W(`Error fetching crate metadata for ${$}`)},parsing:{parsingCrateMetadata:($)=>W(`Parsing Cargo.toml from ${$}`),cargoTomlParseError:($)=>W(`Error parsing Cargo.toml from ${$}`)}};var gX=f$.object({package:f$.object({name:f$.string(),version:f$.string(),edition:f$.string().optional(),description:f$.string().optional(),authors:f$.array(f$.string()).optional(),license:f$.string().optional(),repository:f$.string().optional(),homepage:f$.string().optional()})});class vQ{downloader;logger;cargoConfig;cratesIoCache;githubRawCache;cratesIoCacheEnabled;cratesIoCacheTtl;githubRawCacheEnabled;githubRawCacheTtl;constructor($,M,J,Q,Y){this.logger=$.getSubLogger({name:"CargoClient"}),this.downloader=J,this.cratesIoCache=Q,this.githubRawCache=Y,this.cargoConfig=M.cargo,this.cratesIoCacheEnabled=this.cargoConfig.cratesIo.cache.enabled&&Boolean(this.cratesIoCache),this.cratesIoCacheTtl=this.cargoConfig.cratesIo.cache.ttl,this.githubRawCacheEnabled=this.cargoConfig.githubRaw.cache.enabled&&Boolean(this.githubRawCache),this.githubRawCacheTtl=this.cargoConfig.githubRaw.cache.ttl,this.logger.getSubLogger({name:"constructor"}).debug(b$.constructor.initialized("CargoClient",this.cargoConfig.userAgent))}async request($,M){this.logger.getSubLogger({name:"request"}).debug(b$.request.makingRequest("GET",$));let Q=this.buildRequestHeaders(),{useCache:Y,cacheKey:G,cacheTtl:X}=this.resolveCacheOptions($,M),Z=await this.tryReadCache(G,Y);if(Z)return Z;let q=await this.performDownload($,Q),I=this.parseJson(q,$);return await this.tryStoreCache(G,I,X,Y),I}resolveCacheOptions($,M){if(!M)return{useCache:!1,cacheTtl:0};let J=M.kind,Q=J==="cratesIo"?this.cratesIoCacheEnabled:this.githubRawCacheEnabled,Y=J==="cratesIo"?this.cratesIoCacheTtl:this.githubRawCacheTtl,G=Q?`cargo:${J}:${$}`:void 0;return{useCache:Q,cacheKey:G,cacheTtl:Y}}async tryReadCache($,M){let J=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!M||!$||!J)return null;try{let Q=await J.get($);if(Q)return Q}catch{}return null}async tryStoreCache($,M,J,Q){let Y=$?.includes("cratesIo:")?this.cratesIoCache:this.githubRawCache;if(!Q||!$||!Y)return;try{await Y.set($,M,J)}catch{}}parseJson($,M){let J=this.logger.getSubLogger({name:"parseJson"});if(!$||$.length===0)throw J.error(b$.errors.emptyResponse(M)),new U$(J,"Empty response received from API",M);try{return JSON.parse($.toString("utf-8"))}catch(Q){if(Q instanceof SyntaxError)throw J.error(b$.errors.jsonParseError(M),Q),new Q0(`Invalid JSON response from ${M}: ${Q.message}`,void 0,Q);throw Q}}async performDownload($,M){let J=this.logger.getSubLogger({name:"performDownload"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q)throw J.error(b$.errors.emptyResponse($)),new U$(J,"Empty response received from API",$);return Q}buildRequestHeaders(){return{Accept:"application/json","User-Agent":this.cargoConfig.userAgent}}async getCrateMetadata($){let M=this.logger.getSubLogger({name:"getCrateMetadata"});M.debug(b$.cratesIo.querying($));let J=`${this.cargoConfig.cratesIo.host}/api/v1/crates/${$}`;try{return await this.request(J,{kind:"cratesIo"})}catch(Q){if(Q instanceof S$)return M.error(b$.cratesIo.notFound($)),null;throw M.error(b$.cratesIo.metadataError($),Q),Q}}buildCargoTomlUrl($,M="main"){return`${this.cargoConfig.githubRaw.host}/${$}/${M}/Cargo.toml`}async getCargoTomlPackage($){let M=this.logger.getSubLogger({name:"getCargoTomlPackage"});M.debug(b$.parsing.parsingCrateMetadata($));let{useCache:J,cacheKey:Q}=this.resolveCacheOptions($,{kind:"githubRaw"});if(J){let Y=await this.tryReadCache(Q,J);if(Y)return Y}try{let Y=await this.downloader.download(M,$,{headers:this.buildRequestHeaders()});if(!Y||Y.length===0)return M.error(b$.errors.emptyResponse($)),null;let G=this.parseCargoToml(Y);return await this.tryStoreCache(Q,G,this.githubRawCacheTtl,J),G}catch(Y){if(Y instanceof Q0)throw Y;if(Y instanceof S$)return null;throw M.error(b$.parsing.cargoTomlParseError($),Y),Y}}parseCargoToml($){let M=this.logger.getSubLogger({name:"parseCargoToml"}),J=$.toString("utf-8"),Q=mX(J),Y=gX.safeParse(Q);if(!Y.success)throw M.zodErrors(Y.error),new Q0("Could not parse version from Cargo.toml [package] section",void 0);return Y.data.package}async getLatestVersion($){return(await this.getCrateMetadata($))?.crate.newest_version||null}}import nX from"path";var H$={installing:($)=>W(`Installing from cargo: ${$}`),foundVersion:($,M)=>W(`Found crate ${$} version ${M}`),downloadingAsset:($,M)=>W(`Downloading asset ${$} from ${M}`),archiveExtracted:()=>W("Archive extracted: %o"),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),parsingMetadata:($)=>W(`Parsing crate metadata from: ${$}`),queryingCratesIo:($)=>W(`Querying crates.io API for crate: ${$}`),queryingGitHubReleases:($)=>W(`Querying GitHub releases for ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($,M)=>W(`Exception while resolving version for ${$}: ${String(M)}`),updateCheckFailed:($)=>W(`Failed to check update for cargo tool: ${$}`)};async function mY($,M,J,Q,Y,G,X,Z,q,I,U){let K=I.getSubLogger({name:"installFromCargo"});if(K.debug(H$.installing($)),!M.installParams)return{success:!1,error:"Install parameters not specified"};let H=M.installParams,_=H.crateName||$;return Q$("cargo",$,K,async()=>{let B=q$(Y,$),j=await aX(_,H,X,K);K.debug(H$.foundVersion(_,j.version));let V=await rX(_,j.version,H,J,U);K.debug(H$.downloadingAsset(`${_}-${j.version}`,V));let D=`${_}-${j.version}.tar.gz`,A=nX.join(J.stagingDir,D);await K$(K,V,A,D,G,Q);let T={...J,version:j.version},S=await iX(M,q,T,A,B,K);if(!S.success)return S;let w=await Z.extract(K,A,{targetDir:J.stagingDir});K.debug(H$.archiveExtracted(),w),await AM(Y,$,M,J,J.stagingDir,K);let u=await lX(M,q,T,w,B,K);if(!u.success)return u;if(await Y.exists(A))await Y.rm(A),K.debug(H$.cleaningArchive(A));let i=e(M.binaries,J.stagingDir),E={method:"cargo",crateName:_,binarySource:H.binarySource||"cargo-quickinstall",downloadUrl:V};return{success:!0,binaryPaths:i,version:j.version,originalTag:j.originalTag,metadata:E}})}async function iX($,M,J,Q,Y,G){let X=$.installParams?.hooks?.["after-download"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,downloadPath:Q},Y);for(let q of X){let I=await M.executeHook(G,"afterDownload",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function lX($,M,J,Q,Y,G){let X=$.installParams?.hooks?.["after-install"];if(!X)return{success:!0};let Z=M.createEnhancedContext({...J,extractResult:Q},Y);for(let q of X){let I=await M.executeHook(G,"afterInstall",q,Z);if(!I.success)return{success:!1,error:I.error}}return{success:!0}}async function aX($,M,J,Q){let Y=M.versionSource||"cargo-toml";switch(Y){case"cargo-toml":{let G=M.cargoTomlUrl||J.buildCargoTomlUrl(M.githubRepo||`${$}-community/${$}`);Q.debug(H$.parsingMetadata(G));let X=await J.getCargoTomlPackage(G);if(!X)throw Error(`Failed to fetch or parse Cargo.toml from ${G}`);return{version:j$(X.version)}}case"crates-io":{Q.debug(H$.queryingCratesIo($));let G=await J.getLatestVersion($);if(!G)throw Error(`Failed to get latest version for crate ${$} from crates.io`);return{version:j$(G)}}case"github-releases":{if(!M.githubRepo)throw Error("githubRepo is required when using github-releases version source");return sX(M.githubRepo,Q)}default:throw Error(`Unknown version source: ${Y}`)}}async function sX($,M){throw M.debug(H$.queryingGitHubReleases($)),Error("GitHub releases version source not yet implemented")}async function rX($,M,J,Q,Y){let G=J.binarySource||"cargo-quickinstall",X=tX(Q.systemInfo.platform),Z=oX(Q.systemInfo.arch);switch(G){case"cargo-quickinstall":return`${Y}/cargo-bins/cargo-quickinstall/releases/download/${$}-${M}/${$}-${M}-${Z}-${X}.tar.gz`;case"github-releases":{if(!J.githubRepo)throw Error("githubRepo is required when using github-releases binary source");let I=(J.assetPattern||"{crateName}-{version}-{platform}-{arch}.tar.gz").replace("{crateName}",$).replace("{version}",M).replace("{platform}",X).replace("{arch}",Z);return`${Y}/${J.githubRepo}/releases/download/v${M}/${I}`}default:throw Error(`Unknown binary source: ${G}`)}}function tX($){switch($){case 2:return"apple-darwin";case 1:return"unknown-linux-gnu";case 4:return"pc-windows-msvc";default:return"unknown"}}function oX($){switch($){case 2:return"aarch64";case 1:return"x86_64";default:return"unknown"}}import{z as Y0}from"zod";var ZJ=r.extend({crateName:Y0.string(),binarySource:Y0.enum(["cargo-quickinstall","github-releases"]).optional(),githubRepo:Y0.string().optional(),assetPattern:Y0.string().optional(),versionSource:Y0.enum(["cargo-toml","crates-io","github-releases"]).optional(),cargoTomlUrl:Y0.string().optional()});import{z as eX}from"zod";var gY=t.extend({installationMethod:eX.literal("cargo"),installParams:ZJ});var $8="1.0.0";class yQ{fs;downloader;cargoClient;archiveExtractor;hookExecutor;githubHost;method="cargo";displayName="Cargo Installer";version=$8;paramsSchema=ZJ;toolConfigSchema=gY;constructor($,M,J,Q,Y,G){this.fs=$;this.downloader=M;this.cargoClient=J;this.archiveExtractor=Q;this.hookExecutor=Y;this.githubHost=G}async install($,M,J,Q,Y){let G=await mY($,M,J,Q,this.fs,this.downloader,this.cargoClient,this.archiveExtractor,this.hookExecutor,Y,this.githubHost);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}async resolveVersion($,M,J,Q){let Y=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.crateName;if(!X)return Y.debug(H$.versionResolutionFailed($,"Missing crateName in install params")),null;let Z=await this.cargoClient.getLatestVersion(X);if(!Z)return Y.debug(H$.versionResolutionFailed($,`Could not fetch version for crate: ${X}`)),null;let q=EM(Z);return Y.debug(H$.versionResolutionResolved($,q)),q}catch(G){return Y.debug(H$.versionResolutionException($,G)),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let G=M.installParams?.crateName;if(!G)return{success:!1,error:"Missing crateName in install params"};let X=await this.cargoClient.getLatestVersion(G);if(!X)return{success:!1,error:`Could not fetch latest version for crate: ${G}`};let Z=M.version||"latest";if(Z==="latest")return{success:!0,hasUpdate:!1,currentVersion:X,latestVersion:X};return{success:!0,hasUpdate:Z!==X,currentVersion:Z,latestVersion:X}}catch(Y){return Q.error(H$.updateCheckFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!1}}import WJ from"path";var GM={installing:($)=>W(`Installing from curl-script: toolName=${$}`),downloadingScript:($)=>W(`Downloading install script from: ${$}`),executingScript:($)=>W(`Executing install script using: ${$}`),movingBinary:($,M)=>W(`Moving binary from ${$} to ${M}`),binaryFoundInInstallDir:($)=>W(`Binary found in install directory: ${$}`),binaryNotFound:($,M)=>W(`Binary ${$} not found in search paths: ${M}`),detectedVersion:($)=>W(`Detected version: ${$}`),versionDetectionFailed:($)=>W(`Failed to detect version: ${$}`),noBinariesInstalled:($)=>W(`No binaries were installed. Expected at: ${$}`),scriptOutput:()=>W("Install script output:")};async function M8($,M,J,Q){let Y=YJ($.binaries);for(let G of Y){let X=WJ.join(M.stagingDir,G);if(await J.exists(X)){Q.debug(GM.binaryFoundInInstallDir(X));continue}let Z=["/usr/local/bin",WJ.join(M.systemInfo.homeDir,".local","bin"),"/usr/bin"],q=!1;for(let I of Z){let U=WJ.join(I,G);if(await J.exists(U)){Q.debug(GM.movingBinary(U,X)),await J.copyFile(U,X),await J.chmod(X,493),q=!0;break}}if(!q)Q.warn(GM.binaryNotFound(G,`${M.stagingDir}, ${Z.join(", ")}`))}}async function nY($,M,J,Q,Y,G,X,Z,q,I){let U=q$(Y,$),K=Z.getSubLogger({name:"installFromCurlScript"});if(K.debug(GM.installing($)),!M.installParams||!("url"in M.installParams)||!("shell"in M.installParams))return{success:!1,error:"URL or shell not specified in installParams"};let H=M.installParams,_=H.url,O=H.shell;return Q$("curl-script",$,K,async()=>{K.debug(GM.downloadingScript(_));let j=WJ.join(J.stagingDir,`${$}-install.sh`);await K$(K,_,j,`${$}-install.sh`,G,Q),await U.chmod(j,493);let V={...J,downloadPath:j},D=await w$(M,V,X,Y,K);if(!D.success)return D;K.debug(GM.executingScript(O));let A={projectConfig:J.projectConfig,scriptPath:j,stagingDir:J.stagingDir},T=H.args?await t$(A,H.args):[],S=H.env?await t$(A,H.env):{},w={...process.env,...S},u=I??W$({logger:K,skipCommandLog:!0}),i="";if(O==="bash"){let y=await u`bash ${j} ${T}`.env(w);i=[y.stdout,y.stderr].filter(Boolean).join(`
|
|
70
|
+
`)}else{let y=await u`sh ${j} ${T}`.env(w);i=[y.stdout,y.stderr].filter(Boolean).join(`
|
|
71
|
+
`)}await M8(M,J,Y,K);let E=e(M.binaries,J.stagingDir),g=[];for(let y of E)if(await Y.exists(y))g.push(y);if(g.length===0){let y=E.join(", ");if(K.error(GM.noBinariesInstalled(y)),i.trim()){K.error(GM.scriptOutput());for(let I$ of i.trim().split(`
|
|
72
|
+
`))K.error(W(I$))}return{success:!1,error:`Installation script completed but no binaries were found at expected locations: ${y}`}}let $$,m=E[0];if(m)$$=await A$({shellExecutor:q,binaryPath:m,args:H.versionArgs,regex:H.versionRegex});return{success:!0,binaryPaths:E,metadata:{method:"curl-script",scriptUrl:_,shell:O},version:$$||(M.version!=="latest"?M.version:void 0)}})}import{z as PM}from"zod";var qJ=r.extend({url:PM.string().url(),shell:PM.enum(["bash","sh"]),args:PM.custom().optional(),env:PM.custom().optional(),versionArgs:PM.array(PM.string()).optional(),versionRegex:PM.string().optional()});import{z as IJ}from"zod";var iY=t.extend({installationMethod:IJ.literal("curl-script"),installParams:qJ,binaries:IJ.array(IJ.union([IJ.string().min(1),Z$])).min(1)});var J8="1.0.0";class PQ{fs;downloader;hookExecutor;shell;method="curl-script";displayName="Curl Script Installer";version=J8;paramsSchema=qJ;toolConfigSchema=iY;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,Y){let G=await nY($,M,J,Q,this.fs,this.downloader,this.hookExecutor,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,metadata:G.metadata,version:G.version}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import Q8 from"path";var G0={installing:($)=>W(`Installing from curl-tar: toolName=${$}`),downloadingArchive:($)=>W(`Downloading archive from: ${$}`),downloadingTarball:($)=>W(`Downloading tarball from: ${$}`),extractingTarball:()=>W("Extracting tarball"),tarballExtracted:()=>W("Tarball extracted successfully"),archiveExtracted:()=>W("Archive extracted: %o"),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`)};async function lY($,M,J,Q,Y,G,X,Z,q,I){let U=q$(Y,$),K=q.getSubLogger({name:"installFromCurlTar"});K.debug(G0.installing($));let H,_;if(!M.installParams||!("url"in M.installParams))return{success:!1,error:"URL not specified in installParams"};let O=M.installParams,B=O.url;return Q$("curl-tar",$,K,async()=>{K.debug(G0.downloadingTarball(B));let V=Q8.join(J.stagingDir,`${$}.tar.gz`);await K$(K,B,V,`${$}.tar.gz`,G,Q),H={...J,downloadPath:V};let D=await w$(M,H,Z,Y,K);if(!D.success)return{success:!1,error:D.error};K.debug(G0.extractingTarball());let A=await X.extract(K,V,{targetDir:J.stagingDir});K.debug(G0.tarballExtracted(),A),_={...H,extractDir:J.stagingDir,extractResult:A};let T=await $0(M,_,Z,Y,K);if(!T.success)return{success:!1,error:T.error};if(await AM(U,$,M,J,J.stagingDir,K),await U.exists(V))K.debug(G0.cleaningArchive(V)),await U.rm(V);let S=e(M.binaries,J.stagingDir),w,u=S[0];if(u)w=await A$({binaryPath:u,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});return{success:!0,binaryPaths:S,metadata:{method:"curl-tar",downloadUrl:B,tarballUrl:B},version:w||(M.version!=="latest"?M.version:void 0)}})}import{z as UJ}from"zod";var KJ=r.extend({url:UJ.string().url(),versionArgs:UJ.array(UJ.string()).optional(),versionRegex:UJ.string().optional()});import{z as HJ}from"zod";var aY=t.extend({installationMethod:HJ.literal("curl-tar"),installParams:KJ,binaries:HJ.array(HJ.union([HJ.string().min(1),Z$])).min(1)});var Y8="1.0.0";class CQ{fs;downloader;archiveExtractor;hookExecutor;shell;method="curl-tar";displayName="Curl Tar Installer";version=Y8;paramsSchema=KJ;toolConfigSchema=aY;constructor($,M,J,Q,Y){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=Y}async install($,M,J,Q,Y){let G=await lY($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function sY($){let M=/\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?/,J=$.match(M);if(!J||J.index===void 0)return"";return $.slice(0,J.index)}function rY($){let M=/(\d+\.\d+(?:\.\d+)?(?:-[\w.]+)?)/,J=$.match(M);if(!J)return $;let Q=J[1];if(!Q)return $;return Q}function tY($,M){let J=sY($),Q=rY(M);return`${J}${Q}`}import G8 from"crypto";import dQ from"semver";class a extends Error{originalError;statusCode;constructor($,M,J){super($);this.name="GitHubApiClientError",this.statusCode=M,this.originalError=J,Object.setPrototypeOf(this,a.prototype)}}var z={constructor:{initialized:($,M)=>W(`GitHub API client initialized with base URL ${$} and User-Agent ${M}`),authTokenPresent:()=>W("GitHub token authentication enabled"),authTokenMissing:()=>W("No GitHub token provided; requests will be unauthenticated")},ghCli:{initialized:($)=>W(`GitHub CLI API client initialized for hostname ${$}`),executing:($)=>W(`Executing gh api request for ${$}`),cacheHit:($)=>W(`Cache hit for gh api ${$}`),cacheMiss:($)=>W(`Cache miss for gh api ${$}`),commandFailed:($)=>W(`gh cli command failed with exit code ${$}`),parseError:($)=>W(`Failed to parse gh api response for ${$}`),notAvailable:()=>W("gh cli is not available or not authenticated"),downloadingAsset:($,M,J)=>W(`Downloading ${$} from ${M}@${J} via gh release download`),downloadComplete:($)=>W(`Downloaded ${$} via gh cli`),downloadFailed:($,M)=>W(`gh release download failed for ${$} with exit code ${M}`)},cache:{enabled:($)=>W(`GitHub API cache enabled with TTL ${$} ms`),disabled:()=>W("GitHub API cache provided but disabled by configuration"),missing:()=>W("No GitHub API cache provided; responses will not be cached")},request:{performing:($,M)=>W(`GitHub API ${$} request to ${M}`),emptyResponse:($)=>W(`GitHub API returned an empty response buffer for ${$}`)},errors:{requestFailure:($)=>W(`GitHub API request failure for ${$}`),notFound:($)=>W(`GitHub resource not found for ${$}`),rateLimit:($,M)=>W(`GitHub API rate limit exceeded for ${$}, resets at ${M}`),forbidden:($)=>W(`GitHub API request forbidden for ${$}`),client:($,M)=>W(`GitHub API client error for ${$} with status ${M}`),server:($,M)=>W(`GitHub API server error for ${$} with status ${M}`),http:($,M)=>W(`GitHub API HTTP error for ${$} with status ${M}`),network:($)=>W(`GitHub API network error for ${$}`),unknown:($)=>W(`Unknown GitHub API error for ${$}`),constraintLatestError:()=>W("GitHub API latest constraint lookup failed"),constraintError:($,M,J)=>W(`GitHub API error while evaluating constraint ${$} for ${M}/${J}`)},releases:{fetchingLatest:($,M)=>W(`Fetching latest GitHub release for ${$}/${M}`),latestNotFound:($,M)=>W(`Latest GitHub release not found for ${$}/${M}`),latestError:($,M)=>W(`Error fetching latest GitHub release for ${$}/${M}`),fetchingByTag:($,M,J)=>W(`Fetching GitHub release ${$} for ${M}/${J}`),tagNotFound:($,M,J)=>W(`GitHub release ${$} not found for ${M}/${J}`),tagError:($,M,J)=>W(`Error fetching GitHub release ${$} for ${M}/${J}`),fetchingAll:($,M)=>W(`Fetching all GitHub releases for ${$}/${M}`),fetchingPage:($,M)=>W(`Fetching GitHub releases page ${$} via ${M}`),totalFetched:($,M,J)=>W(`Fetched ${$} GitHub releases for ${M}/${J}`),filteredPrereleases:($)=>W(`Filtered prereleases leaving ${$} GitHub releases`),fetchingLatestTags:($,M,J)=>W(`Fetching ${J} latest release tags for ${$}/${M}`),fetchedTags:($)=>W(`Fetched ${$} release tags`),fetchTagsError:($,M)=>W(`Error fetching release tags for ${$}/${M}`)},constraints:{searching:($,M,J)=>W(`Searching for GitHub release matching constraint ${$} in ${M}/${J}`),pageFetch:($)=>W(`Iterating GitHub releases pages for constraint ${$}`),pageRequest:($,M,J)=>W(`Fetching GitHub releases page ${$} for ${M}/${J}`),bestCandidate:($,M)=>W(`Best GitHub release candidate so far ${$} (version ${M})`),resultFound:($,M)=>W(`Found GitHub release ${M} for constraint ${$}`),resultMissing:($)=>W(`No GitHub release found for constraint ${$}`)},rateLimit:{fetching:()=>W("Fetching GitHub API rate limit status")},tagPattern:{probing:($,M)=>W(`Probing release tag pattern for ${$}/${M}`),detected:($)=>W(`Detected latest release tag: ${$}`),noRedirect:($,M)=>W(`No redirect found for ${$}/${M} latest release`),probeFailed:($,M)=>W(`Failed to probe tag pattern for ${$}/${M}`)}};class _J{hostname;shell;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q){this.logger=$.getSubLogger({name:"GhCliApiClient"}),this.hostname=this.extractHostname(M.github.host),this.shell=J,this.cache=Q,this.cacheEnabled=M.github.cache.enabled,this.cacheTtlMs=M.github.cache.ttl;let Y=this.logger.getSubLogger({name:"constructor"});if(Y.debug(z.ghCli.initialized(this.hostname)),this.cache&&this.cacheEnabled)Y.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)Y.debug(z.cache.disabled());else Y.debug(z.cache.missing())}extractHostname($){try{let M=new URL($);if(M.hostname==="api.github.com")return"github.com";return M.hostname.replace(/^api\./,"")}catch{return"github.com"}}generateCacheKey($,M){let J=`${M}:${$}`,Q=G8.createHash("sha256").update("gh-cli").digest("hex").substring(0,8);return J+=`:${Q}`,J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=this.generateCacheKey($,M),Y=await this.tryGetFromCache(Q,M,$);if(Y)return Y;J.debug(z.ghCli.executing($));let G=this.buildGhApiArgs($,M);try{let X=await this.executeGhCommand($,G);return await this.tryCacheResponse(Q,X,M),X}catch(X){return this.handleRequestError(X,$)}}buildGhApiArgs($,M){let J=["api"];if(this.hostname!=="github.com")J.push("--hostname",this.hostname);if(M!=="GET")J.push("--method",M);let Q=$.startsWith("/")?$.substring(1):$;return J.push(Q),J}async executeGhCommand($,M){let J=this.logger.getSubLogger({name:"executeGhCommand"}),Q=["gh",...M].join(" "),Y=await this.shell(Q).quiet().noThrow();if(Y.code!==0)throw J.debug(z.ghCli.commandFailed(Y.code)),this.parseGhError(Y.stderr,Y.code,$);try{return JSON.parse(Y.stdout)}catch{throw J.debug(z.ghCli.parseError($)),new a(`Failed to parse gh api response for ${$}`,void 0)}}parseGhError($,M,J){let Q=$.toLowerCase();if(Q.includes("not found")||Q.includes("404"))return new a(`GitHub resource not found: ${J}. Status: 404`,404);if(Q.includes("rate limit")||Q.includes("403"))return new a(`GitHub API rate limit exceeded for ${J}. Status: 403`,403);if(Q.includes("unauthorized")||Q.includes("401"))return new a(`GitHub API unauthorized for ${J}. Status: 401`,401);if(Q.includes("forbidden"))return new a(`GitHub API forbidden for ${J}. Status: 403`,403);return new a(`gh api command failed for ${J} with exit code ${M}: ${$}`,void 0)}async tryGetFromCache($,M,J){let Q=this.logger.getSubLogger({name:"tryGetFromCache"});if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let Y=await this.cache.get($);if(Y)return Q.debug(z.ghCli.cacheHit(J)),Y;Q.debug(z.ghCli.cacheMiss(J))}catch{}return null}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){if(this.logger.getSubLogger({name:"handleRequestError"}).debug(z.errors.requestFailure(M),$),$ instanceof a)throw $;if($ instanceof Error)throw new a(`Error during gh api request to ${M}: ${$.message}`,void 0,$);throw new a(`Unknown error during gh api request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(z.releases.fetchingLatest($,M));try{return await this.request(`/repos/${$}/${M}/releases/latest`)}catch(Q){if(Q instanceof a&&Q.statusCode===404)return J.debug(z.releases.latestNotFound($,M)),null;throw J.debug(z.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(z.releases.fetchingByTag(J,$,M));try{return await this.request(`/repos/${$}/${M}/releases/tags/${J}`)}catch(Y){if(Y instanceof a&&Y.statusCode===404)return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),Y),Y}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let Y=J?.perPage||30,G=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${Y}&page=${X}`;Q.debug(z.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{if(Z=Z.concat(U),X++,U.length<Y)q=!1;if(G!==void 0&&Z.length>=G)Z=Z.slice(0,G),q=!1}}if(Q.debug(z.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(z.releases.filteredPrereleases(I.length)),I}return Z}async getReleaseByConstraint($,M,J){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(J,$,M)),J==="latest")return await this.handleLatestConstraint($,M);return await this.findReleaseByVersionConstraint($,M,J)}async handleLatestConstraint($,M){try{return await this.getLatestRelease($,M)}catch(J){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),J),null}}async findReleaseByVersionConstraint($,M,J){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(J));let Y=null,G=null,X=1,Z=30,q=100;while(X<=q){let I=await this.fetchReleasesPage($,M,X,Z,J);if(!I)break;if(I.length===0)break;let U=this.findBestReleaseFromPage(I,J,Y,G);if(U.release)Y=U.release,G=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,Y),Y}async fetchReleasesPage($,M,J,Q,Y){let G=`/repos/${$}/${M}/releases?per_page=${Q}&page=${J}`,X=this.logger.getSubLogger({name:"fetchReleasesPage"});X.debug(z.constraints.pageRequest(J,$,M));try{return await this.request(G)}catch(Z){return X.debug(z.errors.constraintError(Y,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let Y=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),G=J,X=Q;for(let Z of $){if(!Z.tag_name)continue;let q=Z.tag_name.startsWith("v")?Z.tag_name.substring(1):Z.tag_name;if(this.isVersionSatisfying(q,M)){if(this.isBetterVersion(q,X))G=Z,X=q,Y.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:G,version:X}}isVersionSatisfying($,M){return Boolean(dQ.valid($))&&dQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||dQ.gt($,M)}logConstraintResult($,M){let J=this.logger.getSubLogger({name:"logConstraintResult"});if(M)J.debug(z.constraints.resultFound($,M.tag_name));else J.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(z.releases.fetchingLatestTags($,M,J));try{let G=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(G.length)),G}catch(Y){return Q.debug(z.releases.fetchTagsError($,M),Y),[]}}async probeLatestTag($,M){let J=this.logger.getSubLogger({name:"probeLatestTag"});J.debug(z.tagPattern.probing($,M));try{let Q=await this.getLatestRelease($,M);if(Q)return J.debug(z.tagPattern.detected(Q.tag_name)),Q.tag_name;return null}catch{return J.debug(z.tagPattern.probeFailed($,M)),null}}async downloadAsset($,M,J,Q,Y){let G=this.logger.getSubLogger({name:"downloadAsset"});G.debug(z.ghCli.downloadingAsset(Q,`${$}/${M}`,J));let X=Y.substring(0,Y.lastIndexOf("/")),Z=["release","download",J];if(Z.push("--repo",`${$}/${M}`),Z.push("--pattern",Q),Z.push("--dir",X),Z.push("--clobber"),this.hostname!=="github.com");let q=["gh",...Z].join(" "),I=await this.shell(q).quiet().noThrow();if(I.code!==0)throw G.debug(z.ghCli.downloadFailed(Q,I.code)),new a(`gh release download failed for ${Q}: ${I.stderr.trim()||`exit code ${I.code}`}`,void 0);G.debug(z.ghCli.downloadComplete(Q))}}import X8 from"crypto";import uQ from"semver";class RJ{baseUrl;githubToken;downloader;userAgent;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q){this.logger=$.getSubLogger({name:"GitHubApiClient"}),this.baseUrl=M.github.host,this.githubToken=M.github.token,this.downloader=J,this.userAgent=M.github.userAgent,this.cache=Q,this.cacheEnabled=M.github.cache.enabled,this.cacheTtlMs=M.github.cache.ttl;let Y=this.logger.getSubLogger({name:"constructor"});if(Y.debug(z.constructor.initialized(this.baseUrl,this.userAgent)),this.githubToken)Y.debug(z.constructor.authTokenPresent());else Y.debug(z.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)Y.debug(z.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)Y.debug(z.cache.disabled());else Y.debug(z.cache.missing())}generateCacheKey($,M){let J=`${M}:${$}`;if(this.githubToken&&typeof this.githubToken==="string"&&this.githubToken.length>0){let Q=X8.createHash("sha256").update(this.githubToken).digest("hex").substring(0,8);J+=`:${Q}`}return J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=`${this.baseUrl}${$}`,Y=this.generateCacheKey($,M),G=await this.tryGetFromCache(Y,M);if(G)return G;J.debug(z.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(Y,Z,M),Z}catch(Z){return this.handleRequestError(Z,Q)}}async tryGetFromCache($,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let J=await this.cache.get($);if(J)return J}catch{}return null}buildRequestHeaders(){let $={Accept:"application/vnd.github.v3+json","User-Agent":this.userAgent};if(this.githubToken)$.Authorization=`token ${this.githubToken}`;return $}async performRequest($,M){let J=this.logger.getSubLogger({name:"performRequest"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q||Q.length===0)throw J.debug(z.request.emptyResponse($)),new U$(this.logger,"Empty response received from API",$);let Y=Q.toString("utf-8");return JSON.parse(Y)}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){let J=this.logger.getSubLogger({name:"handleRequestError"});if(J.debug(z.errors.requestFailure(M),$),$ instanceof S$)throw J.debug(z.errors.notFound(M),$.responseBody),Error(`GitHub resource not found: ${M}. Status: ${$.statusCode}`);if($ instanceof BM)return this.handleRateLimitError($,M);if($ instanceof bM)return this.handleForbiddenError($,M);if($ instanceof NM)return this.handleClientError($,M);if($ instanceof vM)return this.handleServerError($,M);if($ instanceof F$)return this.handleHttpError($,M);if($ instanceof U$)return this.handleNetworkError($,M);return this.handleUnknownError($,M)}handleRateLimitError($,M){let J=this.logger.getSubLogger({name:"handleRateLimitError"}),Q=$.resetTimestamp?new Date($.resetTimestamp).toISOString():"N/A";throw J.debug(z.errors.rateLimit(M,Q),$.responseBody),new a(`GitHub API rate limit exceeded for ${M}. Status: ${$.statusCode}. Resets at ${Q}.`,$.statusCode,$)}handleForbiddenError($,M){throw this.logger.getSubLogger({name:"handleForbiddenError"}).debug(z.errors.forbidden(M),$.responseBody),new a(`GitHub API request forbidden for ${M}. Status: ${$.statusCode}.`,$.statusCode,$)}handleClientError($,M){throw this.logger.getSubLogger({name:"handleClientError"}).debug(z.errors.client(M,$.statusCode),$.responseBody),new a(`GitHub API client error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleServerError($,M){throw this.logger.getSubLogger({name:"handleServerError"}).debug(z.errors.server(M,$.statusCode),$.responseBody),new a(`GitHub API server error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleHttpError($,M){throw this.logger.getSubLogger({name:"handleHttpError"}).debug(z.errors.http(M,$.statusCode),$),new a(`GitHub API HTTP error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$)}handleNetworkError($,M){throw this.logger.getSubLogger({name:"handleNetworkError"}).debug(z.errors.network(M),$),new a(`Network error while requesting ${M}: ${$.message}`,void 0,$)}handleUnknownError($,M){if(this.logger.getSubLogger({name:"handleUnknownError"}).debug(z.errors.unknown(M),$),$ instanceof Error)throw new a(`Unknown error during GitHub API request to ${M}: ${$.message}`,void 0,$);throw new a(`Unknown error during GitHub API request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(z.releases.fetchingLatest($,M));try{return await this.request(`/repos/${$}/${M}/releases/latest`)}catch(Q){if(Q instanceof Error&&Q.message.includes("GitHub resource not found"))return J.debug(z.releases.latestNotFound($,M)),null;throw J.debug(z.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(z.releases.fetchingByTag(J,$,M));try{return await this.request(`/repos/${$}/${M}/releases/tags/${J}`)}catch(Y){if(Y instanceof Error&&Y.message.includes("GitHub resource not found"))return Q.debug(z.releases.tagNotFound(J,$,M)),null;throw Q.debug(z.releases.tagError(J,$,M),Y),Y}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(z.releases.fetchingAll($,M),J);let Y=J?.perPage||30,G=J?.limit,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?per_page=${Y}&page=${X}`;Q.debug(z.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{if(Z=Z.concat(U),X++,U.length<Y)q=!1;if(G!==void 0&&Z.length>=G)Z=Z.slice(0,G),q=!1}}if(Q.debug(z.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(z.releases.filteredPrereleases(I.length)),I}return Z}async getReleaseByConstraint($,M,J){if(this.logger.getSubLogger({name:"getReleaseByConstraint"}).debug(z.constraints.searching(J,$,M)),J==="latest")return await this.handleLatestConstraint($,M);return await this.findReleaseByVersionConstraint($,M,J)}async handleLatestConstraint($,M){try{return await this.getLatestRelease($,M)}catch(J){return this.logger.getSubLogger({name:"handleLatestConstraint"}).debug(z.errors.constraintLatestError(),J),null}}async findReleaseByVersionConstraint($,M,J){this.logger.getSubLogger({name:"findReleaseByVersionConstraint"}).debug(z.constraints.pageFetch(J));let Y=null,G=null,X=1,Z=30,q=100;while(X<=q){let I=await this.fetchReleasesPage($,M,X,Z,J);if(!I)break;if(I.length===0)break;let U=this.findBestReleaseFromPage(I,J,Y,G);if(U.release)Y=U.release,G=U.version;if(I.length<Z)break;X++}return this.logConstraintResult(J,Y),Y}async fetchReleasesPage($,M,J,Q,Y){let G=`/repos/${$}/${M}/releases?per_page=${Q}&page=${J}`,X=this.logger.getSubLogger({name:"fetchReleasesPage"});X.debug(z.constraints.pageRequest(J,$,M));try{return await this.request(G)}catch(Z){return X.debug(z.errors.constraintError(Y,$,M),Z),null}}findBestReleaseFromPage($,M,J,Q){let Y=this.logger.getSubLogger({name:"findBestReleaseFromPage"}),G=J,X=Q;for(let Z of $){if(!Z.tag_name)continue;let q=Z.tag_name.startsWith("v")?Z.tag_name.substring(1):Z.tag_name;if(this.isVersionSatisfying(q,M)){if(this.isBetterVersion(q,X))G=Z,X=q,Y.debug(z.constraints.bestCandidate(Z.tag_name,q))}}return{release:G,version:X}}isVersionSatisfying($,M){return Boolean(uQ.valid($))&&uQ.satisfies($,M,{includePrerelease:!0})}isBetterVersion($,M){return!M||uQ.gt($,M)}logConstraintResult($,M){let J=this.logger.getSubLogger({name:"logConstraintResult"});if(M)J.debug(z.constraints.resultFound($,M.tag_name));else J.debug(z.constraints.resultMissing($))}async getRateLimit(){return this.logger.getSubLogger({name:"getRateLimit"}).debug(z.rateLimit.fetching()),(await this.request("/rate_limit")).resources.core}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(z.releases.fetchingLatestTags($,M,J));try{let G=(await this.request(`/repos/${$}/${M}/releases?per_page=${J}`)).map((X)=>X.tag_name);return Q.debug(z.releases.fetchedTags(G.length)),G}catch(Y){return Q.debug(z.releases.fetchTagsError($,M),Y),[]}}async probeLatestTag($,M){let J=this.logger.getSubLogger({name:"probeLatestTag"});J.debug(z.tagPattern.probing($,M));let Q=`https://github.com/${$}/${M}/releases/latest`;try{let G=(await fetch(Q,{method:"HEAD",redirect:"manual"})).headers.get("location");if(!G)return J.debug(z.tagPattern.noRedirect($,M)),null;let Z=G.match(/\/releases\/tag\/(.+)$/)?.[1];if(!Z)return J.debug(z.tagPattern.noRedirect($,M)),null;let q=decodeURIComponent(Z);return J.debug(z.tagPattern.detected(q)),q}catch(Y){return J.debug(z.tagPattern.probeFailed($,M),Y),null}}}function fQ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oY($){let M=$.system.length>0?`(${$.system.map(fQ).join("|")})`:"",J=$.cpu.length>0?`(${$.cpu.map(fQ).join("|")})`:"",Q=$.variants.length>0?`(${$.variants.map(fQ).join("|")})`:"";return{systemPattern:M,cpuPattern:J,variantPattern:Q}}function OJ($){let M={system:[],cpu:[],variants:[]};switch($.platform){case 2:M.system=["apple","darwin","apple-darwin","dmg","mac","macos","mac-os","osx","os-x","os64x"],M.variants=["darwin"];break;case 1:M.system=["linux"],M.variants=["musl","gnu","unknown-linux"];break;case 4:M.system=["windows","win32","win64","pc-windows-gnu"],M.variants=["mingw","msys","cygwin","pc-windows"];break;default:M.system=[],M.variants=[];break}switch($.arch){case 2:M.cpu=["arm64","aarch64","aarch"];break;case 1:M.cpu=["amd64","x86_64","x64","x86-64"];break;default:M.cpu=[];break}return M}function eY($){let M=OJ($);return oY(M)}var Z8=[/\.sha\d+(sum)?$/i,/\.md5(sum)?$/i,/\.sum$/i,/^shasums/i,/\.sig$/i,/\.asc$/i,/\.pem$/i,/\.json$/i,/\.txt$/i,/\.sbom$/i,/\.deb$/i,/\.rpm$/i,/\.apk$/i,/\.pkg$/i,/buildable-artifact/i,/\.vsix$/i,/\.b3$/i,/\.zst$/i];function W8($){let M=$.filter((J)=>!Z8.some((Q)=>Q.test(J)));return M.length>0?M:$}function q8($,M){let J=new RegExp(M,"i"),Q=$.filter((Y)=>J.test(Y.toLowerCase()));return Q.length>0?Q:$}function jJ($,M){let J=eY(M),Q=OJ(M),Y=W8($),G;if(J.systemPattern){let Z=new RegExp(J.systemPattern,"i");G=Y.filter((q)=>Z.test(q.toLowerCase()))}else G=[...Y];if(G.length===0)return;let X=[];if(J.cpuPattern)X.push(J.cpuPattern);X.push(...Q.variants);for(let Z of X){if(G.length<=1)break;G=q8(G,Z)}return G[0]}import K8 from"path";var P={startingInstallation:($)=>W(`Starting installation: ${$}`),fetchLatest:($)=>W(`Getting latest release for ${$}`),fetchByTag:($,M)=>W(`Fetching release ${$} for ${M}`),assetSelectorCustom:()=>W("Using custom asset selector"),assetPatternMatch:($)=>W(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,M)=>W(`Selecting asset for platform ${$} and architecture ${M}`),determiningDownloadUrl:($,M)=>W(`Determining download URL. rawBrowserDownloadUrl="${$}", hasCustomHost=${M}`),usingAbsoluteUrl:($)=>W(`Using absolute browser_download_url directly: "${$}"`),invalidRelativeUrl:($)=>W(`Invalid asset download URL format: ${$}`),resolvedRelativeUrl:($,M,J)=>W(`Resolved relative URL. Base: "${$}", Relative Path: "${M}", Result: "${J}"`),finalDownloadUrl:($,M,J)=>W(`Final download URL determined. Raw: "${$}", Result: "${M}", hasCustomHost=${J}`),downloadUrlError:($,M)=>W(`Download URL construction failed: Raw: "${$}", hasCustomHost=${M}`),downloadingAsset:($)=>W(`Downloading asset: ${$}`),downloadingViaGhCli:($)=>W(`Downloading ${$} via gh release download (authenticated)`),downloadingViaHttp:($)=>W(`Downloading ${$} via HTTP`),extractingArchive:($)=>W(`Extracting archive: ${$}`),archiveExtracted:($,M)=>W(`Archive extracted. fileCount=${$}, executableCount=${M}`),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),invalidUrl:($)=>W(`Invalid URL: ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($)=>W(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>W(`Failed to check update for ${$}`),detectingTagPattern:()=>W("Detecting tag pattern from latest release"),tagPatternDetectionFailed:()=>W("Failed to detect tag pattern"),tryingCorrectedTag:($,M)=>W(`Trying corrected tag '${$}' (original: '${M}')`),usingCorrectedTag:($,M)=>W(`Found release with corrected tag '${$}' (you specified: '${M}')`),availableReleaseTags:()=>W("Available release tags:"),releaseTagItem:($)=>W(` - ${$}`),noReleaseTagsAvailable:()=>W("No release tags available for this repository")};import{minimatch as I8}from"minimatch";function U8($){return/^[dgimsuvy]*$/.test($)}function $9($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function M9($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!U8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function J9($){if(!$9($))return!0;try{return M9($),!0}catch{return!1}}function Q9($){if(typeof $==="string")return $;return $.toString()}function Y9($,M){if(typeof M==="string"){if($9(M))return M9(M).test($);return I8($,M)}return M.test($)}async function X9($,M,J,Q,Y,G,X,Z,q,I,U){let K=U.getSubLogger({name:"installFromGitHubRelease"});if(K.debug(P.startingInstallation($)),!M.installParams||!("repo"in M.installParams))return{success:!1,error:"GitHub repository not specified in installParams"};let H=M.installParams,_=H.repo,O=H.version||"latest",[B,j]=_.split("/");if(!B||!j)return{success:!1,error:`Invalid GitHub repository format: ${_}. Expected format: owner/repo`};try{let V=await A0(_,O,H.prerelease??!1,X,K);if(!V.success)return V;let D=await pQ(V.data,H,J,K);if(!D.success)return D;let A=j8(D.data.browser_download_url,q,K);if(!A.success)return A;let T=K8.join(J.stagingDir,D.data.name),S=await D8(A.data,D.data,G,X,B,j,V.data.tag_name,T,Q,K);if(!S.success)return S;let w={...J,downloadPath:S.data.downloadPath},u=await A8(M,w,I,Y,K);if(!u.success)return u;let i=j$(V.data.tag_name),E=await E8(D.data,S.data.downloadPath,$,M,J,w,Y,Z,I,Y,K);if(!E.success)return E;let g=e(M.binaries,J.stagingDir),$$={method:"github-release",releaseUrl:V.data.html_url,publishedAt:V.data.published_at,releaseName:V.data.name,downloadUrl:A.data,assetName:D.data.name};return{success:!0,binaryPaths:g,version:i,originalTag:V.data.tag_name,metadata:$$}}catch(V){return{success:!1,error:V instanceof Error?V.message:String(V)}}}var H8=5;async function A0($,M,J,Q,Y){let G=Y.getSubLogger({name:"fetchGitHubRelease"}),[X,Z]=$.split("/");if(!X||!Z)return{success:!1,error:`Invalid GitHub repository format: ${$}. Expected format: owner/repo`};if(M==="latest"){if(G.debug(P.fetchLatest($)),J){let O=(await Q.getAllReleases(X,Z,{perPage:1,includePrerelease:!0,limit:1}))[0];if(!O)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:O}}let K=await Q.getLatestRelease(X,Z);if(!K)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:K}}G.debug(P.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};let I=await _8(X,Z,M,Q,G);if(I)return{success:!0,data:I};return await R8(X,Z,Q,G),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function _8($,M,J,Q,Y){let G=Y.getSubLogger({name:"fetchWithTagPatternDetection"});G.debug(P.detectingTagPattern());let X=await Q.probeLatestTag($,M);if(!X)return G.debug(P.tagPatternDetectionFailed()),null;let Z=tY(X,J);if(Z!==J){G.debug(P.tryingCorrectedTag(Z,J));let q=await Q.getReleaseByTag($,M,Z);if(q)return G.info(P.usingCorrectedTag(Z,J)),q}return null}async function R8($,M,J,Q){let Y=Q.getSubLogger({name:"showAvailableReleaseTags"}),G=await J.getLatestReleaseTags($,M,H8);if(G.length===0){Y.error(P.noReleaseTagsAvailable());return}Y.info(P.availableReleaseTags());for(let X of G)Y.info(P.releaseTagItem(X))}async function pQ($,M,J,Q){let Y;if(M.assetSelector){Q.debug(P.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};Y=M.assetSelector(X)}else if(M.assetPattern){Q.debug(P.assetPatternMatch(Q9(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>Y9(q.name,X));if(Y=G9(Z,J.systemInfo),!Y&&Z.length>0)Y=Z[0]}else Q.debug(P.assetPlatformMatch(o$(J.systemInfo.platform),e$(J.systemInfo.arch))),Y=G9($.assets,J.systemInfo);if(!Y)return{success:!1,error:O8($,M,J)};return{success:!0,data:Y}}function G9($,M){let J=$.map((Y)=>Y.name),Q=jJ(J,M);if(!Q)return;return $.find((Y)=>Y.name===Q)}function O8($,M,J){let Q=$.assets.map((q)=>q.name),Y=o$(J.systemInfo.platform),G=e$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${Y}/${G}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${Y}/${G}.`;else X=`for platform "${Y}" and architecture "${G}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
|
|
73
|
+
`)}function j8($,M,J){let Q=M.github.host,Y=Boolean(Q);J.debug(P.determiningDownloadUrl($,Y));try{let X=V8($)?z8($,J):B8($,Q,J);if(!X.success)return X;return J.debug(P.finalDownloadUrl($,X.data,Y)),X}catch(G){return J.error(P.invalidUrl($)),J.debug(P.downloadUrlError($,Y),G),{success:!1,error:G instanceof Error?G.message:String(G)}}}function V8($){return URL.canParse($)}function z8($,M){return M.debug(P.usingAbsoluteUrl($)),{success:!0,data:$}}function B8($,M,J){if(!$.startsWith("/"))return J.debug(P.invalidRelativeUrl($)),{success:!1,error:`Invalid asset download URL format: ${$}`};let Q=M&&!M.includes("api.github.com")?M:"https://github.com";if(!/^https?:\/\//.test(Q))Q=`https:${Q.startsWith("//")?"":"//"}${Q}`;let G=new URL($,Q).toString();return J.debug(P.resolvedRelativeUrl(Q,$,G)),{success:!0,data:G}}async function D8($,M,J,Q,Y,G,X,Z,q,I){if(Q.downloadAsset){I.debug(P.downloadingViaGhCli(M.name));try{return await Q.downloadAsset(Y,G,X,M.name,Z),{success:!0,data:{downloadPath:Z}}}catch(U){I.debug(P.downloadingAsset($),U instanceof Error?U:Error(String(U)))}}I.debug(P.downloadingViaHttp(M.name));try{return await K$(I,$,Z,M.name,J,q),{success:!0,data:{downloadPath:Z}}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}async function A8($,M,J,Q,Y){let G=await w$($,M,J,Q,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}async function E8($,M,J,Q,Y,G,X,Z,q,I,U){if(CM($.name))return await F8($,M,J,Q,Y,G,X,Z,q,I,U);else return await M0(X,J,Q,Y,M,U),{success:!0,data:void 0}}async function F8($,M,J,Q,Y,G,X,Z,q,I,U){U.debug(P.extractingArchive($.name));let K=await Z.extract(U,M,{targetDir:Y.stagingDir});U.debug(P.archiveExtracted(K.extractedFiles.length,K.executables.length));let H={...G,extractDir:Y.stagingDir,extractResult:K},_=await L8(Q,H,I,q,U);if(!_.success)return _;if(await AM(X,J,Q,Y,Y.stagingDir,U),await X.exists(M))U.debug(P.cleaningArchive(M)),await X.rm(M);return{success:!0,data:void 0}}async function L8($,M,J,Q,Y){let G=await $0($,M,Q,J,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}import{z as FM}from"zod";var X0=r.extend({repo:FM.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:FM.union([FM.string().refine(J9,"assetPattern must be a valid glob or a regex string like /.../"),FM.instanceof(RegExp)]).optional(),version:FM.string().optional(),assetSelector:FM.custom(($)=>typeof $==="function","Must be a function").optional(),ghCli:FM.boolean().optional(),prerelease:FM.boolean().optional()});import{z as VJ}from"zod";var Z9=t.extend({installationMethod:VJ.literal("github-release"),installParams:X0,binaries:VJ.array(VJ.union([VJ.string().min(1),Z$])).min(1)});class cQ{fs;downloader;githubApiClient;ghCliApiClient;archiveExtractor;projectConfig;hookExecutor;method="github-release";displayName="GitHub Release";version="1.0.0";paramsSchema=X0;toolConfigSchema=Z9;constructor($,M,J,Q,Y,G,X){this.fs=$;this.downloader=M;this.githubApiClient=J;this.ghCliApiClient=Q;this.archiveExtractor=Y;this.projectConfig=G;this.hookExecutor=X}getApiClient($){if($.installParams.ghCli&&this.ghCliApiClient)return this.ghCliApiClient;return this.githubApiClient}async install($,M,J,Q,Y){let G=q$(this.fs,$);return await X9($,M,J,Q,G,this.downloader,this.getApiClient(M),this.archiveExtractor,this.projectConfig,this.hookExecutor,Y)}async resolveVersion($,M,J,Q){try{let Y=M.installParams,G=M.version||"latest",X=await A0(Y.repo,G,Y.prerelease??!1,this.getApiClient(M),Q);if(!X.success)return Q.debug(P.versionResolutionFailed($,X.error)),null;let Z=EM(X.data.tag_name);return Q.debug(P.versionResolutionResolved($,Z)),Z}catch(Y){return Q.debug(P.versionResolutionException($),Y),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let G=M.installParams.repo,[X,Z]=G.split("/");if(!X||!Z)return{success:!1,error:`Invalid repo format: ${G}. Expected owner/repo`};let q=await this.getApiClient(M).getLatestRelease(X,Z);if(!q||!q.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let I=M.version||"latest",U=q.tag_name.replace(/^v/,"");if(I==="latest")return{success:!0,hasUpdate:!1,currentVersion:U,latestVersion:U};return{success:!0,hasUpdate:I!==U,currentVersion:I,latestVersion:U}}catch(Y){return Q.error(P.updateCheckFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,M){let Q=M.installParams.repo,[Y,G]=Q.split("/");if(!Y||!G)return null;let X=M.version||"main";return`https://raw.githubusercontent.com/${Y}/${G}/${X}/README.md`}}import dM from"path";var L$={installing:($)=>W(`Installing from dmg: toolName=${$}`),skippingNonMacOS:($)=>W(`Skipping DMG installation for ${$}: not running on macOS`),downloadingDmg:($)=>W(`Downloading DMG from: ${$}`),mountingDmg:($)=>W(`Mounting DMG: ${$}`),dmgMounted:($)=>W(`DMG mounted at: ${$}`),copyingApp:($)=>W(`Copying app bundle: ${$}`),symlinkingBinary:($,M)=>W(`Symlinking binary: ${$} -> ${M}`),unmountingDmg:($)=>W(`Unmounting DMG: ${$}`),appNotFound:($)=>W(`No .app bundle found in DMG at: ${$}`),extractingArchive:()=>W("Extracting archive to find DMG"),archiveExtracted:($)=>W(`Archive extracted: ${$} files`),dmgFoundInArchive:($)=>W(`Found DMG in archive: ${$}`),noDmgInArchive:()=>W("No .dmg file found in archive")};async function W9($,M,J,Q,Y,G,X,Z,q,I,U,K){let H=q$(Y,$),_=q.getSubLogger({name:"installFromDmg"});if(_.debug(L$.installing($)),J.systemInfo.platform!==2)return _.info(L$.skippingNonMacOS($)),{success:!0,binaryPaths:[],metadata:{method:"dmg",dmgUrl:x8(M.installParams.source)}};let O=M.installParams;return Q$("dmg",$,_,async()=>{await Y.ensureDir(J.stagingDir);let j=await k8(O.source,J,Q,G,U,K,_);if(!j.success)return{success:!1,error:j.error};let V={...J,downloadPath:j.data.downloadPath},D=await w$(M,V,Z,Y,_);if(!D.success)return{success:!1,error:D.error};let A=j.data.downloadPath;if(CM(j.data.downloadName)){_.debug(L$.extractingArchive());let o=await X.extract(_,j.data.downloadPath,{targetDir:J.stagingDir});_.debug(L$.archiveExtracted(o.extractedFiles.length));let y=o.extractedFiles.find((I$)=>I$.endsWith(".dmg"));if(!y)return _.error(L$.noDmgInArchive()),{success:!1,error:"No .dmg file found in extracted archive"};_.debug(L$.dmgFoundInArchive(y)),A=y}let T=W$({logger:_,skipCommandLog:!0}),S=dM.join(J.stagingDir,".dmg-mount");await Y.ensureDir(S),_.debug(L$.mountingDmg(A)),await T`hdiutil attach -nobrowse -noautoopen -mountpoint ${S} ${A}`,_.debug(L$.dmgMounted(S));let w,u;try{let o=await v8(O.appName,S,Y,_);if(!o)return{success:!1,error:"No .app bundle found in DMG"};w=o;let y=dM.join(S,w),I$="/Applications";await Y.ensureDir(I$);let r$=dM.join(I$,w);if(await Y.exists(r$))await Y.rm(r$,{recursive:!0,force:!0});_.debug(L$.copyingApp(w)),await I`cp -R ${y} ${r$}`.quiet(),u=r$}finally{_.debug(L$.unmountingDmg(S)),await I`hdiutil detach ${S}`.quiet().noThrow()}if(await H.exists(A))await H.rm(A);if(A!==j.data.downloadPath&&await H.exists(j.data.downloadPath))await H.rm(j.data.downloadPath);if(!u)return{success:!1,error:"App installation path was not resolved"};let E=l$(M.binaries).map((o)=>O.binaryPath?dM.join(u,O.binaryPath):dM.join(u,"Contents","MacOS",o.name)),g,$$=E[0];if($$)g=await A$({binaryPath:$$,args:O.versionArgs,regex:O.versionRegex,shellExecutor:I});let m={method:"dmg",downloadUrl:j.data.sourceUrl,dmgUrl:j.data.sourceUrl};return{success:!0,binaryPaths:E,metadata:m,version:g||(M.version!=="latest"?M.version:void 0)}})}function x8($){if($.type==="url")return $.url;return`github-release:${$.repo}`}function T8($,M,J){if($.ghCli&&J)return J;return M}async function k8($,M,J,Q,Y,G,X){if($.type==="url")return await S8($,M,J,Q,X);return await w8($,M,J,Q,Y,G,X)}async function S8($,M,J,Q,Y){Y.debug(L$.downloadingDmg($.url));let G=N8($.url,"download.dmg"),X=dM.join(M.stagingDir,G);try{return await K$(Y,$.url,X,G,Q,J),{success:!0,data:{downloadPath:X,downloadName:G,sourceUrl:$.url}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:String(Z)}}}async function w8($,M,J,Q,Y,G,X){if(!Y)return{success:!1,error:"GitHub API client is not configured for DMG github-release source"};let Z=T8($,Y,G),q=$.version||"latest",I=await A0($.repo,q,$.prerelease??!1,Z,X);if(!I.success)return I;let U=await pQ(I.data,$,M,X);if(!U.success)return U;let K=U.data.name.endsWith(".dmg"),H=CM(U.data.name);if(!K&&!H)return{success:!1,error:`Selected GitHub release asset must be a .dmg or supported archive: ${U.data.name}`};let[_,O]=$.repo.split("/");if(!_||!O)return{success:!1,error:`Invalid GitHub repository format: ${$.repo}. Expected format: owner/repo`};let B=dM.join(M.stagingDir,U.data.name),j=await b8($,U.data,_,O,I.data.tag_name,B,J,Q,Z,X);if(!j.success)return j;return{success:!0,data:{downloadPath:B,downloadName:U.data.name,sourceUrl:U.data.browser_download_url}}}async function b8($,M,J,Q,Y,G,X,Z,q,I){if($.ghCli&&q.downloadAsset)try{return await q.downloadAsset(J,Q,Y,M.name,G),{success:!0,data:void 0}}catch{}try{return await K$(I,M.browser_download_url,G,M.name,Z,X),{success:!0,data:void 0}}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}}function N8($,M){try{let Q=new URL($).pathname.split("/").pop();if(!Q)return M;return decodeURIComponent(Q)}catch{return M}}async function v8($,M,J,Q){if($)return $;let G=(await J.readdir(M)).find((X)=>X.endsWith(".app"));if(!G)return Q.error(L$.appNotFound(M)),null;return G}import{z as p$}from"zod";var y8=X0.pick({repo:!0,version:!0,assetPattern:!0,assetSelector:!0,ghCli:!0,prerelease:!0}),P8=p$.object({type:p$.literal("url"),url:p$.string().url()}),C8=p$.object({type:p$.literal("github-release")}).extend(y8.shape),d8=p$.discriminatedUnion("type",[P8,C8]),zJ=r.extend({source:d8,appName:p$.string().optional(),binaryPath:p$.string().optional(),versionArgs:p$.array(p$.string()).optional(),versionRegex:p$.string().optional()});import{z as u8}from"zod";var q9=t.extend({installationMethod:u8.literal("dmg"),installParams:zJ});var f8="1.0.0";class hQ{fs;downloader;archiveExtractor;hookExecutor;shell;githubApiClient;ghCliApiClient;method="dmg";displayName="DMG Installer";version=f8;paramsSchema=zJ;toolConfigSchema=q9;staticValidation=!0;externallyManaged=!0;missingBinaryMessage="Installation completed. This tool was installed as a macOS app bundle in /Applications. Launch it from Spotlight, Launchpad, or the Applications folder.";constructor($,M,J,Q,Y,G,X){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.shell=Y;this.githubApiClient=G;this.ghCliApiClient=X}async validate($){if($.systemInfo.platform!==2)return{valid:!0,warnings:["DMG installer only works on macOS"]};try{return await this.shell`which hdiutil`.quiet(),{valid:!0}}catch{return{valid:!1,errors:["hdiutil not found \u2014 required for DMG installation"]}}}async install($,M,J,Q,Y){return W9($,M,J,Q,this.fs,this.downloader,this.archiveExtractor,this.hookExecutor,Y,this.shell,this.githubApiClient,this.ghCliApiClient)}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import p8 from"crypto";class c$ extends Error{originalError;statusCode;constructor($,M,J){super($);this.name="GiteaApiClientError",this.statusCode=M,this.originalError=J,Object.setPrototypeOf(this,c$.prototype)}}function I9($){return{name:$.name,browser_download_url:$.browser_download_url,size:$.size,content_type:"application/octet-stream",state:"uploaded",download_count:$.download_count,created_at:$.created_at,updated_at:$.created_at}}var d={constructor:{initialized:($)=>W(`Gitea API client initialized. baseUrl=${$}`),authTokenPresent:()=>W("API token is configured"),authTokenMissing:()=>W("No API token configured")},cache:{enabled:($)=>W(`Cache enabled. TTL=${$}ms`),disabled:()=>W("Cache is present but disabled"),missing:()=>W("No cache configured")},request:{performing:($,M)=>W(`Gitea API ${$} request to ${M}`),emptyResponse:($)=>W(`Empty response from ${$}`)},releases:{fetchingLatest:($,M)=>W(`Fetching latest release for ${$}/${M}`),latestNotFound:($,M)=>W(`Latest release not found for ${$}/${M}`),latestError:($,M)=>W(`Error fetching latest release for ${$}/${M}`),fetchingByTag:($,M,J)=>W(`Fetching release by tag ${$} for ${M}/${J}`),tagNotFound:($,M,J)=>W(`Release tag ${$} not found for ${M}/${J}`),tagError:($,M,J)=>W(`Error fetching release ${$} for ${M}/${J}`),fetchingAll:($,M)=>W(`Fetching all releases for ${$}/${M}`),fetchingPage:($,M)=>W(`Fetching page ${$}: ${M}`),totalFetched:($,M,J)=>W(`Fetched ${$} releases for ${M}/${J}`),filteredPrereleases:($)=>W(`After filtering prereleases: ${$} releases`),fetchingLatestTags:($,M,J)=>W(`Fetching ${J} latest release tags for ${$}/${M}`),fetchedTags:($)=>W(`Fetched ${$} release tags`),fetchTagsError:($,M)=>W(`Error fetching release tags for ${$}/${M}`)},errors:{requestFailure:($)=>W(`Request failure: ${$}`),notFound:($)=>W(`Resource not found: ${$}`),rateLimit:($)=>W(`Rate limit exceeded: ${$}`),forbidden:($)=>W(`Forbidden: ${$}`),client:($,M)=>W(`Client error ${M}: ${$}`),server:($,M)=>W(`Server error ${M}: ${$}`),http:($,M)=>W(`HTTP error ${M}: ${$}`),network:($)=>W(`Network error: ${$}`),unknown:($)=>W(`Unknown error: ${$}`)}};function mQ($){let M=$.assets.map(I9);return{id:$.id,tag_name:$.tag_name,name:$.name,draft:$.draft,prerelease:$.prerelease,created_at:$.created_at,published_at:$.published_at,assets:M,body:$.body,html_url:$.html_url}}class gQ{baseUrl;token;downloader;cache;cacheEnabled;cacheTtlMs;logger;constructor($,M,J,Q,Y){this.logger=$.getSubLogger({name:"GiteaApiClient"});let G=M.replace(/\/+$/,"");this.baseUrl=`${G}/api/v1`,this.token=Y?.token,this.downloader=J,this.cache=Q,this.cacheEnabled=Y?.cacheEnabled??!0,this.cacheTtlMs=Y?.cacheTtlMs??300000;let X=this.logger.getSubLogger({name:"constructor"});if(X.debug(d.constructor.initialized(this.baseUrl)),this.token)X.debug(d.constructor.authTokenPresent());else X.debug(d.constructor.authTokenMissing());if(this.cache&&this.cacheEnabled)X.debug(d.cache.enabled(this.cacheTtlMs));else if(this.cache&&!this.cacheEnabled)X.debug(d.cache.disabled());else X.debug(d.cache.missing())}generateCacheKey($,M){let J=`gitea:${M}:${$}`;if(this.token&&typeof this.token==="string"&&this.token.length>0){let Q=p8.createHash("sha256").update(this.token).digest("hex").substring(0,8);J+=`:${Q}`}return J}async request($,M="GET"){let J=this.logger.getSubLogger({name:"request"}),Q=`${this.baseUrl}${$}`,Y=this.generateCacheKey($,M),G=await this.tryGetFromCache(Y,M);if(G)return G;J.debug(d.request.performing(M,Q));let X=this.buildRequestHeaders();try{let Z=await this.performRequest(Q,X);return await this.tryCacheResponse(Y,Z,M),Z}catch(Z){return this.handleRequestError(Z,Q)}}async tryGetFromCache($,M){if(!this.cache||!this.cacheEnabled||M!=="GET")return null;try{let J=await this.cache.get($);if(J)return J}catch{}return null}buildRequestHeaders(){let $={Accept:"application/json"};if(this.token)$.Authorization=`token ${this.token}`;return $}async performRequest($,M){let J=this.logger.getSubLogger({name:"performRequest"}),Q=await this.downloader.download(J,$,{headers:M});if(!Q||Q.length===0)throw J.debug(d.request.emptyResponse($)),new U$(this.logger,"Empty response received from API",$);let Y=Q.toString("utf-8");return JSON.parse(Y)}async tryCacheResponse($,M,J){if(!this.cache||!this.cacheEnabled||J!=="GET")return;try{await this.cache.set($,M,this.cacheTtlMs)}catch{}}handleRequestError($,M){let J=this.logger.getSubLogger({name:"handleRequestError"});if(J.debug(d.errors.requestFailure(M),$),$ instanceof S$)throw J.debug(d.errors.notFound(M)),Error(`Gitea resource not found: ${M}. Status: ${$.statusCode}`);if($ instanceof BM)throw J.debug(d.errors.rateLimit(M)),new c$(`Gitea API rate limit exceeded for ${M}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof bM)throw J.debug(d.errors.forbidden(M)),new c$(`Gitea API request forbidden for ${M}. Status: ${$.statusCode}.`,$.statusCode,$);if($ instanceof NM)throw J.debug(d.errors.client(M,$.statusCode)),new c$(`Gitea API client error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof vM)throw J.debug(d.errors.server(M,$.statusCode)),new c$(`Gitea API server error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof F$)throw J.debug(d.errors.http(M,$.statusCode)),new c$(`Gitea API HTTP error for ${M}. Status: ${$.statusCode} ${$.statusText}.`,$.statusCode,$);if($ instanceof U$)throw J.debug(d.errors.network(M)),new c$(`Network error while requesting ${M}: ${$.message}`,void 0,$);if(J.debug(d.errors.unknown(M),$),$ instanceof Error)throw new c$(`Unknown error during Gitea API request to ${M}: ${$.message}`,void 0,$);throw new c$(`Unknown error during Gitea API request to ${M}`)}async getLatestRelease($,M){let J=this.logger.getSubLogger({name:"getLatestRelease"});J.debug(d.releases.fetchingLatest($,M));try{let Q=await this.request(`/repos/${$}/${M}/releases/latest`);return mQ(Q)}catch(Q){if(Q instanceof Error&&Q.message.includes("Gitea resource not found"))return J.debug(d.releases.latestNotFound($,M)),null;throw J.debug(d.releases.latestError($,M),Q),Q}}async getReleaseByTag($,M,J){let Q=this.logger.getSubLogger({name:"getReleaseByTag"});Q.debug(d.releases.fetchingByTag(J,$,M));try{let Y=await this.request(`/repos/${$}/${M}/releases/tags/${J}`);return mQ(Y)}catch(Y){if(Y instanceof Error&&Y.message.includes("Gitea resource not found"))return Q.debug(d.releases.tagNotFound(J,$,M)),null;throw Q.debug(d.releases.tagError(J,$,M),Y),Y}}async getAllReleases($,M,J){let Q=this.logger.getSubLogger({name:"getAllReleases"});Q.debug(d.releases.fetchingAll($,M));let Y=J?.limit||30,G=J?.maxResults,X=1,Z=[],q=!0;while(q){let I=`/repos/${$}/${M}/releases?limit=${Y}&page=${X}`;Q.debug(d.releases.fetchingPage(X,I));let U=await this.request(I);if(U.length===0)q=!1;else{let K=U.map(mQ);if(Z=Z.concat(K),X++,U.length<Y)q=!1;if(G!==void 0&&Z.length>=G)Z=Z.slice(0,G),q=!1}}if(Q.debug(d.releases.totalFetched(Z.length,$,M)),J?.includePrerelease===!1){let I=Z.filter((U)=>!U.prerelease);return Q.debug(d.releases.filteredPrereleases(I.length)),I}return Z}async getLatestReleaseTags($,M,J=5){let Q=this.logger.getSubLogger({name:"getLatestReleaseTags"});Q.debug(d.releases.fetchingLatestTags($,M,J));try{let G=(await this.request(`/repos/${$}/${M}/releases?limit=${J}`)).map((X)=>X.tag_name);return Q.debug(d.releases.fetchedTags(G.length)),G}catch(Y){return Q.debug(d.releases.fetchTagsError($,M),Y),[]}}}import m8 from"path";var J$={startingInstallation:($)=>W(`Starting installation: ${$}`),fetchLatest:($)=>W(`Getting latest release for ${$}`),fetchByTag:($,M)=>W(`Fetching release ${$} for ${M}`),assetSelectorCustom:()=>W("Using custom asset selector"),assetPatternMatch:($)=>W(`Finding asset matching pattern: ${$}`),assetPlatformMatch:($,M)=>W(`Selecting asset for platform ${$} and architecture ${M}`),downloadingAsset:($)=>W(`Downloading asset: ${$}`),extractingArchive:($)=>W(`Extracting archive: ${$}`),archiveExtracted:($,M)=>W(`Archive extracted. fileCount=${$}, executableCount=${M}`),cleaningArchive:($)=>W(`Cleaning up downloaded archive: ${$}`),versionResolutionResolved:($,M)=>W(`Resolved version for ${$}: ${M}`),versionResolutionFailed:($,M)=>W(`Failed to resolve version for ${$}: ${M}`),versionResolutionException:($)=>W(`Exception while resolving version for ${$}`),updateCheckFailed:($)=>W(`Failed to check update for ${$}`),availableReleaseTags:()=>W("Available release tags:"),releaseTagItem:($)=>W(` - ${$}`),noReleaseTagsAvailable:()=>W("No release tags available for this repository")};import{minimatch as c8}from"minimatch";function h8($){return/^[dgimsuvy]*$/.test($)}function U9($){if(!$.startsWith("/"))return!1;if($.lastIndexOf("/")<=0)return!1;return!0}function K9($){let M=$.lastIndexOf("/");if(M<=0)throw Error('Invalid regex string: missing closing "/"');let J=$.slice(1,M),Q=$.slice(M+1);if(!h8(Q))throw Error("Invalid regex string: invalid flags");return new RegExp(J,Q)}function H9($){if(!U9($))return!0;try{return K9($),!0}catch{return!1}}function _9($){if(typeof $==="string")return $;return $.toString()}function R9($,M){if(typeof M==="string"){if(U9(M))return K9(M).test($);return c8($,M)}return M.test($)}var g8=5;async function j9($,M,J,Q,Y,G,X,Z,q,I){let U=I.getSubLogger({name:"installFromGiteaRelease"});if(U.debug(J$.startingInstallation($)),!M.installParams||!("repo"in M.installParams))return{success:!1,error:"Repository not specified in installParams"};let K=M.installParams,H=K.repo,_=K.version||"latest",[O,B]=H.split("/");if(!O||!B)return{success:!1,error:`Invalid repository format: ${H}. Expected format: owner/repo`};try{let j=await nQ(H,_,K.prerelease??!1,X,U);if(!j.success)return j;let V=i8(j.data,K,J,U);if(!V.success)return V;let D=V.data.browser_download_url,A=m8.join(J.stagingDir,V.data.name),T=await a8(D,V.data,G,A,Q,U);if(!T.success)return T;let S={...J,downloadPath:T.data.downloadPath},w=await s8(M,S,q,Y,U);if(!w.success)return w;let u=j$(j.data.tag_name),i=await r8(V.data,T.data.downloadPath,$,M,J,S,Y,Z,q,Y,U);if(!i.success)return i;let E=e(M.binaries,J.stagingDir),g={method:"gitea-release",releaseUrl:j.data.html_url,publishedAt:j.data.published_at,releaseName:j.data.name,instanceUrl:K.instanceUrl,downloadUrl:D,assetName:V.data.name};return{success:!0,binaryPaths:E,version:u,originalTag:j.data.tag_name,metadata:g}}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}}async function nQ($,M,J,Q,Y){let G=Y.getSubLogger({name:"fetchGiteaRelease"}),[X,Z]=$.split("/");if(!X||!Z)return{success:!1,error:`Invalid repository format: ${$}. Expected format: owner/repo`};if(M==="latest"){if(G.debug(J$.fetchLatest($)),J){let _=(await Q.getAllReleases(X,Z,{limit:1,includePrerelease:!0,maxResults:1}))[0];if(!_)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:_}}let U=await Q.getLatestRelease(X,Z);if(!U)return{success:!1,error:`Failed to fetch latest release for ${$}`};return{success:!0,data:U}}G.debug(J$.fetchByTag(M,$));let q=await Q.getReleaseByTag(X,Z,M);if(q)return{success:!0,data:q};return await n8(X,Z,Q,G),{success:!1,error:`Release '${M}' not found for ${$}. Check the available tags above.`}}async function n8($,M,J,Q){let Y=Q.getSubLogger({name:"showAvailableReleaseTags"}),G=await J.getLatestReleaseTags($,M,g8);if(G.length===0){Y.error(J$.noReleaseTagsAvailable());return}Y.info(J$.availableReleaseTags());for(let X of G)Y.info(J$.releaseTagItem(X))}function i8($,M,J,Q){let Y;if(M.assetSelector){Q.debug(J$.assetSelectorCustom());let X={...J,assets:$.assets,release:$,assetPattern:M.assetPattern};Y=M.assetSelector(X)}else if(M.assetPattern){Q.debug(J$.assetPatternMatch(_9(M.assetPattern)));let X=M.assetPattern,Z=$.assets.filter((q)=>R9(q.name,X));if(Y=O9(Z,J.systemInfo),!Y&&Z.length>0)Y=Z[0]}else Q.debug(J$.assetPlatformMatch(o$(J.systemInfo.platform),e$(J.systemInfo.arch))),Y=O9($.assets,J.systemInfo);if(!Y)return{success:!1,error:l8($,M,J)};return{success:!0,data:Y}}function O9($,M){let J=$.map((Y)=>Y.name),Q=jJ(J,M);if(!Q)return;return $.find((Y)=>Y.name===Q)}function l8($,M,J){let Q=$.assets.map((q)=>q.name),Y=o$(J.systemInfo.platform),G=e$(J.systemInfo.arch),X="";if(M.assetSelector)X=`using a custom assetSelector function for ${Y}/${G}.`;else if(M.assetPattern)X=`for asset pattern: "${M.assetPattern}" for ${Y}/${G}.`;else X=`for platform "${Y}" and architecture "${G}".`;return[`No suitable asset found in release "${$.tag_name}" ${X}`,`Available assets in release "${$.tag_name}":`,...Q.map((q)=>` - ${q}`)].join(`
|
|
74
|
+
`)}async function a8($,M,J,Q,Y,G){G.debug(J$.downloadingAsset($));try{return await K$(G,$,Q,M.name,J,Y),{success:!0,data:{downloadPath:Q}}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}async function s8($,M,J,Q,Y){let G=await w$($,M,J,Q,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}async function r8($,M,J,Q,Y,G,X,Z,q,I,U){if(CM($.name))return await t8($,M,J,Q,Y,G,X,Z,q,I,U);return await M0(X,J,Q,Y,M,U),{success:!0,data:void 0}}async function t8($,M,J,Q,Y,G,X,Z,q,I,U){U.debug(J$.extractingArchive($.name));let K=await Z.extract(U,M,{targetDir:Y.stagingDir});U.debug(J$.archiveExtracted(K.extractedFiles.length,K.executables.length));let H={...G,extractDir:Y.stagingDir,extractResult:K},_=await o8(Q,H,I,q,U);if(!_.success)return _;if(await AM(X,J,Q,Y,Y.stagingDir,U),await X.exists(M))U.debug(J$.cleaningArchive(M)),await X.rm(M);return{success:!0,data:void 0}}async function o8($,M,J,Q,Y){let G=await $0($,M,Q,J,Y);if(G.success)return{success:!0,data:void 0};return{success:!1,error:G.error||"Hook execution failed"}}import{z as XM}from"zod";var BJ=r.extend({instanceUrl:XM.string().url("instanceUrl must be a valid URL"),repo:XM.string().regex(/^[^/]+\/[^/]+$/,'Repository must be in "owner/repo" format'),assetPattern:XM.union([XM.string().refine(H9,"assetPattern must be a valid glob or a regex string like /.../"),XM.instanceof(RegExp)]).optional(),version:XM.string().optional(),assetSelector:XM.custom(($)=>typeof $==="function","Must be a function").optional(),prerelease:XM.boolean().optional(),token:XM.string().optional()});import{z as DJ}from"zod";var V9=t.extend({installationMethod:DJ.literal("gitea-release"),installParams:BJ,binaries:DJ.array(DJ.union([DJ.string().min(1),Z$])).min(1)});class iQ{fs;downloader;archiveExtractor;hookExecutor;cache;method="gitea-release";displayName="Gitea Release";version="1.0.0";paramsSchema=BJ;toolConfigSchema=V9;constructor($,M,J,Q,Y){this.fs=$;this.downloader=M;this.archiveExtractor=J;this.hookExecutor=Q;this.cache=Y}createApiClient($,M){let J=$.installParams;return new gQ(M,J.instanceUrl,this.downloader,this.cache,{token:J.token})}async install($,M,J,Q,Y){let G=q$(this.fs,$),X=this.createApiClient(M,Y);return await j9($,M,J,Q,G,this.downloader,X,this.archiveExtractor,this.hookExecutor,Y)}async resolveVersion($,M,J,Q){try{let Y=M.installParams,G=M.version||"latest",X=this.createApiClient(M,Q),Z=await nQ(Y.repo,G,Y.prerelease??!1,X,Q);if(!Z.success)return Q.debug(J$.versionResolutionFailed($,Z.error)),null;let q=EM(Z.data.tag_name);return Q.debug(J$.versionResolutionResolved($,q)),q}catch(Y){return Q.debug(J$.versionResolutionException($),Y),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){try{let G=M.installParams.repo,[X,Z]=G.split("/");if(!X||!Z)return{success:!1,error:`Invalid repo format: ${G}. Expected owner/repo`};let I=await this.createApiClient(M,Q).getLatestRelease(X,Z);if(!I||!I.tag_name)return{success:!1,error:`Could not fetch latest release for ${$}`};let U=M.version||"latest",K=I.tag_name.replace(/^v/,"");if(U==="latest")return{success:!0,hasUpdate:!1,currentVersion:K,latestVersion:K};return{success:!0,hasUpdate:U!==K,currentVersion:U,latestVersion:K}}catch(Y){return Q.error(J$.updateCheckFailed($),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!0}getReadmeUrl($,M){let J=M.installParams,Q=J.repo,[Y,G]=Q.split("/");if(!Y||!G)return null;let X=J.instanceUrl.replace(/\/+$/,""),Z=M.version||"main";return`${X}/${Y}/${G}/raw/branch/${Z}/README.md`}}import z9 from"path";var lQ={installing:($)=>W(`Manual installation: toolName=${$}`),manualInstructions:()=>W("Manual installation requires user action"),multipleBinariesNotSupported:()=>W("Manual installation does not support multiple binaries")};async function B9($,M,J,Q,Y,G){let X=q$(Y,$),Z=G.getSubLogger({name:"installManually"});Z.debug(lQ.installing($));let q=M.installParams;return Q$("manual",$,Z,async()=>{let U=[];if(q?.binaryPath){let H=RM(M.configFilePath,q.binaryPath,J.projectConfig,J.systemInfo);if(!await X.exists(H))return{success:!1,error:`Binary not found at ${H}`};await e8(M,$,J,X,H,Z),U=e(M.binaries,J.stagingDir)}return{success:!0,binaryPaths:U,metadata:{method:"manual",manualInstall:!0}}})}async function e8($,M,J,Q,Y,G){let X=G.getSubLogger({name:"installBinariesManually"}),Z=YJ($.binaries);for(let q of Z){let I=z9.join(J.stagingDir,q);if(q===M||Z.length===1)await Q.ensureDir(z9.dirname(I)),await Q.copyFile(Y,I),await Q.chmod(I,493);else X.debug(lQ.multipleBinariesNotSupported())}}import{z as $1}from"zod";var AJ=r.extend({binaryPath:$1.string().min(1).optional()});import{z as EJ}from"zod";var D9=t.extend({installationMethod:EJ.literal("manual"),installParams:AJ.optional(),binaries:EJ.array(EJ.union([EJ.string().min(1),Z$])).optional()});var M1="1.0.0";class aQ{fs;method="manual";displayName="Manual Installer";version=M1;paramsSchema=AJ;toolConfigSchema=D9;constructor($){this.fs=$}async install($,M,J,Q,Y){let G=await B9($,M,J,Q,this.fs,Y);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,metadata:G.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}function J1($,M){if(M.platform===0)return!1;if(!rM($.platforms,M.platform))return!1;if($.architectures!==void 0){if(M.arch===0)return!1;if(!tM($.architectures,M.arch))return!1}return!0}function sQ($){return{...$,scripts:$.scripts?[...$.scripts]:void 0,functions:$.functions?{...$.functions}:void 0,paths:$.paths?[...$.paths]:void 0}}function Q1($){if(!$)return;return{zsh:$.zsh?sQ($.zsh):void 0,bash:$.bash?sQ($.bash):void 0,powershell:$.powershell?sQ($.powershell):void 0}}function Y1($){if(!$.shellConfigs)$.shellConfigs={zsh:void 0,bash:void 0,powershell:void 0}}function rQ($,M,J){if(!J)return;if(!$[M])$[M]={};let Q=$[M];if(J.scripts)Q.scripts=[...Q.scripts||[],...J.scripts];if(J.completions)Q.completions=J.completions;if(J.aliases)Q.aliases={...Q.aliases,...J.aliases};if(J.env)Q.env={...Q.env,...J.env};if(J.functions)Q.functions={...Q.functions,...J.functions};if(J.paths)Q.paths=[...Q.paths||[],...J.paths]}function G1($,M){if(!M)return;Y1($);let J=$.shellConfigs;rQ(J,"zsh",M.zsh),rQ(J,"bash",M.bash),rQ(J,"powershell",M.powershell)}function X1($,M){if(M.binaries!==void 0)$.binaries=M.binaries;if(M.dependencies!==void 0)$.dependencies=M.dependencies;if(M.version!==void 0)$.version=M.version;if(M.updateCheck!==void 0)$.updateCheck=M.updateCheck;if(M.installationMethod!==void 0)$.installationMethod=M.installationMethod;if(M.installParams!==void 0)$.installParams=M.installParams}function Z1($){let M={...$,shellConfigs:Q1($.shellConfigs),dependencies:$.dependencies?[...$.dependencies]:void 0},{platformConfigs:J,...Q}=M;return Q}function Y$($,M){if(!$.platformConfigs||$.platformConfigs.length===0)return $;let J=$.platformConfigs.filter((Y)=>J1(Y,M));if(J.length===0){let{platformConfigs:Y,...G}=$;return G}let Q=Z1($);for(let Y of J){let G=Y.config;if(G1(Q,G.shellConfigs),G.symlinks)Q.symlinks=[...Q.symlinks||[],...G.symlinks];if(G.copies)Q.copies=[...Q.copies||[],...G.copies];X1(Q,G)}return Q}import A9 from"path";function FJ($,M){let J=M.trim();if(A9.isAbsolute(J))return J;return A9.resolve($,J)}function EM($){if(!$)return $;if($.startsWith("v")||$.startsWith("V"))return $.slice(1);return $}import{randomUUID as W1}from"crypto";import{basename as E9,extname as q1,join as E0}from"path";var ZM={shellCommandStarted:($)=>W(`Executing shell command: ${$}`),shellCommandFailed:($,M)=>W(`Shell command failed (exit ${M??"unknown"}): ${$}`),fileCommandFallbackFailed:($)=>W(`Failed to detect archive format using file command: ${$}`),extractionRequested:($)=>W(`Extracting archive ${$}`),executableFlagApplied:($)=>W(`Marked file as executable: ${$}`),executableCheckFailed:($)=>W(`Failed to inspect file for executable permissions: ${$}`)};class tQ{fs;logger;shell;constructor($,M,J){this.fs=M,this.logger=$.getSubLogger({name:"ArchiveExtractor"}),this.shell=J}detectFormatByExtension($){let M=$.toLowerCase();if(M.endsWith(".tar.gz")||M.endsWith(".tgz"))return"tar.gz";if(M.endsWith(".gz"))return"gzip";if(M.endsWith(".tar.bz2")||M.endsWith(".tbz2")||M.endsWith(".tbz"))return"tar.bz2";if(M.endsWith(".tar.xz")||M.endsWith(".txz"))return"tar.xz";if(M.endsWith(".tar.lzma"))return"tar.lzma";if(M.endsWith(".tar"))return"tar";if(M.endsWith(".zip"))return"zip";if(M.endsWith(".rar"))return"rar";if(M.endsWith(".7z"))return"7z";if(M.endsWith(".deb"))return"deb";if(M.endsWith(".rpm"))return"rpm";if(M.endsWith(".dmg"))return"dmg";return null}detectFormatByMimeType($){if($.includes("gzip"))return"tar.gz";if($.includes("zip"))return"zip";if($.includes("x-bzip2"))return"tar.bz2";if($.includes("x-xz"))return"tar.xz";if($.includes("x-tar"))return"tar";if($.includes("x-7z-compressed"))return"7z";if($.includes("x-rar-compressed"))return"rar";if($.includes("x-debian-package"))return"deb";if($.includes("x-rpm"))return"rpm";if($.includes("x-apple-diskimage"))return"dmg";return null}async detectFormatUsingFileCommand($,M){try{M.debug(ZM.shellCommandStarted("file"));let Y=(await this.shell`file -b --mime-type ${$}`.quiet()).stdout.trim();return this.detectFormatByMimeType(Y)}catch(J){return M.debug(ZM.fileCommandFallbackFailed($),J),null}}async detectFormat($){let M=this.logger.getSubLogger({name:"detectFormat"}),J=E9($),Q=this.detectFormatByExtension(J);if(Q)return Q;let Y=await this.detectFormatUsingFileCommand($,M);if(Y)return Y;throw Error(`Unsupported or undetectable archive format for: ${$}`)}isSupported($){return["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"].includes($)}getTarFlagForFormat($){switch($){case"tar.gz":return"-xzf";case"tar.bz2":return"-xjf";case"tar.xz":return"-xJf";case"tar":return"-xf";default:throw Error(`Unsupported tar format: ${$}`)}}async extractArchiveByFormat($,M,J){switch($){case"tar.gz":case"tar.bz2":case"tar.xz":case"tar":{let Q=this.getTarFlagForFormat($),Y="tar";this.logger.debug(ZM.shellCommandStarted("tar")),await this.shell`tar ${Q} ${M} -C ${J}`.quiet();break}case"zip":{this.logger.debug(ZM.shellCommandStarted("unzip")),await this.shell`unzip -qo ${M} -d ${J}`.quiet();break}case"gzip":{this.logger.debug(ZM.shellCommandStarted("gunzip"));let Y=E9(M),G=Y.endsWith(".gz")?Y.slice(0,-3):Y,X=E0(J,G);await this.shell`gunzip -c ${M} > ${X}`.quiet();break}default:throw Error(`Extraction for format ${$} not implemented.`)}}async extract($,M,J={}){let Q=$.getSubLogger({name:"extract"}),{format:Y,targetDir:G=".",detectExecutables:X=!0}=J;Q.debug(ZM.extractionRequested(M),J);let Z=Y||await this.detectFormat(M);if(!this.isSupported(Z))throw Error(`Unsupported archive format: ${Z}`);await this.fs.ensureDir(G);let q=W1(),I=E0(G,`.extract-temp-${q}`);await this.fs.ensureDir(I);try{await this.extractArchiveByFormat(Z,M,I);let U=await wM(this.fs,I);for(let _ of U){let O=_.substring(I.length+1),B=E0(G,O),j=E0(B,"..");await this.fs.ensureDir(j),await this.fs.rename(_,B)}await this.fs.rm(I,{recursive:!0,force:!0});let K=U.map((_)=>{let O=_.substring(I.length+1);return E0(G,O)}),H={extractedFiles:K,executables:[]};if(X)H.executables=await this.detectAndSetExecutables(K);return H}catch(U){try{await this.fs.rm(I,{recursive:!0,force:!0})}catch{}throw U}}async detectAndSetExecutables($){let M=this.logger.getSubLogger({name:"detectAndSetExecutables"}),J=[];for(let Q of $)try{let Y=await this.fs.stat(Q);if(Y.isFile()){let G=q1(Q);if(G===""||[".sh",".py",".pl",".rb"].includes(G)){if(!(Y.mode&64))M.debug(ZM.executableFlagApplied(Q)),await this.fs.chmod(Q,Y.mode|64);J.push(Q)}}}catch(Y){M.debug(ZM.executableCheckFailed(Q),Y)}return J}}var I1=["tar.gz","tar.bz2","tar.xz","tar","zip","gzip"];function U1($){let M=$.toLowerCase();if(M.endsWith(".tar.gz")||M.endsWith(".tgz"))return"tar.gz";if(M.endsWith(".tar.bz2")||M.endsWith(".tbz2")||M.endsWith(".tbz"))return"tar.bz2";if(M.endsWith(".tar.xz")||M.endsWith(".txz"))return"tar.xz";if(M.endsWith(".tar.lzma"))return"tar.lzma";if(M.endsWith(".tar"))return"tar";if(M.endsWith(".gz"))return"gzip";if(M.endsWith(".zip"))return"zip";if(M.endsWith(".rar"))return"rar";if(M.endsWith(".7z"))return"7z";if(M.endsWith(".deb"))return"deb";if(M.endsWith(".rpm"))return"rpm";if(M.endsWith(".dmg"))return"dmg";return null}function CM($){let M=U1($);if(!M)return!1;return I1.includes(M)}var WM={configurationFieldIgnored:($,M)=>W(`Configuration field "${$}" ignored: ${M}`),configurationFieldRequired:($,M)=>W(`Required configuration missing: ${$}${M?`. Example: ${M}`:""}`),configurationFieldInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),invalidFunctionName:($)=>W(`Invalid function name: "${$}"`)};import oQ from"path";var D$={generationStarted:($,M)=>W(`Starting completion generation for "${$}" (shell: ${M})`),generationComplete:($,M,J)=>W(`Generated completion ${$} for ${M} (${J})`),commandExecutionStarted:($,M,J)=>W(`Executing completion command for "${$}" (shell: ${J}): ${M}`),commandExecutionFailed:($,M,J,Q)=>W(`Completion command failed for "${$}" [${M}] exit ${J}: ${Q}`),commandExecutionCompleted:($,M)=>W(`Completion command succeeded for "${$}" (shell: ${M})`),symlinkCreated:($,M)=>W(`Symlinked completion: ${$} -> ${M}`),sourceNotFound:($)=>W(`Completion source file not found: ${$}`),downloadingCompletion:($)=>W(`Downloading completion from: ${$}`),completionDownloaded:($)=>W(`Completion downloaded to: ${$}`),completionAlreadyDownloaded:($)=>W(`Completion already downloaded: ${$}`),extractingCompletionArchive:($)=>W(`Extracting completion archive: ${$}`),completionArchiveExtracted:($)=>W(`Completion archive extracted to: ${$}`)};class F0{logger;shell;constructor($,M){this.logger=$.getSubLogger({name:"CompletionCommandExecutor"}),this.shell=M}async executeCompletionCommand($,M,J,Q,Y){let G=this.logger.getSubLogger({name:"executeCompletionCommand"}).setPrefix(M);G.debug(D$.commandExecutionStarted(M,$,J));let X=Y?.map((I)=>oQ.dirname(I))??[],Z=[...new Set([...X,Q])],q=Z.join(oQ.delimiter);if(Y&&Y.length>0){let I=[...new Set(Y.map((K)=>oQ.basename(K)))];if(!await this.checkAnyBinaryExistsInPath(I,q)){let K=Z.join(", ");throw Error(`None of the expected binaries (${I.join(", ")}) found in: ${K}. Skipping completion generation to prevent infinite loop.`)}}try{let I=`cd ${Q} && PATH=${q}:$PATH ${$}`,U=await this.shell`sh -c ${I}`.quiet();return G.debug(D$.commandExecutionCompleted(M,J)),U.stdout}catch(I){let U=I&&typeof I==="object"&&"exitCode"in I?I.exitCode:-1,K=I&&typeof I==="object"&&"stderr"in I?I.stderr.toString():"Unknown error",H=`Completion command failed for ${M}: ${$}`;throw G.error(D$.commandExecutionFailed(M,$,U,K)),Error(`${H}
|
|
75
75
|
Exit code: ${U}
|
|
76
|
-
Stderr: ${K}`,{cause:I})}}async checkAnyBinaryExistsInPath($,M){for(let J of $)try{let Q=`PATH=${M} command -v ${J}`;return await this.shell`sh -c ${Q}`.quiet(),!0}catch{}return!1}}import{minimatch as
|
|
76
|
+
Stderr: ${K}`,{cause:I})}}async checkAnyBinaryExistsInPath($,M){for(let J of $)try{let Q=`PATH=${M} command -v ${J}`;return await this.shell`sh -c ${Q}`.quiet(),!0}catch{}return!1}}import{minimatch as K1}from"minimatch";import N$ from"path";var H1=["tar.gz","tar.xz","tar.bz2","zip","tar","tar.lzma","7z"];class eQ{logger;commandExecutor;fs;downloader;archiveExtractor;constructor($,M,J,Q,Y){this.logger=$.getSubLogger({name:"CompletionGenerator"}),this.fs=M,this.commandExecutor=Q||new F0(this.logger,J),this.downloader=Y?.downloader,this.archiveExtractor=Y?.archiveExtractor}async prepareUrlCompletionSource($,M,J){if(!$.url)throw Error(`URL not provided for ${M}`);await this.downloadCompletionFromUrl($.url,J.toolInstallDir,M);let Q=$.source||this.getFilenameFromUrl($.url),Y=N$.isAbsolute(Q)?Q:N$.join(J.toolInstallDir,Q);if(!await this.fs.exists(Y))throw this.logger.warn(D$.sourceNotFound(Y)),Error(`Completion source file not found: ${Y}`);return Y}async generateCompletionFile($,M,J,Q){this.logger.getSubLogger({name:"generateCompletionFile"}).setPrefix(M).debug(D$.generationStarted(M,J));let G=$.url?await this.prepareUrlCompletionSource($,M,Q):$.source;if($.cmd)return this.generateFromCommand($,M,J,Q);if(G){let X={...$,source:G};return this.generateFromSource(X,M,J,Q)}throw Error(`Invalid completion config for ${M}: either 'cmd', 'source', or 'url' must be provided`)}async downloadCompletionFromUrl($,M,J){let Q=this.logger.getSubLogger({name:"downloadCompletionFromUrl"}).setPrefix(J);if(!this.downloader)throw Error("Downloader not provided - cannot download completion from URL");Q.info(D$.downloadingCompletion($)),await this.fs.ensureDir(M);let Y=this.getFilenameFromUrl($),G=N$.join(M,Y);if(await this.fs.exists(G)){Q.debug(D$.completionAlreadyDownloaded(G));return}if(await this.downloader.downloadToFile(Q,$,G),Q.debug(D$.completionDownloaded(G)),this.detectArchiveFormat(Y))await this.extractCompletionArchive(G,M,J)}async extractCompletionArchive($,M,J){let Q=this.logger.getSubLogger({name:"extractCompletionArchive"}).setPrefix(J);if(!this.archiveExtractor)throw Error("Archive extractor not provided - cannot extract completion archive");Q.debug(D$.extractingCompletionArchive($)),await this.archiveExtractor.extract(Q,$,{targetDir:M}),Q.debug(D$.completionArchiveExtracted(M))}getFilenameFromUrl($){let J=new URL($).pathname;return N$.basename(J)||"completion-download"}detectArchiveFormat($){let M=$.toLowerCase();for(let J of H1)if(M.endsWith(`.${J}`))return J;return null}async generateAndWriteCompletionFile($){let{config:M,toolName:J,shellType:Q,context:Y,fs:G}=$,X=await this.generateCompletionFile(M,J,Q,Y);if(await G.ensureDir(N$.dirname(X.targetPath)),X.generatedBy==="source"&&X.sourcePath){if(await G.exists(X.targetPath))await G.rm(X.targetPath);await G.symlink(X.sourcePath,X.targetPath),this.logger.debug(D$.symlinkCreated(X.sourcePath,X.targetPath))}else await G.writeFile(X.targetPath,X.content);return X}async generateFromCommand($,M,J,Q){if(!$.cmd)throw Error(`Command not provided for ${M}`);let Y=await this.commandExecutor.executeCompletionCommand($.cmd,M,J,Q.toolInstallDir,Q.binaryPaths),G=this.generateCompletionFilename($,M,J),X=this.resolveTargetPath(J,Q);return{content:Y,filename:G,targetPath:N$.join(X,G),generatedBy:"command"}}async generateFromSource($,M,J,Q){if(!$.source)throw Error(`Source not provided for ${M}`);let Y=await this.resolveSourcePath($.source,Q.configFilePath);if(!await this.fs.exists(Y))throw this.logger.warn(D$.sourceNotFound(Y)),Error(`Completion source file not found: ${Y}`);let G=this.generateCompletionFilename($,M,J),X=this.resolveTargetPath(J,Q);return{content:"",filename:G,targetPath:N$.join(X,G),generatedBy:"source",sourcePath:Y}}async resolveSourcePath($,M){if(N$.isAbsolute($))return $;let J=M?N$.dirname(M):void 0;if(!J)throw Error(`Cannot resolve relative path '${$}' without configFilePath`);if($.includes("*")||$.includes("?")||$.includes("[")){let Y=(await wM(this.fs,J,J)).find((G)=>K1(G,$));if(Y)return N$.join(J,Y);throw Error(`No files matching pattern '${$}' found in toolDir: ${J}`)}return FJ(J,$)}generateCompletionFilename($,M,J){let Q=$.bin??M;switch(J){case"zsh":return`_${Q}`;case"bash":return`${Q}.bash`;case"powershell":return`${Q}.ps1`;default:return`${Q}.${J}`}}resolveTargetPath($,M){return N$.join(M.shellScriptsDir,$,"completions")}}var F9=/^[a-zA-Z_][a-zA-Z0-9_-]*$/;class Z0{headerWidth;indentSize;onceScriptDir;constructor($){this.headerWidth=$.headerWidth??80,this.indentSize=$.indentSize??2,this.onceScriptDir=$.onceScriptDir}comment($){return`# ${$}`}commentBlock($){return $.map((M)=>this.comment(M)).join(`
|
|
77
77
|
`)}formatFileHeader($){let M=[this.headerLine("="),this.comment("THIS FILE IS AUTOMATICALLY GENERATED BY THE DOTFILES MANAGEMENT TOOL"),this.comment("DO NOT EDIT THIS FILE DIRECTLY - YOUR CHANGES WILL BE OVERWRITTEN"),this.headerLine("="),""];if($?.sourceFile)M.push(this.comment(`Dotfiles directory: ${$.sourceFile}`)),M.push("");return M.join(`
|
|
78
|
-
`)}formatSectionHeader($){return this.headerLine("=",$)}formatChildBlockHeader($){return this.headerLine("=")}formatFileFooter(){return this.headerLine("=","End of Generated File")}headerLine($,M){let J=this.headerWidth;if(!M)return this.comment($.repeat(J-2));let Q=` ${M} `,
|
|
79
|
-
`)}}class
|
|
80
|
-
`),fileExtension:M.fileExtension,onceScripts:
|
|
78
|
+
`)}formatSectionHeader($){return this.headerLine("=",$)}formatChildBlockHeader($){return this.headerLine("=")}formatFileFooter(){return this.headerLine("=","End of Generated File")}headerLine($,M){let J=this.headerWidth;if(!M)return this.comment($.repeat(J-2));let Q=` ${M} `,Y=Math.max(0,J-1-Q.length),G=$.repeat(Math.floor(Y/2)),X=$.repeat(Math.ceil(Y/2));return this.comment(`${G}${Q}${X}`)}generateSourceFunctionName($){return`__source_${$.replace(/[^a-zA-Z0-9]/g,"_").replace(/^_+|_+$/g,"").toLowerCase()}`}}class W0 extends Z0{generateOnceScriptContent($,M){let J=["# Generated once script - will self-delete after execution"];return J.push($),J.push(`rm "${M}"`),J.join(`
|
|
79
|
+
`)}}class LM extends Error{blockId;constructor($,M){super(`Block "${$}": ${M}`);this.blockId=$;this.name="BlockValidationError"}}class qM extends Error{emissionKind;field;constructor($,M,J){super(`${$}.${M}: ${J}`);this.emissionKind=$;this.field=M;this.name="EmissionValidationError"}}var L9=/^[a-zA-Z_][a-zA-Z0-9_]*$/,x9=/^[a-zA-Z_][a-zA-Z0-9_-]*$/;function _1($,M,J){if(!L9.test(J))throw new qM($,M,`"${J}" is not a valid identifier (must match ${L9.source})`)}function $6($,M,J){if(!x9.test(J))throw new qM($,M,`"${J}" is not a valid name (must match ${x9.source})`)}function LJ($,M,J){if(J.trim().length===0)throw new qM($,M,"cannot be empty")}function T9($,M,J){if(Object.keys(J).length===0)throw new qM($,M,"must have at least one entry")}function k9($){T9("environment","variables",$);for(let M of Object.keys($))_1("environment",`variables.${M}`,M)}function S9($){T9("alias","aliases",$);for(let M of Object.keys($))$6("alias",`aliases.${M}`,M)}function L0($){return k9($),{kind:"environment",variables:$}}function x0($){return S9($),{kind:"alias",aliases:$}}function q0($,M){return $6("function","name",$),LJ("function","body",M),{kind:"function",name:$,body:M}}function IM($,M){return LJ("script","content",$),{kind:"script",content:$,timing:M}}function T0($){let M=$.directories&&$.directories.length>0,J=$.files&&$.files.length>0,Q=$.commands&&$.commands.length>0;if(!M&&!J&&!Q)throw new qM("completion","config","at least one of directories, files, or commands must be provided");return{kind:"completion",directories:$.directories,files:$.files,commands:$.commands}}function xJ($,M){return LJ("path","directory",$),{kind:"path",directory:$,position:M?.position??"prepend",deduplicate:M?.deduplicate??!0}}function x$($,M){return{...$,source:M}}function M6($,M){return{...$,priority:M}}function uM($){return $.kind==="environment"}function fM($){return $.kind==="alias"}function pM($){return $.kind==="function"}function h$($){return $.kind==="script"}function cM($){return $.kind==="sourceFile"}function hM($){return $.kind==="source"}function mM($){return $.kind==="sourceFunction"}function UM($){return $.kind==="completion"}function gM($){return $.kind==="path"}var R1=new Set(["environment","path","completion"]);function J6($){return R1.has($.kind)}class TJ{sections=new Map;sectionOrder=[];addSection($,M){if(this.sections.has($))throw new LM($,"section already exists");if(M.priority<0)throw new LM($,"priority must be non-negative");return this.sections.set($,{id:$,options:M,emissions:[],children:new Map,childInsertionOrder:[]}),this.sectionOrder.push($),this}addEmission($,M){if(J6($))this.addHoistedEmission($);else this.addNonHoistedEmission($,M);return this}addEmissionToSection($,M){let J=this.sections.get(M);if(!J)throw new LM(M,"section does not exist");return J.emissions.push($),this}build(){let $=[];for(let M of this.sectionOrder){let J=this.sections.get(M);if(!J)continue;let Q=this.buildBlock(J);$.push(Q)}return $.toSorted((M,J)=>M.priority-J.priority)}addHoistedEmission($){let M=this.findHoistTarget($.kind);if(!M)throw new LM("unknown",`no section accepts hoisted emission kind "${$.kind}"`);M.emissions.push($)}addNonHoistedEmission($,M){let J=this.findChildrenSection();if(!J)throw new LM("unknown","no section allows children for non-hoisted emissions");if(M){let Q=J.children.get(M);if(!Q)Q={id:M,emissions:[],sourceFile:$.source},J.children.set(M,Q),J.childInsertionOrder.push(M);Q.emissions.push($)}else J.emissions.push($)}findHoistTarget($){for(let M of this.sections.values())if(M.options.hoistKinds?.includes($))return M;return}findChildrenSection(){for(let $ of this.sections.values())if($.options.allowChildren)return $;return}buildBlock($){let J=this.deduplicateCompletions($.emissions).toSorted((Y,G)=>(Y.priority??0)-(G.priority??0)),Q=[];for(let Y of $.childInsertionOrder){let G=$.children.get(Y);if(!G)continue;let X=G.emissions.toSorted((Z,q)=>(Z.priority??0)-(q.priority??0));Q.push({id:G.id,title:G.id,priority:Q.length,emissions:X,metadata:G.sourceFile?{sourceFile:G.sourceFile}:void 0})}return{id:$.id,title:$.options.title,priority:$.options.priority,emissions:J,children:Q.length>0?Q:void 0,metadata:$.options.metadata,isFileHeader:$.options.isFileHeader,isFileFooter:$.options.isFileFooter}}deduplicateCompletions($){let M=[],J=[];for(let q of $)if(UM(q))M.push(q);else J.push(q);if(M.length<=1)return $;let Q=new Set,Y=new Set,G=new Set,X;for(let q of M){if(q.directories)for(let I of q.directories)Q.add(I);if(q.files)for(let I of q.files)Y.add(I);if(q.commands)for(let I of q.commands)G.add(I);if(q.priority!==void 0)X=X===void 0?q.priority:Math.min(X,q.priority)}let Z={kind:"completion",directories:Q.size>0?[...Q]:void 0,files:Y.size>0?[...Y]:void 0,commands:G.size>0?[...G]:void 0,priority:X};return[...J,Z]}}var w9=1,nM=3;class kJ{render($,M){let J=$.toSorted((q,I)=>q.priority-I.priority),Q=[],Y=[],G=w9,X=[];for(let q of J)this.collectOnceScripts(q,X);let Z=-1;if(X.length>0)for(let q=J.length-1;q>=0;q--){let I=J[q];if(I&&I.priority<400){Z=q;break}}for(let[q,I]of J.entries()){let U=this.renderBlock(I,M,Y,G);if(U.length>0){if(Q.length>0)Q.push("");Q.push(...U)}if(G=Y.length+1,q===Z&&X.length>0)Q.push(""),Q.push(M.formatOnceScriptInitializer())}return{content:Q.join(`
|
|
80
|
+
`),fileExtension:M.fileExtension,onceScripts:Y}}collectOnceScripts($,M){for(let J of $.emissions)if(h$(J)&&J.timing==="once")M.push({emission:J,blockPriority:$.priority});for(let J of $.children??[])this.collectOnceScripts(J,M)}renderBlock($,M,J,Q){let Y=[],G=Q;if($.isFileHeader)return Y.push(M.formatFileHeader($.metadata)),Y;if($.isFileFooter)return Y.push(M.formatFileFooter()),Y;let X=$.emissions.length>0,Z=($.children?.length??0)>0;if(!X&&!Z)return Y;if($.title)Y.push(M.formatSectionHeader($.title));let q;for(let I of $.emissions){if(I.source&&I.source!==q)Y.push(M.comment(I.source)),q=I.source;if(h$(I)&&I.timing==="once"){let U=M.formatOnceScript(I,G);J.push({filename:U.filename,content:U.content,executable:!0}),G++}else Y.push(M.formatEmission(I))}for(let I of $.children??[]){if(I.emissions.length===0)continue;Y.push(""),Y.push(M.formatChildBlockHeader(I));let U;for(let K of I.emissions){if(K.source&&K.source!==U)Y.push(M.comment(K.source)),U=K.source;if(h$(K)&&K.timing==="once"){let H=M.formatOnceScript(K,G);J.push({filename:H.filename,content:H.content,executable:!0}),G++}else Y.push(M.formatEmission(K))}}return Y}}class SJ extends W0{fileExtension=".bash";formatEmission($){if(uM($))return this.formatEnvironment($);if(fM($))return this.formatAlias($);if(pM($))return this.formatFunction($);if(h$($))return this.formatScript($);if(hM($))return this.formatSource($);if(cM($))return this.formatSourceFile($);if(mM($))return this.formatSourceFunction($);if(UM($))return this.formatCompletion($);if(gM($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,M){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let Q=`once-${M.toString().padStart(nM,"0")}.bash`,Y=`${this.onceScriptDir}/${Q}`,G=c($.content);return{content:this.generateOnceScriptContent(G,Y),filename:Q}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
|
|
81
81
|
# Execute once scripts (runs only once per script)
|
|
82
82
|
shopt -s nullglob
|
|
83
83
|
for once_script in "${this.onceScriptDir}"/*.bash; do
|
|
@@ -87,15 +87,15 @@ Stderr: ${K}`,{cause:I})}}async checkAnyBinaryExistsInPath($,M){for(let J of $)t
|
|
|
87
87
|
`)}formatEnvironment($){let M=[];for(let[J,Q]of Object.entries($.variables))M.push(`export ${J}=${JSON.stringify(Q)}`);return M.join(`
|
|
88
88
|
`)}formatAlias($){let M=[];for(let[J,Q]of Object.entries($.aliases))M.push(`alias ${J}='${Q.replace(/'/g,"'\\''")}'`);return M.join(`
|
|
89
89
|
`)}formatFunction($){let M=c($.body),J=" ".repeat(this.indentSize),Q=M.split(`
|
|
90
|
-
`).map((
|
|
90
|
+
`).map((Y)=>`${J}${Y}`).join(`
|
|
91
91
|
`);return[`${$.name}() {`,Q,"}"].join(`
|
|
92
|
-
`)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),
|
|
93
|
-
`).map((
|
|
94
|
-
`);return[`${J}() {`,
|
|
92
|
+
`)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),Y=M.split(`
|
|
93
|
+
`).map((G)=>`${Q}${G}`).join(`
|
|
94
|
+
`);return[`${J}() {`,Y,"}",`source <(${J})`,`unset -f ${J}`].join(`
|
|
95
95
|
`)}formatSourceFunction($){return`source <(${$.functionName})`}formatCompletion($){let M=[];if($.files)for(let J of $.files)M.push(`[[ -f "${J}" ]] && source "${J}"`);return M.join(`
|
|
96
96
|
`)}formatPath($){let M=$.directory;if($.deduplicate){if($.position==="prepend")return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="${M}:$PATH"`,"fi"].join(`
|
|
97
97
|
`);return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="$PATH:${M}"`,"fi"].join(`
|
|
98
|
-
`)}if($.position==="prepend")return`export PATH="${M}:$PATH"`;return`export PATH="$PATH:${M}"`}}class wJ extends
|
|
98
|
+
`)}if($.position==="prepend")return`export PATH="${M}:$PATH"`;return`export PATH="$PATH:${M}"`}}class wJ extends Z0{fileExtension=".ps1";formatEmission($){if(uM($))return this.formatEnvironment($);if(fM($))return this.formatAlias($);if(pM($))return this.formatFunction($);if(h$($))return this.formatScript($);if(hM($))return this.formatSource($);if(cM($))return this.formatSourceFile($);if(mM($))return this.formatSourceFunction($);if(UM($))return this.formatCompletion($);if(gM($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,M){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let Q=`once-${M.toString().padStart(nM,"0")}.ps1`,Y=`${this.onceScriptDir}/${Q}`,G=c($.content);return{content:this.generateOnceScriptContent(G,Y),filename:Q}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
|
|
99
99
|
# Execute once scripts (runs only once per script)
|
|
100
100
|
Get-ChildItem -Path "${this.onceScriptDir}/*.ps1" -ErrorAction SilentlyContinue | ForEach-Object {
|
|
101
101
|
if (Test-Path $_.FullName) {
|
|
@@ -105,14 +105,14 @@ Stderr: ${K}`,{cause:I})}}async checkAnyBinaryExistsInPath($,M){for(let J of $)t
|
|
|
105
105
|
`)}formatEnvironment($){let M=[];for(let[J,Q]of Object.entries($.variables))M.push(`$env:${J} = ${JSON.stringify(Q)}`);return M.join(`
|
|
106
106
|
`)}formatAlias($){let M=[];for(let[J,Q]of Object.entries($.aliases))M.push(`Set-Alias -Name ${J} -Value '${Q.replace(/'/g,"''")}'`);return M.join(`
|
|
107
107
|
`)}formatFunction($){let M=c($.body),J=" ".repeat(this.indentSize),Q=M.split(`
|
|
108
|
-
`).map((
|
|
108
|
+
`).map((Y)=>`${J}${Y}`).join(`
|
|
109
109
|
`);return[`function ${$.name} {`,Q,"}"].join(`
|
|
110
|
-
`)}formatScript($){return c($.content)}formatSourceFile($){return`. "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),
|
|
111
|
-
`).map((
|
|
112
|
-
`);return[`function ${J} {`,
|
|
110
|
+
`)}formatScript($){return c($.content)}formatSourceFile($){return`. "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),Y=M.split(`
|
|
111
|
+
`).map((G)=>`${Q}${G}`).join(`
|
|
112
|
+
`);return[`function ${J} {`,Y,"}",`Invoke-Expression (& ${J})`,`Remove-Item Function:\\${J} -ErrorAction SilentlyContinue`].join(`
|
|
113
113
|
`)}formatSourceFunction($){return`Invoke-Expression (& ${$.functionName})`}formatCompletion($){let M=[];if($.files)for(let J of $.files)M.push(`if (Test-Path "${J}") { . "${J}" }`);return M.join(`
|
|
114
114
|
`)}formatPath($){let M=$.directory;if($.deduplicate){if($.position==="prepend")return`if ($env:PATH -notlike "*${M}*") { $env:PATH = "${M};$env:PATH" }`;return`if ($env:PATH -notlike "*${M}*") { $env:PATH = "$env:PATH;${M}" }`}if($.position==="prepend")return`$env:PATH = "${M};$env:PATH"`;return`$env:PATH = "$env:PATH;${M}"`}generateOnceScriptContent($,M){let J=["# Generated once script - will self-delete after execution"];return J.push($),J.push(`Remove-Item "${M}"`),J.join(`
|
|
115
|
-
`)}}class bJ extends
|
|
115
|
+
`)}}class bJ extends W0{fileExtension=".zsh";formatEmission($){if(uM($))return this.formatEnvironment($);if(fM($))return this.formatAlias($);if(pM($))return this.formatFunction($);if(h$($))return this.formatScript($);if(hM($))return this.formatSource($);if(cM($))return this.formatSourceFile($);if(mM($))return this.formatSourceFunction($);if(UM($))return this.formatCompletion($);if(gM($))return this.formatPath($);throw Error(`Unknown emission kind: ${$.kind}`)}formatOnceScript($,M){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once scripts");let Q=`once-${M.toString().padStart(nM,"0")}.zsh`,Y=`${this.onceScriptDir}/${Q}`,G=c($.content);return{content:this.generateOnceScriptContent(G,Y),filename:Q}}formatOnceScriptInitializer(){if(!this.onceScriptDir)throw Error("onceScriptDir is required for once script initializer");return c(`
|
|
116
116
|
# Execute once scripts (runs only once per script)
|
|
117
117
|
for once_script in "${this.onceScriptDir}"/*.zsh(N); do
|
|
118
118
|
[[ -f "$once_script" ]] && source "$once_script"
|
|
@@ -120,45 +120,45 @@ Stderr: ${K}`,{cause:I})}}async checkAnyBinaryExistsInPath($,M){for(let J of $)t
|
|
|
120
120
|
`)}formatEnvironment($){let M=[];for(let[J,Q]of Object.entries($.variables))M.push(`export ${J}=${JSON.stringify(Q)}`);return M.join(`
|
|
121
121
|
`)}formatAlias($){let M=[];for(let[J,Q]of Object.entries($.aliases))M.push(`alias ${J}='${Q.replace(/'/g,"'\\''")}'`);return M.join(`
|
|
122
122
|
`)}formatFunction($){let M=c($.body),J=" ".repeat(this.indentSize),Q=M.split(`
|
|
123
|
-
`).map((
|
|
123
|
+
`).map((Y)=>`${J}${Y}`).join(`
|
|
124
124
|
`);return[`${$.name}() {`,Q,"}"].join(`
|
|
125
|
-
`)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),
|
|
126
|
-
`).map((
|
|
127
|
-
`);return[`${J}() {`,
|
|
125
|
+
`)}formatScript($){return c($.content)}formatSourceFile($){return`source "${$.path}"`}formatSource($){let M=c($.content),J=$.functionName,Q=" ".repeat(this.indentSize),Y=M.split(`
|
|
126
|
+
`).map((G)=>`${Q}${G}`).join(`
|
|
127
|
+
`);return[`${J}() {`,Y,"}",`source <(${J})`,`unset -f ${J}`].join(`
|
|
128
128
|
`)}formatSourceFunction($){return`source <(${$.functionName})`}formatCompletion($){let M=[];if(M.push("typeset -U fpath"),$.directories)for(let J of $.directories)M.push(`fpath=(${JSON.stringify(J)} $fpath)`);if($.files)for(let J of $.files)M.push(`source "${J}"`);return M.join(`
|
|
129
129
|
`)}formatPath($){let M=$.directory;if($.deduplicate){if($.position==="prepend")return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="${M}:$PATH"`,"fi"].join(`
|
|
130
130
|
`);return[`if [[ ":$PATH:" != *":${M}:"* ]]; then`,` export PATH="$PATH:${M}"`,"fi"].join(`
|
|
131
|
-
`)}if($.position==="prepend")return`export PATH="${M}:$PATH"`;return`export PATH="$PATH:${M}"`}}function
|
|
132
|
-
`)}class
|
|
133
|
-
${
|
|
134
|
-
`))
|
|
135
|
-
`;let U=`${
|
|
131
|
+
`)}if($.position==="prepend")return`export PATH="${M}:$PATH"`;return`export PATH="$PATH:${M}"`}}function Q6($,M){switch($){case"zsh":return new bJ(M);case"bash":return new SJ(M);case"powershell":return new wJ(M);default:throw Error(`Unsupported shell type: ${$}`)}}import NJ from"path";function Y6($,M){return`# ${M}`}function O1($,M,J){if(!J)return Y6($,M.repeat(78));let Y=` ${J} `,G=Math.max(0,79-Y.length),X=M.repeat(Math.floor(G/2)),Z=M.repeat(Math.ceil(G/2));return Y6($,`${X}${Y}${Z}`)}function N9($,M){switch($){case"zsh":case"bash":return`source "${M}"`;case"powershell":return`. "${M}"`;default:throw Error(`Unsupported shell type: ${$}`)}}function v9($){return[Y6($,"Generated via dotfiles generator - do not modify"),O1($,"-")].join(`
|
|
132
|
+
`)}class G6{fileSystem;homeDir;constructor($,M){this.fileSystem=$,this.homeDir=M}async updateProfiles($){let M=[];for(let J of $){let Q=await this.updateProfile(J);M.push(Q)}return M}getProfilePath($){switch($){case"zsh":return NJ.join(this.homeDir,".zshrc");case"bash":return NJ.join(this.homeDir,".bashrc");case"powershell":return NJ.join(this.homeDir,".config/powershell/profile.ps1");default:throw Error(`Unsupported shell type: ${$}`)}}async hasSourceLine($,M){try{let J=await this.fileSystem.readFile($);return this.getSourcePatterns(M).some((Y)=>J.includes(Y))}catch(J){return!1}}async updateProfile($){let M=$.profilePath??this.getProfilePath($.shellType),J=await this.fileSystem.exists(M),Q={shellType:$.shellType,profilePath:M,fileExists:J,wasUpdated:!1,wasAlreadyPresent:!1};if(!J&&$.onlyIfExists)return Q;let Y="";if(J)try{Y=await this.fileSystem.readFile(M)}catch(H){Y=""}let G=N9($.shellType,$.generatedScriptPath),Z=`${v9($.shellType)}
|
|
133
|
+
${G}`,q="# Generated via dotfiles generator - do not modify";if(Y.includes(q)){let H=this.replaceGeneratedBlocks(Y,Z);if(H!==Y)await this.fileSystem.writeFile(M,H),Q.wasUpdated=!0;else Q.wasAlreadyPresent=!0;return Q}if(this.getSourcePatterns($.generatedScriptPath).some((H)=>Y.includes(H)))return Q.wasAlreadyPresent=!0,Q;if(Y&&!Y.endsWith(`
|
|
134
|
+
`))Y+=`
|
|
135
|
+
`;let U=`${Y}
|
|
136
136
|
${Z}
|
|
137
|
-
`,K=
|
|
137
|
+
`,K=NJ.dirname(M);return await this.fileSystem.ensureDir(K),await this.fileSystem.writeFile(M,U),Q.wasUpdated=!0,Q}replaceGeneratedBlocks($,M){let Q="# Generated via dotfiles generator - do not modify".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Y=new RegExp(`${Q}[\\s\\S]*?^\\s*(?:source|\\.)\\s+["'].*?["'].*?$`,"gm"),G=$.split(Y),X=G[0]||"";if(X&&!X.endsWith(`
|
|
138
138
|
`))X+=`
|
|
139
139
|
`;X+=`${M}
|
|
140
|
-
`;for(let Z=1;Z<Y.length;Z++){let q=Y[Z];if(q)X+=q}return X}getSourcePatterns($){return[`source "${$}"`,`source '${$}'`,`source ${$}`,`. "${$}"`,`. '${$}'`,`. ${$}`]}}import k0 from"path";var v$={constructor:{initialized:()=>W("ShellInitGenerator initialized")},generate:{parsedToolCount:($)=>W(`Resolved ${$} tool configurations for shell init generation`),resolvedOutputPath:($)=>W(`Shell init output path resolved to ${$}`),shellTypeFailure:($)=>W(`Shell init generation failed for ${$}`),writeFailure:($)=>W(`Failed to write shell init artifact ${$}`)},profiles:{starting:($)=>W(`Updating ${$} shell profile entries`),skipped:($)=>W(`Skipping profile update for ${$} as it is not configured`)},cleanup:{onceScriptRemoved:($)=>W(`Removed stale once script ${$}`),failure:($)=>W(`Failed to clean shell init once directory ${$}`)}};import O1 from"path";import YG from"path";class iM{projectConfig;constructor($){this.projectConfig=$}extractEmissions($){let M=[],J=$.configFilePath,Q=this.getShellConfig($);if(Q?.env){let G=L0(Q.env);M.push(J?x$(G,J):G)}if(Q?.aliases){let G=x0(Q.aliases);M.push(J?x$(G,J):G)}if(Q?.functions)for(let[G,Y]of Object.entries(Q.functions)){let X=W0(G,Y);M.push(J?x$(X,J):X)}if(Q?.scripts)for(let G of Q.scripts){let Y=this.createScriptEmission(G);if(Y)M.push(J?x$(Y,J):Y)}if(Q?.completions){let G=this.resolveCompletionConfig(Q.completions);if(G){let Y=this.createCompletionEmission(G);if(Y)M.push(J?x$(Y,J):Y)}}if(Q?.paths){let G=new Set;for(let Y of Q.paths){let X=this.resolvePathInput(Y);if(X&&!G.has(X)){G.add(X);let Z=xJ(X);M.push(J?x$(Z,J):Z)}}}return M}createScriptEmission($){let M=e0($);if(r0($))return qM(M,"once");else if(t0($))return qM(M,"always");else if(o0($))return qM(M,"raw");return}createCompletionEmission($){let M=this.getCompletionDir();if($.cmd||$.source)return T0({files:[M]});return}resolveCompletionConfig($){if(typeof $==="function")return{source:"callback"};if(typeof $==="string")return{source:$};return $}resolvePathInput($){if(typeof $==="function"){let M=$(void 0);if(M instanceof Promise)return;return M}return $}hasEmissions($){let M=this.getShellConfig($);if(!M)return!1;return Boolean(M.env&&Object.keys(M.env).length>0||M.aliases&&Object.keys(M.aliases).length>0||M.functions&&Object.keys(M.functions).length>0||M.scripts&&M.scripts.length>0||M.paths&&M.paths.length>0||M.completions)}generateFileContent($){return this.renderContent($).content}getDefaultOutputPath(){return YG.join(this.projectConfig.paths.shellScriptsDir,`main${this.fileExtension}`)}getAdditionalFiles($){return this.renderContent($).onceScripts.map((J)=>({content:J.content,outputPath:YG.join(this.projectConfig.paths.shellScriptsDir,".once",J.filename)}))}createFormatterConfig(){return{onceScriptDir:YG.join(this.projectConfig.paths.shellScriptsDir,".once")}}renderContent($){let M=this.createFormatterConfig(),J=JG(this.shellType,M),Q=new kJ,G=new TJ().addSection("header",{priority:0,isFileHeader:!0,metadata:{sourceFile:this.projectConfig.paths.dotfilesDir}}).addSection("cli",{title:"Dotfiles CLI",priority:50}).addSection("path",{title:"PATH Modifications",priority:100,hoistKinds:["path"]}).addSection("environment",{title:"Environment Variables",priority:200,hoistKinds:["environment"]}).addSection("main",{title:"Tool-Specific Initializations",priority:300,allowChildren:!0}).addSection("completions",{title:"Shell Completions Setup",priority:500,hoistKinds:["completion"]}).addSection("footer",{priority:999,isFileFooter:!0}),Y=$G(xJ(this.projectConfig.paths.targetDir,{deduplicate:!0}),-1);G.addEmission(Y);let X=aM(),Z=this.projectConfig.configFilePath?.replaceAll('"',"\\\""),q=Z?` --config "${Z}"`:"",I=`${X}${q} "$@"`,U=W0("dotfiles",I);G.addEmissionToSection(U,"cli");for(let[H,_]of $)for(let O of _)G.addEmission(O,H);let K=G.build();return Q.render(K,J)}}class XG extends iM{shellType="bash";fileExtension=".bash";getShellConfig($){return $.shellConfigs?.bash}getCompletionDir(){return O1.join(this.projectConfig.paths.shellScriptsDir,"bash","completions")}}import j1 from"path";class ZG extends iM{shellType="powershell";fileExtension=".ps1";getShellConfig($){return $.shellConfigs?.powershell}getCompletionDir(){return j1.join(this.projectConfig.paths.shellScriptsDir,"powershell","completions")}}import V1 from"path";class WG extends iM{shellType="zsh";fileExtension=".zsh";getShellConfig($){return $.shellConfigs?.zsh}getCompletionDir(){return V1.join(this.projectConfig.paths.shellScriptsDir,"zsh","completions")}createCompletionEmission($){let M=this.getCompletionDir();if($.cmd||$.source)return T0({directories:[M]});return}}var z1=new Map([["zsh",($)=>new WG($)],["bash",($)=>new XG($)],["powershell",($)=>new ZG($)]]);function NY($,M){let J=z1.get($);if(!J)throw Error(`Unsupported shell type: ${$}`);return J(M)}class qG{fs;projectConfig;logger;constructor($,M,J){this.logger=$.getSubLogger({name:"ShellInitGenerator"}),this.logger.getSubLogger({name:"constructor"}).debug(v$.constructor.initialized()),this.fs=M,this.projectConfig=J}async generate($,M){let J=this.logger.getSubLogger({name:"generate"}),Q=M?.shellTypes??["zsh"],G=new Map,Y=null,X=$?Object.keys($).length:0;J.debug(v$.generate.parsedToolCount(X));for(let I of Q){let U=await this.generateForShellType(I,$,M);if(U){if(G.set(I,U.outputPath),Y===null)Y=U.outputPath}}if(G.size===0)return null;let Z={files:G,primaryPath:Y};if(M?.updateProfileFiles??!0)Z.profileUpdates=await this.updateProfileFiles(G);return Z}async generateForShellType($,M,J){let Q=this.logger.getSubLogger({name:"generateForShellType"});try{let G=NY($,this.projectConfig),Y=J?.outputPath??G.getDefaultOutputPath();Q.debug(v$.generate.resolvedOutputPath(Y));let X=this.extractToolEmissions(M,G,J),Z=G.generateFileContent(X);await this.cleanupOnceScriptsDirectory($);let q=G.getAdditionalFiles(X);return await this.writeShellFiles(Y,Z,q)?{outputPath:Y}:null}catch(G){return Q.debug(v$.generate.shellTypeFailure($),G),null}}extractToolEmissions($,M,J){let Q=new Map;for(let G in $){let Y=$[G];if(!Y)continue;let X=J?.systemInfo?G$(Y,J.systemInfo):Y,Z=M.extractEmissions(X),q=J?.pluginShellInit?.[G]?.[M.shellType];if(q){let I=this.convertPluginShellInit(q,X.configFilePath);Z.push(...I)}if(Z.length>0)Q.set(G,Z)}return Q}convertPluginShellInit($,M){let J=[],Q=M;if($.environmentVariables){let G=L0($.environmentVariables);J.push(Q?x$(G,Q):G)}if($.aliases){let G=x0($.aliases);J.push(Q?x$(G,Q):G)}if($.scripts)for(let G of $.scripts){let Y=e0(G),X;if(r0(G))X=qM(Y,"once");else if(t0(G))X=qM(Y,"always");else if(o0(G))X=qM(Y,"raw");if(X)J.push(Q?x$(X,Q):X)}if($.functions)for(let[G,Y]of Object.entries($.functions)){let X=W0(G,Y);J.push(Q?x$(X,Q):X)}return J}async writeShellFiles($,M,J){let Q=this.logger.getSubLogger({name:"writeShellFiles"});try{await this.fs.ensureDir(k0.dirname($)),await this.fs.writeFile($,M);for(let G of J)await this.writeAdditionalFile(G);return!0}catch(G){return Q.debug(v$.generate.writeFailure($),G),!1}}async writeAdditionalFile($){let M=this.logger.getSubLogger({name:"writeAdditionalFile"});try{await this.fs.ensureDir(k0.dirname($.outputPath)),await this.fs.writeFile($.outputPath,$.content)}catch(J){M.debug(v$.generate.writeFailure($.outputPath),J)}}async updateProfileFiles($){let M=this.logger.getSubLogger({name:"updateProfileFiles"}),J=new GG(this.fs,this.projectConfig.paths.homeDir),Q=this.projectConfig.features.shellInstall;if(!Q)return M.debug(v$.profiles.skipped("all")),[];let G=[];for(let[Y,X]of $){let Z;if(Y==="zsh")Z=Q?.zsh;else if(Y==="bash")Z=Q?.bash;else if(Y==="powershell")Z=Q?.powershell;if(!Z){M.debug(v$.profiles.skipped(Y));continue}if(Z?.startsWith("~/"))Z=k0.join(this.projectConfig.paths.homeDir,Z.slice(2));else if(Z==="~")Z=this.projectConfig.paths.homeDir;G.push({shellType:Y,generatedScriptPath:X,onlyIfExists:!0,projectConfigPath:this.projectConfig.configFilePath,profilePath:Z})}return M.debug(v$.profiles.starting(G.length)),await J.updateProfiles(G)}async cleanupOnceScriptsDirectory($){let M=this.logger.getSubLogger({name:"cleanupOnceScriptsDirectory"}),J=k0.join(this.projectConfig.paths.shellScriptsDir,".once");try{if(!await this.fs.exists(J))return;let G=this.getShellExtension($),Y=await this.fs.readdir(J);for(let X of Y)if(X.endsWith(`.${G}`)){let Z=k0.join(J,X);await this.fs.rm(Z),M.debug(v$.cleanup.onceScriptRemoved(Z))}}catch(Q){M.debug(v$.cleanup.failure(J),Q)}}getShellExtension($){switch($){case"zsh":return"zsh";case"bash":return"bash";case"powershell":return"ps1";default:throw Error(`Unsupported shell type: ${$}`)}}}import B1 from"path";class IG{storage;shellType;context;logger;toolName;sourceFileCounter=0;sourceCounter=0;constructor($,M,J,Q,G){this.storage=$,this.shellType=M,this.context=J,this.logger=Q.getSubLogger({name:"ShellConfigurator"}).setPrefix(G),this.toolName=G}env($){return this.storage.env={...this.storage.env,...$},this}aliases($){return this.storage.aliases={...this.storage.aliases,...$},this}sourceFile($){let M=this.resolvePath($),J=this.generateSourceFileFunctionName(),Q=this.createSourceFileFunctionBody(M);this.storage.functions[J]=Q;let G=this.createSourceFunctionCommand(J),Y=this.createUnsetFunctionCommand(J);return this.storage.scripts.push(n$(G)),this.storage.scripts.push(n$(Y)),this}sourceFunction($){let M=this.createSourceFunctionCommand($);return this.storage.scripts.push(n$(M)),this}source($){let M=this.generateSourceFunctionName();this.storage.functions[M]=$;let J=this.createSourceFunctionCommand(M),Q=this.createUnsetFunctionCommand(M);return this.storage.scripts.push(n$(J)),this.storage.scripts.push(n$(Q)),this}completions($){return this.storage.completions=$,this}once($){return this.storage.scripts.push(x6($)),this}always($){return this.storage.scripts.push(T6($)),this}functions($){let M=this.validateFunctionNames($);return this.storage.functions={...this.storage.functions,...M},this}path($){return this.storage.paths.push($),this}validateFunctionNames($){let M={};for(let[J,Q]of Object.entries($)){if(!J||!EY.test(J)){this.logger.error(ZM.invalidFunctionName(J));continue}M[J]=Q}return M}generateSourceFileFunctionName(){let $=this.sourceFileCounter++;return`__dotfiles_source_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}generateSourceFunctionName(){let $=this.sourceCounter++;return`__dotfiles_source_inline_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}createSourceFileFunctionBody($){let M=JSON.stringify($);if(this.shellType==="powershell")return`if (Test-Path ${M}) { Get-Content ${M} -Raw }`;return`[[ -f ${M} ]] && cat ${M}`}createUnsetFunctionCommand($){if(this.shellType==="powershell")return`Remove-Item Function:\\${$} -ErrorAction SilentlyContinue`;return`unset -f ${$}`}createSourceFunctionCommand($){if(this.shellType==="powershell")return`. (${$})`;return`source <(${$})`}resolvePath($){let M=$.trim();if(M.length===0){let Q=ZM.configurationFieldInvalid("shell source path",$,"non-empty value");throw this.logger.error(Q),Error(Q)}if(B1.isAbsolute(M))return this.normalizePath(M);if(!this.context){let Q=ZM.configurationFieldRequired("tool context",`Please ensure createInstallFunction receives tool context before using shell.sourceFile() for "${this.toolName}"`);throw this.logger.error(Q),Error(Q)}let J=FJ(this.context.toolDir,M);return this.normalizePath(J)}normalizePath($){if(this.shellType==="powershell")return $.replace(/\//gu,"\\");return $.replace(/\\/gu,"/")}}class S0{logger;toolName;binaries=[];versionNum="latest";currentInstallationMethod;currentInstallParams;dependencies=[];isDisabled=!1;hostnamePattern;internalShellConfigs={zsh:{scripts:[],aliases:{},env:{},functions:{},paths:[]},bash:{scripts:[],aliases:{},env:{},functions:{},paths:[]},powershell:{scripts:[],aliases:{},env:{},functions:{},paths:[]}};context;symlinkPairs=[];copyPairs=[];updateCheckConfig;platformConfigEntries=[];isPlatformScope;bin($,M){let J=M||`*/${$}`;return this.binaries.push({name:$,pattern:J}),this}version($){return this.versionNum=$,this}install($,M){return this.currentInstallationMethod=$,this.currentInstallParams=M,this}hook($,M){if(!this.currentInstallParams)return this.logger.warn(ZM.configurationFieldIgnored("hook",`hook() called for tool "${this.toolName}" before install(). Hook will not be set as install() was not called first.`)),this;let J=this.currentInstallParams.hooks||{},Q=J[$]||[];return Q.push(M),J[$]=Q,this.currentInstallParams.hooks=J,this}zsh($){return this.configureShell("zsh",$)}bash($){return this.configureShell("bash",$)}powershell($){return this.configureShell("powershell",$)}buildShellConfigs(){let $=["zsh","bash","powershell"],M={},J=!1;for(let Q of $){let G=this.internalShellConfigs[Q],Y=G.scripts.length>0,X=Object.keys(G.aliases).length>0,Z=Object.keys(G.env).length>0,q=Object.keys(G.functions).length>0,I=G.paths.length>0,U=G.completions!==void 0;if(Y||X||Z||q||I||U)M[Q]={...Y&&{scripts:G.scripts},...X&&{aliases:G.aliases},...Z&&{env:G.env},...q&&{functions:G.functions},...I&&{paths:G.paths},...U&&{completions:G.completions}},J=!0}return J?M:void 0}symlink($,M){return this.symlinkPairs.push({source:$,target:M}),this}copy($,M){return this.copyPairs.push({source:$,target:M}),this}dependsOn(...$){for(let M of $){let J=M.trim();if(J.length===0){let Q=ZM.configurationFieldInvalid("dependency",M,"non-empty string");this.logger.warn(Q);continue}if(!this.dependencies.includes(J))this.dependencies.push(J)}return this}platform($,M,J){let Q,G;if(typeof M==="function")G=M,Q=void 0;else{if(Q=M,typeof J!=="function"){let q=ZM.configurationFieldRequired("configure callback",`platform() called for tool "${this.toolName}" with architectures but without a configure callback`);throw this.logger.error(q),Error(q)}G=J}let Y=new S0(this.logger,this.toolName,!0);Y.setContext(this.context),G((...q)=>{if(q.length===0)return Y;let[I,U]=q;return Y.install(I,U),Y});let Z=Y.buildPlatformConfig();return this.platformConfigEntries.push({platforms:$,architectures:Q,config:Z}),this}disable(){return this.isDisabled=!0,this}hostname($){if($ instanceof RegExp)this.hostnamePattern=$.source;else this.hostnamePattern=$;return this}updateCheck($){return this.updateCheckConfig=$,this}build(){let $=this.buildBaseConfig();if(this.hasInstallationMethod())return this.buildInstallableToolConfig($);return this.validateConfigurationOnly($),this.buildConfigurationOnlyTool($)}buildBaseConfig(){return{name:this.toolName,binaries:this.binaries.length>0?this.binaries.map(($)=>$.pattern===`*/${$.name}`?$.name:$):void 0,version:this.versionNum,disabled:this.isDisabled?!0:void 0,hostname:this.hostnamePattern,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0,platformConfigs:this.isPlatformScope?void 0:this.platformConfigEntries.length>0?this.platformConfigEntries:void 0}}buildPlatformConfig(){let $={binaries:this.binaries.length>0?this.binaries.map((M)=>M.pattern===`*/${M.name}`?M.name:M):void 0,version:this.versionNum!=="latest"?this.versionNum:void 0,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0};if(this.hasInstallationMethod())$.installationMethod=this.currentInstallationMethod,$.installParams=this.currentInstallParams;return Object.keys($).forEach((M)=>{if($[M]===void 0)delete $[M]}),$}hasInstallationMethod(){return Boolean(this.currentInstallationMethod&&this.currentInstallParams)}buildInstallableToolConfig($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:this.currentInstallationMethod,installParams:this.currentInstallParams}}validateConfigurationOnly($){if(!(($.binaries&&$.binaries.length>0?$.binaries:[]).length>0||$.shellConfigs||$.symlinks||$.copies||$.platformConfigs&&$.platformConfigs.length>0)){let Q=ZM.configurationFieldRequired("tool definition",`Tool "${$.name}" must define at least binaries, shell init scripts (zsh/bash/powershell), symlinks, or platformConfigs`);throw this.logger.error(Q),Error(Q)}}buildConfigurationOnlyTool($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:"manual",installParams:{}}}constructor($,M,J=!1){this.logger=$.getSubLogger({name:"IToolConfigBuilder"}),this.toolName=M,this.isPlatformScope=J}setContext($){this.context=$}get shellConfigs(){return this.internalShellConfigs}configureShell($,M){let J=this.internalShellConfigs[$],Q=new IG(J,$,this.context,this.logger,this.toolName),G=M(Q);if(this.isPromise(G))return G.then(()=>this);return this}isPromise($){if($===null||$===void 0)return!1;if(typeof $!=="object"&&typeof $!=="function")return!1;return typeof $.then==="function"}}function yY($,M,J){let Q=null,G=()=>{if(!Q)Q=new S0($,M);return Q.setContext(J),Q};function Y(X,Z){let q=G();if(X){let I={};q.currentInstallationMethod=X,q.currentInstallParams=Z??I}return q}return Y}import NJ from"path";var p={configurationProcessing:()=>W("config processing"),platformOverrides:($,M)=>W(`platform overrides: ${$} ${M}`),configurationValidationFailed:($)=>W(`Configuration validation failed:
|
|
140
|
+
`;for(let Z=1;Z<G.length;Z++){let q=G[Z];if(q)X+=q}return X}getSourcePatterns($){return[`source "${$}"`,`source '${$}'`,`source ${$}`,`. "${$}"`,`. '${$}'`,`. ${$}`]}}import k0 from"path";var v$={constructor:{initialized:()=>W("ShellInitGenerator initialized")},generate:{parsedToolCount:($)=>W(`Resolved ${$} tool configurations for shell init generation`),resolvedOutputPath:($)=>W(`Shell init output path resolved to ${$}`),shellTypeFailure:($)=>W(`Shell init generation failed for ${$}`),writeFailure:($)=>W(`Failed to write shell init artifact ${$}`)},profiles:{starting:($)=>W(`Updating ${$} shell profile entries`),skipped:($)=>W(`Skipping profile update for ${$} as it is not configured`)},cleanup:{onceScriptRemoved:($)=>W(`Removed stale once script ${$}`),failure:($)=>W(`Failed to clean shell init once directory ${$}`)}};import j1 from"path";import X6 from"path";class iM{projectConfig;constructor($){this.projectConfig=$}extractEmissions($){let M=[],J=$.configFilePath,Q=this.getShellConfig($);if(Q?.env){let Y=L0(Q.env);M.push(J?x$(Y,J):Y)}if(Q?.aliases){let Y=x0(Q.aliases);M.push(J?x$(Y,J):Y)}if(Q?.functions)for(let[Y,G]of Object.entries(Q.functions)){let X=q0(Y,G);M.push(J?x$(X,J):X)}if(Q?.scripts)for(let Y of Q.scripts){let G=this.createScriptEmission(Y);if(G)M.push(J?x$(G,J):G)}if(Q?.completions){let Y=this.resolveCompletionConfig(Q.completions);if(Y){let G=this.createCompletionEmission(Y);if(G)M.push(J?x$(G,J):G)}}if(Q?.paths){let Y=new Set;for(let G of Q.paths){let X=this.resolvePathInput(G);if(X&&!Y.has(X)){Y.add(X);let Z=xJ(X);M.push(J?x$(Z,J):Z)}}}return M}createScriptEmission($){let M=e0($);if(r0($))return IM(M,"once");else if(t0($))return IM(M,"always");else if(o0($))return IM(M,"raw");return}createCompletionEmission($){let M=this.getCompletionDir();if($.cmd||$.source)return T0({files:[M]});return}resolveCompletionConfig($){if(typeof $==="function")return{source:"callback"};if(typeof $==="string")return{source:$};return $}resolvePathInput($){if(typeof $==="function"){let M=$(void 0);if(M instanceof Promise)return;return M}return $}hasEmissions($){let M=this.getShellConfig($);if(!M)return!1;return Boolean(M.env&&Object.keys(M.env).length>0||M.aliases&&Object.keys(M.aliases).length>0||M.functions&&Object.keys(M.functions).length>0||M.scripts&&M.scripts.length>0||M.paths&&M.paths.length>0||M.completions)}generateFileContent($){return this.renderContent($).content}getDefaultOutputPath(){return X6.join(this.projectConfig.paths.shellScriptsDir,`main${this.fileExtension}`)}getAdditionalFiles($){return this.renderContent($).onceScripts.map((J)=>({content:J.content,outputPath:X6.join(this.projectConfig.paths.shellScriptsDir,".once",J.filename)}))}createFormatterConfig(){return{onceScriptDir:X6.join(this.projectConfig.paths.shellScriptsDir,".once")}}renderContent($){let M=this.createFormatterConfig(),J=Q6(this.shellType,M),Q=new kJ,Y=new TJ().addSection("header",{priority:0,isFileHeader:!0,metadata:{sourceFile:this.projectConfig.paths.dotfilesDir}}).addSection("cli",{title:"Dotfiles CLI",priority:50}).addSection("path",{title:"PATH Modifications",priority:100,hoistKinds:["path"]}).addSection("environment",{title:"Environment Variables",priority:200,hoistKinds:["environment"]}).addSection("main",{title:"Tool-Specific Initializations",priority:300,allowChildren:!0}).addSection("completions",{title:"Shell Completions Setup",priority:500,hoistKinds:["completion"]}).addSection("footer",{priority:999,isFileFooter:!0}),G=M6(xJ(this.projectConfig.paths.targetDir,{deduplicate:!0}),-1);Y.addEmission(G);let X=sM(),Z=this.projectConfig.configFilePath?.replaceAll('"',"\\\""),q=Z?` --config "${Z}"`:"",I=`${X}${q} "$@"`,U=q0("dotfiles",I);Y.addEmissionToSection(U,"cli");for(let[H,_]of $)for(let O of _)Y.addEmission(O,H);let K=Y.build();return Q.render(K,J)}}class Z6 extends iM{shellType="bash";fileExtension=".bash";getShellConfig($){return $.shellConfigs?.bash}getCompletionDir(){return j1.join(this.projectConfig.paths.shellScriptsDir,"bash","completions")}}import V1 from"path";class W6 extends iM{shellType="powershell";fileExtension=".ps1";getShellConfig($){return $.shellConfigs?.powershell}getCompletionDir(){return V1.join(this.projectConfig.paths.shellScriptsDir,"powershell","completions")}}import z1 from"path";class q6 extends iM{shellType="zsh";fileExtension=".zsh";getShellConfig($){return $.shellConfigs?.zsh}getCompletionDir(){return z1.join(this.projectConfig.paths.shellScriptsDir,"zsh","completions")}createCompletionEmission($){let M=this.getCompletionDir();if($.cmd||$.source)return T0({directories:[M]});return}}var B1=new Map([["zsh",($)=>new q6($)],["bash",($)=>new Z6($)],["powershell",($)=>new W6($)]]);function y9($,M){let J=B1.get($);if(!J)throw Error(`Unsupported shell type: ${$}`);return J(M)}class I6{fs;projectConfig;logger;constructor($,M,J){this.logger=$.getSubLogger({name:"ShellInitGenerator"}),this.logger.getSubLogger({name:"constructor"}).debug(v$.constructor.initialized()),this.fs=M,this.projectConfig=J}async generate($,M){let J=this.logger.getSubLogger({name:"generate"}),Q=M?.shellTypes??["zsh"],Y=new Map,G=null,X=$?Object.keys($).length:0;J.debug(v$.generate.parsedToolCount(X));for(let I of Q){let U=await this.generateForShellType(I,$,M);if(U){if(Y.set(I,U.outputPath),G===null)G=U.outputPath}}if(Y.size===0)return null;let Z={files:Y,primaryPath:G};if(M?.updateProfileFiles??!0)Z.profileUpdates=await this.updateProfileFiles(Y);return Z}async generateForShellType($,M,J){let Q=this.logger.getSubLogger({name:"generateForShellType"});try{let Y=y9($,this.projectConfig),G=J?.outputPath??Y.getDefaultOutputPath();Q.debug(v$.generate.resolvedOutputPath(G));let X=this.extractToolEmissions(M,Y,J),Z=Y.generateFileContent(X);await this.cleanupOnceScriptsDirectory($);let q=Y.getAdditionalFiles(X);return await this.writeShellFiles(G,Z,q)?{outputPath:G}:null}catch(Y){return Q.debug(v$.generate.shellTypeFailure($),Y),null}}extractToolEmissions($,M,J){let Q=new Map;for(let Y in $){let G=$[Y];if(!G)continue;let X=J?.systemInfo?Y$(G,J.systemInfo):G,Z=M.extractEmissions(X),q=J?.pluginShellInit?.[Y]?.[M.shellType];if(q){let I=this.convertPluginShellInit(q,X.configFilePath);Z.push(...I)}if(Z.length>0)Q.set(Y,Z)}return Q}convertPluginShellInit($,M){let J=[],Q=M;if($.environmentVariables){let Y=L0($.environmentVariables);J.push(Q?x$(Y,Q):Y)}if($.aliases){let Y=x0($.aliases);J.push(Q?x$(Y,Q):Y)}if($.scripts)for(let Y of $.scripts){let G=e0(Y),X;if(r0(Y))X=IM(G,"once");else if(t0(Y))X=IM(G,"always");else if(o0(Y))X=IM(G,"raw");if(X)J.push(Q?x$(X,Q):X)}if($.functions)for(let[Y,G]of Object.entries($.functions)){let X=q0(Y,G);J.push(Q?x$(X,Q):X)}return J}async writeShellFiles($,M,J){let Q=this.logger.getSubLogger({name:"writeShellFiles"});try{await this.fs.ensureDir(k0.dirname($)),await this.fs.writeFile($,M);for(let Y of J)await this.writeAdditionalFile(Y);return!0}catch(Y){return Q.debug(v$.generate.writeFailure($),Y),!1}}async writeAdditionalFile($){let M=this.logger.getSubLogger({name:"writeAdditionalFile"});try{await this.fs.ensureDir(k0.dirname($.outputPath)),await this.fs.writeFile($.outputPath,$.content)}catch(J){M.debug(v$.generate.writeFailure($.outputPath),J)}}async updateProfileFiles($){let M=this.logger.getSubLogger({name:"updateProfileFiles"}),J=new G6(this.fs,this.projectConfig.paths.homeDir),Q=this.projectConfig.features.shellInstall;if(!Q)return M.debug(v$.profiles.skipped("all")),[];let Y=[];for(let[G,X]of $){let Z;if(G==="zsh")Z=Q?.zsh;else if(G==="bash")Z=Q?.bash;else if(G==="powershell")Z=Q?.powershell;if(!Z){M.debug(v$.profiles.skipped(G));continue}if(Z?.startsWith("~/"))Z=k0.join(this.projectConfig.paths.homeDir,Z.slice(2));else if(Z==="~")Z=this.projectConfig.paths.homeDir;Y.push({shellType:G,generatedScriptPath:X,onlyIfExists:!0,projectConfigPath:this.projectConfig.configFilePath,profilePath:Z})}return M.debug(v$.profiles.starting(Y.length)),await J.updateProfiles(Y)}async cleanupOnceScriptsDirectory($){let M=this.logger.getSubLogger({name:"cleanupOnceScriptsDirectory"}),J=k0.join(this.projectConfig.paths.shellScriptsDir,".once");try{if(!await this.fs.exists(J))return;let Y=this.getShellExtension($),G=await this.fs.readdir(J);for(let X of G)if(X.endsWith(`.${Y}`)){let Z=k0.join(J,X);await this.fs.rm(Z),M.debug(v$.cleanup.onceScriptRemoved(Z))}}catch(Q){M.debug(v$.cleanup.failure(J),Q)}}getShellExtension($){switch($){case"zsh":return"zsh";case"bash":return"bash";case"powershell":return"ps1";default:throw Error(`Unsupported shell type: ${$}`)}}}import D1 from"path";class U6{storage;shellType;context;logger;toolName;sourceFileCounter=0;sourceCounter=0;constructor($,M,J,Q,Y){this.storage=$,this.shellType=M,this.context=J,this.logger=Q.getSubLogger({name:"ShellConfigurator"}).setPrefix(Y),this.toolName=Y}env($){return this.storage.env={...this.storage.env,...$},this}aliases($){return this.storage.aliases={...this.storage.aliases,...$},this}sourceFile($){let M=this.resolvePath($),J=this.generateSourceFileFunctionName(),Q=this.createSourceFileFunctionBody(M);this.storage.functions[J]=Q;let Y=this.createSourceFunctionCommand(J),G=this.createUnsetFunctionCommand(J);return this.storage.scripts.push(n$(Y)),this.storage.scripts.push(n$(G)),this}sourceFunction($){let M=this.createSourceFunctionCommand($);return this.storage.scripts.push(n$(M)),this}source($){let M=this.generateSourceFunctionName();this.storage.functions[M]=$;let J=this.createSourceFunctionCommand(M),Q=this.createUnsetFunctionCommand(M);return this.storage.scripts.push(n$(J)),this.storage.scripts.push(n$(Q)),this}completions($){return this.storage.completions=$,this}once($){return this.storage.scripts.push(TY($)),this}always($){return this.storage.scripts.push(kY($)),this}functions($){let M=this.validateFunctionNames($);return this.storage.functions={...this.storage.functions,...M},this}path($){return this.storage.paths.push($),this}validateFunctionNames($){let M={};for(let[J,Q]of Object.entries($)){if(!J||!F9.test(J)){this.logger.error(WM.invalidFunctionName(J));continue}M[J]=Q}return M}generateSourceFileFunctionName(){let $=this.sourceFileCounter++;return`__dotfiles_source_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}generateSourceFunctionName(){let $=this.sourceCounter++;return`__dotfiles_source_inline_${this.toolName.replace(/[^a-zA-Z0-9]/gu,"_")}_${$}`}createSourceFileFunctionBody($){let M=JSON.stringify($);if(this.shellType==="powershell")return`if (Test-Path ${M}) { Get-Content ${M} -Raw }`;return`[[ -f ${M} ]] && cat ${M}`}createUnsetFunctionCommand($){if(this.shellType==="powershell")return`Remove-Item Function:\\${$} -ErrorAction SilentlyContinue`;return`unset -f ${$}`}createSourceFunctionCommand($){if(this.shellType==="powershell")return`. (${$})`;return`source <(${$})`}resolvePath($){let M=$.trim();if(M.length===0){let Q=WM.configurationFieldInvalid("shell source path",$,"non-empty value");throw this.logger.error(Q),Error(Q)}if(D1.isAbsolute(M))return this.normalizePath(M);if(!this.context){let Q=WM.configurationFieldRequired("tool context",`Please ensure createInstallFunction receives tool context before using shell.sourceFile() for "${this.toolName}"`);throw this.logger.error(Q),Error(Q)}let J=FJ(this.context.toolDir,M);return this.normalizePath(J)}normalizePath($){if(this.shellType==="powershell")return $.replace(/\//gu,"\\");return $.replace(/\\/gu,"/")}}class S0{logger;toolName;binaries=[];versionNum="latest";currentInstallationMethod;currentInstallParams;dependencies=[];isDisabled=!1;hostnamePattern;internalShellConfigs={zsh:{scripts:[],aliases:{},env:{},functions:{},paths:[]},bash:{scripts:[],aliases:{},env:{},functions:{},paths:[]},powershell:{scripts:[],aliases:{},env:{},functions:{},paths:[]}};context;symlinkPairs=[];copyPairs=[];updateCheckConfig;platformConfigEntries=[];isPlatformScope;bin($,M){let J=M||`*/${$}`;return this.binaries.push({name:$,pattern:J}),this}version($){return this.versionNum=$,this}install($,M){return this.currentInstallationMethod=$,this.currentInstallParams=M,this}hook($,M){if(!this.currentInstallParams)return this.logger.warn(WM.configurationFieldIgnored("hook",`hook() called for tool "${this.toolName}" before install(). Hook will not be set as install() was not called first.`)),this;let J=this.currentInstallParams.hooks||{},Q=J[$]||[];return Q.push(M),J[$]=Q,this.currentInstallParams.hooks=J,this}zsh($){return this.configureShell("zsh",$)}bash($){return this.configureShell("bash",$)}powershell($){return this.configureShell("powershell",$)}buildShellConfigs(){let $=["zsh","bash","powershell"],M={},J=!1;for(let Q of $){let Y=this.internalShellConfigs[Q],G=Y.scripts.length>0,X=Object.keys(Y.aliases).length>0,Z=Object.keys(Y.env).length>0,q=Object.keys(Y.functions).length>0,I=Y.paths.length>0,U=Y.completions!==void 0;if(G||X||Z||q||I||U)M[Q]={...G&&{scripts:Y.scripts},...X&&{aliases:Y.aliases},...Z&&{env:Y.env},...q&&{functions:Y.functions},...I&&{paths:Y.paths},...U&&{completions:Y.completions}},J=!0}return J?M:void 0}symlink($,M){return this.symlinkPairs.push({source:$,target:M}),this}copy($,M){return this.copyPairs.push({source:$,target:M}),this}dependsOn(...$){for(let M of $){let J=M.trim();if(J.length===0){let Q=WM.configurationFieldInvalid("dependency",M,"non-empty string");this.logger.warn(Q);continue}if(!this.dependencies.includes(J))this.dependencies.push(J)}return this}platform($,M,J){let Q,Y;if(typeof M==="function")Y=M,Q=void 0;else{if(Q=M,typeof J!=="function"){let q=WM.configurationFieldRequired("configure callback",`platform() called for tool "${this.toolName}" with architectures but without a configure callback`);throw this.logger.error(q),Error(q)}Y=J}let G=new S0(this.logger,this.toolName,!0);G.setContext(this.context),Y((...q)=>{if(q.length===0)return G;let[I,U]=q;return G.install(I,U),G});let Z=G.buildPlatformConfig();return this.platformConfigEntries.push({platforms:$,architectures:Q,config:Z}),this}disable(){return this.isDisabled=!0,this}hostname($){if($ instanceof RegExp)this.hostnamePattern=$.source;else this.hostnamePattern=$;return this}updateCheck($){return this.updateCheckConfig=$,this}build(){let $=this.buildBaseConfig();if(this.hasInstallationMethod())return this.buildInstallableToolConfig($);return this.validateConfigurationOnly($),this.buildConfigurationOnlyTool($)}buildBaseConfig(){return{name:this.toolName,binaries:this.binaries.length>0?this.binaries.map(($)=>$.pattern===`*/${$.name}`?$.name:$):void 0,version:this.versionNum,disabled:this.isDisabled?!0:void 0,hostname:this.hostnamePattern,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0,platformConfigs:this.isPlatformScope?void 0:this.platformConfigEntries.length>0?this.platformConfigEntries:void 0}}buildPlatformConfig(){let $={binaries:this.binaries.length>0?this.binaries.map((M)=>M.pattern===`*/${M.name}`?M.name:M):void 0,version:this.versionNum!=="latest"?this.versionNum:void 0,shellConfigs:this.buildShellConfigs(),symlinks:this.symlinkPairs.length>0?this.symlinkPairs:void 0,copies:this.copyPairs.length>0?this.copyPairs:void 0,updateCheck:this.updateCheckConfig,dependencies:this.dependencies.length>0?[...this.dependencies]:void 0};if(this.hasInstallationMethod())$.installationMethod=this.currentInstallationMethod,$.installParams=this.currentInstallParams;return Object.keys($).forEach((M)=>{if($[M]===void 0)delete $[M]}),$}hasInstallationMethod(){return Boolean(this.currentInstallationMethod&&this.currentInstallParams)}buildInstallableToolConfig($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:this.currentInstallationMethod,installParams:this.currentInstallParams}}validateConfigurationOnly($){if(!(($.binaries&&$.binaries.length>0?$.binaries:[]).length>0||$.shellConfigs||$.symlinks||$.copies||$.platformConfigs&&$.platformConfigs.length>0)){let Q=WM.configurationFieldRequired("tool definition",`Tool "${$.name}" must define at least binaries, shell init scripts (zsh/bash/powershell), symlinks, or platformConfigs`);throw this.logger.error(Q),Error(Q)}}buildConfigurationOnlyTool($){return{...$,binaries:$.binaries&&$.binaries.length>0?$.binaries:[],installationMethod:"manual",installParams:{}}}constructor($,M,J=!1){this.logger=$.getSubLogger({name:"IToolConfigBuilder"}),this.toolName=M,this.isPlatformScope=J}setContext($){this.context=$}get shellConfigs(){return this.internalShellConfigs}configureShell($,M){let J=this.internalShellConfigs[$],Q=new U6(J,$,this.context,this.logger,this.toolName),Y=M(Q);if(this.isPromise(Y))return Y.then(()=>this);return this}isPromise($){if($===null||$===void 0)return!1;if(typeof $!=="object"&&typeof $!=="function")return!1;return typeof $.then==="function"}}function P9($,M,J){let Q=null,Y=()=>{if(!Q)Q=new S0($,M);return Q.setContext(J),Q};function G(X,Z){let q=Y();if(X){let I={};q.currentInstallationMethod=X,q.currentInstallParams=Z??I}return q}return G}import vJ from"path";var p={configurationProcessing:()=>W("config processing"),platformOverrides:($,M)=>W(`platform overrides: ${$} ${M}`),configurationValidationFailed:($)=>W(`Configuration validation failed:
|
|
141
141
|
${$.join(`
|
|
142
|
-
`)}`),configurationParseError:($,M,J)=>W(`Failed to parse ${M} configuration ${$}: ${J}`),configurationLoadFailed:($)=>W(`Failed to load configuration: ${$}`),configurationLoaded:($,M)=>W(`Configuration loaded from ${$} (${M} tools configured)`),toolConfigLoadingStarted:($)=>W(`tool config loading: ${$}`),singleToolConfigLoadingStarted:($,M)=>W(`single tool config load: ${$} in ${M}`),toolConfigDirectoryScan:($)=>W(`Directory scan: ${$}`),toolConfigLoadingCompleted:()=>W("tool config loading completed"),configurationFieldInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),fsItemNotFound:($,M)=>W(`${$} not found: ${M}`),fsReadFailed:($)=>W(`Failed to read ${$}`),loadingTypeScriptConfiguration:()=>W("Loading TypeScript configuration"),binarySearchStarted:($,M)=>W(`Searching for tool providing binary '${$}' in ${M}`),binaryNotFound:($)=>W(`No tool provides binary '${$}'`),binaryFoundInTool:($,M)=>W(`Binary '${$}' is provided by tool '${M}'`),multipleBinaryProviders:($,M)=>W(`Multiple tools provide binary '${$}': ${M.join(", ")}`)};function
|
|
143
|
-
${
|
|
142
|
+
`)}`),configurationParseError:($,M,J)=>W(`Failed to parse ${M} configuration ${$}: ${J}`),configurationLoadFailed:($)=>W(`Failed to load configuration: ${$}`),configurationLoaded:($,M)=>W(`Configuration loaded from ${$} (${M} tools configured)`),toolConfigLoadingStarted:($)=>W(`tool config loading: ${$}`),singleToolConfigLoadingStarted:($,M)=>W(`single tool config load: ${$} in ${M}`),toolConfigDirectoryScan:($)=>W(`Directory scan: ${$}`),toolConfigLoadingCompleted:()=>W("tool config loading completed"),configurationFieldInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),fsItemNotFound:($,M)=>W(`${$} not found: ${M}`),fsReadFailed:($)=>W(`Failed to read ${$}`),loadingTypeScriptConfiguration:()=>W("Loading TypeScript configuration"),binarySearchStarted:($,M)=>W(`Searching for tool providing binary '${$}' in ${M}`),binaryNotFound:($)=>W(`No tool provides binary '${$}'`),binaryFoundInTool:($,M)=>W(`Binary '${$}' is provided by tool '${M}'`),multipleBinaryProviders:($,M)=>W(`Multiple tools provide binary '${$}': ${M.join(", ")}`)};function A1($){if(typeof $!=="object"||$===null)return!1;return"name"in $}function E1($){return typeof $==="function"}function K6($){if(A1($))return $;return null}async function F1($,M,J,Q,Y,G,X){let Z=vJ.dirname(Q),q=R0(Y,G,J,Z,X,M),I=P9(M,J,q),U=await $(I,q);if(U&&typeof U==="object"&&"name"in U)return K6(U);if(U&&typeof U==="object"&&"build"in U&&typeof U.build==="function"){let K=U.build();return K6(K)}return M.error(p.configurationParseError(Q,"ToolConfig","Invalid return from configuration function")),null}function L1($,M,J,Q){let Y=K6($);if(Y){if(Y.name!==Q)M.warn(p.configurationFieldInvalid("tool config object name",Y.name,`filename: ${Q}`),J)}return Y}async function x1($,M,J,Q,Y,G){try{let X=await import(M);if(!X.default)return $.error(p.configurationParseError(M,"ToolConfig","no default export")),null;let Z,q=X.default;if(E1(q))Z=await F1(q,$,J,M,Q,Y,G);else Z=L1(q,$,M,J);if(Z)Z.configFilePath=M;return Z}catch(X){let Z=X instanceof Error?X.message:JSON.stringify(X);return $.error(p.configurationLoadFailed(vJ.relative(Q.configFileDir,M)),Z),null}}function T1($,M,J,Q){if(M?.name)Q[M.name]=M,$.debug(p.configurationLoaded(J,1),M.name);else if(M)$.warn(p.configurationFieldInvalid("tool config","missing name","valid name property"),J);else $.error(p.configurationParseError(J,"ToolConfig","Could not derive valid configuration"))}async function C9($,M,J){let Q=[];try{let Y=await $.readdir(M);for(let G of Y){let X=vJ.join(M,G);try{if((await $.stat(X)).isDirectory()){let q=await C9($,X,J);Q.push(...q)}else if(G.endsWith(".tool.ts")){let q=vJ.basename(G,".tool.ts");Q.push({filePath:X,toolName:q})}}catch(Z){J.debug(p.fsReadFailed(X),Z)}}}catch(Y){J.debug(p.fsReadFailed(M),Y)}return Q}async function yJ($,M,J,Q,Y,G){let X=$.getSubLogger({name:"loadToolConfigs"}),Z={};if(G)X.debug(p.singleToolConfigLoadingStarted(G,M));else X.debug(p.toolConfigLoadingStarted(M));try{if(!await J.exists(M))return X.debug(p.fsItemNotFound("tool configs directory",M)),{};X.trace(p.toolConfigDirectoryScan(M));let q=await C9(J,M,X),I=G?q.filter(({toolName:U})=>U===G):q;for(let{filePath:U,toolName:K}of I){let H=await x1(X,U,K,Q,Y,J);T1(X,H,U,Z)}}catch(q){return X.error(p.fsReadFailed(M),q),{}}return Z}async function H6($,M,J,Q,Y,G){return(await yJ($,J,Q,Y,G,M))[M]}function k1($){if(typeof $==="string")return $;return $.name}async function S1($,M,J,Q,Y,G){let X=$.getSubLogger({name:"findToolByBinary",context:M});X.debug(p.binarySearchStarted(M,J));let Z=await yJ(X,J,Q,Y,G),q=[];for(let[K,H]of Object.entries(Z)){if(!H.binaries)continue;if(H.binaries.some((O)=>k1(O)===M))q.push(K)}if(q.length===0)return X.debug(p.binaryNotFound(M)),{success:!1,error:`No tool provides binary '${M}'`};if(q.length>1)return X.debug(p.multipleBinaryProviders(M,q)),{success:!1,error:`Multiple tools provide the binary '${M}': ${q.join(", ")}. Please specify the tool name instead.`,matchingTools:q};let I=q[0];if(!I)return{success:!1,error:`No tool provides binary '${M}'`};return X.debug(p.binaryFoundInTool(M,I)),{success:!0,toolName:I}}async function d9($,M,J,Q,Y,G){let X=$.getSubLogger({name:"loadToolConfigByBinary"}),Z=await S1(X,M,J,Q,Y,G);if(!Z.success){if(Z.matchingTools)return{error:Z.error};return}return await H6(X,Z.toolName,J,Q,Y,G)}class _6{async loadSingleToolConfig($,M,J,Q,Y,G){return H6($,M,J,Q,Y,G)}async loadToolConfigByBinary($,M,J,Q,Y,G){return d9($,M,J,Q,Y,G)}async loadToolConfigs($,M,J,Q,Y){return yJ($,M,J,Q,Y)}}function w1($){return $}import g1 from"path";import R6 from"path";import{z as b1}from"zod";function xM($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function lM($){if(xM($))return $;return{}}function PJ($,M){let J={...$};for(let Q of Object.keys(M)){let Y=M[Q];if(Y===void 0)continue;let G=$[Q];if(xM(Y)&&xM(G)){J[Q]=PJ(G,Y);continue}J[Q]=Y}return J}function N1($){switch($){case 2:return"macos";case 1:return"linux";case 4:return"windows";default:return"unknown"}}function v1($){switch($){case 1:return"x86_64";case 2:return"arm64";default:return"unknown"}}function y1($,M,J){let Q=$.getSubLogger({name:"applyPlatformOverrides"}),Y=M.platform;if(!Array.isArray(Y)){let U={...M};return delete U.platform,U}let G=N1(J.platform),X=v1(J.arch);Q.debug(p.platformOverrides(G,X));let Z={macos:2,linux:1,windows:4}[G]??0,q={x86_64:1,arm64:2}[X]??0,I=PJ({},M);for(let U of Y){if(!xM(U))continue;let{match:K,config:H}=U;if(!Array.isArray(K)||!xM(H))continue;if(K.some((O)=>{if(!xM(O))return!1;let{os:B,arch:j}=O,V=typeof B==="string"?{macos:2,linux:1,windows:4}[B]??0:0,D=typeof j==="string"?{x86_64:1,arm64:2}[j]??0:0,A=typeof B!=="string"||rM(V,Z),T=typeof j!=="string"||tM(D,q);return A&&T}))I=PJ(I,H)}return delete I.platform,I}function P1($,M){let J=$.split("."),Q=M;for(let Y of J){if(!xM(Q))return;if(!(Y in Q))return;Q=Q[Y]}if(typeof Q==="string")return Q;return}function C1($,M,J){let Q=/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g;return $.replace(Q,(G,X)=>{if(X.includes("."))return P1(X,J)??G;return M[X]??G})}function u9($){let M=/(?<!\$)\{([a-zA-Z0-9_.]+)\}/g,J=[];for(let Y of $.matchAll(M)){let G=Y[1];if(typeof G!=="string")continue;J.push(`{${G}}`)}return[...new Set(J)].toSorted((Y,G)=>Y.localeCompare(G))}function p9($,M,J){let Y=$,G=new Set([Y]);for(let q=0;q<20;q++){let I=C1(Y,M,J);if(I===Y)return Y;if(G.has(I)){let U=u9(I),K=U.length>0?` Possible cyclic/unresolved tokens: ${U.join(", ")}.`:"";throw Error(`String token substitution did not converge due to a cycle.${K}`)}G.add(I),Y=I}let X=u9(Y),Z=X.length>0?` Remaining tokens after 20 iterations: ${X.join(", ")}.`:"";throw Error(`String token substitution did not converge after 20 iterations.${Z}`)}function O6($,M,J){if(typeof $==="string")return p9($,M,J);if(Array.isArray($))return $.map((Y)=>O6(Y,M,J));if(xM($)){let Q={};for(let[Y,G]of Object.entries($))Q[Y]=O6(G,M,J);return Q}return $}function d1($,M){let Q=$,Y="";for(let G=0;G<20;G++){let X=JSON.stringify(Q);if(X===Y)break;Y=X;let Z=O6(Q,M,Q);Q=lM(Z)}return Q}function u1($,M){let J=$.paths,Q=lM(J),Y={};for(let[X,Z]of Object.entries(Q)){if(typeof Z==="string"){Y[X]=n(M,Z);continue}Y[X]=Z}return{...$,paths:Y}}function f1($,M){let J=$.paths,Q=lM(J),Y={};for(let[X,Z]of Object.entries(Q)){if(typeof Z!=="string"){Y[X]=Z;continue}Y[X]=R6.isAbsolute(Z)?Z:R6.resolve(M,Z)}return{...$,paths:Y}}function p1($){let M=$.paths,J=lM(M);for(let Q of Object.values(J)){if(typeof Q!=="string")continue;if(Q.startsWith("~"))throw Error("Configuration contains unsupported tilde path in paths.*")}}function c1($,M,J){let Q=$.paths,G=lM(Q).homeDir,Z=p9(typeof G==="string"?G:"{HOME}",M,$);return n(J,Z)}function f9($,M){let J={...$};for(let[Q,Y]of Object.entries(M))J[Q]=Y;return J}function h1($,M,J,Q,Y,G){let X=$.getSubLogger({name:"processConfig"});X.debug(p.configurationProcessing(),M);let Z=PJ(J,Q),q=y1($,Z,Y),I=R6.dirname(M),U={...q,configFilePath:M,configFileDir:I},K=f9(G,{HOME:Y.homeDir,configFileDir:I}),H=c1(U,K,Y.homeDir),_={...lM(U.paths),homeDir:H},O={...U,paths:_},B=f9(G,{HOME:H,configFileDir:I}),j=d1(O,B),V=u1(j,H);p1(V);let D=f1(V,I),A=ZQ.extend(GY.shape).safeParse(D);if(!A.success){let T=b1.prettifyError(A.error);throw X.error(p.configurationValidationFailed([T])),Error(`Project configuration is invalid.
|
|
143
|
+
${T}`)}return A.data}async function m1($){return ZQ.parse({})}async function c9($,M,J={},Q={platform:2,arch:2,homeDir:"/Users/testuser",hostname:"test-host"},Y={},G){let X=G.userConfigPath,Z=await m1(M),q=lM(J);return h1($,X,Z,q,Q,Y)}function h9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n1($){if(!h9($))return!1;return"default"in $}function i1($){return typeof $==="function"}function l1($){return $ instanceof Promise}function a1($){let M={};return Object.assign(M,$),M}async function m9($,M,J,Q,Y){let G=$.getSubLogger({name:"loadTsConfig"});if(!await M.exists(J))G.error(p.fsItemNotFound("Config file",J)),N(1);let X={};try{let Z=await import(J);if(!n1(Z)||!Z.default)G.error(p.configurationParseError(J,"TypeScript","no default export")),N(1);let I={configFileDir:g1.dirname(J),systemInfo:Q},U=Z.default,K=i1(U)?U(I):U,H=l1(K)?await K:K;if(h9(H))X=a1(H);else G.error(p.configurationParseError(J,"TypeScript","default export must be an object, function or Promise")),N(1)}catch(Z){G.error(p.configurationParseError(J,"TypeScript",Z instanceof Error?Z.message:String(Z))),N(1)}return c9(G,M,X,Q,Y,{userConfigPath:J})}async function g9($,M,J,Q,Y){let G=$.getSubLogger({name:"loadConfig"});if(J.endsWith(".ts"))return G.debug(p.loadingTypeScriptConfiguration()),m9(G,M,J,Q,Y);throw Error(`Unsupported configuration file type: ${J}. Configuration must use .ts extension.`)}var w0=604800000,n9="https://raw.githubusercontent.com",i9="README.md";var C={fetchingReadme:($,M,J)=>W(`Fetching README for ${$}/${M}@${J}`),readmeFetched:($,M,J,Q)=>W(`README fetched for ${$}/${M}@${J} (${Q} characters)`),readmeNotFound:($,M,J,Q)=>W(`README not found for ${$}/${M}@${J} at ${Q}`),readmeCacheHit:($,M,J)=>W(`README cache hit for ${$}/${M}@${J}`),readmeCacheMiss:($,M,J)=>W(`README cache miss for ${$}/${M}@${J}`),readmeCached:($,M,J,Q)=>W(`README cached for ${$}/${M}@${J} with TTL ${Q}ms`),generatingCombinedReadme:($)=>W(`Generating combined README for ${$} tools`),combinedReadmeGenerated:($,M)=>W(`Combined README generated for ${$} tools (${M} characters)`),fetchingInstalledTools:()=>W("Fetching installed GitHub tools from registry"),installedToolsFound:($)=>W(`Found ${$} GitHub tools in registry`),githubToolsExtracted:($)=>W(`Extracted ${$} GitHub tools from configurations`),clearingExpiredCache:()=>W("Clearing expired README cache entries"),cacheCleared:($)=>W(`Cleared ${$} expired README cache entries`),fetchError:($,M,J,Q)=>W(`Error fetching README for ${$}/${M}@${J}: ${Q}`),cacheError:($,M,J)=>W(`Cache ${$} error for ${M}: ${J}`),urlConstruction:($)=>W(`Constructed README URL: ${$}`),serviceInitialized:()=>W("README service initialized"),serviceDestroyed:()=>W("README service destroyed"),writingReadmeToPath:($,M,J)=>W(`Writing README for ${$}@${M} to ${J}`),readmeWritten:($,M,J,Q)=>W(`README written for ${$}@${M} to ${J} (${Q} characters)`),readmeWriteError:($,M,J,Q)=>W(`Error writing README for ${$}@${M} to ${J}: ${Q}`),readmeNotAvailableForWrite:($,M)=>W(`README not available for ${$}@${M}, skipping write`),catalogGeneration:{started:($)=>W(`Starting catalog generation at ${$}`),completed:($,M)=>W(`Catalog generated at ${$} (${M} characters)`),failed:($,M)=>W(`Failed to generate catalog at ${$}: ${M}`),noGitHubTools:()=>W("No GitHub tools installed. Run the generate command to install tools before generating a catalog.")}};class j6{logger;cache;defaultTtl;constructor($,M,J=w0){this.logger=$.getSubLogger({name:"ReadmeCache"}),this.cache=M,this.defaultTtl=J}async get($){try{let M=await this.cache.get($);if(M)this.logger.debug(C.readmeCacheHit(M.owner,M.repo,M.version));return M}catch(M){return this.logger.error(C.cacheError("get",$,M instanceof Error?M.message:String(M))),null}}async set($,M,J=this.defaultTtl){try{await this.cache.set($,M,J),this.logger.debug(C.readmeCached(M.owner,M.repo,M.version,J))}catch(Q){this.logger.error(C.cacheError("set",$,Q instanceof Error?Q.message:String(Q)))}}async has($){try{return await this.cache.has($)}catch(M){return this.logger.error(C.cacheError("has",$,M instanceof Error?M.message:String(M))),!1}}async delete($){try{await this.cache.delete($)}catch(M){this.logger.error(C.cacheError("delete",$,M instanceof Error?M.message:String(M)))}}async clearExpired(){try{this.logger.debug(C.clearingExpiredCache()),await this.cache.clearExpired(),this.logger.debug(C.cacheCleared(0))}catch($){this.logger.error(C.cacheError("clearExpired","all",$ instanceof Error?$.message:String($)))}}generateCacheKey($,M,J){return`readme:${$}/${M}:${J}`}}import s1 from"path";class V6{logger;downloader;registry;fileSystem;catalogFileSystem;readmeCache;pluginRegistry;constructor($,M,J,Q,Y,G,X){this.logger=$.getSubLogger({name:"ReadmeService"}),this.downloader=M,this.registry=J,this.fileSystem=Q,this.catalogFileSystem=Y,this.pluginRegistry=X;let Z=new MM(this.logger,Q,{enabled:!0,defaultTtl:w0,cacheDir:G,storageStrategy:"json"});this.readmeCache=new j6(this.logger,Z),this.logger.debug(C.serviceInitialized())}async fetchReadmeForVersion($,M,J,Q){let Y=this.readmeCache.generateCacheKey($,M,J),G=await this.readmeCache.get(Y);if(G)return G;this.logger.debug(C.readmeCacheMiss($,M,J));let X=this.constructReadmeUrl($,M,J);this.logger.debug(C.urlConstruction(X));try{this.logger.debug(C.fetchingReadme($,M,J));let Z=await this.downloader.download(this.logger,X);if(!Z)return this.logger.debug(C.readmeNotFound($,M,J,X)),null;let q=Z.toString("utf-8"),I={content:q,toolName:Q,owner:$,repo:M,version:J,sourceUrl:X,fetchedAt:Date.now()};return this.logger.debug(C.readmeFetched($,M,J,q.length)),await this.readmeCache.set(Y,I,w0),I}catch(Z){return this.logger.error(C.fetchError($,M,J,"Download failed"),Z),null}}async getCachedReadme($,M,J){let Q=this.readmeCache.generateCacheKey($,M,J);return await this.readmeCache.get(Q)}async generateCombinedReadme($={}){let M=await this.getGitHubTools();this.logger.debug(C.generatingCombinedReadme(M.length));let J={title:$.title||"Installed Tools",includeTableOfContents:$.includeTableOfContents??!0,includeVersions:$.includeVersions??!0},Q=[];if(Q.push(`# ${J.title}
|
|
144
144
|
`),M.length===0)return Q.push(`No GitHub tools are currently installed.
|
|
145
145
|
`),Q.join(`
|
|
146
|
-
`);if(J.includeTableOfContents)this.addTableOfContents(Q,M,J.includeVersions);await this.addToolSections(Q,M,J);let
|
|
147
|
-
`);return this.logger.debug(C.combinedReadmeGenerated(M.length,
|
|
148
|
-
`);for(let Q of M){let
|
|
149
|
-
`),I)this.addToolWithReadme($,Q,I);else this.addToolWithoutReadme($,
|
|
150
|
-
**Source:** [${
|
|
146
|
+
`);if(J.includeTableOfContents)this.addTableOfContents(Q,M,J.includeVersions);await this.addToolSections(Q,M,J);let Y=Q.join(`
|
|
147
|
+
`);return this.logger.debug(C.combinedReadmeGenerated(M.length,Y.length)),Y}addTableOfContents($,M,J){$.push(`## Table of Contents
|
|
148
|
+
`);for(let Q of M){let Y=J?` (${Q.version})`:"";$.push(`- [${Q.toolName}${Y}](#${Q.toolName.toLowerCase().replace(/[^a-z0-9]/g,"-")})`)}$.push("")}async addToolSections($,M,J){for(let Q of M){let Y=Q.downloadUrl?.match(/github\.com\/([^/]+)\/([^/]+)/);if(!Y)continue;let[,G,X]=Y;if(!G||!X)continue;let Z=Q.originalTag||Q.configuredVersion||Q.version,q=Z==="latest"?"main":Z,I=await this.fetchReadmeForVersion(G,X,q,Q.toolName),U=J.includeVersions?` (${Q.version})`:"";if($.push(`## ${Q.toolName}${U}
|
|
149
|
+
`),I)this.addToolWithReadme($,Q,I);else this.addToolWithoutReadme($,G,X)}}addToolWithReadme($,M,J){$.push(J.content);let Q=M.downloadUrl?.match(/github\.com\/([^/]+)\/([^/]+)/);if(Q){let[,Y,G]=Q;$.push(`
|
|
150
|
+
**Source:** [${Y}/${G}](https://github.com/${Y}/${G})
|
|
151
151
|
`)}}addToolWithoutReadme($,M,J){$.push(`**Repository:** [${M}/${J}](https://github.com/${M}/${J})
|
|
152
152
|
`),$.push(`*README not available*
|
|
153
|
-
`)}async getGitHubTools(){this.logger.debug(C.fetchingInstalledTools());try{let M=(await this.registry.getAllToolInstallations()).filter((J)=>{return J.downloadUrl?.includes("github.com")||J.downloadUrl?.includes("api.github.com")});return this.logger.debug(C.installedToolsFound(M.length)),M}catch($){return this.logger.error(C.fetchError("registry","tools","unknown","Failed to get installed tools"),$),[]}}async clearExpiredCache(){await this.readmeCache.clearExpired()}async writeReadmeToPath($,M,J,Q,
|
|
154
|
-
`);let
|
|
153
|
+
`)}async getGitHubTools(){this.logger.debug(C.fetchingInstalledTools());try{let M=(await this.registry.getAllToolInstallations()).filter((J)=>{return J.downloadUrl?.includes("github.com")||J.downloadUrl?.includes("api.github.com")});return this.logger.debug(C.installedToolsFound(M.length)),M}catch($){return this.logger.error(C.fetchError("registry","tools","unknown","Failed to get installed tools"),$),[]}}async clearExpiredCache(){await this.readmeCache.clearExpired()}async writeReadmeToPath($,M,J,Q,Y){try{let G=await this.fetchReadmeForVersion(Q,Y,J,M);if(!G)return this.logger.debug(C.readmeNotAvailableForWrite(M,J)),null;let Z=`${`${$}/${M}`}/${J}`,q=`${Z}/README.md`;return this.logger.debug(C.writingReadmeToPath(M,J,q)),await this.fileSystem.ensureDir(Z),await this.fileSystem.writeFile(q,G.content),this.logger.debug(C.readmeWritten(M,J,q,G.content.length)),q}catch(G){let X=`${$}/${M}/${J}/README.md`;return this.logger.error(C.readmeWriteError(M,J,X,"Write operation failed"),G),null}}constructReadmeUrl($,M,J){return`${n9}/${$}/${M}/${J}/${i9}`}async generateCatalogFromConfigs($,M,J={}){try{if(this.logger.debug(C.catalogGeneration.started($)),(await this.getGitHubTools()).length===0)return this.logger.warn(C.catalogGeneration.noGitHubTools()),null;let Y=await this.generateCatalogContentFromConfigs(M,J),G=s1.dirname($);return await this.fileSystem.ensureDir(G),await this.catalogFileSystem.writeFile($,Y),this.logger.debug(C.catalogGeneration.completed($,Y.length)),$}catch(Q){return this.logger.error(C.catalogGeneration.failed($,"Catalog generation failed"),Q),null}}async generateCatalogContentFromConfigs($,M={}){let J={title:M.title||"Tool Catalog",includeTableOfContents:M.includeTableOfContents??!0,includeVersions:M.includeVersions??!0},Q=[];Q.push(`# ${J.title}
|
|
154
|
+
`);let Y=this.filterGitHubConfigs($);if(this.logger.debug(C.githubToolsExtracted(Y.length)),J.includeTableOfContents)this.addCatalogTableOfContents(Q,Y,J.includeVersions);return await this.addCatalogToolSections(Q,Y,J),Q.join(`
|
|
155
155
|
`)}filterGitHubConfigs($){return Object.entries($).filter(([,M])=>{return this.pluginRegistry.get(M.installationMethod)?.supportsReadme?.()===!0})}addCatalogTableOfContents($,M,J){$.push(`## Table of Contents
|
|
156
|
-
`);for(let[Q,
|
|
156
|
+
`);for(let[Q,Y]of M){let G=J?` (${Y.version||"main"})`:"";$.push(`- [${Q}${G}](#${Q.toLowerCase().replace(/[^a-z0-9]/g,"-")})`)}$.push("")}async addCatalogToolSections($,M,J){for(let[Q,Y]of M){if(Y.installationMethod!=="github-release")continue;let X=Y.installParams.repo,[Z,q]=X.split("/");if(!Z||!q)continue;let I=Y.version||"main",U=I==="latest"?"main":I,K=await this.fetchReadmeForVersion(Z,q,U,Q),H=J.includeVersions?` (${I})`:"";if($.push(`## ${Q}${H}
|
|
157
157
|
`),K)this.addCatalogToolWithReadme($,K,X);else this.addCatalogToolWithoutReadme($,X)}}addCatalogToolWithReadme($,M,J){$.push(M.content),$.push(`
|
|
158
158
|
**Source:** [${J}](https://github.com/${J})
|
|
159
159
|
`)}addCatalogToolWithoutReadme($,M){$.push(`**Repository:** [${M}](https://github.com/${M})
|
|
160
160
|
`),$.push(`*README not available*
|
|
161
|
-
`)}}import{randomUUID as jG}from"crypto";import M4 from"path";var N={constructor:{initialized:()=>W("Initializing GeneratorOrchestrator")},autoInstall:{completed:($)=>W(`Auto-installed: ${$}`)},generateAll:{parsedOptions:($)=>W(`Parsed ${$} tool configuration entries`),toolDisabled:($)=>W(`Skipping disabled tool: ${$}`),toolHostnameMismatch:($,M,J)=>W(`Skipping tool "${$}": hostname "${J}" does not match pattern "${M}"`),dependenciesValidationStarted:($)=>W(`Validating tool dependencies (${$} tools)`),dependenciesOrderResolved:($)=>W(`Dependency order resolved: ${$}`),missingDependency:($,M,J,Q)=>W(`Missing dependency: tool "${$}" requires binary "${M}" but no tool provides it for platform ${J}/${Q}.`),ambiguousDependency:($,M,J)=>W(`Ambiguous dependency: binary "${$}" is provided by multiple tools (${M}). Tool "${J}" cannot determine which to use.`),circularDependency:($)=>W(`Circular dependency detected between tools: ${$}`),shimGenerate:()=>W("Generating shims with resolved options"),shimGenerationComplete:($)=>W(`Shim generation completed with ${$} paths recorded`),shellGenerate:()=>W("Generating shell initialization files with resolved options"),shellInitComplete:($)=>W(`Shell initialization generation complete; primary path: ${$}`),completionGenerated:($,M,J)=>W(`Generated completion ${$} for ${M} (${J})`),completionGeneratedAtPath:($)=>W(`Generated completion at ${$}`),completionGenerationFailed:($,M)=>W(`Failed to generate completion for ${$} (${M})`),completionSkippedNotInstalled:($,M)=>W(`Skipping completion generation for ${$} (${M}) - tool not installed yet`),symlinkGenerationComplete:($)=>W(`Symlink generation completed with ${$} operations recorded`),copyGenerationComplete:($)=>W(`Copy generation completed with ${$} operations recorded`)},cleanup:{started:($)=>W(`Cleaning up artifacts for disabled tool: ${$}`),noFilesToCleanup:($)=>W(`No tracked artifacts found to clean up for: ${$}`),filesFound:($,M)=>W(`Found ${M} artifacts to clean up for: ${$}`),fileDeleted:($,M)=>W(`Removed ${M}: ${$}`),deleteError:($,M)=>W(`Failed to delete: ${$}`),completed:($,M)=>W(`Cleanup completed for ${$}: ${M} files removed`)},orphanCleanup:{found:($)=>W(`Found ${$} orphaned tool${$===1?"":"s"} with no configuration`),cleaningUp:()=>W("Cleaning up orphaned tool")},staleSymlinkCleanup:{removing:($,M)=>W(`Removing stale symlink ${$} for tool: ${M}`)},staleCopyCleanup:{removing:($,M)=>W(`Removing stale copy ${$} for tool: ${M}`)}};function s1($,M){let J=new Set;if(M.binaries&&M.binaries.length>0)for(let G of M.binaries)if(typeof G==="string")J.add(G);else J.add(G.name);if(J.size===0)J.add($);return[...J]}function r1($){if(!$.dependencies||$.dependencies.length===0)return[];let M=new Set;for(let Q of $.dependencies){let G=Q.trim();if(G.length>0)M.add(G)}return[...M]}function iY($,M,J){let Q=J.get(M)??Number.MAX_SAFE_INTEGER,G=$.findIndex((Y)=>{return(J.get(Y)??Number.MAX_SAFE_INTEGER)>Q});if(G===-1)G=$.length;$.splice(G,0,M)}function t1($,M){let J=new Map,Q=new Map,G=!1;for(let[X,Z]of Object.entries($)){if(!Z)continue;let q=G$(Z,M),I=s1(X,q),U=r1(q),K={providedBinaries:I,dependencies:U};if(J.set(X,K),U.length>0)G=!0;for(let H of I){let _=Q.get(H);if(_)_.add(X);else{let O=new Set([X]);Q.set(H,O)}}}return{metadataByTool:J,binaryProviders:Q,hasDependencies:G}}function o1($,M,J,Q,G){let Y=Q.get(J);if(!Y||Y.size===0)throw $.error(N.generateAll.missingDependency(M,J,t$(G.platform),o$(G.arch))),Error("Dependency validation failed");if(Y.size>1){let Z=[...Y];throw $.error(N.generateAll.ambiguousDependency(J,Z.join(", "),M)),Error("Dependency validation failed")}let[X]=Y;if(!X)throw $.error(N.generateAll.missingDependency(M,J,t$(G.platform),o$(G.arch))),Error("Dependency validation failed");return X}function e1($,M,J,Q,G){let Y=new Map,X=new Map;for(let q of M)Y.set(q,new Set),X.set(q,0);for(let q of M){let I=J.get(q);if(!I)continue;for(let U of I.dependencies){let K=o1($,q,U,Q,G);if(K===q)continue;let H=Y.get(K);if(H)H.add(q);let _=X.get(q)??0;X.set(q,_+1)}}return{adjacency:Y,inDegree:X}}function $4($,M,J){let Q=[];for(let Y of $)if((M.inDegree.get(Y)??0)===0)iY(Q,Y,J);let G=[];while(Q.length>0){let Y=Q.shift();if(!Y)continue;G.push(Y);let X=M.adjacency.get(Y);if(!X)continue;for(let Z of X){let q=(M.inDegree.get(Z)??0)-1;if(M.inDegree.set(Z,q),q===0)iY(Q,Z,J)}}return G}function lY($,M,J){let Q=$.getSubLogger({name:"orderToolConfigsByDependencies"}),G=Object.keys(M);if(Q.debug(N.generateAll.dependenciesValidationStarted(G.length)),G.length===0)return M;let Y=new Map;G.forEach((H,_)=>{Y.set(H,_)});let{metadataByTool:X,binaryProviders:Z,hasDependencies:q}=t1(M,J);if(!q)return M;let I=e1(Q,G,X,Z,J),U=$4(G,I,Y);if(U.length!==G.length){let H=G.filter((_)=>(I.inDegree.get(_)??0)>0);throw Q.error(N.generateAll.circularDependency(H.join(", "))),Error("Dependency validation failed")}Q.debug(N.generateAll.dependenciesOrderResolved(U.join(" -> ")));let K={};for(let H of U){let _=M[H];if(!_)throw Error(`Tool configuration missing for "${H}" after dependency ordering.`);K[H]=_}return K}var aY=new Set(["shim","symlink","copy","completion"]);class VG{logger;shimGenerator;shellInitGenerator;symlinkGenerator;copyGenerator;completionGenerator;systemInfo;projectConfig;fileRegistry;fs;completionTrackedFs;constructor($,M,J,Q,G,Y,X,Z,q,I,U){this.logger=$.getSubLogger({name:"GeneratorOrchestrator"}),this.logger.getSubLogger({name:"constructor"}).debug(N.constructor.initialized()),this.shimGenerator=M,this.shellInitGenerator=J,this.symlinkGenerator=Q,this.copyGenerator=G,this.completionGenerator=Y,this.systemInfo=X,this.projectConfig=Z,this.fileRegistry=q,this.fs=I,this.completionTrackedFs=U}matchesHostname($){let M=this.systemInfo.hostname;if($.startsWith("/")&&$.lastIndexOf("/")>0){let J=$.lastIndexOf("/"),Q=$.slice(1,J),G=$.slice(J+1);try{return new RegExp(Q,G).test(M)}catch{return M===$}}try{return new RegExp($).test(M)}catch{return M===$}}async generateAll($,M){let J=this.logger.getSubLogger({name:"generateAll"}),Q={};for(let[A,b]of Object.entries($)){if(b.disabled){J.warn(N.generateAll.toolDisabled(A)),await this.cleanupToolArtifacts(A);continue}if(b.hostname&&!this.matchesHostname(b.hostname)){J.warn(N.generateAll.toolHostnameMismatch(A,b.hostname,this.systemInfo.hostname)),await this.cleanupToolArtifacts(A);continue}Q[A]=b}await this.cleanupOrphanedTools($);let G=lY(this.logger,Q,this.systemInfo),Y=Object.keys(G).length;J.debug(N.generateAll.parsedOptions(Y));let X=await this.runAutoInstalls(G,M?.installer),Z={overwrite:!0,overwriteConflicts:M?.overwrite};J.debug(N.generateAll.shimGenerate());let I=(await this.shimGenerator.generate(G,Z))?.length??0;J.debug(N.generateAll.shimGenerationComplete(I));let U={shellTypes:["zsh","bash","powershell"],systemInfo:this.systemInfo,pluginShellInit:X};J.debug(N.generateAll.shellGenerate());let H=(await this.shellInitGenerator.generate(G,U))?.primaryPath??"null";J.debug(N.generateAll.shellInitComplete(H));let _={overwrite:!0,backup:!0},O=await this.symlinkGenerator.generate(G,_),B=O?.length??0;J.debug(N.generateAll.symlinkGenerationComplete(B));let j={overwrite:!0,backup:!0},V=await this.copyGenerator.generate(G,j),D=V?.length??0;J.debug(N.generateAll.copyGenerationComplete(D)),await this.cleanupStaleSymlinks(G,O),await this.cleanupStaleCopies(G,V)}async runAutoInstalls($,M){let J=this.logger.getSubLogger({name:"runAutoInstalls"}),Q={};if(!M)return Q;for(let[G,Y]of Object.entries($)){if(Y.installParams?.auto!==!0)continue;let q=await M.install(G,Y);if(!q.success)continue;if(q.installationMethod!=="already-installed")J.info(N.autoInstall.completed(G));if(q.shellInit)Q[G]=q.shellInit}return Q}async generateCompletionsForTool($,M,J,Q){let G=this.logger.getSubLogger({name:"generateCompletionsForTool"}).setPrefix($),Y=G$(M,this.systemInfo),X=["zsh","bash","powershell"],Z=J??Y.version;for(let q of X){let U=Y.shellConfigs?.[q]?.completions;if(!U)continue;try{let K=M4.join(this.projectConfig.paths.binariesDir,$,"current"),H={version:Z},_=await wM(H,U),O=this.normalizeCompletionConfig(_);if(!O.cmd&&!O.source&&!O.url)continue;let B={...H,homeDir:this.projectConfig.paths.homeDir,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,toolInstallDir:K,toolName:$,configFilePath:M.configFilePath,binaryPaths:Q},j=this.completionTrackedFs.withContext({toolName:$}),V=await this.completionGenerator.generateAndWriteCompletionFile({config:O,toolName:$,shellType:q,context:B,fs:j});G.info(N.generateAll.completionGeneratedAtPath(V.targetPath))}catch{G.warn(N.generateAll.completionGenerationFailed($,q))}}}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin&&{bin:$.bin}};if("url"in $)return{url:$.url,...$.source&&{source:$.source},...$.bin&&{bin:$.bin}};return{source:$.source,...$.bin&&{bin:$.bin}}}async cleanupOrphanedTools($){let M=this.logger.getSubLogger({name:"cleanupOrphanedTools"}),J=await this.fileRegistry.getRegisteredTools(),Q=new Set(Object.keys($)),G=[];for(let Y of J){if(Y==="system"||Q.has(Y))continue;if((await this.fileRegistry.getFileStatesForTool(Y)).some((q)=>aY.has(q.fileType)))G.push(Y)}if(G.length===0)return;M.warn(N.orphanCleanup.found(G.length));for(let Y of G)M.getSubLogger({name:"cleanupOrphanedTools",context:Y}).warn(N.orphanCleanup.cleaningUp()),await this.cleanupToolArtifacts(Y)}async cleanupToolArtifacts($){let M=this.logger.getSubLogger({name:"cleanupToolArtifacts",context:$});M.debug(N.cleanup.started($));let Q=(await this.fileRegistry.getFileStatesForTool($)).filter((Y)=>aY.has(Y.fileType));if(Q.length===0){M.debug(N.cleanup.noFilesToCleanup($));return}M.debug(N.cleanup.filesFound($,Q.length));let G=Q.toSorted((Y,X)=>X.filePath.length-Y.filePath.length);for(let Y of G)try{if(Y.fileType==="symlink"?await this.fs.lstat(Y.filePath).then(()=>!0,()=>!1):await this.fs.exists(Y.filePath)){if(Y.lastOperation==="mkdir")await this.fs.rmdir(Y.filePath);else await this.fs.rm(Y.filePath,{recursive:Y.fileType==="copy",force:!0});M.warn(N.cleanup.fileDeleted(Y.filePath,Y.fileType))}await this.fileRegistry.recordOperation({toolName:$,operationType:"rm",filePath:Y.filePath,fileType:Y.fileType,operationId:jG()})}catch(X){M.debug(N.cleanup.deleteError(Y.filePath,X))}M.debug(N.cleanup.completed($,Q.length))}async cleanupStaleSymlinks($,M){let J=this.logger.getSubLogger({name:"cleanupStaleSymlinks"}),Q=new Set(M.filter((Y)=>Y.success).map((Y)=>Y.targetPath)),G=this.projectConfig.paths.binariesDir;for(let Y of Object.keys($)){let Z=(await this.fileRegistry.getFileStatesForTool(Y)).filter((q)=>q.fileType==="symlink"&&q.lastOperation==="symlink"&&!q.filePath.startsWith(G));for(let q of Z){if(Q.has(q.filePath))continue;J.warn(N.staleSymlinkCleanup.removing(q.filePath,Y));try{try{await this.fs.lstat(q.filePath),await this.fs.rm(q.filePath)}catch{}await this.fileRegistry.recordOperation({toolName:Y,operationType:"rm",filePath:q.filePath,fileType:"symlink",operationId:jG()})}catch(I){J.debug(N.cleanup.deleteError(q.filePath,I))}}}}async cleanupStaleCopies($,M){let J=this.logger.getSubLogger({name:"cleanupStaleCopies"}),Q=new Set(M.filter((G)=>G.success).map((G)=>G.targetPath));for(let G of Object.keys($)){let X=(await this.fileRegistry.getFileStatesForTool(G)).filter((Z)=>Z.fileType==="copy"&&Z.lastOperation==="cp");for(let Z of X){if(Q.has(Z.filePath))continue;J.warn(N.staleCopyCleanup.removing(Z.filePath,G));try{if(await this.fs.exists(Z.filePath))await this.fs.rm(Z.filePath,{recursive:!0,force:!0});await this.fileRegistry.recordOperation({toolName:G,operationType:"rm",filePath:Z.filePath,fileType:"copy",operationId:jG()})}catch(q){J.debug(N.cleanup.deleteError(Z.filePath,q))}}}}}import J4 from"path";var b0={installing:($)=>W(`Installing from curl-binary: toolName=${$}`),downloadingBinary:($)=>W(`Downloading binary from: ${$}`),binaryDownloaded:()=>W("Binary downloaded successfully"),settingPermissions:()=>W("Setting binary executable permissions")};async function sY($,M,J,Q,G,Y,X,Z,q){let I=q$(G,$),U=Z.getSubLogger({name:"installFromCurlBinary"});if(U.debug(b0.installing($)),!M.installParams||!("url"in M.installParams))return{success:!1,error:"URL not specified in installParams"};let K=M.installParams,H=K.url;return Q$("curl-binary",$,U,async()=>{U.debug(b0.downloadingBinary(H));let O=J4.join(J.stagingDir,$);await U$(U,H,O,$,Y,Q),U.debug(b0.binaryDownloaded());let B={...J,downloadPath:O},j=await w$(M,B,X,G,U);if(!j.success)return{success:!1,error:j.error};U.debug(b0.settingPermissions()),await $0(I,$,M,J,O,U);let V=e(M.binaries,J.stagingDir),D,A=V[0];if(A)D=await D$({binaryPath:A,args:K.versionArgs,regex:K.versionRegex,shellExecutor:q});return{success:!0,binaryPaths:V,metadata:{method:"curl-binary",downloadUrl:H,binaryUrl:H},version:D||(M.version!=="latest"?M.version:void 0)}})}import{z as CJ}from"zod";var dJ=r.extend({url:CJ.string().url(),versionArgs:CJ.array(CJ.string()).optional(),versionRegex:CJ.string().optional()});import{z as uJ}from"zod";var rY=t.extend({installationMethod:uJ.literal("curl-binary"),installParams:dJ,binaries:uJ.array(uJ.union([uJ.string().min(1),Z$])).min(1)});var Q4="1.0.0";class zG{fs;downloader;hookExecutor;shell;method="curl-binary";displayName="Curl Binary Installer";version=Q4;paramsSchema=dJ;toolConfigSchema=rY;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,G){let Y=await sY($,M,J,Q,this.fs,this.downloader,this.hookExecutor,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import G4 from"path";var UM={installing:($)=>W(`Installing from npm: package=${$}`),executingCommand:($)=>W(`Executing command: ${$}`),versionFetched:($,M)=>W(`Fetched version ${M} for npm package ${$}`),versionFetchFailed:($)=>W(`Failed to fetch version for npm package ${$}`),updateCheckFailed:()=>W("Failed to check update for npm tool")};async function tY($,M,J,Q,G,Y,X){let Z=G.getSubLogger({name:"installFromNpm"});if(!M.installParams)return{success:!1,error:"Install parameters not specified"};let q=M.installParams,I=q.package||$,U=q.version,K=U?`${I}@${U}`:I;Z.debug(UM.installing(I));let H=q.packageManager==="bun";return Q$("npm",$,Z,async()=>{let O=X??W$({logger:Z,skipCommandLog:!0});if(H)await X4(K,Z,O);else await Z4(K,Z,O);let B=await Y4(H,O),j=e(M.binaries,B),V;if(q.versionArgs&&q.versionRegex){let b=j[0];if(b)V=await D$({binaryPath:b,args:q.versionArgs,regex:q.versionRegex,shellExecutor:Y})}else if(H){let b=j[0];if(b)V=await D$({binaryPath:b,args:["--version"],regex:"(\\d+\\.\\d+\\.\\d+)",shellExecutor:Y})}else V=await W4(I,Y);let D={method:"npm",packageName:I};return{success:!0,binaryPaths:j,version:V?j$(V):void 0,metadata:D}})}async function Y4($,M){if($)return(await M`bun pm bin -g`.quiet()).stdout.toString().trim();let J=await M`npm prefix -g`.quiet();return G4.join(J.stdout.toString().trim(),"bin")}async function X4($,M,J){let Q=`bun install -g ${$}`;M.debug(UM.executingCommand(Q)),await J`bun install -g ${$}`}async function Z4($,M,J){let Q=`npm install -g ${$}`;M.debug(UM.executingCommand(Q)),await J`npm install -g ${$}`}async function W4($,M){try{return(await M`npm view ${$} version`.quiet().noThrow()).stdout.toString().trim()||void 0}catch{return}}import{z as I0}from"zod";var fJ=r.extend({package:I0.string().min(1).optional(),version:I0.string().optional(),versionArgs:I0.array(I0.string()).optional(),versionRegex:I0.string().optional(),packageManager:I0.enum(["npm","bun"]).optional()});import{z as pJ}from"zod";var oY=t.extend({installationMethod:pJ.literal("npm"),installParams:fJ,binaries:pJ.array(pJ.union([pJ.string().min(1),Z$])).min(1)});var q4="1.0.0";class BG{shell;method="npm";displayName="npm Installer";version=q4;externallyManaged=!0;paramsSchema=fJ;toolConfigSchema=oY;constructor($){this.shell=$}async install($,M,J,Q,G){let Y=await tY($,M,J,Q,G,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata}}async resolveVersion($,M,J,Q){let G=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.package||$,q=(await this.shell`npm view ${X} version`.quiet().noThrow()).stdout.toString().trim();if(!q)return G.debug(UM.versionFetchFailed(X)),null;let I=AM(q);return G.debug(UM.versionFetched(X,I)),I}catch(Y){return G.debug(UM.versionFetchFailed($),Y),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){let G=Q.getSubLogger({name:"checkUpdate",context:$});try{let X=M.installParams?.package||$,q=(await this.shell`npm view ${X} version`.quiet().noThrow()).stdout.toString().trim();if(!q)return{success:!1,error:`Could not fetch latest version for npm package: ${X}`};let I=M.version||"latest";if(I==="latest")return{success:!0,hasUpdate:!1,currentVersion:q,latestVersion:q};return{success:!0,hasUpdate:I!==q,currentVersion:I,latestVersion:q}}catch(Y){return G.error(UM.updateCheckFailed(),Y),{success:!1,error:Y instanceof Error?Y.message:"Unknown error"}}}supportsReadme(){return!1}}import v0 from"path";var m$={installing:($)=>W(`Installing zsh plugin: ${$}`),cloning:($,M)=>W(`Cloning ${$} to ${M}`),updating:($)=>W(`Updating existing plugin at ${$}`),cloneSuccess:($)=>W(`Cloned plugin: ${$}`),updateSuccess:($)=>W(`Updated plugin: ${$}`),cloneFailed:($)=>W(`Failed to clone: ${$}`),updateFailed:($)=>W(`Failed to update: ${$}`),versionDetected:($)=>W(`Detected version: ${$}`),sourceFileDetected:($)=>W(`Detected source file: ${$}`),sourceFileNotFound:($)=>W(`Specified source file not found: ${$}`),noParamsProvided:()=>W("No install parameters provided"),invalidParams:()=>W("Either repo or url must be specified")};async function eY($,M,J,Q,G,Y,X){let Z=Q.getSubLogger({name:"installFromZshPlugin"});Z.debug(m$.installing($));let q=M.installParams;if(!q)return{success:!1,error:"No install parameters provided"};if(!q.repo&&!q.url)return{success:!1,error:"Either repo or url must be specified"};return Q$("zsh-plugin",$,Z,async()=>{let U=q.url??`https://github.com/${q.repo}.git`,K=DG(q.pluginName,q.repo,q.url),H=v0.join(J.stagingDir,K),_=await G.exists(H),O=X??W$({logger:Z,skipCommandLog:!0});if(_)Z.debug(m$.updating(H)),await K4(H,O),Z.info(m$.updateSuccess(K));else Z.debug(m$.cloning(U,H)),await U4(U,H,O),Z.info(m$.cloneSuccess(K));let B=await I4(H,K,q.source,G,Z);if(!B)return{success:!1,error:`Could not detect plugin source file in ${H}. Specify 'source' parameter explicitly.`};let j=await H4(H,Y,Z),V=v0.join(J.currentDir,K,B);return{success:!0,binaryPaths:[],version:j,metadata:{method:"zsh-plugin",pluginName:K,gitUrl:U,pluginPath:H,sourceFile:B},shellInit:{zsh:{scripts:[n$(`source "${V}"`)]}}}})}function DG($,M,J){if($)return $;if(M)return M.split("/")[1]??M;if(J){let Q=new URL(J).pathname;return v0.basename(Q,".git")}throw Error("Cannot determine plugin name")}async function I4($,M,J,Q,G){let Y=G.getSubLogger({name:"detectSourceFile"});if(J){let Z=v0.join($,J);if(await Q.exists(Z))return Y.debug(m$.sourceFileDetected(J)),J;Y.warn(m$.sourceFileNotFound(J));return}let X=[`${M}.plugin.zsh`,`${M}.zsh`,"init.zsh","plugin.zsh",`${M}.zsh-theme`];for(let Z of X){let q=v0.join($,Z);if(await Q.exists(q))return Y.debug(m$.sourceFileDetected(Z)),Z}return}async function U4($,M,J){await J`git clone --depth 1 ${$} ${M}`}async function K4($,M){await M`git -C ${$} pull --ff-only`}async function H4($,M,J){let Q=J.getSubLogger({name:"getGitVersion"});try{let G=await M`git -C ${$} describe --tags --abbrev=0`.quiet().noThrow();if(G.code===0){let X=G.stdout.trim();return Q.debug(m$.versionDetected(X)),X}let Y=await M`git -C ${$} rev-parse --short HEAD`.quiet().noThrow();if(Y.code===0){let X=Y.stdout.trim();return Q.debug(m$.versionDetected(X)),X}return}catch{return}}import{z as N0}from"zod";var cJ=r.extend({repo:N0.string().regex(/^[^/]+\/[^/]+$/,"Must be in user/repo format").optional(),url:N0.string().url().optional(),pluginName:N0.string().min(1).optional(),source:N0.string().min(1).optional(),auto:N0.boolean().default(!0)}).refine(($)=>$.repo||$.url,{message:"Either repo or url must be specified"});import{z as AG}from"zod";var $9=t.extend({installationMethod:AG.literal("zsh-plugin"),installParams:cJ,binaries:AG.array(AG.string().min(1)).default([])});import _4 from"path";var R4="1.0.0";class EG{fs;shell;method="zsh-plugin";displayName="Zsh Plugin Installer";version=R4;paramsSchema=cJ;toolConfigSchema=$9;externallyManaged=!1;constructor($,M){this.fs=$;this.shell=M}async install($,M,J,Q,G){let Y=await eY($,M,J,G,this.fs,this.shell);if(!Y.success)return{success:!1,error:Y.error};return{success:!0,binaryPaths:Y.binaryPaths,version:Y.version,metadata:Y.metadata,shellInit:Y.shellInit}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}getShellInit($,M,J){let Q=M.installParams;if(!Q)return;let G=DG(Q.pluginName,Q.repo,Q.url),Y=Q.source??`${G}.plugin.zsh`,X=_4.join(J,G,Y);return{zsh:{scripts:[n$(`source "${X}"`)]}}}}import FG from"path";var H$={constructor:{initialized:()=>W("ShimGenerator initialized")},generate:{missingToolConfig:($)=>W(`Skipping shim generation for ${$} because configuration is missing`)},generateForTool:{started:($,M)=>W(`Generating shims for ${$} using ${M}`),skippedExternallyManaged:($,M)=>W(`Skipping shim generation for ${$} (externally managed via ${M})`),skippedNoBinaries:($)=>W(`Skipping shim generation for ${$} (no binaries defined)`),skippedAlreadyInstalled:($)=>W(`Skipping shim generation for ${$} (already installed)`),skippedManualNoBinaryPath:()=>W("Skipping shim generation (manual tool has .bin() but no binaryPath \u2014 use shell functions instead)")},generateShim:{resolvedShimPath:($)=>W(`Resolved shim output path ${$}`),existingShim:($)=>W(`Existing shim found at ${$}; overwrite is disabled`),conflictingFile:($,M)=>W(`Cannot create shim for "${$}": conflicting file exists at ${M}. Use --overwrite to replace it.`),overwritingConflict:($)=>W(`Overwriting conflicting file at ${$}`),resolvedBinaryPath:($,M,J)=>W(`Resolved binary path for ${$}/${M} to ${J}`),generatedContent:($)=>W(`Generated shim content for ${$}`),success:($,M,J)=>W(`Generated shim ${$} at ${M} using ${J}`)}};class LG{fs;config;logger;systemInfo;externallyManagedMethods;missingBinaryMessagesByMethod;toolInstallationRegistry;isConfigurationOnlyToolConfig($){let M=$.installationMethod==="manual",J=!$.installParams||Object.keys($.installParams).length===0,Q=!$.binaries||$.binaries.length===0;return M&&J&&Q}constructor($,M,J,Q,G,Y,X){let Z=$.getSubLogger({name:"ShimGenerator"});this.logger=Z,Z.getSubLogger({name:"constructor"}).debug(H$.constructor.initialized()),this.fs=M,this.config=J,this.systemInfo=Q,this.externallyManagedMethods=G??new Set,this.missingBinaryMessagesByMethod=Y??new Map,this.toolInstallationRegistry=X}async generate($,M){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let G in $)if(Object.hasOwn($,G)){let Y=$[G];if(Y){let X=await this.generateForTool(G,Y,M);Q.push(...X)}else J.debug(H$.generate.missingToolConfig(G))}return Q}async generateForTool($,M,J){let Q=this.logger.getSubLogger({name:"generateForTool",context:$}),G=this.fs instanceof f?this.fs.withToolName($):this.fs,Y=G.constructor.name;Q.debug(H$.generateForTool.started($,Y));let X=G$(M,this.systemInfo),Z=[],q=J?.overwrite??!1,I=J?.overwriteConflicts??!1;if(this.isConfigurationOnlyToolConfig(X))return Z;if(X.installationMethod==="manual"&&!X.installParams?.binaryPath)return Q.warn(H$.generateForTool.skippedManualNoBinaryPath()),Z;if(this.externallyManagedMethods.has(X.installationMethod)){if(!this.toolInstallationRegistry)return Q.debug(H$.generateForTool.skippedExternallyManaged($,X.installationMethod)),Z;if(await this.toolInstallationRegistry.isToolInstalled($))return Q.debug(H$.generateForTool.skippedAlreadyInstalled($)),Z}let U=X.binaries&&X.binaries.length>0?X.binaries:[];if(U.length===0)return Q.debug(H$.generateForTool.skippedNoBinaries($)),Z;let K=U.map((H)=>typeof H==="string"?H:H.name);for(let H of K){let _=await this.generateShimForBinary(G,$,X,H,q,I);if(_)Z.push(_)}return Z}async generateShimForBinary($,M,J,Q,G,Y){let X=this.logger.getSubLogger({name:"generateShimForBinary"}),Z=this.config.paths.targetDir,q=FG.join(Z,Q);if(X.debug(H$.generateShim.resolvedShimPath(q)),await $.exists(q)){if(!await this.isGeneratedShim($,q)){if(!Y)return X.error(H$.generateShim.conflictingFile(M,q)),null;X.debug(H$.generateShim.overwritingConflict(q))}else if(!G)return X.debug(H$.generateShim.existingShim(q)),null}let I=FG.join(this.config.paths.binariesDir,M,"current",Q);X.debug(H$.generateShim.resolvedBinaryPath(M,Q,I));let U=M.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),K=this.missingBinaryMessagesByMethod.get(J.installationMethod),H=K?`echo "${K.replaceAll('"',"\\\"")}" >&2`:'echo "Installation completed but binary not found at: $TOOL_EXECUTABLE" >&2',_=c(`
|
|
161
|
+
`)}}import{randomUUID as z6}from"crypto";import J4 from"path";var v={constructor:{initialized:()=>W("Initializing GeneratorOrchestrator")},autoInstall:{completed:($)=>W(`Auto-installed: ${$}`)},generateAll:{parsedOptions:($)=>W(`Parsed ${$} tool configuration entries`),toolDisabled:($)=>W(`Skipping disabled tool: ${$}`),toolHostnameMismatch:($,M,J)=>W(`Skipping tool "${$}": hostname "${J}" does not match pattern "${M}"`),dependenciesValidationStarted:($)=>W(`Validating tool dependencies (${$} tools)`),dependenciesOrderResolved:($)=>W(`Dependency order resolved: ${$}`),missingDependency:($,M,J,Q)=>W(`Missing dependency: tool "${$}" requires binary "${M}" but no tool provides it for platform ${J}/${Q}.`),ambiguousDependency:($,M,J)=>W(`Ambiguous dependency: binary "${$}" is provided by multiple tools (${M}). Tool "${J}" cannot determine which to use.`),circularDependency:($)=>W(`Circular dependency detected between tools: ${$}`),shimGenerate:()=>W("Generating shims with resolved options"),shimGenerationComplete:($)=>W(`Shim generation completed with ${$} paths recorded`),shellGenerate:()=>W("Generating shell initialization files with resolved options"),shellInitComplete:($)=>W(`Shell initialization generation complete; primary path: ${$}`),completionGenerated:($,M,J)=>W(`Generated completion ${$} for ${M} (${J})`),completionGeneratedAtPath:($)=>W(`Generated completion at ${$}`),completionGenerationFailed:($,M)=>W(`Failed to generate completion for ${$} (${M})`),completionSkippedNotInstalled:($,M)=>W(`Skipping completion generation for ${$} (${M}) - tool not installed yet`),symlinkGenerationComplete:($)=>W(`Symlink generation completed with ${$} operations recorded`),copyGenerationComplete:($)=>W(`Copy generation completed with ${$} operations recorded`)},cleanup:{started:($)=>W(`Cleaning up artifacts for disabled tool: ${$}`),noFilesToCleanup:($)=>W(`No tracked artifacts found to clean up for: ${$}`),filesFound:($,M)=>W(`Found ${M} artifacts to clean up for: ${$}`),fileDeleted:($,M)=>W(`Removed ${M}: ${$}`),deleteError:($,M)=>W(`Failed to delete: ${$}`),completed:($,M)=>W(`Cleanup completed for ${$}: ${M} files removed`)},orphanCleanup:{found:($)=>W(`Found ${$} orphaned tool${$===1?"":"s"} with no configuration`),cleaningUp:()=>W("Cleaning up orphaned tool")},staleSymlinkCleanup:{removing:($,M)=>W(`Removing stale symlink ${$} for tool: ${M}`)},staleCopyCleanup:{removing:($,M)=>W(`Removing stale copy ${$} for tool: ${M}`)}};function r1($,M){let J=new Set;if(M.binaries&&M.binaries.length>0)for(let Y of M.binaries)if(typeof Y==="string")J.add(Y);else J.add(Y.name);if(J.size===0)J.add($);return[...J]}function t1($){if(!$.dependencies||$.dependencies.length===0)return[];let M=new Set;for(let Q of $.dependencies){let Y=Q.trim();if(Y.length>0)M.add(Y)}return[...M]}function l9($,M,J){let Q=J.get(M)??Number.MAX_SAFE_INTEGER,Y=$.findIndex((G)=>{return(J.get(G)??Number.MAX_SAFE_INTEGER)>Q});if(Y===-1)Y=$.length;$.splice(Y,0,M)}function o1($,M){let J=new Map,Q=new Map,Y=!1;for(let[X,Z]of Object.entries($)){if(!Z)continue;let q=Y$(Z,M),I=r1(X,q),U=t1(q),K={providedBinaries:I,dependencies:U};if(J.set(X,K),U.length>0)Y=!0;for(let H of I){let _=Q.get(H);if(_)_.add(X);else{let O=new Set([X]);Q.set(H,O)}}}return{metadataByTool:J,binaryProviders:Q,hasDependencies:Y}}function e1($,M,J,Q,Y){let G=Q.get(J);if(!G||G.size===0)throw $.error(v.generateAll.missingDependency(M,J,o$(Y.platform),e$(Y.arch))),Error("Dependency validation failed");if(G.size>1){let Z=[...G];throw $.error(v.generateAll.ambiguousDependency(J,Z.join(", "),M)),Error("Dependency validation failed")}let[X]=G;if(!X)throw $.error(v.generateAll.missingDependency(M,J,o$(Y.platform),e$(Y.arch))),Error("Dependency validation failed");return X}function $4($,M,J,Q,Y){let G=new Map,X=new Map;for(let q of M)G.set(q,new Set),X.set(q,0);for(let q of M){let I=J.get(q);if(!I)continue;for(let U of I.dependencies){let K=e1($,q,U,Q,Y);if(K===q)continue;let H=G.get(K);if(H)H.add(q);let _=X.get(q)??0;X.set(q,_+1)}}return{adjacency:G,inDegree:X}}function M4($,M,J){let Q=[];for(let G of $)if((M.inDegree.get(G)??0)===0)l9(Q,G,J);let Y=[];while(Q.length>0){let G=Q.shift();if(!G)continue;Y.push(G);let X=M.adjacency.get(G);if(!X)continue;for(let Z of X){let q=(M.inDegree.get(Z)??0)-1;if(M.inDegree.set(Z,q),q===0)l9(Q,Z,J)}}return Y}function a9($,M,J){let Q=$.getSubLogger({name:"orderToolConfigsByDependencies"}),Y=Object.keys(M);if(Q.debug(v.generateAll.dependenciesValidationStarted(Y.length)),Y.length===0)return M;let G=new Map;Y.forEach((H,_)=>{G.set(H,_)});let{metadataByTool:X,binaryProviders:Z,hasDependencies:q}=o1(M,J);if(!q)return M;let I=$4(Q,Y,X,Z,J),U=M4(Y,I,G);if(U.length!==Y.length){let H=Y.filter((_)=>(I.inDegree.get(_)??0)>0);throw Q.error(v.generateAll.circularDependency(H.join(", "))),Error("Dependency validation failed")}Q.debug(v.generateAll.dependenciesOrderResolved(U.join(" -> ")));let K={};for(let H of U){let _=M[H];if(!_)throw Error(`Tool configuration missing for "${H}" after dependency ordering.`);K[H]=_}return K}var s9=new Set(["shim","symlink","copy","completion"]);class B6{logger;shimGenerator;shellInitGenerator;symlinkGenerator;copyGenerator;completionGenerator;systemInfo;projectConfig;fileRegistry;fs;completionTrackedFs;constructor($,M,J,Q,Y,G,X,Z,q,I,U){this.logger=$.getSubLogger({name:"GeneratorOrchestrator"}),this.logger.getSubLogger({name:"constructor"}).debug(v.constructor.initialized()),this.shimGenerator=M,this.shellInitGenerator=J,this.symlinkGenerator=Q,this.copyGenerator=Y,this.completionGenerator=G,this.systemInfo=X,this.projectConfig=Z,this.fileRegistry=q,this.fs=I,this.completionTrackedFs=U}matchesHostname($){let M=this.systemInfo.hostname;if($.startsWith("/")&&$.lastIndexOf("/")>0){let J=$.lastIndexOf("/"),Q=$.slice(1,J),Y=$.slice(J+1);try{return new RegExp(Q,Y).test(M)}catch{return M===$}}try{return new RegExp($).test(M)}catch{return M===$}}async generateAll($,M){let J=this.logger.getSubLogger({name:"generateAll"}),Q={};for(let[A,T]of Object.entries($)){if(T.disabled){J.warn(v.generateAll.toolDisabled(A)),await this.cleanupToolArtifacts(A);continue}if(T.hostname&&!this.matchesHostname(T.hostname)){J.warn(v.generateAll.toolHostnameMismatch(A,T.hostname,this.systemInfo.hostname)),await this.cleanupToolArtifacts(A);continue}Q[A]=T}await this.cleanupOrphanedTools($);let Y=a9(this.logger,Q,this.systemInfo),G=Object.keys(Y).length;J.debug(v.generateAll.parsedOptions(G));let X=await this.runAutoInstalls(Y,M?.installer),Z={overwrite:!0,overwriteConflicts:M?.overwrite};J.debug(v.generateAll.shimGenerate());let I=(await this.shimGenerator.generate(Y,Z))?.length??0;J.debug(v.generateAll.shimGenerationComplete(I));let U={shellTypes:["zsh","bash","powershell"],systemInfo:this.systemInfo,pluginShellInit:X};J.debug(v.generateAll.shellGenerate());let H=(await this.shellInitGenerator.generate(Y,U))?.primaryPath??"null";J.debug(v.generateAll.shellInitComplete(H));let _={overwrite:!0,backup:!0},O=await this.symlinkGenerator.generate(Y,_),B=O?.length??0;J.debug(v.generateAll.symlinkGenerationComplete(B));let j={overwrite:!0,backup:!0},V=await this.copyGenerator.generate(Y,j),D=V?.length??0;J.debug(v.generateAll.copyGenerationComplete(D)),await this.cleanupStaleSymlinks(Y,O),await this.cleanupStaleCopies(Y,V)}async runAutoInstalls($,M){let J=this.logger.getSubLogger({name:"runAutoInstalls"}),Q={};if(!M)return Q;for(let[Y,G]of Object.entries($)){if(G.installParams?.auto!==!0)continue;let q=await M.install(Y,G);if(!q.success)continue;if(q.installationMethod!=="already-installed")J.info(v.autoInstall.completed(Y));if(q.shellInit)Q[Y]=q.shellInit}return Q}async generateCompletionsForTool($,M,J,Q){let Y=this.logger.getSubLogger({name:"generateCompletionsForTool"}).setPrefix($),G=Y$(M,this.systemInfo),X=["zsh","bash","powershell"],Z=J??G.version;for(let q of X){let U=G.shellConfigs?.[q]?.completions;if(!U)continue;try{let K=J4.join(this.projectConfig.paths.binariesDir,$,"current"),H={version:Z},_=await t$(H,U),O=this.normalizeCompletionConfig(_);if(!O.cmd&&!O.source&&!O.url)continue;let B={...H,homeDir:this.projectConfig.paths.homeDir,shellScriptsDir:this.projectConfig.paths.shellScriptsDir,toolInstallDir:K,toolName:$,configFilePath:M.configFilePath,binaryPaths:Q},j=this.completionTrackedFs.withContext({toolName:$}),V=await this.completionGenerator.generateAndWriteCompletionFile({config:O,toolName:$,shellType:q,context:B,fs:j});Y.info(v.generateAll.completionGeneratedAtPath(V.targetPath))}catch{Y.warn(v.generateAll.completionGenerationFailed($,q))}}}normalizeCompletionConfig($){if(typeof $==="string")return{source:$};if("cmd"in $)return{cmd:$.cmd,...$.bin&&{bin:$.bin}};if("url"in $)return{url:$.url,...$.source&&{source:$.source},...$.bin&&{bin:$.bin}};return{source:$.source,...$.bin&&{bin:$.bin}}}async cleanupOrphanedTools($){let M=this.logger.getSubLogger({name:"cleanupOrphanedTools"}),J=await this.fileRegistry.getRegisteredTools(),Q=new Set(Object.keys($)),Y=[];for(let G of J){if(G==="system"||Q.has(G))continue;if((await this.fileRegistry.getFileStatesForTool(G)).some((q)=>s9.has(q.fileType)))Y.push(G)}if(Y.length===0)return;M.warn(v.orphanCleanup.found(Y.length));for(let G of Y)M.getSubLogger({name:"cleanupOrphanedTools",context:G}).warn(v.orphanCleanup.cleaningUp()),await this.cleanupToolArtifacts(G)}async cleanupToolArtifacts($){let M=this.logger.getSubLogger({name:"cleanupToolArtifacts",context:$});M.debug(v.cleanup.started($));let Q=(await this.fileRegistry.getFileStatesForTool($)).filter((G)=>s9.has(G.fileType));if(Q.length===0){M.debug(v.cleanup.noFilesToCleanup($));return}M.debug(v.cleanup.filesFound($,Q.length));let Y=Q.toSorted((G,X)=>X.filePath.length-G.filePath.length);for(let G of Y)try{if(G.fileType==="symlink"?await this.fs.lstat(G.filePath).then(()=>!0,()=>!1):await this.fs.exists(G.filePath)){if(G.lastOperation==="mkdir")await this.fs.rmdir(G.filePath);else await this.fs.rm(G.filePath,{recursive:G.fileType==="copy",force:!0});M.warn(v.cleanup.fileDeleted(G.filePath,G.fileType))}await this.fileRegistry.recordOperation({toolName:$,operationType:"rm",filePath:G.filePath,fileType:G.fileType,operationId:z6()})}catch(X){M.debug(v.cleanup.deleteError(G.filePath,X))}M.debug(v.cleanup.completed($,Q.length))}async cleanupStaleSymlinks($,M){let J=this.logger.getSubLogger({name:"cleanupStaleSymlinks"}),Q=new Set(M.filter((G)=>G.success).map((G)=>G.targetPath)),Y=this.projectConfig.paths.binariesDir;for(let G of Object.keys($)){let Z=(await this.fileRegistry.getFileStatesForTool(G)).filter((q)=>q.fileType==="symlink"&&q.lastOperation==="symlink"&&!q.filePath.startsWith(Y));for(let q of Z){if(Q.has(q.filePath))continue;J.warn(v.staleSymlinkCleanup.removing(q.filePath,G));try{try{await this.fs.lstat(q.filePath),await this.fs.rm(q.filePath)}catch{}await this.fileRegistry.recordOperation({toolName:G,operationType:"rm",filePath:q.filePath,fileType:"symlink",operationId:z6()})}catch(I){J.debug(v.cleanup.deleteError(q.filePath,I))}}}}async cleanupStaleCopies($,M){let J=this.logger.getSubLogger({name:"cleanupStaleCopies"}),Q=new Set(M.filter((Y)=>Y.success).map((Y)=>Y.targetPath));for(let Y of Object.keys($)){let X=(await this.fileRegistry.getFileStatesForTool(Y)).filter((Z)=>Z.fileType==="copy"&&Z.lastOperation==="cp");for(let Z of X){if(Q.has(Z.filePath))continue;J.warn(v.staleCopyCleanup.removing(Z.filePath,Y));try{if(await this.fs.exists(Z.filePath))await this.fs.rm(Z.filePath,{recursive:!0,force:!0});await this.fileRegistry.recordOperation({toolName:Y,operationType:"rm",filePath:Z.filePath,fileType:"copy",operationId:z6()})}catch(q){J.debug(v.cleanup.deleteError(Z.filePath,q))}}}}}import Q4 from"path";var b0={installing:($)=>W(`Installing from curl-binary: toolName=${$}`),downloadingBinary:($)=>W(`Downloading binary from: ${$}`),binaryDownloaded:()=>W("Binary downloaded successfully"),settingPermissions:()=>W("Setting binary executable permissions")};async function r9($,M,J,Q,Y,G,X,Z,q){let I=q$(Y,$),U=Z.getSubLogger({name:"installFromCurlBinary"});if(U.debug(b0.installing($)),!M.installParams||!("url"in M.installParams))return{success:!1,error:"URL not specified in installParams"};let K=M.installParams,H=K.url;return Q$("curl-binary",$,U,async()=>{U.debug(b0.downloadingBinary(H));let O=Q4.join(J.stagingDir,$);await K$(U,H,O,$,G,Q),U.debug(b0.binaryDownloaded());let B={...J,downloadPath:O},j=await w$(M,B,X,Y,U);if(!j.success)return{success:!1,error:j.error};U.debug(b0.settingPermissions()),await M0(I,$,M,J,O,U);let V=e(M.binaries,J.stagingDir),D,A=V[0];if(A)D=await A$({binaryPath:A,args:K.versionArgs,regex:K.versionRegex,shellExecutor:q});return{success:!0,binaryPaths:V,metadata:{method:"curl-binary",downloadUrl:H,binaryUrl:H},version:D||(M.version!=="latest"?M.version:void 0)}})}import{z as CJ}from"zod";var dJ=r.extend({url:CJ.string().url(),versionArgs:CJ.array(CJ.string()).optional(),versionRegex:CJ.string().optional()});import{z as uJ}from"zod";var t9=t.extend({installationMethod:uJ.literal("curl-binary"),installParams:dJ,binaries:uJ.array(uJ.union([uJ.string().min(1),Z$])).min(1)});var Y4="1.0.0";class D6{fs;downloader;hookExecutor;shell;method="curl-binary";displayName="Curl Binary Installer";version=Y4;paramsSchema=dJ;toolConfigSchema=t9;constructor($,M,J,Q){this.fs=$;this.downloader=M;this.hookExecutor=J;this.shell=Q}async install($,M,J,Q,Y){let G=await r9($,M,J,Q,this.fs,this.downloader,this.hookExecutor,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}supportsUpdate(){return!1}supportsUpdateCheck(){return!1}supportsReadme(){return!1}}import G4 from"path";var KM={installing:($)=>W(`Installing from npm: package=${$}`),executingCommand:($)=>W(`Executing command: ${$}`),versionFetched:($,M)=>W(`Fetched version ${M} for npm package ${$}`),versionFetchFailed:($)=>W(`Failed to fetch version for npm package ${$}`),updateCheckFailed:()=>W("Failed to check update for npm tool")};async function o9($,M,J,Q,Y,G,X){let Z=Y.getSubLogger({name:"installFromNpm"});if(!M.installParams)return{success:!1,error:"Install parameters not specified"};let q=M.installParams,I=q.package||$,U=q.version,K=U?`${I}@${U}`:I;Z.debug(KM.installing(I));let H=q.packageManager==="bun";return Q$("npm",$,Z,async()=>{let O=X??W$({logger:Z,skipCommandLog:!0});if(H)await Z4(K,Z,O);else await W4(K,Z,O);let B=await X4(H,O),j=e(M.binaries,B),V;if(q.versionArgs&&q.versionRegex){let T=j[0];if(T)V=await A$({binaryPath:T,args:q.versionArgs,regex:q.versionRegex,shellExecutor:G})}else if(H){let T=j[0];if(T)V=await A$({binaryPath:T,args:["--version"],regex:"(\\d+\\.\\d+\\.\\d+)",shellExecutor:G})}else V=await q4(I,G);let D={method:"npm",packageName:I};return{success:!0,binaryPaths:j,version:V?j$(V):void 0,metadata:D}})}async function X4($,M){if($)return(await M`bun pm bin -g`.quiet()).stdout.toString().trim();let J=await M`npm prefix -g`.quiet();return G4.join(J.stdout.toString().trim(),"bin")}async function Z4($,M,J){let Q=`bun install -g ${$}`;M.debug(KM.executingCommand(Q)),await J`bun install -g ${$}`}async function W4($,M,J){let Q=`npm install -g ${$}`;M.debug(KM.executingCommand(Q)),await J`npm install -g ${$}`}async function q4($,M){try{return(await M`npm view ${$} version`.quiet().noThrow()).stdout.toString().trim()||void 0}catch{return}}import{z as I0}from"zod";var fJ=r.extend({package:I0.string().min(1).optional(),version:I0.string().optional(),versionArgs:I0.array(I0.string()).optional(),versionRegex:I0.string().optional(),packageManager:I0.enum(["npm","bun"]).optional()});import{z as pJ}from"zod";var e9=t.extend({installationMethod:pJ.literal("npm"),installParams:fJ,binaries:pJ.array(pJ.union([pJ.string().min(1),Z$])).min(1)});var I4="1.0.0";class A6{shell;method="npm";displayName="npm Installer";version=I4;externallyManaged=!0;paramsSchema=fJ;toolConfigSchema=e9;constructor($){this.shell=$}async install($,M,J,Q,Y){let G=await o9($,M,J,Q,Y,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata}}async resolveVersion($,M,J,Q){let Y=Q.getSubLogger({name:"resolveVersion"});try{let X=M.installParams?.package||$,q=(await this.shell`npm view ${X} version`.quiet().noThrow()).stdout.toString().trim();if(!q)return Y.debug(KM.versionFetchFailed(X)),null;let I=EM(q);return Y.debug(KM.versionFetched(X,I)),I}catch(G){return Y.debug(KM.versionFetchFailed($),G),null}}supportsUpdate(){return!0}supportsUpdateCheck(){return!0}async checkUpdate($,M,J,Q){let Y=Q.getSubLogger({name:"checkUpdate",context:$});try{let X=M.installParams?.package||$,q=(await this.shell`npm view ${X} version`.quiet().noThrow()).stdout.toString().trim();if(!q)return{success:!1,error:`Could not fetch latest version for npm package: ${X}`};let I=M.version||"latest";if(I==="latest")return{success:!0,hasUpdate:!1,currentVersion:q,latestVersion:q};return{success:!0,hasUpdate:I!==q,currentVersion:I,latestVersion:q}}catch(G){return Y.error(KM.updateCheckFailed(),G),{success:!1,error:G instanceof Error?G.message:"Unknown error"}}}supportsReadme(){return!1}}import N0 from"path";var m$={installing:($)=>W(`Installing zsh plugin: ${$}`),cloning:($,M)=>W(`Cloning ${$} to ${M}`),updating:($)=>W(`Updating existing plugin at ${$}`),cloneSuccess:($)=>W(`Cloned plugin: ${$}`),updateSuccess:($)=>W(`Updated plugin: ${$}`),cloneFailed:($)=>W(`Failed to clone: ${$}`),updateFailed:($)=>W(`Failed to update: ${$}`),versionDetected:($)=>W(`Detected version: ${$}`),sourceFileDetected:($)=>W(`Detected source file: ${$}`),sourceFileNotFound:($)=>W(`Specified source file not found: ${$}`),noParamsProvided:()=>W("No install parameters provided"),invalidParams:()=>W("Either repo or url must be specified")};async function $G($,M,J,Q,Y,G,X){let Z=Q.getSubLogger({name:"installFromZshPlugin"});Z.debug(m$.installing($));let q=M.installParams;if(!q)return{success:!1,error:"No install parameters provided"};if(!q.repo&&!q.url)return{success:!1,error:"Either repo or url must be specified"};return Q$("zsh-plugin",$,Z,async()=>{let U=q.url??`https://github.com/${q.repo}.git`,K=E6(q.pluginName,q.repo,q.url),H=N0.join(J.stagingDir,K),_=await Y.exists(H),O=X??W$({logger:Z,skipCommandLog:!0});if(_)Z.debug(m$.updating(H)),await H4(H,O),Z.info(m$.updateSuccess(K));else Z.debug(m$.cloning(U,H)),await K4(U,H,O),Z.info(m$.cloneSuccess(K));let B=await U4(H,K,q.source,Y,Z);if(!B)return{success:!1,error:`Could not detect plugin source file in ${H}. Specify 'source' parameter explicitly.`};let j=await _4(H,G,Z),V=N0.join(J.currentDir,K,B);return{success:!0,binaryPaths:[],version:j,metadata:{method:"zsh-plugin",pluginName:K,gitUrl:U,pluginPath:H,sourceFile:B},shellInit:{zsh:{scripts:[n$(`source "${V}"`)]}}}})}function E6($,M,J){if($)return $;if(M)return M.split("/")[1]??M;if(J){let Q=new URL(J).pathname;return N0.basename(Q,".git")}throw Error("Cannot determine plugin name")}async function U4($,M,J,Q,Y){let G=Y.getSubLogger({name:"detectSourceFile"});if(J){let Z=N0.join($,J);if(await Q.exists(Z))return G.debug(m$.sourceFileDetected(J)),J;G.warn(m$.sourceFileNotFound(J));return}let X=[`${M}.plugin.zsh`,`${M}.zsh`,"init.zsh","plugin.zsh",`${M}.zsh-theme`];for(let Z of X){let q=N0.join($,Z);if(await Q.exists(q))return G.debug(m$.sourceFileDetected(Z)),Z}return}async function K4($,M,J){await J`git clone --depth 1 ${$} ${M}`}async function H4($,M){await M`git -C ${$} pull --ff-only`}async function _4($,M,J){let Q=J.getSubLogger({name:"getGitVersion"});try{let Y=await M`git -C ${$} describe --tags --abbrev=0`.quiet().noThrow();if(Y.code===0){let X=Y.stdout.trim();return Q.debug(m$.versionDetected(X)),X}let G=await M`git -C ${$} rev-parse --short HEAD`.quiet().noThrow();if(G.code===0){let X=G.stdout.trim();return Q.debug(m$.versionDetected(X)),X}return}catch{return}}import{z as v0}from"zod";var cJ=r.extend({repo:v0.string().regex(/^[^/]+\/[^/]+$/,"Must be in user/repo format").optional(),url:v0.string().url().optional(),pluginName:v0.string().min(1).optional(),source:v0.string().min(1).optional(),auto:v0.boolean().default(!0)}).refine(($)=>$.repo||$.url,{message:"Either repo or url must be specified"});import{z as F6}from"zod";var MG=t.extend({installationMethod:F6.literal("zsh-plugin"),installParams:cJ,binaries:F6.array(F6.string().min(1)).default([])});import R4 from"path";var O4="1.0.0";class L6{fs;shell;method="zsh-plugin";displayName="Zsh Plugin Installer";version=O4;paramsSchema=cJ;toolConfigSchema=MG;externallyManaged=!1;constructor($,M){this.fs=$;this.shell=M}async install($,M,J,Q,Y){let G=await $G($,M,J,Y,this.fs,this.shell);if(!G.success)return{success:!1,error:G.error};return{success:!0,binaryPaths:G.binaryPaths,version:G.version,metadata:G.metadata,shellInit:G.shellInit}}supportsUpdate(){return!0}supportsUpdateCheck(){return!1}supportsReadme(){return!1}getShellInit($,M,J){let Q=M.installParams;if(!Q)return;let Y=E6(Q.pluginName,Q.repo,Q.url),G=Q.source??`${Y}.plugin.zsh`,X=R4.join(J,Y,G);return{zsh:{scripts:[n$(`source "${X}"`)]}}}}import x6 from"path";var _$={constructor:{initialized:()=>W("ShimGenerator initialized")},generate:{missingToolConfig:($)=>W(`Skipping shim generation for ${$} because configuration is missing`)},generateForTool:{started:($,M)=>W(`Generating shims for ${$} using ${M}`),skippedExternallyManaged:($,M)=>W(`Skipping shim generation for ${$} (externally managed via ${M})`),skippedNoBinaries:($)=>W(`Skipping shim generation for ${$} (no binaries defined)`),skippedAlreadyInstalled:($)=>W(`Skipping shim generation for ${$} (already installed)`),skippedManualNoBinaryPath:()=>W("Skipping shim generation (manual tool has .bin() but no binaryPath \u2014 use shell functions instead)")},generateShim:{resolvedShimPath:($)=>W(`Resolved shim output path ${$}`),existingShim:($)=>W(`Existing shim found at ${$}; overwrite is disabled`),conflictingFile:($,M)=>W(`Cannot create shim for "${$}": conflicting file exists at ${M}. Use --overwrite to replace it.`),overwritingConflict:($)=>W(`Overwriting conflicting file at ${$}`),resolvedBinaryPath:($,M,J)=>W(`Resolved binary path for ${$}/${M} to ${J}`),generatedContent:($)=>W(`Generated shim content for ${$}`),success:($,M,J)=>W(`Generated shim ${$} at ${M} using ${J}`)}};class T6{fs;config;logger;systemInfo;externallyManagedMethods;missingBinaryMessagesByMethod;toolInstallationRegistry;isConfigurationOnlyToolConfig($){let M=$.installationMethod==="manual",J=!$.installParams||Object.keys($.installParams).length===0,Q=!$.binaries||$.binaries.length===0;return M&&J&&Q}constructor($,M,J,Q,Y,G,X){let Z=$.getSubLogger({name:"ShimGenerator"});this.logger=Z,Z.getSubLogger({name:"constructor"}).debug(_$.constructor.initialized()),this.fs=M,this.config=J,this.systemInfo=Q,this.externallyManagedMethods=Y??new Set,this.missingBinaryMessagesByMethod=G??new Map,this.toolInstallationRegistry=X}async generate($,M){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let Y in $)if(Object.hasOwn($,Y)){let G=$[Y];if(G){let X=await this.generateForTool(Y,G,M);Q.push(...X)}else J.debug(_$.generate.missingToolConfig(Y))}return Q}async generateForTool($,M,J){let Q=this.logger.getSubLogger({name:"generateForTool",context:$}),Y=this.fs instanceof f?this.fs.withToolName($):this.fs,G=Y.constructor.name;Q.debug(_$.generateForTool.started($,G));let X=Y$(M,this.systemInfo),Z=[],q=J?.overwrite??!1,I=J?.overwriteConflicts??!1;if(this.isConfigurationOnlyToolConfig(X))return Z;if(X.installationMethod==="manual"&&!X.installParams?.binaryPath)return Q.warn(_$.generateForTool.skippedManualNoBinaryPath()),Z;if(this.externallyManagedMethods.has(X.installationMethod)){if(!this.toolInstallationRegistry)return Q.debug(_$.generateForTool.skippedExternallyManaged($,X.installationMethod)),Z;if(await this.toolInstallationRegistry.isToolInstalled($))return Q.debug(_$.generateForTool.skippedAlreadyInstalled($)),Z}let U=X.binaries&&X.binaries.length>0?X.binaries:[];if(U.length===0)return Q.debug(_$.generateForTool.skippedNoBinaries($)),Z;let K=U.map((H)=>typeof H==="string"?H:H.name);for(let H of K){let _=await this.generateShimForBinary(Y,$,X,H,q,I);if(_)Z.push(_)}return Z}async generateShimForBinary($,M,J,Q,Y,G){let X=this.logger.getSubLogger({name:"generateShimForBinary"}),Z=this.config.paths.targetDir,q=x6.join(Z,Q);if(X.debug(_$.generateShim.resolvedShimPath(q)),await $.exists(q)){if(!await this.isGeneratedShim($,q)){if(!G)return X.error(_$.generateShim.conflictingFile(M,q)),null;X.debug(_$.generateShim.overwritingConflict(q))}else if(!Y)return X.debug(_$.generateShim.existingShim(q)),null}let I=x6.join(this.config.paths.binariesDir,M,"current",Q);X.debug(_$.generateShim.resolvedBinaryPath(M,Q,I));let U=M.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),K=this.missingBinaryMessagesByMethod.get(J.installationMethod),H=K?`echo "${K.replaceAll('"',"\\\"")}" >&2`:'echo "Installation completed but binary not found at: $TOOL_EXECUTABLE" >&2',_=c(`
|
|
162
162
|
#!/usr/bin/env bash
|
|
163
163
|
# Shim for ${Q}
|
|
164
164
|
# Generated by Dotfiles Management Tool
|
|
@@ -168,7 +168,7 @@ ${A}`)}return D.data}async function h1($){return XQ.parse({})}async function pY(
|
|
|
168
168
|
TOOL_NAME="${M}"
|
|
169
169
|
BINARY_NAME="${Q}"
|
|
170
170
|
TOOL_EXECUTABLE="${I}"
|
|
171
|
-
GENERATOR_CLI_EXECUTABLE="${
|
|
171
|
+
GENERATOR_CLI_EXECUTABLE="${sM()}"
|
|
172
172
|
CONFIG_PATH="${this.config.configFilePath}"
|
|
173
173
|
|
|
174
174
|
# Check for recursion
|
|
@@ -219,11 +219,11 @@ ${A}`)}return D.data}async function h1($){return XQ.parse({})}async function pY(
|
|
|
219
219
|
exit $install_exit_code
|
|
220
220
|
fi
|
|
221
221
|
fi
|
|
222
|
-
`);X.debug(H$.generateShim.generatedContent(Q)),await this.fs.ensureDir(FG.dirname(q)),await $.writeFile(q,_);let O=493;try{if(((await $.stat(q)).mode&511)!==O)await $.chmod(q,O)}catch{await $.chmod(q,O)}return X.debug(H$.generateShim.success(Q,q,$.constructor.name)),q}async isGeneratedShim($,M){try{try{if((await $.lstat(M)).isSymbolicLink())return!0}catch{}return(await $.readFile(M,"utf8")).includes("# Generated by Dotfiles Management Tool")}catch{return!1}}}import xG from"path";var h={generate:{processingTool:($)=>W(`Processing symlinks for tool "${$}"`),missingToolConfig:($)=>W(`Tool config for "${$}" is undefined. Skipping.`)},process:{symlinkDetails:($,M,J,Q)=>W(`Processing symlink: source="${$}" (abs: "${M}"), target="${J}" (abs: "${Q}")`),sourceMissing:($,M)=>W(`Tool "${$}" source file not found: ${M}`),targetExists:($)=>W(`Target path "${$}" already exists.`),skipExistingTarget:($)=>W(`Target "${$}" exists and overwrite is false. Skipping symlink creation.`)},filesystem:{backupFailed:($)=>W(`Failed to write backup of ${$}`),deleteFailed:($)=>W(`Failed to delete ${$}`),directoryCreateFailed:($)=>W(`Failed to create directory ${$}`),symlinkFailed:($,M)=>W(`Failed to create symlink ${$} \u2192 ${M}`),symlinkAlreadyExists:($,M)=>W(`Symlink already exists and is valid: ${$} -> ${M}`),creatingSymlink:($,M)=>W(`Creating symlink: ${$} -> ${M}`),symlinkCreated:($,M)=>W(`Successfully created symlink: ${$} -> ${M}`),removingBrokenSymlink:($)=>W(`Removing broken symlink: ${$}`)},copy:{processingTool:($)=>W(`Processing copies for tool "${$}"`),missingToolConfig:($)=>W(`Tool config for "${$}" is undefined. Skipping.`),copyDetails:($,M,J,Q)=>W(`Processing copy: source="${$}" (abs: "${M}"), target="${J}" (abs: "${Q}")`),sourceMissing:($,M)=>W(`Tool "${$}" source file not found: ${M}`),targetExists:($)=>W(`Target path "${$}" already exists.`),skipExistingTarget:($)=>W(`Target "${$}" exists and overwrite is false. Skipping copy.`),copyFailed:($,M)=>W(`Failed to copy ${$} \u2192 ${M}`)}};class TG{fs;projectConfig;systemInfo;logger;constructor($,M,J,Q){this.fs=M,this.projectConfig=J,this.systemInfo=Q,this.logger=$.getSubLogger({name:"CopyGenerator"})}async generate($,M={}){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let G in $){let Y=$[G];if(!Y)continue;let X=G$(Y,this.systemInfo);if(!this.shouldProcessTool(X,G,J))continue;let Z=J.getSubLogger({context:G}),q=this.fs instanceof f?this.fs.withToolName(G):this.fs;Z.debug(h.copy.processingTool(G));for(let I of X.copies){let U=await this.processCopy(X,I,q,M,Z);Q.push(U)}}return Q}shouldProcessTool($,M,J){let Q=J.getSubLogger({name:"shouldProcessTool"});if(!$)return Q.debug(h.copy.missingToolConfig(M)),!1;if(!$.copies||$.copies.length===0)return!1;return!0}async processCopy($,M,J,Q,G){let Y=G.getSubLogger({name:"processCopy"}),{overwrite:X=!1,backup:Z=!1}=Q,q=_M($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=_M($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(Y.debug(h.copy.copyDetails(M.source,q,M.target,I)),!await J.exists(q))return Y.error(h.copy.sourceMissing($.name,q)),{success:!1,sourcePath:q,targetPath:I,status:"failed",error:h.copy.sourceMissing($.name,q)};if(await J.exists(I)){if(Y.debug(h.copy.targetExists(I)),!X)return Y.debug(h.copy.skipExistingTarget(I)),{success:!0,sourcePath:q,targetPath:I,status:"skipped_exists"};let K=await this.handleOverwrite(I,J,Z,Y);if(K.failed)return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:K.error};return this.performCopy(q,I,J,K.status,Y)}return this.performCopy(q,I,J,"created",Y)}async handleOverwrite($,M,J,Q){if(J){let G=`${$}.bak`;try{if(await M.exists(G))await M.rm(G,{recursive:!0,force:!0});return await M.rename($,G),{failed:!1,status:"backed_up"}}catch{let Y=h.filesystem.backupFailed($);return Q.error(Y),{failed:!0,error:Y}}}try{if((await M.stat($)).isDirectory())await M.rm($,{recursive:!0,force:!0});else await M.rm($,{force:!0});return{failed:!1,status:"updated_target"}}catch{let G=h.filesystem.deleteFailed($);return Q.error(G),{failed:!0,error:G}}}async performCopy($,M,J,Q,G){let Y=G.getSubLogger({name:"performCopy"}),X=xG.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return Y.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}try{if((await J.stat($)).isDirectory())await this.copyDirectory($,M,J);else await J.copyFile($,M);return{success:!0,sourcePath:$,targetPath:M,status:Q}}catch{let Z=h.copy.copyFailed($,M);return Y.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}async copyDirectory($,M,J){await J.ensureDir(M);let Q=await J.readdir($);for(let G of Q){let Y=xG.join($,G),X=xG.join(M,G);if((await J.stat(Y)).isDirectory())await this.copyDirectory(Y,X,J);else await J.copyFile(Y,X)}}}import a$ from"path";class kG{fs;projectConfig;systemInfo;logger;constructor($,M,J,Q){this.fs=M,this.projectConfig=J,this.systemInfo=Q,this.logger=$.getSubLogger({name:"SymlinkGenerator"})}async createBinarySymlink($,M,J){let Q=$.getSubLogger({name:"createBinarySymlink"});try{if((await this.fs.lstat(J)).isSymbolicLink()){let I=await this.fs.readlink(J),U=a$.resolve(a$.dirname(J),I),K=a$.resolve(M);if(U===K){if(await this.fs.exists(U)){Q.debug(h.filesystem.symlinkAlreadyExists(J,U));return}}await this.fs.rm(J,{force:!0})}else await this.fs.rm(J,{force:!0})}catch{}if(!await this.fs.exists(M))throw Error(`Cannot create symlink: binary does not exist at ${M}`);Q.debug(h.filesystem.creatingSymlink(J,M)),await this.fs.symlink(M,J);let Y=await this.fs.readlink(J),X=a$.resolve(a$.dirname(J),Y),Z=a$.resolve(M);if(X!==Z)throw Error(`Symlink verification failed: ${J} points to ${X}, expected ${Z}`);Q.debug(h.filesystem.symlinkCreated(J,M))}async generate($,M={}){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let G in $){let Y=$[G];if(!Y)continue;let X=G$(Y,this.systemInfo);if(!this.shouldProcessTool(X,G,J))continue;let Z=J.getSubLogger({context:G}),q=this.fs instanceof f?this.fs.withToolName(G):this.fs;Z.debug(h.generate.processingTool(G));for(let I of X.symlinks){let U=await this.processSymlink(X,I,q,M,Z);Q.push(U)}}return Q}shouldProcessTool($,M,J){let Q=J.getSubLogger({name:"shouldProcessTool"});if(!$)return Q.debug(h.generate.missingToolConfig(M)),!1;if(!$.symlinks||$.symlinks.length===0)return!1;return!0}async processSymlink($,M,J,Q,G){let Y=G.getSubLogger({name:"processSymlink"}),{overwrite:X=!1,backup:Z=!1}=Q,q=_M($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=_M($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(Y.debug(h.process.symlinkDetails(M.source,q,M.target,I),M.source,q,M.target,I),!await J.exists(q))return Y.error(h.process.sourceMissing($.name,q)),{success:!1,sourcePath:q,targetPath:I,status:"failed",error:h.process.sourceMissing($.name,q)};let U=await this.handleExistingTarget(q,I,J,{overwrite:X,backup:Z},Y);if(U.shouldSkip){if(U.status==="failed")return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:U.error??"Unknown error"};if(U.status==="skipped_correct"&&J instanceof f)await J.recordExistingSymlink(q,I);return{success:!0,sourcePath:q,targetPath:I,status:U.status}}return await this.createSymlink(q,I,J,U.status,Y)}async handleExistingTarget($,M,J,Q,G){let Y=G.getSubLogger({name:"handleExistingTarget"});if(!await J.exists(M)){let q=await this.removeBrokenSymlink(M,J,Y);if(q.failed)return{shouldSkip:!0,status:"failed",error:q.error};return{shouldSkip:!1,status:"created"}}if(Y.debug(h.process.targetExists(M)),(await this.checkCorrectSymlink($,M,J)).isCorrect)return{shouldSkip:!0,status:"skipped_correct"};if(!Q.overwrite)return Y.debug(h.process.skipExistingTarget(M)),{shouldSkip:!0,status:"skipped_exists"};return await this.handleOverwrite(M,J,Q.backup,Y)}async checkCorrectSymlink($,M,J){try{if((await J.lstat(M)).isSymbolicLink()){let G=await J.readlink(M),Y=a$.resolve(a$.dirname(M),G),X=a$.resolve($);return{isCorrect:Y===X}}}catch{}return{isCorrect:!1}}async handleOverwrite($,M,J,Q){let G=Q.getSubLogger({name:"handleOverwrite"}),Y="updated_target";if(J){let X=await this.createBackup($,M,G);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error};Y="backed_up"}else{let X=await this.deleteTarget($,M,G);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error}}return{shouldSkip:!1,status:Y}}async createBackup($,M,J){let Q=J.getSubLogger({name:"createBackup"}),G=`${$}.bak`;try{if(await M.exists(G))await M.rm(G,{recursive:!0,force:!0});return await M.rename($,G),{failed:!1}}catch{let Y=h.filesystem.backupFailed($);return Q.error(Y),{failed:!0,error:Y}}}async deleteTarget($,M,J){let Q=J.getSubLogger({name:"deleteTarget"});try{if((await M.stat($)).isDirectory())await M.rm($,{recursive:!0,force:!0});else await M.rm($,{force:!0});return{failed:!1}}catch{let G=h.filesystem.deleteFailed($);return Q.error(G),{failed:!0,error:G}}}async removeBrokenSymlink($,M,J){let Q=J.getSubLogger({name:"removeBrokenSymlink"});try{if((await M.lstat($)).isSymbolicLink())Q.debug(h.filesystem.removingBrokenSymlink($)),await M.rm($,{force:!0});return{failed:!1}}catch{return{failed:!1}}}async createSymlink($,M,J,Q,G){let Y=G.getSubLogger({name:"createSymlink"}),X=a$.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return Y.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}try{return await J.symlink($,M),{success:!0,sourcePath:$,targetPath:M,status:Q}}catch{let Z=h.filesystem.symlinkFailed($,M);return Y.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}}import{eq as j4,gt as V4,valid as M9}from"semver";var N$={initializing:()=>W("Initializing VersionChecker with githubClient"),fetchingLatestRelease:($,M)=>W(`Fetching latest version for ${$}/${M}`),latestReleaseFound:($)=>W(`Latest release found ${$}`),latestReleaseError:($,M)=>W(`Failed to fetch latest release for ${$}/${M}`),noLatestRelease:($,M)=>W(`No latest release found for ${$}/${M}`),comparingVersions:($,M)=>W(`Comparing versions configured ${$} vs latest ${M}`),invalidConfiguredVersion:($)=>W(`Configured version invalid ${$}`),invalidLatestVersion:($)=>W(`Latest version invalid ${$}`),versionComparisonResult:($)=>W(`Version comparison result ${$}`)};class SG{githubClient;logger;constructor($,M){this.logger=$.getSubLogger({name:"VersionChecker"}),this.logger.debug(N$.initializing()),this.githubClient=M}async getLatestToolVersion($,M){let J=this.logger.getSubLogger({name:"getLatestToolVersion"});J.debug(N$.fetchingLatestRelease($,M));try{let Q=await this.githubClient.getLatestRelease($,M);if(Q?.tag_name){let G=Q.tag_name.replace(/^v/,"");return J.debug(N$.latestReleaseFound(G)),G}return J.debug(N$.noLatestRelease($,M)),null}catch(Q){return J.debug(N$.latestReleaseError($,M),Q),null}}async checkVersionStatus($,M){let J=this.logger.getSubLogger({name:"checkVersionStatus"});J.debug(N$.comparingVersions($,M));let Q=$.replace(/^v/,""),G=M.replace(/^v/,"");if(!M9(Q))return J.debug(N$.invalidConfiguredVersion(Q)),"INVALID_CURRENT_VERSION";if(!M9(G))return J.debug(N$.invalidLatestVersion(G)),"INVALID_LATEST_VERSION";if(V4(G,Q))return J.debug(N$.versionComparisonResult("NEWER_AVAILABLE")),"NEWER_AVAILABLE";if(j4(G,Q))return J.debug(N$.versionComparisonResult("UP_TO_DATE")),"UP_TO_DATE";return J.debug(N$.versionComparisonResult("AHEAD_OF_LATEST")),"AHEAD_OF_LATEST"}}import G5 from"net";import K0 from"path";import{realpath as z4}from"fs/promises";import B4 from"path";var J9={name:"bin",description:"Print the real path to a binary",hasPositionalArg:!0,positionalArgDescription:"binary name",positionalArgType:"tool"};async function D4($,M,J,Q,G,Y,X){let Z=await Y.loadSingleToolConfig($,M,J,Q,G,X);if(Z){let K=(G$(Z,X).binaries??[])[0],H=K?typeof K==="string"?K:K.name:M;return{toolName:M,binaryName:H}}let q=await Y.loadToolConfigByBinary($,M,J,Q,G,X);if(q&&!("error"in q))return{toolName:q.name,binaryName:M};return}async function A4($,M,J){let{projectConfig:Q,fs:G,configService:Y,systemInfo:X}=J,Z=$.getSubLogger({minLevel:7}),q=await D4(Z,M,Q.paths.toolConfigsDir,G,Q,Y,X);if(!q)return x.ERROR;let{toolName:I,binaryName:U}=q,K=B4.join(Q.paths.binariesDir,I,"current",U);try{let H=await z4(K);return process.stdout.write(H),x.SUCCESS}catch{return x.ERROR}}function Q9($,M,J){let Q=$.getSubLogger({name:"registerBinCommand"});M.command("bin <name>").description("Print the absolute real path to a binary (resolving symlinks). Accepts tool name or binary name (from .bin()).").action(async(G)=>{let Y=await J(),X=await A4(Q,G,Y);v(X)})}import G9 from"path";var R={proxyUnavailable:($)=>W(`HTTP proxy not available on port ${$}. Start with 'bun proxy' or unset DEV_PROXY env var.`),proxyEnabled:($)=>W(`Routing requests through HTTP proxy on port ${$}`),proxyCheckingAvailability:($)=>W(`Checking proxy availability on port ${$}`),commandActionStarted:($,M)=>W(`${$} command action logic started${M?`. Tool: ${M}`:""}`),commandConfigErrorDetails:()=>W("Configuration loading error details: %O"),dryRunEnabled:()=>W("Dry run enabled. Initializing MemFileSystem"),componentInitialized:($)=>W(`${$} initialized`),toolConfigsLoading:($)=>W(`tool config loading: ${$}`),toolConfigsLoaded:($,M)=>W(`Configuration loaded from ${$} (${M} tools configured)`),toolConfigsForDryRun:()=>W("tool configs for dry run"),commandCompleted:($)=>W(`DONE${$?" (dry run)":""}`),commandExecutionFailed:($,M)=>W(`Command failed [${$}] exit ${M}`),commandVersionComparison:($,M,J)=>W(`Tool: ${$}, Configured: ${M}, Latest: ${J}`),commandUnsupportedOperation:($,M)=>W(`${$} not yet supported (${M})`),toolNotFound:($,M)=>W(`Tool "${$}" not found in ${M}`),toolInstalled:($,M,J)=>W(`Tool "${$}" \`${M}\` installed successfully using ${J}`),toolAlreadyInstalled:($,M)=>W(`Tool "${$}" \`${M}\` is already installed`),toolInstallSkippedConfigurationOnly:($)=>W(`Tool "${$}" has no installation steps`),shimDeleted:($,M)=>W(`Deleted temporary shim ${$} at ${M}`),toolNoConfigurationsFound:($)=>W(`No tool configurations found in ${$}`),toolCheckingUpdates:($)=>W(`updates for ${$}`),toolUpdateAvailable:($,M,J)=>W(`Update available for ${$}: ${M} -> ${J}`),toolUpToDate:($,M,J)=>W(`${$} (${M}) is up to date. Latest: ${J}`),toolAheadOfLatest:($,M,J)=>W(`${$} (${M}) is ahead of the latest known version (${J})`),toolConfiguredToLatest:($,M)=>W(`Tool "${$}" is configured to 'latest'. The latest available version is ${M}`),toolVersionComparisonFailed:($,M,J)=>W(`Could not determine update status for ${$} (${M}) against latest ${J}`),toolShimUpToDate:($,M)=>W(`${$} is already up to date (${M})`),toolShimOnLatest:($,M)=>W(`${$} is already on latest version (${M})`),toolShimUpdateStarting:($,M,J)=>W(`Updating ${$} from ${M} to ${J}...`),toolProcessingUpdate:($,M,J)=>W(`${$} update from ${M} to ${J}`),toolShimUpdateSuccess:($,M)=>W(`${$} successfully updated to ${M}`),toolUpdated:($,M,J)=>W(`Tool "${$}" updated from \`${M}\` to \`${J}\``),toolUpdateFailed:($,M)=>W(`Update failed for tool "${$}": ${M}`),toolVersionPinned:($,M)=>W(`Tool "${$}" is pinned to version \`${M}\`. Set version to "latest" in the tool config to enable updates`),toolUpdateNotSupported:($,M)=>W(`Tool "${$}" uses ${M} which does not support updates. Performing regular install instead`),commandCheckingUpdatesFor:($)=>W(`Checking "${$}" for updates`),commandCheckingUpdatesForAll:()=>W("Checking all tools for updates"),fsReadFailed:($)=>W(`Failed to read ${$}`),fsAccessDenied:($,M)=>W(`Access denied ${$}: ${M}`),fsItemNotFound:($,M)=>W(`${$} not found: ${M}`),fsWrite:($,M)=>W(`[${$}] write ${M}`),toolConflictsDetected:($,M)=>W(`${$}
|
|
223
|
-
${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles:()=>W("Registry-based cleanup: Removing all tracked files"),cleanupRegistryDatabase:()=>W("registry database cleanup"),cleanupRegistryDryRun:()=>W("Would clean up registry database (dry run)"),cleanupToolFiles:($)=>W(`Registry-based cleanup: files for tool '${$}'`),cleanupRegistryTool:($,M)=>W(M?`Would remove registry entries for tool: ${$} (dry run)`:`Removed registry entries for tool: ${$}`),cleanupTypeFiles:($)=>W(`Registry-based cleanup: files of type '${$}'`),cleanupFoundFiles:($,M,J)=>W(`Found ${$} files for tool '${M}'${J?` of type '${J}'`:""}`),cleanupFileRemoved:($)=>W(`[cleanup] rm ${$}`),fileCleanupDryRun:($)=>W(`Would delete: ${$}`),cleanupFileNotFound:($)=>W(`file not found ${$}`),cleanupDeleteFailed:($)=>W(`Failed to delete ${$}`),cleanupProcessStarted:($)=>W(`starting cleanup process, dryRun=${$}: %O`),configParameterOverridden:($,M)=>W(`${$.charAt(0).toUpperCase()+$.slice(1)} overridden to: ${M}`),cleanupProcessFinished:($)=>W(`cleanup process finished, dryRun=${$}`),logCheckingFileStates:()=>W("Checking file states for all tools"),logFileStatesForTool:($)=>W(`${$} files`),logFileStatus:($,M,J,Q,G)=>W(`${$} ${M} [${J}] - ${Q}${G}`),logTargetStatus:($,M)=>W(`${$} ${M}`),logNoOperationsFound:()=>W("No file operations found matching criteria"),logOperationHistory:($,M,J)=>W(`${$} ${M}${J?` ${J}`:""}`),cachingDisabled:()=>W("Caching disabled"),registryInitialized:($)=>W(`File tracking initialized: ${$}`),cliStarted:()=>W("CLI starting with arguments"),serviceGithubResourceNotFound:($,M)=>W(`GitHub ${$} not found: ${M}`),serviceGithubApiFailed:($,M)=>W(`GitHub API failed [${$}] ${M}`),configLoadFailed:($)=>W(`Failed to load configuration from ${$}`),configPathResolved:($)=>W(`Using configuration: ${$}`),configNotFound:()=>W("No configuration file found. Create dotfiles.config.ts or specify --config <path>"),configParameterIgnored:($,M)=>W(`Configuration field "${$}" ignored: ${M}`),configParameterInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),updatesCommandCompleted:()=>W("Check-updates command completed"),toolTypesGenerated:($)=>W(`Generated tool types: ${$}`),toolNotInstalled:($)=>W(`Tool "${$}" is not installed`),installPathNotFound:($)=>W(`Installation path not found: ${$}`),filesCommandShowingTree:($)=>W($),filesCommandEmptyDirectory:()=>W("(empty directory)"),filesCommandTree:($)=>W($),skillAlreadyExists:($)=>W(`Destination already exists, removing: ${$}`),skillDryRun:($,M)=>W(`Would copy skill: ${M} -> ${$}`),skillCopied:($,M)=>W(`Copied skill: ${M} -> ${$}`),skillCopyFailed:($)=>W(`Failed to copy skill to: ${$}`),cliCompletionGenerated:($)=>W(`CLI completion generated: ${$}`),dashboardStopping:()=>W("Stopping dashboard server"),dashboardBrowserOpenFailed:()=>W("Failed to open browser"),toolLookupByBinaryStarted:($)=>W(`Tool not found by name '${$}', searching by binary name`),toolFoundByBinary:($,M)=>W(`Binary '${$}' is provided by tool '${M}'`),toolNotFoundByBinary:($,M)=>W(`No tool or binary named "${$}" found in ${M}`),envCreated:($)=>W(`Environment created at ${$}`),envDeleted:($)=>W(`Environment deleted at ${$}`),envNotFound:($)=>W(`Environment not found at ${$}`),envOperationFailed:($,M)=>W(`Environment ${$} failed: ${M}`),envDeletionCancelled:()=>W("Deletion cancelled"),envActivationHint:($)=>W(`To activate: source ${$}/source`),envConfigPath:($)=>W(`Config file: ${$}`),envConfigFromEnvVar:($)=>W(`Using config from DOTFILES_ENV_DIR: ${$}`)};var Y9={name:"check-updates",description:"Check for available tool updates",hasPositionalArg:!0,positionalArgDescription:"tool name (optional, checks all if omitted)",positionalArgType:"tool"};async function E4($,M,J,Q,G,Y){let X={};if(J){$.debug(R.commandCheckingUpdatesFor(J));try{let Z=await M.loadSingleToolConfig($,J,Q.paths.toolConfigsDir,G,Q,Y);if(Z)X[J]=Z;else return $.error(R.toolNotFound(J,Q.paths.toolConfigsDir)),null}catch(Z){return $.error(R.configLoadFailed(`tool "${J}"`),Z),null}}else try{if($.debug(R.commandCheckingUpdatesForAll()),X=await M.loadToolConfigs($,Q.paths.toolConfigsDir,G,Q,Y),Object.keys(X).length===0)return $.error(R.toolNoConfigurationsFound(Q.paths.toolConfigsDir)),null}catch(Z){return $.error(R.configLoadFailed("tool configurations"),Z),null}return X}function F4($,M,J,Q,G){let Y=new Date().toISOString().replace(/:/g,"-").split(".")[0],X=$.configFilePath?G9.dirname($.configFilePath):M.paths.toolConfigsDir,Z=G9.join(M.paths.binariesDir,$.name,"current");return{toolName:$.name,toolDir:X,currentDir:Z,stagingDir:"",timestamp:Y||"",systemInfo:J,toolConfig:$,projectConfig:M,$:e$(W$(),process.env),fileSystem:Q,replaceInFile:(I,U,K,H)=>c0(Q,I,U,K,H),resolve:()=>{throw Error("resolve not supported in version check context")},log:qQ(G,$.name)}}async function L4($,M,J,Q,G,Y){if(Q==="latest"){$.info(R.toolConfiguredToLatest(J.name,G));return}if(Y){$.info(R.toolUpdateAvailable(J.name,Q,G));return}let X=await M.checkVersionStatus(Q,G);if(X==="UP_TO_DATE")$.info(R.toolUpToDate(J.name,Q,G));else if(X==="AHEAD_OF_LATEST")$.info(R.toolAheadOfLatest(J.name,Q,G));else $.warn(R.toolVersionComparisonFailed(J.name,Q,G))}async function x4($,M,J){let{projectConfig:Q,versionChecker:G,pluginRegistry:Y,systemInfo:X,fs:Z}=J,q=F4(M,Q,X,Z,$),I=Y.get(M.installationMethod);if(!I){$.warn(R.commandUnsupportedOperation("check-updates",`installation method: "${M.installationMethod}" for tool "${M.name}"`));return}if(!I.supportsUpdateCheck||!I.supportsUpdateCheck()){$.info(R.commandUnsupportedOperation("check-updates",`installation method: "${M.installationMethod}" for tool "${M.name}"`));return}let U=await I.checkUpdate?.(M.name,M,q,$);if(!U){$.warn(R.commandUnsupportedOperation("check-updates",M.name));return}if(!U.success){$.error(R.serviceGithubApiFailed("check update",0),Error(U.error));return}let K=U.currentVersion||M.version||"unknown",H=U.latestVersion||"unknown";await L4($,G,M,K,H,U.hasUpdate)}async function T4($,M,J){$.trace(R.commandActionStarted("check-updates",M||"all"));let Q=await E4($,J.configService,M,J.projectConfig,J.fs,J.systemInfo);if(!Q)return;for(let G of Object.values(Q))await x4($,G,J)}function X9($,M,J){let Q=$.getSubLogger({name:"registerCheckUpdatesCommand"});M.command("check-updates [toolName]").description("Checks for available updates for configured tools. If [toolName] is provided, checks only that tool.").action(async(G)=>{try{let Y=await J();await T4(Q,G,Y)}catch(Y){Q.error(R.commandExecutionFailed("check-updates",x.ERROR),Y),v(x.ERROR)}})}var Z9={name:"cleanup",description:"Clean up generated files and registry entries",options:[{flag:"--tool",description:"Cleanup files for specific tool",hasArg:!0,argPlaceholder:"<name>"},{flag:"--type",description:"Cleanup files of specific type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--all",description:"Cleanup all tracked files"}]};async function k4($,M,J,Q,G){$.info(R.cleanupAllTrackedFiles());let Y=await J.getRegisteredTools();for(let X of Y)await W9($,M,J,X,Q,void 0,G);if(!G){for(let X of Y)await J.removeToolOperations(X);$.info(R.cleanupRegistryDatabase())}else $.info(R.cleanupRegistryDryRun())}async function S4($,M,J,Q,G,Y,X){if($.info(R.cleanupToolFiles(Q)),await W9($,M,J,Q,G,Y,X),!X)await J.removeToolOperations(Q),$.info(R.cleanupRegistryTool(Q,!1));else $.info(R.cleanupRegistryTool(Q,!0))}async function w4($,M,J,Q,G,Y){$.info(R.cleanupTypeFiles(Q));let X=await J.getOperations({fileType:Q});for(let Z of X){let q=await J.getFileState(Z.filePath);if(q&&q.lastOperation!=="rm")await q9($,M,Z.filePath,G,Y)}}async function b4($,M,J){let{fs:Q,fileRegistry:G}=M,{dryRun:Y,tool:X,type:Z,all:q}=J,I=M.projectConfig.paths.homeDir;if(q)await k4($,Q,G,I,Y);else if(X)await S4($,Q,G,X,I,Z,Y);else if(Z)await w4($,Q,G,Z,I,Y);else $.warn(R.configParameterIgnored("cleanup options","Registry-based cleanup requires --all, --tool <name>, or --type <type> option"))}async function W9($,M,J,Q,G,Y,X){let Z=await J.getFileStatesForTool(Q),q=Z;if(Y)q=Z.filter((I)=>I.fileType===Y);$.trace(R.cleanupFoundFiles(q.length,Q,Y));for(let I of q)if(I.lastOperation!=="rm"){let U=I.fileType==="symlink"&&I.targetPath?I.targetPath:I.filePath;await q9($,M,U,G,X||!1)}}async function q9($,M,J,Q,G){try{if(await M.exists(J))if(!G)await M.rm(J,{force:!0}),$.info(R.cleanupFileRemoved(s(Q,J)));else $.info(R.fileCleanupDryRun(J));else $.debug(R.cleanupFileNotFound(J))}catch(Y){$.error(R.cleanupDeleteFailed(J),Y)}}async function v4($,M,J){let{dryRun:Q,tool:G,type:Y,all:X}=M;try{$.trace(R.cleanupProcessStarted(Q),M);let Z={...M,all:X||!G&&!Y};await b4($,J,Z),$.trace(R.cleanupProcessFinished(Q))}catch(Z){$.error(R.commandExecutionFailed("cleanup",1),Z),v(1)}}function I9($,M,J){let Q=$.getSubLogger({name:"registerCleanupCommand"});M.command("cleanup").description("Remove all generated artifacts, including shims, shell configurations, and the .generated directory.").option("--tool <name>","Remove files for specific tool only (registry-based)").option("--type <type>","Remove files of specific type only (registry-based)").option("--all","Remove all tracked files (registry-based)").action(async(G)=>{let Y={...G,...M.opts()},X=await J();await v4(Q,Y,X)})}import{Command as N4}from"commander";var U9={name:"dotfiles",description:"Dotfiles management CLI",options:[{flag:"--config",description:"Path to configuration file",hasArg:!0,argPlaceholder:"<path>"},{flag:"--dry-run",description:"Simulate operations without changes"},{flag:"--log",description:"Set log level",hasArg:!0,argPlaceholder:"<level>"},{flag:"--verbose",description:"Enable detailed debug messages"},{flag:"--quiet",description:"Suppress informational output"},{flag:"--platform",description:"Override detected platform",hasArg:!0,argPlaceholder:"<platform>"},{flag:"--arch",description:"Override detected architecture",hasArg:!0,argPlaceholder:"<arch>"}]};function K9(){return new N4().name("generator").description("CLI tool for managing dotfiles and tool configurations").version("0.0.2").option("--config <path>","Path to a configuration file","").option("--dry-run","Simulate all operations without making changes to the file system",!1).option("--trace","Show file paths and line numbers in log output",!1).option("--log <level>",`Set log level (${ZQ.join(", ")})`,"default").option("--verbose","Enable detailed debug messages (alias for --log=verbose)",!1).option("--quiet","Suppress all informational and debug output. Errors are still displayed (alias for --log=quiet)",!1).option("--platform <platform>",`Override the detected platform (${m0.join(", ")})`).option("--arch <arch>",`Override the detected architecture (${g0.join(", ")})`)}import s4 from"fs";import r4 from"path";var w={serverStarted:($)=>W(`Dashboard available at ${$}`),serverStopping:()=>W("Stopping dashboard server"),serverStopped:()=>W("Dashboard server stopped"),requestReceived:($,M)=>W(`${$} ${M}`),apiError:($)=>W(`API error in ${$}`),installFailed:($)=>W(`Installation failed: ${$}`),installSucceeded:()=>W("Installation succeeded"),checkUpdateCompleted:($,M,J)=>W(`Update check complete: hasUpdate=${$} current=${M} latest=${J}`),checkUpdateFailed:($)=>W(`Update check failed: ${$}`),updateNotSupported:($)=>W(`Update not supported for method ${$}`),updateFailed:($)=>W(`Update failed: ${$}`),updateSucceeded:($,M)=>W(`Updated from ${$} to ${M}`)};function y4($){let M=[];if($&1)M.push("Linux");if($&2)M.push("macOS");if($&4)M.push("Windows");return M}function P4($){let M=[];if($&1)M.push("x86_64");if($&2)M.push("arm64");return M}function H9($){let M={};if(typeof $.repo==="string")M.repo=$.repo;if(typeof $.assetPattern==="string")M.assetPattern=$.assetPattern;if(typeof $.ghCli==="boolean")M.ghCli=$.ghCli;if(typeof $.crate==="string")M.crate=$.crate;if(typeof $.crateName==="string")M.crate=$.crateName;if(typeof $.formula==="string")M.formula=$.formula;if(typeof $.url==="string")M.url=$.url;return M}function C4($){let M={};if("installParams"in $&&$.installParams){let Q=$.installParams;Object.assign(M,H9(Q))}let J;if($.platformConfigs&&$.platformConfigs.length>0)J=$.platformConfigs.map((Q)=>{let G={platforms:y4(Q.platforms)};if(Q.architectures!==void 0)G.architectures=P4(Q.architectures);let Y=Q.config;if(Y.installationMethod)G.installationMethod=Y.installationMethod;if(Y.installParams)G.installParams=H9(Y.installParams);if(Y.binaries)G.binaries=Y.binaries;if(Y.symlinks)G.symlinks=Y.symlinks;return G});return{name:$.name,version:$.version,installationMethod:$.installationMethod,installParams:M,binaries:$.binaries,dependencies:$.dependencies,symlinks:$.symlinks,disabled:$.disabled,hostname:$.hostname,configFilePath:$.configFilePath,platformConfigs:J}}function d4($,M){let J=M.get($);if(!J)return{status:"not-installed",installedVersion:null,installedAt:null,installPath:null,binaryPaths:[],hasUpdate:!1};return{status:"installed",installedVersion:J.version,installedAt:J.installedAt.toISOString(),installPath:J.installPath,binaryPaths:J.binaryPaths||[],hasUpdate:!1}}function _9($,M,J,Q,G,Y){return{config:C4($),runtime:d4($.name,M),files:J,binaryDiskSize:G,usage:Y}}function y$($){return new Date($).toISOString()}function U0($){let J=Date.now()-$,Q=Math.floor(J/1000);if(Q<60)return"just now";let G=Math.floor(Q/60);if(G<60)return`${G} minute${G===1?"":"s"} ago`;let Y=Math.floor(G/60);if(Y<24)return`${Y} hour${Y===1?"":"s"} ago`;let X=Math.floor(Y/24);if(X<30)return`${X} day${X===1?"":"s"} ago`;let Z=Math.floor(X/30);return`${Z} month${Z===1?"":"s"} ago`}async function R9($,M,J=20){try{let G=(await M.fileRegistry.getOperations()).toSorted((Z,q)=>q.createdAt-Z.createdAt),Y=G.length;return{success:!0,data:{activities:G.slice(0,J).map((Z)=>({id:Z.id,toolName:Z.toolName,action:Z.operationType,description:`${Z.operationType} ${Z.fileType}: ${Z.filePath}`,timestamp:y$(Z.createdAt),relativeTime:U0(Z.createdAt)})),totalCount:Y}}}catch(Q){return $.error(w.apiError("getActivity"),Q),{success:!1,error:"Failed to retrieve activity feed"}}}async function O9($,M){try{let J=M.projectConfig.paths;return{success:!0,data:{dotfilesDir:J.dotfilesDir,generatedDir:J.generatedDir,binariesDir:J.binariesDir,targetDir:J.targetDir,toolConfigsDir:J.toolConfigsDir}}}catch(J){return $.error(w.apiError("getConfig"),J),{success:!1,error:"Failed to retrieve configuration"}}}import y0 from"path";async function u4($){let{fs:M,projectConfig:J}=$,Q=J.paths.binariesDir,G=[];if(!await M.exists(Q))return[];let Y=await M.readdir(Q);for(let X of Y){let Z=y0.join(Q,X);if(!(await M.stat(Z).catch(()=>null))?.isDirectory())continue;let I=await M.readdir(Z),U=y0.join(Z,"current"),K=null;if(I.includes("current")){if((await M.lstat(U).catch(()=>null))?.isSymbolicLink()){let _=await M.readlink(U).catch(()=>null);if(_)K=y0.isAbsolute(_)?_:y0.resolve(Z,_)}}for(let H of I){if(H==="current")continue;let _=y0.join(Z,H);if(!(await M.lstat(_).catch(()=>null))?.isDirectory())continue;if(K!==_)G.push(_)}}return G}async function j9($,M){try{let J=[],Q=await u4(M);if(Q.length>0)J.push({name:"Unused Binaries",status:"warn",message:"",details:Q});let Y=await M.fileRegistry.validate();J.push({name:"Registry Integrity",status:Y.valid?"pass":"warn",message:Y.valid?"Registry is healthy":`Found ${Y.issues.length} issues`,details:Y.issues});let Z=(await M.toolInstallationRegistry.getAllToolInstallations()).length;J.push({name:"Tool Installations",status:Z>0?"pass":"warn",message:`${Z} tool${Z===1?"":"s"} installed`});let q=J.some((H)=>H.status==="fail"),I=J.some((H)=>H.status==="warn");return{success:!0,data:{overall:q?"unhealthy":I?"warning":"healthy",checks:J,lastCheck:new Date().toISOString()}}}catch(J){return $.error(w.apiError("getHealth"),J),{success:!1,error:"Failed to retrieve health status"}}}import wG from"path";async function V9($,M){let J=$.fs,Q=0;try{if(!await J.exists(M))return 0;let G=await J.readdir(M);for(let Y of G){let X=wG.join(M,Y),Z=await J.stat(X);if(Z.isDirectory())Q+=await V9($,X);else if(Z.isFile())Q+=Z.size}}catch{}return Q}async function bG($,M){let J=wG.join($.projectConfig.paths.generatedDir,"binaries"),Q=wG.join(J,M);return V9($,Q)}var hJ=null;async function f4(){let $=new Map;try{let M=Bun.spawn(["git","rev-parse","--show-toplevel"],{stdout:"pipe",stderr:"pipe"}),J=(await new Response(M.stdout).text()).trim();if(await M.exited!==0||!J)return $;let G=Bun.spawn(["git","log","--diff-filter=A","--name-only","--format=%aI"],{stdout:"pipe",stderr:"pipe"}),Y=await new Response(G.stdout).text();if(await G.exited!==0)return $;let Z=Y.split(`
|
|
224
|
-
`),q=null;for(let I of Z){let U=I.trim();if(!U)continue;if(/^\d{4}-\d{2}-\d{2}/.test(U))q=new Date(U);else if(q){let K=`${J}/${U}`;if(!$.has(K))$.set(K,q)}}}catch{}return $}async function
|
|
225
|
-
`)[0];if(!G)return null;return new Date(G)}catch{return null}}async function vG($){if(!hJ)hJ=await f4();let M=hJ.get($);if(M)return M;let J=await p4($);if(J)hJ.set($,J);return J}var mJ=null;async function _$($,M){if(mJ)return mJ;let{projectConfig:J,fs:Q,configService:G,systemInfo:Y}=M;return mJ=await G.loadToolConfigs($,J.paths.toolConfigsDir,Q,J,Y),mJ}async function z9($,M,J=10){try{let Q=M.projectConfig.paths.toolConfigsDir,G=[];async function Y(I){let U=await M.fs.readdir(I);for(let K of U){let H=`${I}/${K}`;if((await M.fs.stat(H)).isDirectory())await Y(H);else if(K.endsWith(".tool.ts")){let O=K.replace(/\.tool\.ts$/,"");G.push({name:O,configFilePath:H})}}}return await Y(Q),{success:!0,data:{tools:(await Promise.all(G.map(async(I)=>{let U=await vG(I.configFilePath);if(U)return{name:I.name,configFilePath:I.configFilePath,timestamp:U.getTime(),source:"git"};let K=await M.fs.stat(I.configFilePath);return{name:I.name,configFilePath:I.configFilePath,timestamp:K.mtimeMs,source:"mtime"}}))).toSorted((I,U)=>U.timestamp-I.timestamp).slice(0,J).map((I)=>({name:I.name,configFilePath:I.configFilePath,createdAt:y$(I.timestamp),relativeTime:U0(I.timestamp),timestampSource:I.source}))}}}catch(Q){return $.error(w.apiError("getRecentTools"),Q),{success:!1,error:"Failed to retrieve recent tools"}}}async function B9($,M){try{let J=await M.fileRegistry.getOperations({fileType:"completion"}),Q=await M.fileRegistry.getOperations({fileType:"init"}),G=new Map;for(let I of J){let U=G.get(I.filePath);if(!U||I.createdAt>U.createdAt)G.set(I.filePath,I)}let Y=new Map;for(let I of Q){let U=Y.get(I.filePath);if(!U||I.createdAt>U.createdAt)Y.set(I.filePath,I)}let X=Array.from(G.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"completion",lastModified:y$(I.createdAt)})),Z=Array.from(Y.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"init",lastModified:y$(I.createdAt)}));return{success:!0,data:{completions:X,initScripts:Z,totalFiles:X.length+Z.length}}}catch(J){return $.error(w.apiError("getShellIntegration"),J),{success:!1,error:"Failed to retrieve shell integration"}}}async function D9($,M){try{let J=await M.fileRegistry.getStats();return{success:!0,data:{toolsInstalled:(await M.toolInstallationRegistry.getAllToolInstallations()).length,updatesAvailable:0,filesTracked:J.totalFiles,totalOperations:J.totalOperations,oldestOperation:J.oldestOperation>0?y$(J.oldestOperation):null,newestOperation:J.newestOperation>0?y$(J.newestOperation):null}}}catch(J){return $.error(w.apiError("getStats"),J),{success:!1,error:"Failed to retrieve statistics"}}}async function A9($,M,J){let Q=$.getSubLogger({name:"checkToolUpdate",context:J});try{let Y=(await _$($,M))[J];if(!Y)return{success:!1,error:`Tool "${J}" not found in configuration`};let X=M.pluginRegistry.get(Y.installationMethod);if(!X||!X.supportsUpdateCheck||!X.supportsUpdateCheck())return{success:!0,data:{hasUpdate:!1,currentVersion:Y.version||"unknown",latestVersion:"unknown",supported:!1,error:`Update checking is not supported for installation method "${Y.installationMethod}"`}};let Z=await X.checkUpdate?.(J,Y,{},Q);if(!Z)return{success:!0,data:{hasUpdate:!1,currentVersion:Y.version||"unknown",latestVersion:"unknown",supported:!1,error:"Update check returned no result"}};if(!Z.success)return{success:!0,data:{hasUpdate:!1,currentVersion:Y.version||"unknown",latestVersion:"unknown",supported:!0,error:Z.error}};return Q.info(w.checkUpdateCompleted(Z.hasUpdate,Z.currentVersion??"unknown",Z.latestVersion??"unknown")),{success:!0,data:{hasUpdate:Z.hasUpdate,currentVersion:Z.currentVersion??Y.version??"unknown",latestVersion:Z.latestVersion??"unknown",supported:!0}}}catch(G){let Y=G instanceof Error?G.message:String(G);return Q.error(w.checkUpdateFailed(Y),G),{success:!1,error:`Failed to check for updates: ${Y}`}}}async function E9($,M){try{let J=M.projectConfig.paths.toolConfigsDir,Q=await _$($,M),G=new Map;for(let Z of Object.values(Q))if(Z.configFilePath)G.set(Z.configFilePath,Z.name);async function Y(Z){let q=[],I=await M.fs.readdir(Z);for(let U of I){let K=`${Z}/${U}`;if((await M.fs.stat(K)).isDirectory()){let _=await Y(K);if(_.length>0)q.push({name:U,path:K,type:"directory",children:_})}else if(U.endsWith(".tool.ts"))q.push({name:U,path:K,type:"file",toolName:G.get(K)})}return q.toSorted((U,K)=>{if(U.type!==K.type)return U.type==="directory"?-1:1;return U.name.localeCompare(K.name)})}let X=await Y(J);return{success:!0,data:{rootPath:J,entries:X}}}catch(J){return $.error(w.apiError("getToolConfigsTree"),J),{success:!1,error:"Failed to retrieve tool configs tree"}}}async function F9($,M,J){try{let G=(await M.fileRegistry.getOperations({toolName:J})).toSorted((Z,q)=>q.createdAt-Z.createdAt),Y=await M.toolInstallationRegistry.getToolInstallation(J),X=G.map((Z)=>({id:Z.id,operationType:Z.operationType,fileType:Z.fileType,filePath:Z.filePath,timestamp:y$(Z.createdAt),relativeTime:U0(Z.createdAt)}));return{success:!0,data:{entries:X,totalCount:X.length,installedAt:Y?.installedAt.toISOString()??null,dotfilesDir:M.projectConfig.paths.dotfilesDir}}}catch(Q){return $.error(w.apiError("getToolHistory"),Q),{success:!1,error:"Failed to retrieve tool history"}}}async function L9($,M,J,Q){let G=$.getSubLogger({name:"installTool",context:J});try{let X=(await _$($,M))[J];if(!X)return{success:!1,error:`Tool "${J}" not found in configuration`};let Z=await M.installer.install(J,X,{force:Q.force??!1});if(!Z.success)return G.error(w.installFailed(Z.error??"Unknown error")),{success:!0,data:{installed:!1,error:Z.error??"Installation failed"}};return G.info(w.installSucceeded()),{success:!0,data:{installed:!0,version:Z.version,alreadyInstalled:Z.installationMethod==="already-installed"}}}catch(Y){let X=Y instanceof Error?Y.message:String(Y);return G.error(w.installFailed(X),Y),{success:!1,error:`Failed to install tool: ${X}`}}}function x9($){if(!$)return null;let M=$.repo;return typeof M==="string"?M:null}function m4($,M){if(M.platform===0)return!1;if(!sM($.platforms,M.platform))return!1;if($.architectures===void 0)return!0;if(M.arch===0)return!1;return rM($.architectures,M.arch)}function g4($,M){let J=x9($.installParams);if(J)return J;for(let Q of $.platformConfigs??[]){if(!m4(Q,M))continue;let G=x9(Q.config?.installParams);if(G)return G}return null}async function T9($,M,J){try{let G=(await _$($,M))[J];if(!G)return{success:!1,error:"Tool not found"};let Y=g4(G,M.systemInfo);if(!Y)return{success:!1,error:"Tool does not have a GitHub repository"};let X=G.version?[G.version,"main","master"]:["main","master"];for(let Z of X){let q=`https://raw.githubusercontent.com/${Y}/${Z}/README.md`;try{let I=await M.downloader.download($,q);if(I)return{success:!0,data:{content:I.toString("utf-8")}}}catch(I){if(I instanceof S$)continue;throw I}}return{success:!1,error:"README not found"}}catch(Q){return $.error(w.apiError("getToolReadme"),Q),{success:!1,error:"Failed to retrieve README"}}}async function k9($,M,J){try{let G=(await _$($,M))[J];if(!G)return{success:!1,error:"Tool not found"};let Y=G.configFilePath;if(!Y)return{success:!1,error:"Tool configuration file path not available"};return{success:!0,data:{content:await M.fs.readFile(Y,"utf-8"),filePath:Y}}}catch(Q){return $.error(w.apiError("getToolSource"),Q),{success:!1,error:"Failed to retrieve tool source"}}}async function S9($,M,J){let Q=$.getSubLogger({name:"updateTool",context:J});try{let Y=(await _$($,M))[J];if(!Y)return{success:!1,error:`Tool "${J}" not found in configuration`};if(Y.version!=="latest")return{success:!0,data:{updated:!1,supported:!1,error:`Tool is pinned to version "${Y.version}". Only tools with version "latest" can be updated.`}};let X=M.pluginRegistry.get(Y.installationMethod);if(!X||!X.supportsUpdate())Q.warn(w.updateNotSupported(Y.installationMethod));let q=(await M.toolInstallationRegistry.getToolInstallation(J))?.version??"unknown",I=await M.installer.install(J,Y,{force:!0});if(!I.success)return Q.error(w.updateFailed(I.error??"Unknown error")),{success:!0,data:{updated:!1,supported:!0,error:I.error??"Update failed"}};let U="version"in I&&typeof I.version==="string"?I.version:"unknown";return Q.info(w.updateSucceeded(q,U)),{success:!0,data:{updated:!0,oldVersion:q,newVersion:U,supported:!0}}}catch(G){let Y=G instanceof Error?G.message:String(G);return Q.error(w.updateFailed(Y),G),{success:!1,error:`Failed to update tool: ${Y}`}}}async function n4($,M){return Promise.all($.map(async(J)=>{if(J.sizeBytes!==void 0)return J;try{let Q=await M.stat(J.filePath);if(Q.isFile())return{...J,sizeBytes:Q.size}}catch{}return J}))}function i4($){if(!$.binaries||$.binaries.length===0)return[];return $.binaries.map((M)=>typeof M==="string"?M:M.name)}async function l4($,M,J){let Q=await Promise.all(J.map(async(Y)=>{let X=await $.toolInstallationRegistry.getToolUsage(M,Y);return{binaryName:Y,count:X?.usageCount??0,lastUsedAt:X?.lastUsedAt?X.lastUsedAt.toISOString():null}}));return{totalCount:Q.reduce((Y,X)=>Y+X.count,0),binaries:Q}}async function w9($,M){try{let J=await _$($,M),Q=await M.toolInstallationRegistry.getAllToolInstallations(),G=new Map(Q.map((Z)=>[Z.toolName,Z]));return{success:!0,data:(await Promise.all(Object.values(J).map(async(Z)=>{let q=await M.fileRegistry.getFileStatesForTool(Z.name),I=await n4(q,M.fs),U=await bG(M,Z.name),K=i4(Z),H=await l4(M,Z.name,K);return _9(Z,G,I,M.systemInfo,U,H)}))).toSorted((Z,q)=>Z.config.name.localeCompare(q.config.name))}}catch(J){return $.error(w.apiError("getTools"),J),{success:!1,error:"Failed to retrieve tools"}}}function b9($,M){let J=$.getSubLogger({name:"api"});return{getTools:()=>w9(J,M),getStats:()=>D9(J,M),getHealth:()=>j9(J,M),getConfig:()=>O9(J,M),getToolConfigsTree:()=>E9(J,M),getShellIntegration:()=>B9(J,M),getActivity:(Q)=>R9(J,M,Q),getToolHistory:(Q)=>F9(J,M,Q),getToolReadme:(Q)=>T9(J,M,Q),getToolSource:(Q)=>k9(J,M,Q),getRecentTools:(Q)=>z9(J,M,Q),installTool:(Q,G)=>L9(J,M,Q,G),checkToolUpdate:(Q)=>A9(J,M,Q),updateTool:(Q)=>S9(J,M,Q)}}var N9=v9("{\"index\":\"./dashboard.js\",\"files\":[{\"path\":\"./cli-w822cqdk.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"IUqVLF461B4\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"path\":\"./cli-fj2hdbnx.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"SXWin7hyR_o\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-0ebz5sqb.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"E4eqVcrkzYE\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard.js\",\"loader\":\"html\",\"isEntry\":true,\"headers\":{\"etag\":\"eqXrNcjoIac\",\"content-type\":\"text/html;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/preact-iso@2.11.1/node_modules/preact-iso/src/prerender.js\",\"path\":\"./prerender-kpxyx916.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"D-BSy7GnzyQ\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/shiki@3.23.0/node_modules/shiki/dist/wasm.mjs\",\"path\":\"./wasm-n3cagcre.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"50fw3f0UtlU\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-3axqywva.css\",\"loader\":\"css\",\"isEntry\":true,\"headers\":{\"etag\":\"gMrIjjRYnE4\",\"content-type\":\"text/css;charset=utf-8\"}}]}");var t4=import.meta.dir,gJ=!1,o4=gJ&&process.env.DOTFILES_IS_RELOAD==="1";function e4($){let M={};try{let J=s4.readdirSync($);for(let Q of J)if(Q.endsWith(".js")){let G=r4.join($,Q);M[`/${Q}`]=()=>{return new Response(Bun.file(G),{headers:{"Content-Type":"text/javascript"}})}}}catch{}return M}function NG($,M,J){let Q=$.getSubLogger({name:"DashboardServer"}),G=b9(Q,M),Y=null;return{async start(){if(process.env.DOTFILES_IS_RELOAD="1",!gJ)process.chdir(t4);let X=gJ?{}:e4(process.cwd());return Y=Bun.serve({port:J.port,hostname:J.host,development:gJ,routes:{...X,"/api/tools":async()=>{let Z=await G.getTools();return Response.json(Z)},"/api/stats":async()=>{let Z=await G.getStats();return Response.json(Z)},"/api/health":async()=>{let Z=await G.getHealth();return Response.json(Z)},"/api/config":async()=>{let Z=await G.getConfig();return Response.json(Z)},"/api/tool-configs-tree":async()=>{let Z=await G.getToolConfigsTree();return Response.json(Z)},"/api/shell":async()=>{let Z=await G.getShellIntegration();return Response.json(Z)},"/api/activity":async(Z)=>{let I=new URL(Z.url).searchParams.get("limit"),U=I?parseInt(I,10):void 0,K=await G.getActivity(U);return Response.json(K)},"/api/tools/:name/history":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await G.getToolHistory(q);return Response.json(I)},"/api/tools/:name/readme":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await G.getToolReadme(q);return Response.json(I)},"/api/tools/:name/source":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await G.getToolSource(q);return Response.json(I)},"/api/tools/:name/install":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Z.json().catch(()=>({})),U=await G.installTool(q,I);return Response.json(U)},"/api/tools/:name/check-update":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await G.checkToolUpdate(q);return Response.json(I)},"/api/tools/:name/update":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await G.updateTool(q);return Response.json(I)},"/api/recent-tools":async(Z)=>{let I=new URL(Z.url).searchParams.get("limit"),U=I?parseInt(I,10):void 0,K=await G.getRecentTools(U);return Response.json(K)},"/api/*":Response.json({success:!1,error:"Not found"},{status:404}),"/server/*":(Z)=>{let q=new URL(Z.url),I=q.pathname.replace(/^\/server\//,"/");return Response.redirect(new URL(I,q.origin).href,302)},"/*":N9},fetch(Z){let q=new URL(Z.url);return Q.debug(w.requestReceived(Z.method,q.pathname)),new Response("Not Found",{status:404})}}),Q.info(w.serverStarted(this.getUrl())),o4},async stop(){if(Q.info(w.serverStopping()),Y)Y.stop(),Y=null;Q.info(w.serverStopped())},getUrl(){return`http://${J.host}:${J.port}`}}}var{$:$3}=globalThis.Bun;var M3=async($,M)=>{let J=M===2?"open":M===4?"start":"xdg-open";await $3`${J} ${$}`.nothrow().quiet()};function y9($,M,J,Q={}){let G=Q.openBrowser??M3,Y=Q.createServer??NG,X=$.getSubLogger({name:"dashboard"});M.command("dashboard").description("Start the web-based visualization dashboard").option("--port <port>","Port to run the server on","3000").option("--host <host>","Host to bind the server to","localhost").option("--no-open","Do not open browser when server starts").action(async(Z)=>{let q=parseInt(Z.port??"3000",10),I=Z.host??"localhost",U=Z.open??!0,K=await J(),H={projectConfig:K.projectConfig,fs:K.fs,configService:K.configService,systemInfo:K.systemInfo,fileRegistry:K.fileRegistry,toolInstallationRegistry:K.toolInstallationRegistry,versionChecker:K.versionChecker,downloader:K.downloader,installer:K.installer,pluginRegistry:K.pluginRegistry},O=await Y(X,H,{port:q,host:I}).start();if(U&&!O){let B=`http://${I}:${q}`;try{await G(B,K.systemInfo.platform)}catch(j){X.warn(R.dashboardBrowserOpenFailed(),j)}}})}import lM from"path";var P9={name:"detect-conflicts",description:"Detect file conflicts before generating"};async function J3($,M,J,Q,G){try{let Y=await Q.loadToolConfigs($,M.paths.toolConfigsDir,J,M,G);return{toolConfigs:Object.values(Y),exitCode:x.SUCCESS}}catch(Y){return $.error(R.configLoadFailed("tool configurations"),Y),{toolConfigs:[],exitCode:x.ERROR}}}async function Q3($,M,J,Q,G){if(!J.binaries)return;for(let Y of J.binaries){let X=typeof Y==="string"?Y:Y.name,Z=lM.join(Q,X);if(await M.exists(Z))try{if(!(await M.readFile(Z)).includes("# Generated by Dotfiles Management Tool"))G.push(`[${J.name}]: ${Z} (exists but is not a generator shim)`)}catch(q){$.warn(R.fsReadFailed(Z),q),G.push(`[${J.name}]: ${Z} (exists but could not be read/verified)`)}}}async function G3($,M,J,Q,G,Y){if(!J.symlinks)return;for(let X of J.symlinks){let Z=lM.join(Q,X.target),q=lM.join(G,X.source);try{let I=await M.lstat(Z);if(I)if(I.isSymbolicLink()){let U=await M.readlink(Z);if(lM.resolve(lM.dirname(Z),U)!==q)Y.push(`[${J.name}]: ${Z} (points to '${U}', expected '${q}')`)}else Y.push(`[${J.name}]: ${Z} (exists but is not a symlink)`)}catch(I){if(I.code!=="ENOENT")$.warn(R.fsReadFailed(Z),I)}}}function Y3($,M){if(M.length>0){let Q=M.map((G)=>` - ${G}`).join(`
|
|
226
|
-
`);return $.warn(R.toolConflictsDetected("Conflicts detected with files not owned by the generator:",Q)),x.ERROR}else return $.info(R.noConflictsDetected()),x.SUCCESS}async function
|
|
222
|
+
`);X.debug(_$.generateShim.generatedContent(Q)),await this.fs.ensureDir(x6.dirname(q)),await $.writeFile(q,_);let O=493;try{if(((await $.stat(q)).mode&511)!==O)await $.chmod(q,O)}catch{await $.chmod(q,O)}return X.debug(_$.generateShim.success(Q,q,$.constructor.name)),q}async isGeneratedShim($,M){try{try{if((await $.lstat(M)).isSymbolicLink())return!0}catch{}return(await $.readFile(M,"utf8")).includes("# Generated by Dotfiles Management Tool")}catch{return!1}}}import k6 from"path";var h={generate:{processingTool:($)=>W(`Processing symlinks for tool "${$}"`),missingToolConfig:($)=>W(`Tool config for "${$}" is undefined. Skipping.`)},process:{symlinkDetails:($,M,J,Q)=>W(`Processing symlink: source="${$}" (abs: "${M}"), target="${J}" (abs: "${Q}")`),sourceMissing:($,M)=>W(`Tool "${$}" source file not found: ${M}`),targetExists:($)=>W(`Target path "${$}" already exists.`),skipExistingTarget:($)=>W(`Target "${$}" exists and overwrite is false. Skipping symlink creation.`)},filesystem:{backupFailed:($)=>W(`Failed to write backup of ${$}`),deleteFailed:($)=>W(`Failed to delete ${$}`),directoryCreateFailed:($)=>W(`Failed to create directory ${$}`),symlinkFailed:($,M)=>W(`Failed to create symlink ${$} \u2192 ${M}`),symlinkAlreadyExists:($,M)=>W(`Symlink already exists and is valid: ${$} -> ${M}`),creatingSymlink:($,M)=>W(`Creating symlink: ${$} -> ${M}`),symlinkCreated:($,M)=>W(`Successfully created symlink: ${$} -> ${M}`),removingBrokenSymlink:($)=>W(`Removing broken symlink: ${$}`)},copy:{processingTool:($)=>W(`Processing copies for tool "${$}"`),missingToolConfig:($)=>W(`Tool config for "${$}" is undefined. Skipping.`),copyDetails:($,M,J,Q)=>W(`Processing copy: source="${$}" (abs: "${M}"), target="${J}" (abs: "${Q}")`),sourceMissing:($,M)=>W(`Tool "${$}" source file not found: ${M}`),targetExists:($)=>W(`Target path "${$}" already exists.`),skipExistingTarget:($)=>W(`Target "${$}" exists and overwrite is false. Skipping copy.`),copyFailed:($,M)=>W(`Failed to copy ${$} \u2192 ${M}`)}};class S6{fs;projectConfig;systemInfo;logger;constructor($,M,J,Q){this.fs=M,this.projectConfig=J,this.systemInfo=Q,this.logger=$.getSubLogger({name:"CopyGenerator"})}async generate($,M={}){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let Y in $){let G=$[Y];if(!G)continue;let X=Y$(G,this.systemInfo);if(!this.shouldProcessTool(X,Y,J))continue;let Z=J.getSubLogger({context:Y}),q=this.fs instanceof f?this.fs.withToolName(Y):this.fs;Z.debug(h.copy.processingTool(Y));for(let I of X.copies){let U=await this.processCopy(X,I,q,M,Z);Q.push(U)}}return Q}shouldProcessTool($,M,J){let Q=J.getSubLogger({name:"shouldProcessTool"});if(!$)return Q.debug(h.copy.missingToolConfig(M)),!1;if(!$.copies||$.copies.length===0)return!1;return!0}async processCopy($,M,J,Q,Y){let G=Y.getSubLogger({name:"processCopy"}),{overwrite:X=!1,backup:Z=!1}=Q,q=RM($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=RM($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(G.debug(h.copy.copyDetails(M.source,q,M.target,I)),!await J.exists(q))return G.error(h.copy.sourceMissing($.name,q)),{success:!1,sourcePath:q,targetPath:I,status:"failed",error:h.copy.sourceMissing($.name,q)};if(await J.exists(I)){if(G.debug(h.copy.targetExists(I)),!X)return G.debug(h.copy.skipExistingTarget(I)),{success:!0,sourcePath:q,targetPath:I,status:"skipped_exists"};let K=await this.handleOverwrite(I,J,Z,G);if(K.failed)return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:K.error};return this.performCopy(q,I,J,K.status,G)}return this.performCopy(q,I,J,"created",G)}async handleOverwrite($,M,J,Q){if(J){let Y=`${$}.bak`;try{if(await M.exists(Y))await M.rm(Y,{recursive:!0,force:!0});return await M.rename($,Y),{failed:!1,status:"backed_up"}}catch{let G=h.filesystem.backupFailed($);return Q.error(G),{failed:!0,error:G}}}try{if((await M.stat($)).isDirectory())await M.rm($,{recursive:!0,force:!0});else await M.rm($,{force:!0});return{failed:!1,status:"updated_target"}}catch{let Y=h.filesystem.deleteFailed($);return Q.error(Y),{failed:!0,error:Y}}}async performCopy($,M,J,Q,Y){let G=Y.getSubLogger({name:"performCopy"}),X=k6.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}try{if((await J.stat($)).isDirectory())await this.copyDirectory($,M,J);else await J.copyFile($,M);return{success:!0,sourcePath:$,targetPath:M,status:Q}}catch{let Z=h.copy.copyFailed($,M);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}async copyDirectory($,M,J){await J.ensureDir(M);let Q=await J.readdir($);for(let Y of Q){let G=k6.join($,Y),X=k6.join(M,Y);if((await J.stat(G)).isDirectory())await this.copyDirectory(G,X,J);else await J.copyFile(G,X)}}}import a$ from"path";class w6{fs;projectConfig;systemInfo;logger;constructor($,M,J,Q){this.fs=M,this.projectConfig=J,this.systemInfo=Q,this.logger=$.getSubLogger({name:"SymlinkGenerator"})}async createBinarySymlink($,M,J){let Q=$.getSubLogger({name:"createBinarySymlink"});try{if((await this.fs.lstat(J)).isSymbolicLink()){let I=await this.fs.readlink(J),U=a$.resolve(a$.dirname(J),I),K=a$.resolve(M);if(U===K){if(await this.fs.exists(U)){Q.debug(h.filesystem.symlinkAlreadyExists(J,U));return}}await this.fs.rm(J,{force:!0})}else await this.fs.rm(J,{force:!0})}catch{}if(!await this.fs.exists(M))throw Error(`Cannot create symlink: binary does not exist at ${M}`);Q.debug(h.filesystem.creatingSymlink(J,M)),await this.fs.symlink(M,J);let G=await this.fs.readlink(J),X=a$.resolve(a$.dirname(J),G),Z=a$.resolve(M);if(X!==Z)throw Error(`Symlink verification failed: ${J} points to ${X}, expected ${Z}`);Q.debug(h.filesystem.symlinkCreated(J,M))}async generate($,M={}){let J=this.logger.getSubLogger({name:"generate"}),Q=[];for(let Y in $){let G=$[Y];if(!G)continue;let X=Y$(G,this.systemInfo);if(!this.shouldProcessTool(X,Y,J))continue;let Z=J.getSubLogger({context:Y}),q=this.fs instanceof f?this.fs.withToolName(Y):this.fs;Z.debug(h.generate.processingTool(Y));for(let I of X.symlinks){let U=await this.processSymlink(X,I,q,M,Z);Q.push(U)}}return Q}shouldProcessTool($,M,J){let Q=J.getSubLogger({name:"shouldProcessTool"});if(!$)return Q.debug(h.generate.missingToolConfig(M)),!1;if(!$.symlinks||$.symlinks.length===0)return!1;return!0}async processSymlink($,M,J,Q,Y){let G=Y.getSubLogger({name:"processSymlink"}),{overwrite:X=!1,backup:Z=!1}=Q,q=RM($.configFilePath,M.source,this.projectConfig,this.systemInfo),I=RM($.configFilePath,M.target,this.projectConfig,this.systemInfo);if(G.debug(h.process.symlinkDetails(M.source,q,M.target,I),M.source,q,M.target,I),!await J.exists(q))return G.error(h.process.sourceMissing($.name,q)),{success:!1,sourcePath:q,targetPath:I,status:"failed",error:h.process.sourceMissing($.name,q)};let U=await this.handleExistingTarget(q,I,J,{overwrite:X,backup:Z},G);if(U.shouldSkip){if(U.status==="failed")return{success:!1,sourcePath:q,targetPath:I,status:"failed",error:U.error??"Unknown error"};if(U.status==="skipped_correct"&&J instanceof f)await J.recordExistingSymlink(q,I);return{success:!0,sourcePath:q,targetPath:I,status:U.status}}return await this.createSymlink(q,I,J,U.status,G)}async handleExistingTarget($,M,J,Q,Y){let G=Y.getSubLogger({name:"handleExistingTarget"});if(!await J.exists(M)){let q=await this.removeBrokenSymlink(M,J,G);if(q.failed)return{shouldSkip:!0,status:"failed",error:q.error};return{shouldSkip:!1,status:"created"}}if(G.debug(h.process.targetExists(M)),(await this.checkCorrectSymlink($,M,J)).isCorrect)return{shouldSkip:!0,status:"skipped_correct"};if(!Q.overwrite)return G.debug(h.process.skipExistingTarget(M)),{shouldSkip:!0,status:"skipped_exists"};return await this.handleOverwrite(M,J,Q.backup,G)}async checkCorrectSymlink($,M,J){try{if((await J.lstat(M)).isSymbolicLink()){let Y=await J.readlink(M),G=a$.resolve(a$.dirname(M),Y),X=a$.resolve($);return{isCorrect:G===X}}}catch{}return{isCorrect:!1}}async handleOverwrite($,M,J,Q){let Y=Q.getSubLogger({name:"handleOverwrite"}),G="updated_target";if(J){let X=await this.createBackup($,M,Y);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error};G="backed_up"}else{let X=await this.deleteTarget($,M,Y);if(X.failed)return{shouldSkip:!0,status:"failed",error:X.error}}return{shouldSkip:!1,status:G}}async createBackup($,M,J){let Q=J.getSubLogger({name:"createBackup"}),Y=`${$}.bak`;try{if(await M.exists(Y))await M.rm(Y,{recursive:!0,force:!0});return await M.rename($,Y),{failed:!1}}catch{let G=h.filesystem.backupFailed($);return Q.error(G),{failed:!0,error:G}}}async deleteTarget($,M,J){let Q=J.getSubLogger({name:"deleteTarget"});try{if((await M.stat($)).isDirectory())await M.rm($,{recursive:!0,force:!0});else await M.rm($,{force:!0});return{failed:!1}}catch{let Y=h.filesystem.deleteFailed($);return Q.error(Y),{failed:!0,error:Y}}}async removeBrokenSymlink($,M,J){let Q=J.getSubLogger({name:"removeBrokenSymlink"});try{if((await M.lstat($)).isSymbolicLink())Q.debug(h.filesystem.removingBrokenSymlink($)),await M.rm($,{force:!0});return{failed:!1}}catch{return{failed:!1}}}async createSymlink($,M,J,Q,Y){let G=Y.getSubLogger({name:"createSymlink"}),X=a$.dirname(M);try{await J.ensureDir(X)}catch{let Z=h.filesystem.directoryCreateFailed(X);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}try{return await J.symlink($,M),{success:!0,sourcePath:$,targetPath:M,status:Q}}catch{let Z=h.filesystem.symlinkFailed($,M);return G.error(Z),{success:!1,sourcePath:$,targetPath:M,status:"failed",error:Z}}}}import{eq as V4,gt as z4,valid as JG}from"semver";var y$={initializing:()=>W("Initializing VersionChecker with githubClient"),fetchingLatestRelease:($,M)=>W(`Fetching latest version for ${$}/${M}`),latestReleaseFound:($)=>W(`Latest release found ${$}`),latestReleaseError:($,M)=>W(`Failed to fetch latest release for ${$}/${M}`),noLatestRelease:($,M)=>W(`No latest release found for ${$}/${M}`),comparingVersions:($,M)=>W(`Comparing versions configured ${$} vs latest ${M}`),invalidConfiguredVersion:($)=>W(`Configured version invalid ${$}`),invalidLatestVersion:($)=>W(`Latest version invalid ${$}`),versionComparisonResult:($)=>W(`Version comparison result ${$}`)};class b6{githubClient;logger;constructor($,M){this.logger=$.getSubLogger({name:"VersionChecker"}),this.logger.debug(y$.initializing()),this.githubClient=M}async getLatestToolVersion($,M){let J=this.logger.getSubLogger({name:"getLatestToolVersion"});J.debug(y$.fetchingLatestRelease($,M));try{let Q=await this.githubClient.getLatestRelease($,M);if(Q?.tag_name){let Y=Q.tag_name.replace(/^v/,"");return J.debug(y$.latestReleaseFound(Y)),Y}return J.debug(y$.noLatestRelease($,M)),null}catch(Q){return J.debug(y$.latestReleaseError($,M),Q),null}}async checkVersionStatus($,M){let J=this.logger.getSubLogger({name:"checkVersionStatus"});J.debug(y$.comparingVersions($,M));let Q=$.replace(/^v/,""),Y=M.replace(/^v/,"");if(!JG(Q))return J.debug(y$.invalidConfiguredVersion(Q)),"INVALID_CURRENT_VERSION";if(!JG(Y))return J.debug(y$.invalidLatestVersion(Y)),"INVALID_LATEST_VERSION";if(z4(Y,Q))return J.debug(y$.versionComparisonResult("NEWER_AVAILABLE")),"NEWER_AVAILABLE";if(V4(Y,Q))return J.debug(y$.versionComparisonResult("UP_TO_DATE")),"UP_TO_DATE";return J.debug(y$.versionComparisonResult("AHEAD_OF_LATEST")),"AHEAD_OF_LATEST"}}import G5 from"net";import K0 from"path";import{realpath as B4}from"fs/promises";import D4 from"path";var QG={name:"bin",description:"Print the real path to a binary",hasPositionalArg:!0,positionalArgDescription:"binary name",positionalArgType:"tool"};async function A4($,M,J,Q,Y,G,X){let Z=await G.loadSingleToolConfig($,M,J,Q,Y,X);if(Z){let K=(Y$(Z,X).binaries??[])[0],H=K?typeof K==="string"?K:K.name:M;return{toolName:M,binaryName:H}}let q=await G.loadToolConfigByBinary($,M,J,Q,Y,X);if(q&&!("error"in q))return{toolName:q.name,binaryName:M};return}async function E4($,M,J){let{projectConfig:Q,fs:Y,configService:G,systemInfo:X}=J,Z=$.getSubLogger({minLevel:7}),q=await A4(Z,M,Q.paths.toolConfigsDir,Y,Q,G,X);if(!q)return x.ERROR;let{toolName:I,binaryName:U}=q,K=D4.join(Q.paths.binariesDir,I,"current",U);try{let H=await B4(K);return process.stdout.write(H),x.SUCCESS}catch{return x.ERROR}}function YG($,M,J){let Q=$.getSubLogger({name:"registerBinCommand"});M.command("bin <name>").description("Print the absolute real path to a binary (resolving symlinks). Accepts tool name or binary name (from .bin()).").action(async(Y)=>{let G=await J(),X=await E4(Q,Y,G);N(X)})}import GG from"path";var R={proxyUnavailable:($)=>W(`HTTP proxy not available on port ${$}. Start with 'bun proxy' or unset DEV_PROXY env var.`),proxyEnabled:($)=>W(`Routing requests through HTTP proxy on port ${$}`),proxyCheckingAvailability:($)=>W(`Checking proxy availability on port ${$}`),commandActionStarted:($,M)=>W(`${$} command action logic started${M?`. Tool: ${M}`:""}`),commandConfigErrorDetails:()=>W("Configuration loading error details: %O"),dryRunEnabled:()=>W("Dry run enabled. Initializing MemFileSystem"),componentInitialized:($)=>W(`${$} initialized`),toolConfigsLoading:($)=>W(`tool config loading: ${$}`),toolConfigsLoaded:($,M)=>W(`Configuration loaded from ${$} (${M} tools configured)`),toolConfigsForDryRun:()=>W("tool configs for dry run"),commandCompleted:($)=>W(`DONE${$?" (dry run)":""}`),commandExecutionFailed:($,M)=>W(`Command failed [${$}] exit ${M}`),commandVersionComparison:($,M,J)=>W(`Tool: ${$}, Configured: ${M}, Latest: ${J}`),commandUnsupportedOperation:($,M)=>W(`${$} not yet supported (${M})`),toolNotFound:($,M)=>W(`Tool "${$}" not found in ${M}`),toolInstalled:($,M,J)=>W(`Tool "${$}" \`${M}\` installed successfully using ${J}`),toolAlreadyInstalled:($,M)=>W(`Tool "${$}" \`${M}\` is already installed`),toolInstallSkippedConfigurationOnly:($)=>W(`Tool "${$}" has no installation steps`),shimDeleted:($,M)=>W(`Deleted temporary shim ${$} at ${M}`),toolNoConfigurationsFound:($)=>W(`No tool configurations found in ${$}`),toolCheckingUpdates:($)=>W(`updates for ${$}`),toolUpdateAvailable:($,M,J)=>W(`Update available for ${$}: ${M} -> ${J}`),toolUpToDate:($,M,J)=>W(`${$} (${M}) is up to date. Latest: ${J}`),toolAheadOfLatest:($,M,J)=>W(`${$} (${M}) is ahead of the latest known version (${J})`),toolConfiguredToLatest:($,M)=>W(`Tool "${$}" is configured to 'latest'. The latest available version is ${M}`),toolVersionComparisonFailed:($,M,J)=>W(`Could not determine update status for ${$} (${M}) against latest ${J}`),toolShimUpToDate:($,M)=>W(`${$} is already up to date (${M})`),toolShimOnLatest:($,M)=>W(`${$} is already on latest version (${M})`),toolShimUpdateStarting:($,M,J)=>W(`Updating ${$} from ${M} to ${J}...`),toolProcessingUpdate:($,M,J)=>W(`${$} update from ${M} to ${J}`),toolShimUpdateSuccess:($,M)=>W(`${$} successfully updated to ${M}`),toolUpdated:($,M,J)=>W(`Tool "${$}" updated from \`${M}\` to \`${J}\``),toolUpdateFailed:($,M)=>W(`Update failed for tool "${$}": ${M}`),toolVersionPinned:($,M)=>W(`Tool "${$}" is pinned to version \`${M}\`. Set version to "latest" in the tool config to enable updates`),toolUpdateNotSupported:($,M)=>W(`Tool "${$}" uses ${M} which does not support updates. Performing regular install instead`),commandCheckingUpdatesFor:($)=>W(`Checking "${$}" for updates`),commandCheckingUpdatesForAll:()=>W("Checking all tools for updates"),fsReadFailed:($)=>W(`Failed to read ${$}`),fsAccessDenied:($,M)=>W(`Access denied ${$}: ${M}`),fsItemNotFound:($,M)=>W(`${$} not found: ${M}`),fsWrite:($,M)=>W(`[${$}] write ${M}`),toolConflictsDetected:($,M)=>W(`${$}
|
|
223
|
+
${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles:()=>W("Registry-based cleanup: Removing all tracked files"),cleanupRegistryDatabase:()=>W("registry database cleanup"),cleanupRegistryDryRun:()=>W("Would clean up registry database (dry run)"),cleanupToolFiles:($)=>W(`Registry-based cleanup: files for tool '${$}'`),cleanupRegistryTool:($,M)=>W(M?`Would remove registry entries for tool: ${$} (dry run)`:`Removed registry entries for tool: ${$}`),cleanupTypeFiles:($)=>W(`Registry-based cleanup: files of type '${$}'`),cleanupFoundFiles:($,M,J)=>W(`Found ${$} files for tool '${M}'${J?` of type '${J}'`:""}`),cleanupFileRemoved:($)=>W(`[cleanup] rm ${$}`),fileCleanupDryRun:($)=>W(`Would delete: ${$}`),cleanupFileNotFound:($)=>W(`file not found ${$}`),cleanupDeleteFailed:($)=>W(`Failed to delete ${$}`),cleanupProcessStarted:($)=>W(`starting cleanup process, dryRun=${$}: %O`),configParameterOverridden:($,M)=>W(`${$.charAt(0).toUpperCase()+$.slice(1)} overridden to: ${M}`),cleanupProcessFinished:($)=>W(`cleanup process finished, dryRun=${$}`),logCheckingFileStates:()=>W("Checking file states for all tools"),logFileStatesForTool:($)=>W(`${$} files`),logFileStatus:($,M,J,Q,Y)=>W(`${$} ${M} [${J}] - ${Q}${Y}`),logTargetStatus:($,M)=>W(`${$} ${M}`),logNoOperationsFound:()=>W("No file operations found matching criteria"),logOperationHistory:($,M,J)=>W(`${$} ${M}${J?` ${J}`:""}`),cachingDisabled:()=>W("Caching disabled"),registryInitialized:($)=>W(`File tracking initialized: ${$}`),cliStarted:()=>W("CLI starting with arguments"),serviceGithubResourceNotFound:($,M)=>W(`GitHub ${$} not found: ${M}`),serviceGithubApiFailed:($,M)=>W(`GitHub API failed [${$}] ${M}`),configLoadFailed:($)=>W(`Failed to load configuration from ${$}`),configPathResolved:($)=>W(`Using configuration: ${$}`),configNotFound:()=>W("No configuration file found. Create dotfiles.config.ts or specify --config <path>"),configParameterIgnored:($,M)=>W(`Configuration field "${$}" ignored: ${M}`),configParameterInvalid:($,M,J)=>W(`Invalid ${$}: "${M}" (expected ${J})`),updatesCommandCompleted:()=>W("Check-updates command completed"),toolTypesGenerated:($)=>W(`Generated tool types: ${$}`),toolNotInstalled:($)=>W(`Tool "${$}" is not installed`),installPathNotFound:($)=>W(`Installation path not found: ${$}`),filesCommandShowingTree:($)=>W($),filesCommandEmptyDirectory:()=>W("(empty directory)"),filesCommandTree:($)=>W($),skillAlreadyExists:($)=>W(`Destination already exists, removing: ${$}`),skillDryRun:($,M)=>W(`Would copy skill: ${M} -> ${$}`),skillCopied:($,M)=>W(`Copied skill: ${M} -> ${$}`),skillCopyFailed:($)=>W(`Failed to copy skill to: ${$}`),cliCompletionGenerated:($)=>W(`CLI completion generated: ${$}`),dashboardStopping:()=>W("Stopping dashboard server"),dashboardBrowserOpenFailed:()=>W("Failed to open browser"),toolLookupByBinaryStarted:($)=>W(`Tool not found by name '${$}', searching by binary name`),toolFoundByBinary:($,M)=>W(`Binary '${$}' is provided by tool '${M}'`),toolNotFoundByBinary:($,M)=>W(`No tool or binary named "${$}" found in ${M}`),envCreated:($)=>W(`Environment created at ${$}`),envDeleted:($)=>W(`Environment deleted at ${$}`),envNotFound:($)=>W(`Environment not found at ${$}`),envOperationFailed:($,M)=>W(`Environment ${$} failed: ${M}`),envDeletionCancelled:()=>W("Deletion cancelled"),envActivationHint:($)=>W(`To activate: source ${$}/source`),envConfigPath:($)=>W(`Config file: ${$}`),envConfigFromEnvVar:($)=>W(`Using config from DOTFILES_ENV_DIR: ${$}`)};var XG={name:"check-updates",description:"Check for available tool updates",hasPositionalArg:!0,positionalArgDescription:"tool name (optional, checks all if omitted)",positionalArgType:"tool"};async function F4($,M,J,Q,Y,G){let X={};if(J){$.debug(R.commandCheckingUpdatesFor(J));try{let Z=await M.loadSingleToolConfig($,J,Q.paths.toolConfigsDir,Y,Q,G);if(Z)X[J]=Z;else return $.error(R.toolNotFound(J,Q.paths.toolConfigsDir)),null}catch(Z){return $.error(R.configLoadFailed(`tool "${J}"`),Z),null}}else try{if($.debug(R.commandCheckingUpdatesForAll()),X=await M.loadToolConfigs($,Q.paths.toolConfigsDir,Y,Q,G),Object.keys(X).length===0)return $.error(R.toolNoConfigurationsFound(Q.paths.toolConfigsDir)),null}catch(Z){return $.error(R.configLoadFailed("tool configurations"),Z),null}return X}function L4($,M,J,Q,Y){let G=new Date().toISOString().replace(/:/g,"-").split(".")[0],X=$.configFilePath?GG.dirname($.configFilePath):M.paths.toolConfigsDir,Z=GG.join(M.paths.binariesDir,$.name,"current");return{toolName:$.name,toolDir:X,currentDir:Z,stagingDir:"",timestamp:G||"",systemInfo:J,toolConfig:$,projectConfig:M,$:$M(W$(),process.env),fileSystem:Q,replaceInFile:(I,U,K,H)=>c0(Q,I,U,K,H),resolve:()=>{throw Error("resolve not supported in version check context")},log:IQ(Y,$.name)}}async function x4($,M,J,Q,Y,G){if(Q==="latest"){$.info(R.toolConfiguredToLatest(J.name,Y));return}if(G){$.info(R.toolUpdateAvailable(J.name,Q,Y));return}let X=await M.checkVersionStatus(Q,Y);if(X==="UP_TO_DATE")$.info(R.toolUpToDate(J.name,Q,Y));else if(X==="AHEAD_OF_LATEST")$.info(R.toolAheadOfLatest(J.name,Q,Y));else $.warn(R.toolVersionComparisonFailed(J.name,Q,Y))}async function T4($,M,J){let{projectConfig:Q,versionChecker:Y,pluginRegistry:G,systemInfo:X,fs:Z}=J,q=L4(M,Q,X,Z,$),I=G.get(M.installationMethod);if(!I){$.warn(R.commandUnsupportedOperation("check-updates",`installation method: "${M.installationMethod}" for tool "${M.name}"`));return}if(!I.supportsUpdateCheck||!I.supportsUpdateCheck()){$.info(R.commandUnsupportedOperation("check-updates",`installation method: "${M.installationMethod}" for tool "${M.name}"`));return}let U=await I.checkUpdate?.(M.name,M,q,$);if(!U){$.warn(R.commandUnsupportedOperation("check-updates",M.name));return}if(!U.success){$.error(R.serviceGithubApiFailed("check update",0),Error(U.error));return}let K=U.currentVersion||M.version||"unknown",H=U.latestVersion||"unknown";await x4($,Y,M,K,H,U.hasUpdate)}async function k4($,M,J){$.trace(R.commandActionStarted("check-updates",M||"all"));let Q=await F4($,J.configService,M,J.projectConfig,J.fs,J.systemInfo);if(!Q)return;for(let Y of Object.values(Q))await T4($,Y,J)}function ZG($,M,J){let Q=$.getSubLogger({name:"registerCheckUpdatesCommand"});M.command("check-updates [toolName]").description("Checks for available updates for configured tools. If [toolName] is provided, checks only that tool.").action(async(Y)=>{try{let G=await J();await k4(Q,Y,G)}catch(G){Q.error(R.commandExecutionFailed("check-updates",x.ERROR),G),N(x.ERROR)}})}var WG={name:"cleanup",description:"Clean up generated files and registry entries",options:[{flag:"--tool",description:"Cleanup files for specific tool",hasArg:!0,argPlaceholder:"<name>"},{flag:"--type",description:"Cleanup files of specific type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--all",description:"Cleanup all tracked files"}]};async function S4($,M,J,Q,Y){$.info(R.cleanupAllTrackedFiles());let G=await J.getRegisteredTools();for(let X of G)await qG($,M,J,X,Q,void 0,Y);if(!Y){for(let X of G)await J.removeToolOperations(X);$.info(R.cleanupRegistryDatabase())}else $.info(R.cleanupRegistryDryRun())}async function w4($,M,J,Q,Y,G,X){if($.info(R.cleanupToolFiles(Q)),await qG($,M,J,Q,Y,G,X),!X)await J.removeToolOperations(Q),$.info(R.cleanupRegistryTool(Q,!1));else $.info(R.cleanupRegistryTool(Q,!0))}async function b4($,M,J,Q,Y,G){$.info(R.cleanupTypeFiles(Q));let X=await J.getOperations({fileType:Q});for(let Z of X){let q=await J.getFileState(Z.filePath);if(q&&q.lastOperation!=="rm")await IG($,M,Z.filePath,Y,G)}}async function N4($,M,J){let{fs:Q,fileRegistry:Y}=M,{dryRun:G,tool:X,type:Z,all:q}=J,I=M.projectConfig.paths.homeDir;if(q)await S4($,Q,Y,I,G);else if(X)await w4($,Q,Y,X,I,Z,G);else if(Z)await b4($,Q,Y,Z,I,G);else $.warn(R.configParameterIgnored("cleanup options","Registry-based cleanup requires --all, --tool <name>, or --type <type> option"))}async function qG($,M,J,Q,Y,G,X){let Z=await J.getFileStatesForTool(Q),q=Z;if(G)q=Z.filter((I)=>I.fileType===G);$.trace(R.cleanupFoundFiles(q.length,Q,G));for(let I of q)if(I.lastOperation!=="rm"){let U=I.fileType==="symlink"&&I.targetPath?I.targetPath:I.filePath;await IG($,M,U,Y,X||!1)}}async function IG($,M,J,Q,Y){try{if(await M.exists(J))if(!Y)await M.rm(J,{force:!0}),$.info(R.cleanupFileRemoved(s(Q,J)));else $.info(R.fileCleanupDryRun(J));else $.debug(R.cleanupFileNotFound(J))}catch(G){$.error(R.cleanupDeleteFailed(J),G)}}async function v4($,M,J){let{dryRun:Q,tool:Y,type:G,all:X}=M;try{$.trace(R.cleanupProcessStarted(Q),M);let Z={...M,all:X||!Y&&!G};await N4($,J,Z),$.trace(R.cleanupProcessFinished(Q))}catch(Z){$.error(R.commandExecutionFailed("cleanup",1),Z),N(1)}}function UG($,M,J){let Q=$.getSubLogger({name:"registerCleanupCommand"});M.command("cleanup").description("Remove all generated artifacts, including shims, shell configurations, and the .generated directory.").option("--tool <name>","Remove files for specific tool only (registry-based)").option("--type <type>","Remove files of specific type only (registry-based)").option("--all","Remove all tracked files (registry-based)").action(async(Y)=>{let G={...Y,...M.opts()},X=await J();await v4(Q,G,X)})}import{Command as y4}from"commander";var KG={name:"dotfiles",description:"Dotfiles management CLI",options:[{flag:"--config",description:"Path to configuration file",hasArg:!0,argPlaceholder:"<path>"},{flag:"--dry-run",description:"Simulate operations without changes"},{flag:"--log",description:"Set log level",hasArg:!0,argPlaceholder:"<level>"},{flag:"--verbose",description:"Enable detailed debug messages"},{flag:"--quiet",description:"Suppress informational output"},{flag:"--platform",description:"Override detected platform",hasArg:!0,argPlaceholder:"<platform>"},{flag:"--arch",description:"Override detected architecture",hasArg:!0,argPlaceholder:"<arch>"}]};function HG(){return new y4().name("generator").description("CLI tool for managing dotfiles and tool configurations").version("0.0.5").option("--config <path>","Path to a configuration file","").option("--dry-run","Simulate all operations without making changes to the file system",!1).option("--trace","Show file paths and line numbers in log output",!1).option("--log <level>",`Set log level (${WQ.join(", ")})`,"default").option("--verbose","Enable detailed debug messages (alias for --log=verbose)",!1).option("--quiet","Suppress all informational and debug output. Errors are still displayed (alias for --log=quiet)",!1).option("--platform <platform>",`Override the detected platform (${m0.join(", ")})`).option("--arch <arch>",`Override the detected architecture (${g0.join(", ")})`)}import r4 from"fs";import t4 from"path";var b={serverStarted:($)=>W(`Dashboard available at ${$}`),serverStopping:()=>W("Stopping dashboard server"),serverStopped:()=>W("Dashboard server stopped"),requestReceived:($,M)=>W(`${$} ${M}`),apiError:($)=>W(`API error in ${$}`),installFailed:($)=>W(`Installation failed: ${$}`),installSucceeded:()=>W("Installation succeeded"),checkUpdateCompleted:($,M,J)=>W(`Update check complete: hasUpdate=${$} current=${M} latest=${J}`),checkUpdateFailed:($)=>W(`Update check failed: ${$}`),updateNotSupported:($)=>W(`Update not supported for method ${$}`),updateFailed:($)=>W(`Update failed: ${$}`),updateSucceeded:($,M)=>W(`Updated from ${$} to ${M}`)};function P4($){let M=[];if($&1)M.push("Linux");if($&2)M.push("macOS");if($&4)M.push("Windows");return M}function C4($){let M=[];if($&1)M.push("x86_64");if($&2)M.push("arm64");return M}function _G($){let M={};if(typeof $.repo==="string")M.repo=$.repo;if(typeof $.assetPattern==="string")M.assetPattern=$.assetPattern;if(typeof $.ghCli==="boolean")M.ghCli=$.ghCli;if(typeof $.crate==="string")M.crate=$.crate;if(typeof $.crateName==="string")M.crate=$.crateName;if(typeof $.formula==="string")M.formula=$.formula;if(typeof $.url==="string")M.url=$.url;return M}function d4($){let M={};if("installParams"in $&&$.installParams){let Q=$.installParams;Object.assign(M,_G(Q))}let J;if($.platformConfigs&&$.platformConfigs.length>0)J=$.platformConfigs.map((Q)=>{let Y={platforms:P4(Q.platforms)};if(Q.architectures!==void 0)Y.architectures=C4(Q.architectures);let G=Q.config;if(G.installationMethod)Y.installationMethod=G.installationMethod;if(G.installParams)Y.installParams=_G(G.installParams);if(G.binaries)Y.binaries=G.binaries;if(G.symlinks)Y.symlinks=G.symlinks;return Y});return{name:$.name,version:$.version,installationMethod:$.installationMethod,installParams:M,binaries:$.binaries,dependencies:$.dependencies,symlinks:$.symlinks,disabled:$.disabled,hostname:$.hostname,configFilePath:$.configFilePath,platformConfigs:J}}function u4($,M){let J=M.get($);if(!J)return{status:"not-installed",installedVersion:null,installedAt:null,installPath:null,binaryPaths:[],hasUpdate:!1};return{status:"installed",installedVersion:J.version,installedAt:J.installedAt.toISOString(),installPath:J.installPath,binaryPaths:J.binaryPaths||[],hasUpdate:!1}}function RG($,M,J,Q,Y,G){return{config:d4($),runtime:u4($.name,M),files:J,binaryDiskSize:Y,usage:G}}function P$($){return new Date($).toISOString()}function U0($){let J=Date.now()-$,Q=Math.floor(J/1000);if(Q<60)return"just now";let Y=Math.floor(Q/60);if(Y<60)return`${Y} minute${Y===1?"":"s"} ago`;let G=Math.floor(Y/60);if(G<24)return`${G} hour${G===1?"":"s"} ago`;let X=Math.floor(G/24);if(X<30)return`${X} day${X===1?"":"s"} ago`;let Z=Math.floor(X/30);return`${Z} month${Z===1?"":"s"} ago`}async function OG($,M,J=20){try{let Y=(await M.fileRegistry.getOperations()).toSorted((Z,q)=>q.createdAt-Z.createdAt),G=Y.length;return{success:!0,data:{activities:Y.slice(0,J).map((Z)=>({id:Z.id,toolName:Z.toolName,action:Z.operationType,description:`${Z.operationType} ${Z.fileType}: ${Z.filePath}`,timestamp:P$(Z.createdAt),relativeTime:U0(Z.createdAt)})),totalCount:G}}}catch(Q){return $.error(b.apiError("getActivity"),Q),{success:!1,error:"Failed to retrieve activity feed"}}}async function jG($,M){try{let J=M.projectConfig.paths;return{success:!0,data:{dotfilesDir:J.dotfilesDir,generatedDir:J.generatedDir,binariesDir:J.binariesDir,targetDir:J.targetDir,toolConfigsDir:J.toolConfigsDir}}}catch(J){return $.error(b.apiError("getConfig"),J),{success:!1,error:"Failed to retrieve configuration"}}}import y0 from"path";async function f4($){let{fs:M,projectConfig:J}=$,Q=J.paths.binariesDir,Y=[];if(!await M.exists(Q))return[];let G=await M.readdir(Q);for(let X of G){let Z=y0.join(Q,X);if(!(await M.stat(Z).catch(()=>null))?.isDirectory())continue;let I=await M.readdir(Z),U=y0.join(Z,"current"),K=null;if(I.includes("current")){if((await M.lstat(U).catch(()=>null))?.isSymbolicLink()){let _=await M.readlink(U).catch(()=>null);if(_)K=y0.isAbsolute(_)?_:y0.resolve(Z,_)}}for(let H of I){if(H==="current")continue;let _=y0.join(Z,H);if(!(await M.lstat(_).catch(()=>null))?.isDirectory())continue;if(K!==_)Y.push(_)}}return Y}async function VG($,M){try{let J=[],Q=await f4(M);if(Q.length>0)J.push({name:"Unused Binaries",status:"warn",message:"",details:Q});let G=await M.fileRegistry.validate();J.push({name:"Registry Integrity",status:G.valid?"pass":"warn",message:G.valid?"Registry is healthy":`Found ${G.issues.length} issues`,details:G.issues});let Z=(await M.toolInstallationRegistry.getAllToolInstallations()).length;J.push({name:"Tool Installations",status:Z>0?"pass":"warn",message:`${Z} tool${Z===1?"":"s"} installed`});let q=J.some((H)=>H.status==="fail"),I=J.some((H)=>H.status==="warn");return{success:!0,data:{overall:q?"unhealthy":I?"warning":"healthy",checks:J,lastCheck:new Date().toISOString()}}}catch(J){return $.error(b.apiError("getHealth"),J),{success:!1,error:"Failed to retrieve health status"}}}import N6 from"path";async function zG($,M){let J=$.fs,Q=0;try{if(!await J.exists(M))return 0;let Y=await J.readdir(M);for(let G of Y){let X=N6.join(M,G),Z=await J.stat(X);if(Z.isDirectory())Q+=await zG($,X);else if(Z.isFile())Q+=Z.size}}catch{}return Q}async function v6($,M){let J=N6.join($.projectConfig.paths.generatedDir,"binaries"),Q=N6.join(J,M);return zG($,Q)}var hJ=null;async function p4(){let $=new Map;try{let M=Bun.spawn(["git","rev-parse","--show-toplevel"],{stdout:"pipe",stderr:"pipe"}),J=(await new Response(M.stdout).text()).trim();if(await M.exited!==0||!J)return $;let Y=Bun.spawn(["git","log","--diff-filter=A","--name-only","--format=%aI"],{stdout:"pipe",stderr:"pipe"}),G=await new Response(Y.stdout).text();if(await Y.exited!==0)return $;let Z=G.split(`
|
|
224
|
+
`),q=null;for(let I of Z){let U=I.trim();if(!U)continue;if(/^\d{4}-\d{2}-\d{2}/.test(U))q=new Date(U);else if(q){let K=`${J}/${U}`;if(!$.has(K))$.set(K,q)}}}catch{}return $}async function c4($){try{let M=Bun.spawn(["git","log","--diff-filter=A","--format=%aI","--",$],{stdout:"pipe",stderr:"pipe"}),J=await new Response(M.stdout).text();if(await M.exited!==0||!J.trim())return null;let Y=J.trim().split(`
|
|
225
|
+
`)[0];if(!Y)return null;return new Date(Y)}catch{return null}}async function y6($){if(!hJ)hJ=await p4();let M=hJ.get($);if(M)return M;let J=await c4($);if(J)hJ.set($,J);return J}var mJ=null;async function R$($,M){if(mJ)return mJ;let{projectConfig:J,fs:Q,configService:Y,systemInfo:G}=M;return mJ=await Y.loadToolConfigs($,J.paths.toolConfigsDir,Q,J,G),mJ}async function BG($,M,J=10){try{let Q=M.projectConfig.paths.toolConfigsDir,Y=[];async function G(I){let U=await M.fs.readdir(I);for(let K of U){let H=`${I}/${K}`;if((await M.fs.stat(H)).isDirectory())await G(H);else if(K.endsWith(".tool.ts")){let O=K.replace(/\.tool\.ts$/,"");Y.push({name:O,configFilePath:H})}}}return await G(Q),{success:!0,data:{tools:(await Promise.all(Y.map(async(I)=>{let U=await y6(I.configFilePath);if(U)return{name:I.name,configFilePath:I.configFilePath,timestamp:U.getTime(),source:"git"};let K=await M.fs.stat(I.configFilePath);return{name:I.name,configFilePath:I.configFilePath,timestamp:K.mtimeMs,source:"mtime"}}))).toSorted((I,U)=>U.timestamp-I.timestamp).slice(0,J).map((I)=>({name:I.name,configFilePath:I.configFilePath,createdAt:P$(I.timestamp),relativeTime:U0(I.timestamp),timestampSource:I.source}))}}}catch(Q){return $.error(b.apiError("getRecentTools"),Q),{success:!1,error:"Failed to retrieve recent tools"}}}async function DG($,M){try{let J=await M.fileRegistry.getOperations({fileType:"completion"}),Q=await M.fileRegistry.getOperations({fileType:"init"}),Y=new Map;for(let I of J){let U=Y.get(I.filePath);if(!U||I.createdAt>U.createdAt)Y.set(I.filePath,I)}let G=new Map;for(let I of Q){let U=G.get(I.filePath);if(!U||I.createdAt>U.createdAt)G.set(I.filePath,I)}let X=Array.from(Y.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"completion",lastModified:P$(I.createdAt)})),Z=Array.from(G.values()).filter((I)=>I.operationType!=="rm").map((I)=>({toolName:I.toolName,filePath:I.filePath,fileType:"init",lastModified:P$(I.createdAt)}));return{success:!0,data:{completions:X,initScripts:Z,totalFiles:X.length+Z.length}}}catch(J){return $.error(b.apiError("getShellIntegration"),J),{success:!1,error:"Failed to retrieve shell integration"}}}async function AG($,M){try{let J=await M.fileRegistry.getStats();return{success:!0,data:{toolsInstalled:(await M.toolInstallationRegistry.getAllToolInstallations()).length,updatesAvailable:0,filesTracked:J.totalFiles,totalOperations:J.totalOperations,oldestOperation:J.oldestOperation>0?P$(J.oldestOperation):null,newestOperation:J.newestOperation>0?P$(J.newestOperation):null}}}catch(J){return $.error(b.apiError("getStats"),J),{success:!1,error:"Failed to retrieve statistics"}}}async function EG($,M,J){let Q=$.getSubLogger({name:"checkToolUpdate",context:J});try{let G=(await R$($,M))[J];if(!G)return{success:!1,error:`Tool "${J}" not found in configuration`};let X=M.pluginRegistry.get(G.installationMethod);if(!X||!X.supportsUpdateCheck||!X.supportsUpdateCheck())return{success:!0,data:{hasUpdate:!1,currentVersion:G.version||"unknown",latestVersion:"unknown",supported:!1,error:`Update checking is not supported for installation method "${G.installationMethod}"`}};let Z=await X.checkUpdate?.(J,G,{},Q);if(!Z)return{success:!0,data:{hasUpdate:!1,currentVersion:G.version||"unknown",latestVersion:"unknown",supported:!1,error:"Update check returned no result"}};if(!Z.success)return{success:!0,data:{hasUpdate:!1,currentVersion:G.version||"unknown",latestVersion:"unknown",supported:!0,error:Z.error}};return Q.info(b.checkUpdateCompleted(Z.hasUpdate,Z.currentVersion??"unknown",Z.latestVersion??"unknown")),{success:!0,data:{hasUpdate:Z.hasUpdate,currentVersion:Z.currentVersion??G.version??"unknown",latestVersion:Z.latestVersion??"unknown",supported:!0}}}catch(Y){let G=Y instanceof Error?Y.message:String(Y);return Q.error(b.checkUpdateFailed(G),Y),{success:!1,error:`Failed to check for updates: ${G}`}}}async function FG($,M){try{let J=M.projectConfig.paths.toolConfigsDir,Q=await R$($,M),Y=new Map;for(let Z of Object.values(Q))if(Z.configFilePath)Y.set(Z.configFilePath,Z.name);async function G(Z){let q=[],I=await M.fs.readdir(Z);for(let U of I){let K=`${Z}/${U}`;if((await M.fs.stat(K)).isDirectory()){let _=await G(K);if(_.length>0)q.push({name:U,path:K,type:"directory",children:_})}else if(U.endsWith(".tool.ts"))q.push({name:U,path:K,type:"file",toolName:Y.get(K)})}return q.toSorted((U,K)=>{if(U.type!==K.type)return U.type==="directory"?-1:1;return U.name.localeCompare(K.name)})}let X=await G(J);return{success:!0,data:{rootPath:J,entries:X}}}catch(J){return $.error(b.apiError("getToolConfigsTree"),J),{success:!1,error:"Failed to retrieve tool configs tree"}}}async function LG($,M,J){try{let Y=(await M.fileRegistry.getOperations({toolName:J})).toSorted((Z,q)=>q.createdAt-Z.createdAt),G=await M.toolInstallationRegistry.getToolInstallation(J),X=Y.map((Z)=>({id:Z.id,operationType:Z.operationType,fileType:Z.fileType,filePath:Z.filePath,timestamp:P$(Z.createdAt),relativeTime:U0(Z.createdAt)}));return{success:!0,data:{entries:X,totalCount:X.length,installedAt:G?.installedAt.toISOString()??null,dotfilesDir:M.projectConfig.paths.dotfilesDir}}}catch(Q){return $.error(b.apiError("getToolHistory"),Q),{success:!1,error:"Failed to retrieve tool history"}}}async function xG($,M,J,Q){let Y=$.getSubLogger({name:"installTool",context:J});try{let X=(await R$($,M))[J];if(!X)return{success:!1,error:`Tool "${J}" not found in configuration`};let Z=await M.installer.install(J,X,{force:Q.force??!1});if(!Z.success)return Y.error(b.installFailed(Z.error??"Unknown error")),{success:!0,data:{installed:!1,error:Z.error??"Installation failed"}};return Y.info(b.installSucceeded()),{success:!0,data:{installed:!0,version:Z.version,alreadyInstalled:Z.installationMethod==="already-installed"}}}catch(G){let X=G instanceof Error?G.message:String(G);return Y.error(b.installFailed(X),G),{success:!1,error:`Failed to install tool: ${X}`}}}function TG($){if(!$)return null;let M=$.repo;return typeof M==="string"?M:null}function g4($,M){if(M.platform===0)return!1;if(!rM($.platforms,M.platform))return!1;if($.architectures===void 0)return!0;if(M.arch===0)return!1;return tM($.architectures,M.arch)}function n4($,M){let J=TG($.installParams);if(J)return J;for(let Q of $.platformConfigs??[]){if(!g4(Q,M))continue;let Y=TG(Q.config?.installParams);if(Y)return Y}return null}async function kG($,M,J){try{let Y=(await R$($,M))[J];if(!Y)return{success:!1,error:"Tool not found"};let G=n4(Y,M.systemInfo);if(!G)return{success:!1,error:"Tool does not have a GitHub repository"};let X=Y.version?[Y.version,"main","master"]:["main","master"];for(let Z of X){let q=`https://raw.githubusercontent.com/${G}/${Z}/README.md`;try{let I=await M.downloader.download($,q);if(I)return{success:!0,data:{content:I.toString("utf-8")}}}catch(I){if(I instanceof S$)continue;throw I}}return{success:!1,error:"README not found"}}catch(Q){return $.error(b.apiError("getToolReadme"),Q),{success:!1,error:"Failed to retrieve README"}}}async function SG($,M,J){try{let Y=(await R$($,M))[J];if(!Y)return{success:!1,error:"Tool not found"};let G=Y.configFilePath;if(!G)return{success:!1,error:"Tool configuration file path not available"};return{success:!0,data:{content:await M.fs.readFile(G,"utf-8"),filePath:G}}}catch(Q){return $.error(b.apiError("getToolSource"),Q),{success:!1,error:"Failed to retrieve tool source"}}}async function wG($,M,J){let Q=$.getSubLogger({name:"updateTool",context:J});try{let G=(await R$($,M))[J];if(!G)return{success:!1,error:`Tool "${J}" not found in configuration`};if(G.version!=="latest")return{success:!0,data:{updated:!1,supported:!1,error:`Tool is pinned to version "${G.version}". Only tools with version "latest" can be updated.`}};let X=M.pluginRegistry.get(G.installationMethod);if(!X||!X.supportsUpdate())Q.warn(b.updateNotSupported(G.installationMethod));let q=(await M.toolInstallationRegistry.getToolInstallation(J))?.version??"unknown",I=await M.installer.install(J,G,{force:!0});if(!I.success)return Q.error(b.updateFailed(I.error??"Unknown error")),{success:!0,data:{updated:!1,supported:!0,error:I.error??"Update failed"}};let U="version"in I&&typeof I.version==="string"?I.version:"unknown";return Q.info(b.updateSucceeded(q,U)),{success:!0,data:{updated:!0,oldVersion:q,newVersion:U,supported:!0}}}catch(Y){let G=Y instanceof Error?Y.message:String(Y);return Q.error(b.updateFailed(G),Y),{success:!1,error:`Failed to update tool: ${G}`}}}async function i4($,M){return Promise.all($.map(async(J)=>{if(J.sizeBytes!==void 0)return J;try{let Q=await M.stat(J.filePath);if(Q.isFile())return{...J,sizeBytes:Q.size}}catch{}return J}))}function l4($){if(!$.binaries||$.binaries.length===0)return[];return $.binaries.map((M)=>typeof M==="string"?M:M.name)}async function a4($,M,J){let Q=await Promise.all(J.map(async(G)=>{let X=await $.toolInstallationRegistry.getToolUsage(M,G);return{binaryName:G,count:X?.usageCount??0,lastUsedAt:X?.lastUsedAt?X.lastUsedAt.toISOString():null}}));return{totalCount:Q.reduce((G,X)=>G+X.count,0),binaries:Q}}async function bG($,M){try{let J=await R$($,M),Q=await M.toolInstallationRegistry.getAllToolInstallations(),Y=new Map(Q.map((Z)=>[Z.toolName,Z]));return{success:!0,data:(await Promise.all(Object.values(J).map(async(Z)=>{let q=await M.fileRegistry.getFileStatesForTool(Z.name),I=await i4(q,M.fs),U=await v6(M,Z.name),K=l4(Z),H=await a4(M,Z.name,K);return RG(Z,Y,I,M.systemInfo,U,H)}))).toSorted((Z,q)=>Z.config.name.localeCompare(q.config.name))}}catch(J){return $.error(b.apiError("getTools"),J),{success:!1,error:"Failed to retrieve tools"}}}function NG($,M){let J=$.getSubLogger({name:"api"});return{getTools:()=>bG(J,M),getStats:()=>AG(J,M),getHealth:()=>VG(J,M),getConfig:()=>jG(J,M),getToolConfigsTree:()=>FG(J,M),getShellIntegration:()=>DG(J,M),getActivity:(Q)=>OG(J,M,Q),getToolHistory:(Q)=>LG(J,M,Q),getToolReadme:(Q)=>kG(J,M,Q),getToolSource:(Q)=>SG(J,M,Q),getRecentTools:(Q)=>BG(J,M,Q),installTool:(Q,Y)=>xG(J,M,Q,Y),checkToolUpdate:(Q)=>EG(J,M,Q),updateTool:(Q)=>wG(J,M,Q)}}var yG=vG("{\"index\":\"./dashboard.js\",\"files\":[{\"path\":\"./cli-w822cqdk.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"IUqVLF461B4\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"path\":\"./cli-fj2hdbnx.js\",\"loader\":\"js\",\"isEntry\":false,\"headers\":{\"etag\":\"SXWin7hyR_o\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-0ebz5sqb.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"E4eqVcrkzYE\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard.js\",\"loader\":\"html\",\"isEntry\":true,\"headers\":{\"etag\":\"eqXrNcjoIac\",\"content-type\":\"text/html;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/preact-iso@2.11.1/node_modules/preact-iso/src/prerender.js\",\"path\":\"./prerender-kpxyx916.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"D-BSy7GnzyQ\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../../node_modules/.bun/shiki@3.23.0/node_modules/shiki/dist/wasm.mjs\",\"path\":\"./wasm-n3cagcre.js\",\"loader\":\"js\",\"isEntry\":true,\"headers\":{\"etag\":\"50fw3f0UtlU\",\"content-type\":\"text/javascript;charset=utf-8\"}},{\"input\":\"../../dashboard/src/client/dashboard.html\",\"path\":\"./dashboard-3axqywva.css\",\"loader\":\"css\",\"isEntry\":true,\"headers\":{\"etag\":\"gMrIjjRYnE4\",\"content-type\":\"text/css;charset=utf-8\"}}]}");var o4=import.meta.dir,gJ=!1,e4=gJ&&process.env.DOTFILES_IS_RELOAD==="1";function $3($){let M={};try{let J=r4.readdirSync($);for(let Q of J)if(Q.endsWith(".js")){let Y=t4.join($,Q);M[`/${Q}`]=()=>{return new Response(Bun.file(Y),{headers:{"Content-Type":"text/javascript"}})}}}catch{}return M}function P6($,M,J){let Q=$.getSubLogger({name:"DashboardServer"}),Y=NG(Q,M),G=null;return{async start(){if(process.env.DOTFILES_IS_RELOAD="1",!gJ)process.chdir(o4);let X=gJ?{}:$3(process.cwd());return G=Bun.serve({port:J.port,hostname:J.host,development:gJ,routes:{...X,"/api/tools":async()=>{let Z=await Y.getTools();return Response.json(Z)},"/api/stats":async()=>{let Z=await Y.getStats();return Response.json(Z)},"/api/health":async()=>{let Z=await Y.getHealth();return Response.json(Z)},"/api/config":async()=>{let Z=await Y.getConfig();return Response.json(Z)},"/api/tool-configs-tree":async()=>{let Z=await Y.getToolConfigsTree();return Response.json(Z)},"/api/shell":async()=>{let Z=await Y.getShellIntegration();return Response.json(Z)},"/api/activity":async(Z)=>{let I=new URL(Z.url).searchParams.get("limit"),U=I?parseInt(I,10):void 0,K=await Y.getActivity(U);return Response.json(K)},"/api/tools/:name/history":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await Y.getToolHistory(q);return Response.json(I)},"/api/tools/:name/readme":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await Y.getToolReadme(q);return Response.json(I)},"/api/tools/:name/source":async(Z)=>{let q=decodeURIComponent(Z.params.name),I=await Y.getToolSource(q);return Response.json(I)},"/api/tools/:name/install":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Z.json().catch(()=>({})),U=await Y.installTool(q,I);return Response.json(U)},"/api/tools/:name/check-update":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Y.checkToolUpdate(q);return Response.json(I)},"/api/tools/:name/update":async(Z)=>{if(Z.method!=="POST")return Response.json({success:!1,error:"Method not allowed"},{status:405});let q=decodeURIComponent(Z.params.name),I=await Y.updateTool(q);return Response.json(I)},"/api/recent-tools":async(Z)=>{let I=new URL(Z.url).searchParams.get("limit"),U=I?parseInt(I,10):void 0,K=await Y.getRecentTools(U);return Response.json(K)},"/api/*":Response.json({success:!1,error:"Not found"},{status:404}),"/server/*":(Z)=>{let q=new URL(Z.url),I=q.pathname.replace(/^\/server\//,"/");return Response.redirect(new URL(I,q.origin).href,302)},"/*":yG},fetch(Z){let q=new URL(Z.url);return Q.debug(b.requestReceived(Z.method,q.pathname)),new Response("Not Found",{status:404})}}),Q.info(b.serverStarted(this.getUrl())),e4},async stop(){if(Q.info(b.serverStopping()),G)G.stop(),G=null;Q.info(b.serverStopped())},getUrl(){return`http://${J.host}:${J.port}`}}}var{$:M3}=globalThis.Bun;var J3=async($,M)=>{let J=M===2?"open":M===4?"start":"xdg-open";await M3`${J} ${$}`.nothrow().quiet()};function PG($,M,J,Q={}){let Y=Q.openBrowser??J3,G=Q.createServer??P6,X=$.getSubLogger({name:"dashboard"});M.command("dashboard").description("Start the web-based visualization dashboard").option("--port <port>","Port to run the server on","3000").option("--host <host>","Host to bind the server to","localhost").option("--no-open","Do not open browser when server starts").action(async(Z)=>{let q=parseInt(Z.port??"3000",10),I=Z.host??"localhost",U=Z.open??!0,K=await J(),H={projectConfig:K.projectConfig,fs:K.fs,configService:K.configService,systemInfo:K.systemInfo,fileRegistry:K.fileRegistry,toolInstallationRegistry:K.toolInstallationRegistry,versionChecker:K.versionChecker,downloader:K.downloader,installer:K.installer,pluginRegistry:K.pluginRegistry},O=await G(X,H,{port:q,host:I}).start();if(U&&!O){let B=`http://${I}:${q}`;try{await Y(B,K.systemInfo.platform)}catch(j){X.warn(R.dashboardBrowserOpenFailed(),j)}}})}import aM from"path";var CG={name:"detect-conflicts",description:"Detect file conflicts before generating"};async function Q3($,M,J,Q,Y){try{let G=await Q.loadToolConfigs($,M.paths.toolConfigsDir,J,M,Y);return{toolConfigs:Object.values(G),exitCode:x.SUCCESS}}catch(G){return $.error(R.configLoadFailed("tool configurations"),G),{toolConfigs:[],exitCode:x.ERROR}}}async function Y3($,M,J,Q,Y){if(!J.binaries)return;for(let G of J.binaries){let X=typeof G==="string"?G:G.name,Z=aM.join(Q,X);if(await M.exists(Z))try{if(!(await M.readFile(Z)).includes("# Generated by Dotfiles Management Tool"))Y.push(`[${J.name}]: ${Z} (exists but is not a generator shim)`)}catch(q){$.warn(R.fsReadFailed(Z),q),Y.push(`[${J.name}]: ${Z} (exists but could not be read/verified)`)}}}async function G3($,M,J,Q,Y,G){if(!J.symlinks)return;for(let X of J.symlinks){let Z=aM.join(Q,X.target),q=aM.join(Y,X.source);try{let I=await M.lstat(Z);if(I)if(I.isSymbolicLink()){let U=await M.readlink(Z);if(aM.resolve(aM.dirname(Z),U)!==q)G.push(`[${J.name}]: ${Z} (points to '${U}', expected '${q}')`)}else G.push(`[${J.name}]: ${Z} (exists but is not a symlink)`)}catch(I){if(I.code!=="ENOENT")$.warn(R.fsReadFailed(Z),I)}}}function X3($,M){if(M.length>0){let Q=M.map((Y)=>` - ${Y}`).join(`
|
|
226
|
+
`);return $.warn(R.toolConflictsDetected("Conflicts detected with files not owned by the generator:",Q)),x.ERROR}else return $.info(R.noConflictsDetected()),x.SUCCESS}async function Z3($,M,J){let{projectConfig:Q,fs:Y,configService:G,systemInfo:X}=J,Z=[],q=await Q3($,Q,Y,G,X);if(q.exitCode!==x.SUCCESS)return q.exitCode;let I=q.toolConfigs;if(I.length===0)return $.info(R.toolNoConfigurationsFound(Q.paths.toolConfigsDir)),x.SUCCESS;for(let U of I)await Y3($,Y,U,Q.paths.targetDir,Z),await G3($,Y,U,Q.paths.homeDir,Q.paths.dotfilesDir,Z);return X3($,Z)}function dG($,M,J){let Q=$.getSubLogger({name:"registerDetectConflictsCommand"});M.command("detect-conflicts").description("Detects conflicts between potential generated artifacts and existing system files.").action(async()=>{let Y=M.opts(),G;try{let X=await J();G=await Z3(Q,Y,X)}catch(X){Q.error(R.commandExecutionFailed("detect-conflicts",x.ERROR),X),G=x.ERROR}N(G)})}var G$="DOTFILES_ENV_DIR",TM="DOTFILES_ENV_NAME",P0="env",nJ="source",uG="source.ps1",HM="config.ts",C6="tools";function fG(){let $=p0();return c(`
|
|
227
227
|
import { defineConfig } from '${$}';
|
|
228
228
|
|
|
229
229
|
export default defineConfig(({ configFileDir }) => {
|
|
@@ -238,7 +238,7 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
238
238
|
},
|
|
239
239
|
};
|
|
240
240
|
});
|
|
241
|
-
`)}function
|
|
241
|
+
`)}function pG($,M){return c(`
|
|
242
242
|
# ==============================================================================
|
|
243
243
|
# Dotfiles Virtual Environment Activation Script (PowerShell)
|
|
244
244
|
# ==============================================================================
|
|
@@ -253,7 +253,7 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
253
253
|
# ==============================================================================
|
|
254
254
|
|
|
255
255
|
function global:dotfiles-deactivate {
|
|
256
|
-
if ($env:${
|
|
256
|
+
if ($env:${G$}) {
|
|
257
257
|
# Restore original XDG_CONFIG_HOME
|
|
258
258
|
if ($env:_DOTFILES_OLD_XDG_CONFIG_HOME) {
|
|
259
259
|
$env:XDG_CONFIG_HOME = $env:_DOTFILES_OLD_XDG_CONFIG_HOME
|
|
@@ -261,15 +261,15 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
261
261
|
} else {
|
|
262
262
|
Remove-Item Env:XDG_CONFIG_HOME -ErrorAction SilentlyContinue
|
|
263
263
|
}
|
|
264
|
-
Remove-Item Env:${
|
|
265
|
-
Remove-Item Env:${
|
|
264
|
+
Remove-Item Env:${G$} -ErrorAction SilentlyContinue
|
|
265
|
+
Remove-Item Env:${TM} -ErrorAction SilentlyContinue
|
|
266
266
|
Remove-Item Function:dotfiles-deactivate -ErrorAction SilentlyContinue
|
|
267
267
|
Write-Host "Deactivated dotfiles environment"
|
|
268
268
|
}
|
|
269
269
|
}
|
|
270
270
|
|
|
271
271
|
# If already active, deactivate first
|
|
272
|
-
if ($env:${
|
|
272
|
+
if ($env:${G$}) {
|
|
273
273
|
dotfiles-deactivate
|
|
274
274
|
}
|
|
275
275
|
|
|
@@ -286,14 +286,14 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
286
286
|
}
|
|
287
287
|
|
|
288
288
|
# Export environment variables
|
|
289
|
-
$env:${
|
|
290
|
-
$env:${
|
|
289
|
+
$env:${G$} = $scriptDir
|
|
290
|
+
$env:${TM} = "${M}"
|
|
291
291
|
$env:XDG_CONFIG_HOME = "$scriptDir\\.config"
|
|
292
292
|
|
|
293
293
|
Write-Host "Activated dotfiles environment: ${M}"
|
|
294
|
-
Write-Host " Directory: $env:${
|
|
295
|
-
Write-Host " Config: $env:${
|
|
296
|
-
`)}function
|
|
294
|
+
Write-Host " Directory: $env:${G$}"
|
|
295
|
+
Write-Host " Config: $env:${G$}\\config.ts"
|
|
296
|
+
`)}function cG($,M){return c(`
|
|
297
297
|
#!/bin/sh
|
|
298
298
|
# ==============================================================================
|
|
299
299
|
# Dotfiles Virtual Environment Activation Script
|
|
@@ -310,7 +310,7 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
310
310
|
|
|
311
311
|
# Deactivate function to clean up environment
|
|
312
312
|
dotfiles-deactivate() {
|
|
313
|
-
if [ -n "\${${
|
|
313
|
+
if [ -n "\${${G$}:-}" ]; then
|
|
314
314
|
# Restore original XDG_CONFIG_HOME
|
|
315
315
|
if [ -n "\${_DOTFILES_OLD_XDG_CONFIG_HOME:-}" ]; then
|
|
316
316
|
export XDG_CONFIG_HOME="\${_DOTFILES_OLD_XDG_CONFIG_HOME}"
|
|
@@ -318,15 +318,15 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
318
318
|
else
|
|
319
319
|
unset XDG_CONFIG_HOME
|
|
320
320
|
fi
|
|
321
|
-
unset ${
|
|
322
|
-
unset ${
|
|
321
|
+
unset ${G$}
|
|
322
|
+
unset ${TM}
|
|
323
323
|
unset -f dotfiles-deactivate 2>/dev/null
|
|
324
324
|
echo "Deactivated dotfiles environment"
|
|
325
325
|
fi
|
|
326
326
|
}
|
|
327
327
|
|
|
328
328
|
# If already active, deactivate first
|
|
329
|
-
if [ -n "\${${
|
|
329
|
+
if [ -n "\${${G$}:-}" ]; then
|
|
330
330
|
dotfiles-deactivate
|
|
331
331
|
fi
|
|
332
332
|
|
|
@@ -347,22 +347,22 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
347
347
|
fi
|
|
348
348
|
|
|
349
349
|
# Export environment variables
|
|
350
|
-
export ${
|
|
351
|
-
export ${
|
|
350
|
+
export ${G$}="\${_dotfiles_script_dir}"
|
|
351
|
+
export ${TM}="${M}"
|
|
352
352
|
export XDG_CONFIG_HOME="\${_dotfiles_script_dir}/.config"
|
|
353
353
|
|
|
354
354
|
# Clean up temporary variable
|
|
355
355
|
unset _dotfiles_script_dir
|
|
356
356
|
|
|
357
357
|
echo "Activated dotfiles environment: ${M}"
|
|
358
|
-
echo " Directory: \${${
|
|
359
|
-
echo " Config: \${${
|
|
360
|
-
`)}import{z as s$}from"zod";var
|
|
361
|
-
`)}async function
|
|
362
|
-
`);else $.error(R.commandExecutionFailed("install",1),M);return 1}async function V3($,M,J,Q){if(!$.binaries||$.binaries.length===0)return;for(let G of $.binaries){let Y=typeof G==="string"?G:G.name,X=H3.join(M,Y);try{await J.lstat(X),await J.rm(X,{force:!0}),Q.debug(R.shimDeleted(Y,X))}catch{}}}function z3($){let M=$.installationMethod==="manual",J=!$.installParams||Object.keys($.installParams).length===0,Q=!$.binaries||$.binaries.length===0;return M&&J&&Q}function B3($){if($ instanceof Error)return $;return Error(typeof $==="string"?$:"Unknown error")}async function D3($,M,J,Q){let{projectConfig:G,fs:Y,installer:X,configService:Z,generatorOrchestrator:q,systemInfo:I}=Q;$.debug(R.commandActionStarted("install",M),G.paths.toolConfigsDir,Y.constructor.name);let U=await R3($,M,G.paths.toolConfigsDir,Y,G,Z,I);if(!U.success)return $.error(R.toolNotFoundByBinary(M,G.paths.toolConfigsDir)),1;let{toolConfig:K,toolName:H}=U,_=G$(K,I);if(z3(_)){if(!J.shimMode)$.info(R.toolInstallSkippedConfigurationOnly(H));return await q.generateCompletionsForTool(H,K),J.shimMode?0:null}let O=await X.install(H,K,{force:J.force,verbose:J.verbose,shimMode:J.shimMode});if(O.success){let j="binaryPaths"in O?O.binaryPaths:void 0;if(await q.generateCompletionsForTool(H,K,O.version,j),Q.pluginRegistry.getExternallyManagedMethods().has(_.installationMethod))await V3(_,G.paths.targetDir,Y,$)}return O3($,O,H,J.shimMode)}function o9($,M,J){let Q=$.getSubLogger({name:"registerInstallCommand"});M.command("install <nameOrBinary>").description("Installs a tool by name or binary. Accepts tool name (filename without .tool.ts) or binary name (from .bin()).").option("--force","Force installation even if the tool is already installed",!1).option("--shim-mode","Optimized output for shim usage: shows progress bars but suppresses log messages",!1).action(async(G,Y)=>{let X={...Y,...M.opts()},Z=await J(),q=null;try{q=await D3(Q,G,X,Z)}catch(I){let U=B3(I);q=j3(Q,U,G,X.shimMode)}if(q!==null)v(q)})}var e9={name:"log",description:"Show file operation history",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool",options:[{flag:"--type",description:"Filter by file type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--status",description:"Show current file states"},{flag:"--since",description:"Show operations since date",hasArg:!0,argPlaceholder:"<date>"}]};function A3($,M){let J=M.getSubLogger({name:"buildOperationsFilter"}),{tool:Q,type:G,since:Y}=$,X={};if(Q)X.toolName=Q;if(G)X.fileType=G;if(Y){let Z=new Date(Y);if(Number.isNaN(Z.getTime()))return J.error(R.configParameterInvalid("date format for --since",Y,'ISO format like "2025-08-01"')),{filter:{},exitCode:x.ERROR};X.createdAfter=Z.getTime()}return{filter:X,exitCode:x.SUCCESS}}async function E3($,M,J,Q){let G=$.getSubLogger({name:"showFileStates"}),Y=await M.getRegisteredTools();G.info(R.logCheckingFileStates());for(let X of Y){if(Q&&X!==Q)continue;let Z=await M.getFileStatesForTool(X);if(Z.length===0)continue;G.info(R.logFileStatesForTool(X));for(let q of Z)await F3(G,J,q)}}async function F3($,M,J){let Q=$.getSubLogger({name:"logFileState"}),G=await M.exists(J.filePath),Y=G?"\u2713":"\u2717",X=G?"exists":"MISSING",Z=J.sizeBytes?` (${J.sizeBytes} bytes)`:"";if(Q.info(R.logFileStatus(Y,J.filePath,J.fileType,X,Z)),J.targetPath){let I=await M.exists(J.targetPath)?"\u2192":"\u2717";Q.info(R.logTargetStatus(I,J.targetPath))}}function L3($){let M=[];if($.sizeBytes&&$.operationType==="writeFile")M.push(`size: ${$.sizeBytes}`);if($.metadata&&Object.keys($.metadata).length>0)for(let[J,Q]of Object.entries($.metadata))if(J==="newMode")M.push(`${J}: ${H0(Q)}`);else M.push(`${J}: ${Q}`);return M.length>0?`(${M.join(", ")})`:""}function x3($){return new Date($).toLocaleString("en-US",{hour12:!1,year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).replace(",","")}function T3($,M,J,Q,G,Y){let X=$.getSubLogger({name:"logOperationByType"});switch(M.operationType){case"writeFile":{let Z=`[${M.toolName}] write ${Q}`;X.info(R.logOperationHistory(J,Z,G));break}case"mkdir":{let Z=`[${M.toolName}] mkdir ${Q}`;X.info(R.logOperationHistory(J,Z,G));break}case"chmod":{let Z=H0(M.permissions||0),q=`[${M.toolName}] chmod ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,G));break}case"rm":{let Z=`[${M.toolName}] rm ${Q}`;X.info(R.logOperationHistory(J,Z,G));break}case"rename":{let Z=M.targetPath?s(Y.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] mv ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,G));break}case"cp":{let Z=M.targetPath?s(Y.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] cp ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,G));break}case"symlink":{let Z=M.targetPath?s(Y.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] ln -s ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,G));break}default:{let Z=`[${M.toolName}] write ${Q}`;X.info(R.logOperationHistory(J,Z,G))}}}function k3($){let M={};for(let J of $){if(!M[J.toolName])M[J.toolName]=[];M[J.toolName]?.push(J)}return M}async function S3($,M,J){let Q=$.getSubLogger({name:"showOperations"});if(M.length===0){Q.info(R.logNoOperationsFound());return}let G=k3(M);for(let[,Y]of Object.entries(G))for(let X of Y){let Z=x3(X.createdAt),q=L3(X),I=s(J.paths.homeDir,X.filePath);T3(Q,X,Z,I,q,J)}}async function w3($,M,J){let Q=$.getSubLogger({name:"logActionLogic"}),{fileRegistry:G,fs:Y,projectConfig:X}=J;try{if(M.status){await E3(Q,G,Y,M.tool);return}let Z=A3(M,Q);if(Z.exitCode!==x.SUCCESS){v(Z.exitCode);return}let q=await G.getOperations(Z.filter);await S3(Q,q,X)}catch(Z){Q.error(R.commandExecutionFailed("log",x.ERROR),Z),v(x.ERROR)}}function $7($,M,J){let Q=$.getSubLogger({name:"registerLogCommand"});M.command("log [tool]").description("Inspect tracked files in the registry").option("--type <type>","Show files of specific type only (shim, binary, symlink, etc.)").option("--status","Check file status (missing, broken links, etc.)").option("--since <date>","Show files created since date (ISO format: 2025-08-01)").action(async(G,Y)=>{let X={...Y,tool:G,...M.opts()},Z=await J();await w3(Q,X,Z)})}import{cp as b3}from"fs/promises";import lJ from"path";var M7={name:"skill",description:"Copy the dotfiles skill folder to the target directory",hasPositionalArg:!0,positionalArgDescription:"target directory for skill folder"};function v3(){let $=aM(),M=$.split(" ").pop()??$,J=lJ.dirname(M);return lJ.join(J,"skill")}async function N3($,M,J){let Q=$.getSubLogger({name:"copySkill"}),G=new z$,Y=v3(),X=lJ.join(M,"dotfiles");if(!await G.exists(Y))return Q.error(R.fsItemNotFound("Skill directory",Y)),x.ERROR;if(!await G.exists(M))return Q.error(R.fsItemNotFound("Target directory",M)),x.ERROR;if(await G.exists(X))Q.info(R.skillAlreadyExists(X)),await G.rmdir(X,{recursive:!0});if(J)return Q.info(R.skillDryRun(X,Y)),x.SUCCESS;try{return await b3(Y,X,{recursive:!0}),Q.info(R.skillCopied(X,Y)),x.SUCCESS}catch(U){return Q.error(R.skillCopyFailed(X),U),x.ERROR}}async function y3($,M){let J=$.getSubLogger({name:"skillActionLogic"}),{targetPath:Q,dryRun:G}=M;J.debug(R.commandActionStarted("skill"));let Y=await N3(J,Q,G);v(Y)}function J7($,M,J){let Q=$.getSubLogger({name:"registerSkillCommand"});M.command("skill <path>").description("Copy the dotfiles skill folder to the target directory").action(async(G)=>{let Y={targetPath:lJ.resolve(G),...M.opts()};await y3(Q,Y)})}var Q7={name:"update",description:"Update an installed tool to latest version",hasPositionalArg:!0,positionalArgDescription:"tool name to update",positionalArgType:"tool",options:[{flag:"--shim-mode",description:"Optimized output for shim usage"}]};async function P3($,M,J,Q,G,Y,X){try{let Z=await M.loadSingleToolConfig($,J,Q,G,Y,X);if(!Z)return $.error(R.toolNotFound(J,Q)),{toolConfig:null,exitCode:x.ERROR};return{toolConfig:Z,exitCode:x.SUCCESS}}catch(Z){return $.error(R.configLoadFailed(`tool "${J}"`),Z),{toolConfig:null,exitCode:x.ERROR}}}async function C3($,M,J,Q,G){let{toolInstallationRegistry:Y,installer:X,pluginRegistry:Z}=M;if(Q.version!=="latest"){$.info(R.toolVersionPinned(J,Q.version));return}let q=Z.get(Q.installationMethod);if(q&&!q.supportsUpdate())$.warn(R.toolUpdateNotSupported(J,Q.installationMethod));let U=(await Y.getToolInstallation(J))?.version||"unknown",K=await X.install(J,Q,{force:!0,shimMode:G});if(!K.success){$.error(R.toolUpdateFailed(J,K.error)),v(x.ERROR);return}let H="version"in K&&typeof K.version==="string"?K.version:"unknown",_=U===H;if(G)if(_)$.info(R.toolShimUpToDate(J,H));else $.info(R.toolShimUpdateStarting(J,U,H)),$.info(R.toolShimUpdateSuccess(J,H));else $.info(R.toolUpdated(J,U,H))}function G7($,M,J){let Q=$.getSubLogger({name:"registerUpdateCommand"});M.command("update <toolName>").description("Updates a specified tool to its latest version.").option("--shim-mode","Run in shim mode with minimal output",!1).action(async(G,Y)=>{let X={...Y,...M.opts()},Z=await J(),{projectConfig:q,fs:I,configService:U,systemInfo:K}=Z;try{let H=await P3(Q,U,G,q.paths.toolConfigsDir,I,q,K);if(H.exitCode!==x.SUCCESS){v(H.exitCode);return}if(!H.toolConfig){Q.error(R.toolNotFound(G,q.paths.toolConfigsDir)),v(x.ERROR);return}let _=H.toolConfig;if(!X.shimMode)Q.info(R.commandCheckingUpdatesFor(G));await C3(Q,Z,G,_,X.shimMode)}catch(H){Q.error(R.commandExecutionFailed("update",x.ERROR),H),v(x.ERROR)}})}var d3=[J9,t9,r9,Z9,Y9,Q7,P9,e9,i9,M7,g9];function PG($){let M=$.flag,J=$.description.replace(/'/g,"\\'");if($.hasArg)return`'${M}=[${J}]:${$.argPlaceholder||"arg"}:'`;return`'${M}[${J}]'`}function u3($){let M=[];for(let J of $)M.push(PG(J));return M.push("'1:command:->command'"),M.push("'*::arg:->args'"),M.join(" \\\n")}function f3($){return $.replace(/'/g,"\\'")}function p3($){return $.map((M)=>f3(M)).join(" ")}function c3($,M,J){if(M==="tool"&&J.length>0){let Q=p3(J);return`'1:${$}:(${Q})'`}return`'1:${$}:'`}function h3(){return"_describe 'command' commands"}function m3($){if($.length===0)return;let M=$.length-1,J=$[M];if(J?.endsWith(" \\"))$[M]=J.slice(0,-2)}function g3($,M){let J=[];if($.options)for(let Q of $.options)J.push(PG(Q));for(let Q of M)J.push(PG(Q));return J}function n3($){let M=[];M.push("'1:subcommand:->subcommand'");let J=$.map((Q)=>`'${Q.name}:${Q.description.replace(/'/g,"\\'")}'`).join(" ");return M.push("case $state in"),M.push(" subcommand)"),M.push(` local -a subcommands=(${J})`),M.push(" _describe 'subcommand' subcommands"),M.push(" ;;"),M.push("esac"),M}function i3($,M,J){let Q=[];Q.push(`${$.name})`);let G=g3($,M);if(G.length>0||$.hasPositionalArg||$.subcommands){Q.push(" _arguments \\");for(let X of G)Q.push(` ${X} \\`);if($.subcommands&&$.subcommands.length>0){let X=n3($.subcommands);for(let Z of X)Q.push(` ${Z}`)}else if($.hasPositionalArg){let X=$.positionalArgDescription||"argument",Z=c3(X,$.positionalArgType,J);Q.push(` ${Z}`)}else m3(Q)}return Q.push(" ;;"),Q.join(`
|
|
363
|
-
`)}function
|
|
364
|
-
`)}function
|
|
365
|
-
`);return
|
|
358
|
+
echo " Directory: \${${G$}}"
|
|
359
|
+
echo " Config: \${${G$}}/config.ts"
|
|
360
|
+
`)}import{z as s$}from"zod";var xx=s$.object({name:s$.string().min(1).default("env"),parentDir:s$.string().min(1),force:s$.boolean().default(!1)}),Tx=s$.object({envDir:s$.string(),name:s$.string(),configPath:s$.string(),sourcePath:s$.string(),toolsDir:s$.string()});import O$ from"path";var C$={creatingEnv:($)=>W(`Creating environment: ${$}`),envCreated:($)=>W(`Environment created at ${$}`),envAlreadyExists:($)=>W(`Environment already exists at ${$}`),envNotFound:($)=>W(`Environment not found at ${$}`),deletingEnv:($)=>W(`Deleting environment: ${$}`),envDeleted:($)=>W(`Environment deleted at ${$}`),envDetected:($)=>W(`Detected environment at ${$}`),envActive:($)=>W(`Active environment: ${$}`),sourceFileGenerated:($)=>W(`Source file generated at ${$}`),configFileGenerated:($)=>W(`Config file generated at ${$}`),toolsDirCreated:($)=>W(`Tools directory created at ${$}`),writeFile:($)=>W(`Writing ${$}`),deleteConfirmationRequired:()=>W("Deletion requires confirmation")};class iJ{parentLogger;fs;env;constructor($,M,J=process.env){this.parentLogger=$;this.fs=M;this.env=J}get logger(){return this.parentLogger.getSubLogger({name:"VirtualEnvManager"})}async create($){let M=this.logger.getSubLogger({name:"create"}),J=$.name,Q=O$.resolve($.parentDir,J);if(M.debug(C$.creatingEnv(J)),await this.fs.exists(Q)){if(!$.force)return M.warn(C$.envAlreadyExists(Q)),{success:!1,error:`Environment already exists at ${Q}`};await this.fs.rm(Q,{recursive:!0})}await this.fs.ensureDir(Q);let Y=O$.join(Q,C6);await this.fs.ensureDir(Y),M.debug(C$.toolsDirCreated(Y));let G=O$.join(Q,nJ),X=cG(Q,J);await this.fs.writeFile(G,X),await this.fs.chmod(G,493),M.debug(C$.sourceFileGenerated(G));let Z=O$.join(Q,uG),q=pG(Q,J);await this.fs.writeFile(Z,q),M.debug(C$.sourceFileGenerated(Z));let I=O$.join(Q,HM),U=fG();return await this.fs.writeFile(I,U),M.debug(C$.configFileGenerated(I)),M.debug(C$.envCreated(Q)),{success:!0,envDir:Q,envName:J}}async delete($){let M=this.logger.getSubLogger({name:"delete"}),J=O$.basename($);if(!await this.isValidEnv($))return M.warn(C$.envNotFound($)),{success:!1,error:`Environment not found at ${$}`};return M.debug(C$.deletingEnv(J)),await this.fs.rm($,{recursive:!0}),M.debug(C$.envDeleted($)),{success:!0,envDir:$,envName:J}}async getEnvInfo($){if(!await this.isValidEnv($))return null;return{envDir:O$.resolve($),name:O$.basename($),configPath:O$.join($,HM),sourcePath:O$.join($,nJ),toolsDir:O$.join($,C6)}}async isValidEnv($){let M=O$.join($,nJ),J=O$.join($,HM),[Q,Y]=await Promise.all([this.fs.exists(M),this.fs.exists(J)]);return Q&&Y}async detectEnv($,M){let J=this.logger.getSubLogger({name:"detectEnv"}),Q=M??P0,Y=O$.resolve($,Q);if(await this.isValidEnv(Y))return J.debug(C$.envDetected(Y)),{found:!0,envDir:Y,envName:Q,configPath:O$.join(Y,HM)};return{found:!1}}getActiveEnv(){let $=this.env[G$],M=this.env[TM];if($&&M)return{active:!0,envDir:$,envName:M};return{active:!1}}}import hG from"path";import*as mG from"readline";async function W3($){let M=mG.createInterface({input:process.stdin,output:process.stdout});return new Promise((J)=>{M.question(`Delete environment at '${$}'? [y/N] `,(Q)=>{M.close(),J(Q.toLowerCase()==="y"||Q.toLowerCase()==="yes")})})}async function q3($,M,J){let Q=new z$,Y=new iJ($,Q),G=process.cwd(),X=await Y.create({name:M,parentDir:G,force:!1});if(!X.success){$.error(R.envOperationFailed("create",X.error)),N(1);return}let Z=hG.join(X.envDir,HM);$.info(R.envCreated(X.envDir)),$.info(R.envActivationHint(M)),$.info(R.envConfigPath(Z))}async function I3($,M,J){let Q=new z$,Y=new iJ($,Q),G=process.cwd(),X=hG.resolve(G,M);if(!await Y.isValidEnv(X)){$.error(R.envNotFound(X)),N(1);return}if(!J.force){if(!await W3(X)){$.info(R.envDeletionCancelled());return}}let Z=await Y.delete(X);if(!Z.success){$.error(R.envOperationFailed("delete",Z.error)),N(1);return}$.info(R.envDeleted(Z.envDir))}function gG($,M){let J=$.getSubLogger({name:"registerEnvCommand"}),Q=M.command("env").description("Manage virtual environments for isolated dotfiles configurations.");Q.command("create [name]").description("Create a new virtual environment").action(async(Y)=>{let G=Y??P0,X=M.opts();await q3(J,G,X)}),Q.command("delete [name]").description("Delete a virtual environment").option("--force","Skip confirmation prompt",!1).action(async(Y,G)=>{let X=Y??P0,Z={...G,...M.opts()};await I3(J,X,Z)})}var nG={name:"features",description:"Manage features and generate artifacts",subcommands:[{name:"catalog",description:"Generate catalog of available features"}]};async function U3($,M,J){try{let{projectConfig:Q,fs:Y,configService:G,readmeService:X,systemInfo:Z}=J,q=await G.loadToolConfigs($,Q.paths.toolConfigsDir,Y,Q,Z);await X.generateCatalogFromConfigs(Q.features.catalog.filePath,q)}catch(Q){$.error(R.commandExecutionFailed("features catalog",1),Q),N(1)}}function iG($,M,J){let Q=$.getSubLogger({name:"registerFeaturesCommand"});M.command("features").description("Manage features and generate feature-specific artifacts.").command("catalog").description("Catalog of available features documentation").action(async()=>{let G=M.opts(),X=await J();await U3(Q,G,X),Q.info(R.commandCompleted(Boolean(G.dryRun)))})}var lG={name:"files",description:"Show generated files structure",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool"};async function aG($,M,J){let Q=[];try{let Y=await M.readdir(J);for(let G of Y){let X=`${J}/${G}`,q=(await M.stat(X)).isDirectory(),I={name:G,isDirectory:q};if(q)I.children=await aG($,M,X);Q.push(I)}}catch(Y){$.error(R.commandExecutionFailed("files",x.ERROR),Y)}return Q.toSorted((Y,G)=>{if(Y.isDirectory===G.isDirectory)return Y.name.localeCompare(G.name);return Y.isDirectory?-1:1})}function sG($,M=""){let J=[];for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(!Y)continue;let G=Q===$.length-1,X=G?"\u2514\u2500 ":"\u251C\u2500 ",Z=Y.name;if(J.push(`${M}${X}${Z}`),Y.isDirectory&&Y.children&&Y.children.length>0){let q=M+(G?" ":"\u2502 "),I=sG(Y.children,q);J.push(I)}}return J.join(`
|
|
361
|
+
`)}async function K3($,M,J,Q,Y){let G=await J.getToolInstallation(Q);if(!G)return $.error(R.toolNotInstalled(Q)),x.ERROR;let X=G.installPath;if(!await M.exists(X))return $.error(R.installPathNotFound(X)),x.ERROR;Y(X);let q=await aG($,M,X);if(q.length===0)return Y("(empty directory)"),x.SUCCESS;let I=sG(q);return Y(I),x.SUCCESS}async function H3($,M,J,Q,Y){let{fs:G,projectConfig:X,configService:Z,toolInstallationRegistry:q,systemInfo:I}=Q;try{if(!await Z.loadSingleToolConfig($,M,X.paths.toolConfigsDir,G,X,I)){$.error(R.toolNotFound(M,X.paths.toolConfigsDir)),N(x.ERROR);return}let K=await K3($,G,q,M,Y);if(K!==x.SUCCESS)N(K)}catch(U){$.error(R.commandExecutionFailed("files",x.ERROR),U),N(x.ERROR)}}function rG($,M,J,Q=console.log){let Y=$.getSubLogger({name:"registerFilesCommand"});M.command("files <toolName>").description("Display a tree view of files in the tool installation directory").action(async(G,X)=>{let Z={...X,...M.opts()},q=await J();await H3(Y,G,Z,q,Q)})}import u6 from"path";var tG={name:"generate",description:"Generate shims, shell init files, and symlinks",options:[{flag:"--overwrite",description:"Overwrite conflicting files not created by generator"}]};import _3 from"path";var oG={name:"install",description:"Install a tool by name or binary",hasPositionalArg:!0,positionalArgDescription:"tool name or binary name to install",positionalArgType:"tool",options:[{flag:"--force",description:"Force installation even if already installed"},{flag:"--shim-mode",description:"Optimized output for shim usage"}]};function R3($){return typeof $==="object"&&$!==null&&"error"in $}async function O3($,M,J,Q,Y,G,X){let Z=await G.loadSingleToolConfig($,M,J,Q,Y,X);if(Z)return{success:!0,toolConfig:Z,toolName:M};$.debug(R.toolLookupByBinaryStarted(M));let q=await G.loadToolConfigByBinary($,M,J,Q,Y,X);if(R3(q))return{success:!1,error:q.error};if(q)return $.debug(R.toolFoundByBinary(M,q.name)),{success:!0,toolConfig:q,toolName:q.name};return{success:!1,error:`No tool or binary named "${M}" found in ${J}`}}function j3($,M,J,Q){if(M.success)if(Q)return 0;else{let Y=M.installationMethod??"unknown",G=M.version??"unknown";if(Y==="already-installed")$.info(R.toolAlreadyInstalled(J,G));else $.info(R.toolInstalled(J,G,Y));return null}else return 1}function V3($,M,J,Q){if(Q)process.stderr.write(`Failed to install '${J}': ${M.message}
|
|
362
|
+
`);else $.error(R.commandExecutionFailed("install",1),M);return 1}async function z3($,M,J,Q){if(!$.binaries||$.binaries.length===0)return;for(let Y of $.binaries){let G=typeof Y==="string"?Y:Y.name,X=_3.join(M,G);try{await J.lstat(X),await J.rm(X,{force:!0}),Q.debug(R.shimDeleted(G,X))}catch{}}}function B3($){let M=$.installationMethod==="manual",J=!$.installParams||Object.keys($.installParams).length===0,Q=!$.binaries||$.binaries.length===0;return M&&J&&Q}function D3($){if($ instanceof Error)return $;return Error(typeof $==="string"?$:"Unknown error")}async function A3($,M,J,Q){let{projectConfig:Y,fs:G,installer:X,configService:Z,generatorOrchestrator:q,systemInfo:I}=Q;$.debug(R.commandActionStarted("install",M),Y.paths.toolConfigsDir,G.constructor.name);let U=await O3($,M,Y.paths.toolConfigsDir,G,Y,Z,I);if(!U.success)return $.error(R.toolNotFoundByBinary(M,Y.paths.toolConfigsDir)),1;let{toolConfig:K,toolName:H}=U,_=Y$(K,I);if(B3(_)){if(!J.shimMode)$.info(R.toolInstallSkippedConfigurationOnly(H));return await q.generateCompletionsForTool(H,K),J.shimMode?0:null}let O=await X.install(H,K,{force:J.force,verbose:J.verbose,shimMode:J.shimMode});if(O.success){let j="binaryPaths"in O?O.binaryPaths:void 0;if(await q.generateCompletionsForTool(H,K,O.version,j),Q.pluginRegistry.getExternallyManagedMethods().has(_.installationMethod))await z3(_,Y.paths.targetDir,G,$)}return j3($,O,H,J.shimMode)}function eG($,M,J){let Q=$.getSubLogger({name:"registerInstallCommand"});M.command("install <nameOrBinary>").description("Installs a tool by name or binary. Accepts tool name (filename without .tool.ts) or binary name (from .bin()).").option("--force","Force installation even if the tool is already installed",!1).option("--shim-mode","Optimized output for shim usage: shows progress bars but suppresses log messages",!1).action(async(Y,G)=>{let X={...G,...M.opts()},Z=await J(),q=null;try{q=await A3(Q,Y,X,Z)}catch(I){let U=D3(I);q=V3(Q,U,Y,X.shimMode)}if(q!==null)N(q)})}var $7={name:"log",description:"Show file operation history",hasPositionalArg:!0,positionalArgDescription:"tool name (optional)",positionalArgType:"tool",options:[{flag:"--type",description:"Filter by file type",hasArg:!0,argPlaceholder:"<type>"},{flag:"--status",description:"Show current file states"},{flag:"--since",description:"Show operations since date",hasArg:!0,argPlaceholder:"<date>"}]};function E3($,M){let J=M.getSubLogger({name:"buildOperationsFilter"}),{tool:Q,type:Y,since:G}=$,X={};if(Q)X.toolName=Q;if(Y)X.fileType=Y;if(G){let Z=new Date(G);if(Number.isNaN(Z.getTime()))return J.error(R.configParameterInvalid("date format for --since",G,'ISO format like "2025-08-01"')),{filter:{},exitCode:x.ERROR};X.createdAfter=Z.getTime()}return{filter:X,exitCode:x.SUCCESS}}async function F3($,M,J,Q){let Y=$.getSubLogger({name:"showFileStates"}),G=await M.getRegisteredTools();Y.info(R.logCheckingFileStates());for(let X of G){if(Q&&X!==Q)continue;let Z=await M.getFileStatesForTool(X);if(Z.length===0)continue;Y.info(R.logFileStatesForTool(X));for(let q of Z)await L3(Y,J,q)}}async function L3($,M,J){let Q=$.getSubLogger({name:"logFileState"}),Y=await M.exists(J.filePath),G=Y?"\u2713":"\u2717",X=Y?"exists":"MISSING",Z=J.sizeBytes?` (${J.sizeBytes} bytes)`:"";if(Q.info(R.logFileStatus(G,J.filePath,J.fileType,X,Z)),J.targetPath){let I=await M.exists(J.targetPath)?"\u2192":"\u2717";Q.info(R.logTargetStatus(I,J.targetPath))}}function x3($){let M=[];if($.sizeBytes&&$.operationType==="writeFile")M.push(`size: ${$.sizeBytes}`);if($.metadata&&Object.keys($.metadata).length>0)for(let[J,Q]of Object.entries($.metadata))if(J==="newMode")M.push(`${J}: ${H0(Q)}`);else M.push(`${J}: ${Q}`);return M.length>0?`(${M.join(", ")})`:""}function T3($){return new Date($).toLocaleString("en-US",{hour12:!1,year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}).replace(",","")}function k3($,M,J,Q,Y,G){let X=$.getSubLogger({name:"logOperationByType"});switch(M.operationType){case"writeFile":{let Z=`[${M.toolName}] write ${Q}`;X.info(R.logOperationHistory(J,Z,Y));break}case"mkdir":{let Z=`[${M.toolName}] mkdir ${Q}`;X.info(R.logOperationHistory(J,Z,Y));break}case"chmod":{let Z=H0(M.permissions||0),q=`[${M.toolName}] chmod ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}case"rm":{let Z=`[${M.toolName}] rm ${Q}`;X.info(R.logOperationHistory(J,Z,Y));break}case"rename":{let Z=M.targetPath?s(G.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] mv ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}case"cp":{let Z=M.targetPath?s(G.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] cp ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}case"symlink":{let Z=M.targetPath?s(G.paths.homeDir,M.targetPath):Q,q=`[${M.toolName}] ln -s ${Z} ${Q}`;X.info(R.logOperationHistory(J,q,Y));break}default:{let Z=`[${M.toolName}] write ${Q}`;X.info(R.logOperationHistory(J,Z,Y))}}}function S3($){let M={};for(let J of $){if(!M[J.toolName])M[J.toolName]=[];M[J.toolName]?.push(J)}return M}async function w3($,M,J){let Q=$.getSubLogger({name:"showOperations"});if(M.length===0){Q.info(R.logNoOperationsFound());return}let Y=S3(M);for(let[,G]of Object.entries(Y))for(let X of G){let Z=T3(X.createdAt),q=x3(X),I=s(J.paths.homeDir,X.filePath);k3(Q,X,Z,I,q,J)}}async function b3($,M,J){let Q=$.getSubLogger({name:"logActionLogic"}),{fileRegistry:Y,fs:G,projectConfig:X}=J;try{if(M.status){await F3(Q,Y,G,M.tool);return}let Z=E3(M,Q);if(Z.exitCode!==x.SUCCESS){N(Z.exitCode);return}let q=await Y.getOperations(Z.filter);await w3(Q,q,X)}catch(Z){Q.error(R.commandExecutionFailed("log",x.ERROR),Z),N(x.ERROR)}}function M7($,M,J){let Q=$.getSubLogger({name:"registerLogCommand"});M.command("log [tool]").description("Inspect tracked files in the registry").option("--type <type>","Show files of specific type only (shim, binary, symlink, etc.)").option("--status","Check file status (missing, broken links, etc.)").option("--since <date>","Show files created since date (ISO format: 2025-08-01)").action(async(Y,G)=>{let X={...G,tool:Y,...M.opts()},Z=await J();await b3(Q,X,Z)})}import{cp as N3}from"fs/promises";import lJ from"path";var J7={name:"skill",description:"Copy the dotfiles skill folder to the target directory",hasPositionalArg:!0,positionalArgDescription:"target directory for skill folder"};function v3(){let $=sM(),M=$.split(" ").pop()??$,J=lJ.dirname(M);return lJ.join(J,"skill")}async function y3($,M,J){let Q=$.getSubLogger({name:"copySkill"}),Y=new z$,G=v3(),X=lJ.join(M,"dotfiles");if(!await Y.exists(G))return Q.error(R.fsItemNotFound("Skill directory",G)),x.ERROR;if(!await Y.exists(M))return Q.error(R.fsItemNotFound("Target directory",M)),x.ERROR;if(await Y.exists(X))Q.info(R.skillAlreadyExists(X)),await Y.rmdir(X,{recursive:!0});if(J)return Q.info(R.skillDryRun(X,G)),x.SUCCESS;try{return await N3(G,X,{recursive:!0}),Q.info(R.skillCopied(X,G)),x.SUCCESS}catch(U){return Q.error(R.skillCopyFailed(X),U),x.ERROR}}async function P3($,M){let J=$.getSubLogger({name:"skillActionLogic"}),{targetPath:Q,dryRun:Y}=M;J.debug(R.commandActionStarted("skill"));let G=await y3(J,Q,Y);N(G)}function Q7($,M,J){let Q=$.getSubLogger({name:"registerSkillCommand"});M.command("skill <path>").description("Copy the dotfiles skill folder to the target directory").action(async(Y)=>{let G={targetPath:lJ.resolve(Y),...M.opts()};await P3(Q,G)})}var Y7={name:"update",description:"Update an installed tool to latest version",hasPositionalArg:!0,positionalArgDescription:"tool name to update",positionalArgType:"tool",options:[{flag:"--shim-mode",description:"Optimized output for shim usage"}]};async function C3($,M,J,Q,Y,G,X){try{let Z=await M.loadSingleToolConfig($,J,Q,Y,G,X);if(!Z)return $.error(R.toolNotFound(J,Q)),{toolConfig:null,exitCode:x.ERROR};return{toolConfig:Z,exitCode:x.SUCCESS}}catch(Z){return $.error(R.configLoadFailed(`tool "${J}"`),Z),{toolConfig:null,exitCode:x.ERROR}}}async function d3($,M,J,Q,Y){let{toolInstallationRegistry:G,installer:X,pluginRegistry:Z}=M;if(Q.version!=="latest"){$.info(R.toolVersionPinned(J,Q.version));return}let q=Z.get(Q.installationMethod);if(q&&!q.supportsUpdate())$.warn(R.toolUpdateNotSupported(J,Q.installationMethod));let U=(await G.getToolInstallation(J))?.version||"unknown",K=await X.install(J,Q,{force:!0,shimMode:Y});if(!K.success){$.error(R.toolUpdateFailed(J,K.error)),N(x.ERROR);return}let H="version"in K&&typeof K.version==="string"?K.version:"unknown",_=U===H;if(Y)if(_)$.info(R.toolShimUpToDate(J,H));else $.info(R.toolShimUpdateStarting(J,U,H)),$.info(R.toolShimUpdateSuccess(J,H));else $.info(R.toolUpdated(J,U,H))}function G7($,M,J){let Q=$.getSubLogger({name:"registerUpdateCommand"});M.command("update <toolName>").description("Updates a specified tool to its latest version.").option("--shim-mode","Run in shim mode with minimal output",!1).action(async(Y,G)=>{let X={...G,...M.opts()},Z=await J(),{projectConfig:q,fs:I,configService:U,systemInfo:K}=Z;try{let H=await C3(Q,U,Y,q.paths.toolConfigsDir,I,q,K);if(H.exitCode!==x.SUCCESS){N(H.exitCode);return}if(!H.toolConfig){Q.error(R.toolNotFound(Y,q.paths.toolConfigsDir)),N(x.ERROR);return}let _=H.toolConfig;if(!X.shimMode)Q.info(R.commandCheckingUpdatesFor(Y));await d3(Q,Z,Y,_,X.shimMode)}catch(H){Q.error(R.commandExecutionFailed("update",x.ERROR),H),N(x.ERROR)}})}var u3=[QG,oG,tG,WG,XG,Y7,CG,$7,lG,J7,nG];function d6($){let M=$.flag,J=$.description.replace(/'/g,"\\'");if($.hasArg)return`'${M}=[${J}]:${$.argPlaceholder||"arg"}:'`;return`'${M}[${J}]'`}function f3($){let M=[];for(let J of $)M.push(d6(J));return M.push("'1:command:->command'"),M.push("'*::arg:->args'"),M.join(" \\\n")}function p3($){return $.replace(/'/g,"\\'")}function c3($){return $.map((M)=>p3(M)).join(" ")}function h3($,M,J){if(M==="tool"&&J.length>0){let Q=c3(J);return`'1:${$}:(${Q})'`}return`'1:${$}:'`}function m3(){return"_describe 'command' commands"}function g3($){if($.length===0)return;let M=$.length-1,J=$[M];if(J?.endsWith(" \\"))$[M]=J.slice(0,-2)}function n3($,M){let J=[];if($.options)for(let Q of $.options)J.push(d6(Q));for(let Q of M)J.push(d6(Q));return J}function i3($){let M=[];M.push("'1:subcommand:->subcommand'");let J=$.map((Q)=>`'${Q.name}:${Q.description.replace(/'/g,"\\'")}'`).join(" ");return M.push("case $state in"),M.push(" subcommand)"),M.push(` local -a subcommands=(${J})`),M.push(" _describe 'subcommand' subcommands"),M.push(" ;;"),M.push("esac"),M}function l3($,M,J){let Q=[];Q.push(`${$.name})`);let Y=n3($,M);if(Y.length>0||$.hasPositionalArg||$.subcommands){Q.push(" _arguments \\");for(let X of Y)Q.push(` ${X} \\`);if($.subcommands&&$.subcommands.length>0){let X=i3($.subcommands);for(let Z of X)Q.push(` ${Z}`)}else if($.hasPositionalArg){let X=$.positionalArgDescription||"argument",Z=h3(X,$.positionalArgType,J);Q.push(` ${Z}`)}else g3(Q)}return Q.push(" ;;"),Q.join(`
|
|
363
|
+
`)}function a3($,M,J){return $.map((Y)=>l3(Y,M,J)).join(`
|
|
364
|
+
`)}function X7($,M){let J=u3,Q=KG.options||[],Y=[...M].toSorted((Z,q)=>Z.localeCompare(q)),G=J.map((Z)=>`'${Z.name}:${Z.description.replace(/'/g,"\\'")}'`).join(`
|
|
365
|
+
`);return oJ(`
|
|
366
366
|
#compdef {binaryName}
|
|
367
367
|
# Generated by Dotfiles Management Tool
|
|
368
368
|
# Do not edit this file manually - it will be overwritten
|
|
@@ -391,7 +391,7 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
391
391
|
}
|
|
392
392
|
|
|
393
393
|
_{binaryName} "$@"
|
|
394
|
-
`,{binaryName:$,commandDescriptions:
|
|
394
|
+
`,{binaryName:$,commandDescriptions:G,globalArgs:f3(Q),commandsCase:m3(),argsCases:a3(J,Q,Y)})}var Z7="dotfiles";async function s3($,M,J){let Q=$.getSubLogger({name:"generateCliCompletions"}),{projectConfig:Y,fs:G}=M,X=X7(Z7,J),Z=u6.join(Y.paths.shellScriptsDir,"zsh","completions"),q=u6.join(Z,`_${Z7}`);await G.ensureDir(Z),await G.writeFile(q,X),Q.debug(R.cliCompletionGenerated(q))}function W7($,M,J){let Q=$.getSubLogger({name:"registerGenerateCommand"});M.command("generate").description("Generates shims, shell init files, and symlinks based on tool configurations.").option("--overwrite","Overwrite conflicting files that were not created by the generator").action(async(Y)=>{let G={...Y,...M.opts()},X=await J(),{projectConfig:Z,fs:q,generatorOrchestrator:I,configService:U,systemInfo:K,installer:H}=X;try{Q.debug(R.toolConfigsLoading(Z.paths.toolConfigsDir),q.constructor.name);let _=await U.loadToolConfigs(Q,Z.paths.toolConfigsDir,q,Z,K);Q.debug(R.toolConfigsLoaded(Z.paths.toolConfigsDir,Object.keys(_).length));let O=u6.join(Z.paths.generatedDir,"tool-types.d.ts");await l6(_,O,q),Q.debug(R.toolTypesGenerated(O)),await I.generateAll(_,{overwrite:G.overwrite,installer:H});let B=Object.keys(_).toSorted((j,V)=>j.localeCompare(V));await s3(Q,X,B),Q.info(R.commandCompleted(Boolean(G.dryRun)))}catch(_){Q.error(R.commandExecutionFailed("generate",1)),N(1)}})}import{Database as r3}from"bun:sqlite";import{mkdirSync as t3}from"fs";import o3 from"path";var f6={initialized:()=>W("Initialized SQLite file registry at: %s"),sqlitePragmaConfigFailed:()=>W("Failed to configure SQLite pragmas; continuing with defaults")};class p6{db;logger;constructor($,M){this.logger=$.getSubLogger({name:"RegistryDatabase"});let J=o3.dirname(M);t3(J,{recursive:!0}),this.db=new r3(M),this.configureConnectionPragmas(),this.logger.debug(f6.initialized(),"shared connection")}configureConnectionPragmas(){try{this.db.run("PRAGMA busy_timeout = 5000;"),this.db.run("PRAGMA journal_mode = WAL;"),this.db.run("PRAGMA synchronous = NORMAL;")}catch($){this.logger.warn(f6.sqlitePragmaConfigFailed(),$)}}getConnection(){return this.db}close(){this.db.close()}}var g$={databaseInitialized:()=>W("Database initialized"),toolInstallationRecorded:()=>W("Tool installation recorded: %s version %s"),toolInstallationNotFound:()=>W("Tool installation not found: %s"),toolInstallationsRetrieved:()=>W("Retrieved %d tool installations"),noUpdatesProvided:()=>W("No updates provided for tool: %s"),toolInstallationUpdated:()=>W("Tool installation updated: %s"),toolInstallationRemoved:()=>W("Tool installation removed: %s"),toolInstallationCheckCompleted:()=>W("Tool installation check: %s version %s - installed: %s"),databaseClosed:()=>W("Database closed")};class c6{db;logger;constructor($,M){this.logger=$.getSubLogger({name:"ToolInstallationRegistry"}),this.db=M,this.initializeDatabase()}initializeDatabase(){let $=this.logger.getSubLogger({name:"initializeDatabase"});this.db.run(`
|
|
395
395
|
CREATE TABLE IF NOT EXISTS tool_installations (
|
|
396
396
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
397
397
|
tool_name TEXT NOT NULL UNIQUE,
|
|
@@ -425,15 +425,15 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
425
425
|
SELECT * FROM tool_installations WHERE tool_name = ?
|
|
426
426
|
`).get($);if(!Q)return M.debug(g$.toolInstallationNotFound(),$),null;return{id:Q.id,toolName:Q.tool_name,version:Q.version,installPath:Q.install_path,timestamp:Q.timestamp,installedAt:new Date(Q.installed_at),binaryPaths:JSON.parse(Q.binary_paths),downloadUrl:Q.download_url||void 0,assetName:Q.asset_name||void 0,configuredVersion:Q.configured_version||void 0,originalTag:Q.original_tag||void 0,installMethod:Q.install_method||void 0}}async getAllToolInstallations(){let $=this.logger.getSubLogger({name:"getAllToolInstallations"}),J=this.db.prepare(`
|
|
427
427
|
SELECT * FROM tool_installations ORDER BY tool_name
|
|
428
|
-
`).all();return $.debug(g$.toolInstallationsRetrieved(),J.length),J.map((Q)=>({id:Q.id,toolName:Q.tool_name,version:Q.version,installPath:Q.install_path,timestamp:Q.timestamp,installedAt:new Date(Q.installed_at),binaryPaths:JSON.parse(Q.binary_paths),downloadUrl:Q.download_url||void 0,assetName:Q.asset_name||void 0,configuredVersion:Q.configured_version||void 0,originalTag:Q.original_tag||void 0,installMethod:Q.install_method||void 0}))}async updateToolInstallation($,M){let J=this.logger.getSubLogger({name:"updateToolInstallation"}),Q=[],
|
|
428
|
+
`).all();return $.debug(g$.toolInstallationsRetrieved(),J.length),J.map((Q)=>({id:Q.id,toolName:Q.tool_name,version:Q.version,installPath:Q.install_path,timestamp:Q.timestamp,installedAt:new Date(Q.installed_at),binaryPaths:JSON.parse(Q.binary_paths),downloadUrl:Q.download_url||void 0,assetName:Q.asset_name||void 0,configuredVersion:Q.configured_version||void 0,originalTag:Q.original_tag||void 0,installMethod:Q.install_method||void 0}))}async updateToolInstallation($,M){let J=this.logger.getSubLogger({name:"updateToolInstallation"}),Q=[],Y=[];if(M.version!==void 0)Q.push("version = ?"),Y.push(M.version);if(M.installPath!==void 0)Q.push("install_path = ?"),Y.push(M.installPath);if(M.timestamp!==void 0)Q.push("timestamp = ?"),Y.push(M.timestamp);if(M.binaryPaths!==void 0)Q.push("binary_paths = ?"),Y.push(JSON.stringify(M.binaryPaths));if(M.downloadUrl!==void 0)Q.push("download_url = ?"),Y.push(M.downloadUrl);if(M.assetName!==void 0)Q.push("asset_name = ?"),Y.push(M.assetName);if(M.configuredVersion!==void 0)Q.push("configured_version = ?"),Y.push(M.configuredVersion);if(M.originalTag!==void 0)Q.push("original_tag = ?"),Y.push(M.originalTag);if(Q.length===0){J.debug(g$.noUpdatesProvided(),$);return}Y.push($),this.db.prepare(`
|
|
429
429
|
UPDATE tool_installations SET ${Q.join(", ")} WHERE tool_name = ?
|
|
430
|
-
`).run(...
|
|
430
|
+
`).run(...Y),J.debug(g$.toolInstallationUpdated(),$)}async removeToolInstallation($){let M=this.logger.getSubLogger({name:"removeToolInstallation"});this.db.prepare(`
|
|
431
431
|
DELETE FROM tool_installations WHERE tool_name = ?
|
|
432
|
-
`).run($),M.debug(g$.toolInstallationRemoved(),$)}async isToolInstalled($,M){let J=this.logger.getSubLogger({name:"isToolInstalled"});if(M){let
|
|
432
|
+
`).run($),M.debug(g$.toolInstallationRemoved(),$)}async isToolInstalled($,M){let J=this.logger.getSubLogger({name:"isToolInstalled"});if(M){let G=this.db.prepare(`
|
|
433
433
|
SELECT 1 FROM tool_installations WHERE tool_name = ? AND version = ?
|
|
434
|
-
`).get($,M)!==null;return J.debug(g$.toolInstallationCheckCompleted(),$,M,
|
|
434
|
+
`).get($,M)!==null;return J.debug(g$.toolInstallationCheckCompleted(),$,M,G),G}else{let G=this.db.prepare(`
|
|
435
435
|
SELECT 1 FROM tool_installations WHERE tool_name = ?
|
|
436
|
-
`).get($)!==null;return J.debug(g$.toolInstallationCheckCompleted(),$,"any",
|
|
436
|
+
`).get($)!==null;return J.debug(g$.toolInstallationCheckCompleted(),$,"any",G),G}}async recordToolUsage($,M){let J=Date.now();this.db.prepare(`
|
|
437
437
|
INSERT INTO tool_usage (tool_name, binary_name, usage_count, last_used_at)
|
|
438
438
|
VALUES (?, ?, 1, ?)
|
|
439
439
|
ON CONFLICT(tool_name, binary_name)
|
|
@@ -444,6 +444,6 @@ ${M}`),noConflictsDetected:()=>W("No conflicts detected"),cleanupAllTrackedFiles
|
|
|
444
444
|
SELECT tool_name, binary_name, usage_count, last_used_at
|
|
445
445
|
FROM tool_usage
|
|
446
446
|
WHERE tool_name = ? AND binary_name = ?
|
|
447
|
-
`).get($,M);if(!Q)return null;return{toolName:Q.tool_name,binaryName:Q.binary_name,usageCount:Q.usage_count,lastUsedAt:new Date(Q.last_used_at)}}async close(){let $=this.logger.getSubLogger({name:"close"});this.db.close(),$.debug(g$.databaseClosed())}}import
|
|
447
|
+
`).get($,M);if(!Q)return null;return{toolName:Q.tool_name,binaryName:Q.binary_name,usageCount:Q.usage_count,lastUsedAt:new Date(Q.last_used_at)}}async close(){let $=this.logger.getSubLogger({name:"close"});this.db.close(),$.debug(g$.databaseClosed())}}import I7 from"os";import M5 from"path";import C0 from"path";var e3=["dotfiles.config.ts"],$5=["project.json",".git"];async function q7($,M,J){let Q=$.getSubLogger({name:"resolveConfigPath"}),{cwd:Y,homeDir:G}=J,X=new z$;if(M.length>0){let I=M.startsWith("~")?M.replace(/^~(?=$|\/|\\)/,G):M,U=C0.resolve(Y,I);return Q.debug(R.configPathResolved(U)),U}let Z=process.env[G$];if(Z){let I=C0.join(Z,HM);if(await X.exists(I))return Q.debug(R.envConfigFromEnvVar(I)),I}let q=Y;while(!0){for(let U of e3){let K=C0.join(q,U);if(await X.exists(K))return Q.debug(R.configPathResolved(K)),K}if(q===G)break;for(let U of $5)if(await X.exists(C0.join(q,U)))return;let I=C0.dirname(q);if(I===q)break;q=I}return}function J5($,M){let J=M.platform||process.platform,Q=M.arch||process.arch;if(M.warnOnPlatformArchOverride){if(M.platform)$.warn(R.configParameterOverridden("platform",M.platform));if(M.arch)$.warn(R.configParameterOverridden("arch",M.arch))}return{platform:$Y(J),arch:MY(Q),homeDir:I7.homedir(),hostname:I7.hostname()}}async function aJ($,M){let J=$.getSubLogger({name:"createBaseRuntimeContext"}),Q=J5($,M),Y=await q7(J,M.config,{cwd:M.cwd,homeDir:Q.homeDir});if(!Y)return null;let G=M.configFileSystem??M.fileSystem,X=await g9(J,G,Y,Q,M.env),Z={...Q,homeDir:X.paths.homeDir},q=M5.join(X.paths.generatedDir,"registry.db"),I=new p6($,q),U=I.getConnection(),K=$.getSubLogger({context:"system"}),H=new zQ(K,U),_=new c6(K,U);return{projectConfig:X,systemInfo:Z,registryPath:q,registryDatabase:I,fileRegistry:H,toolInstallationRegistry:_}}async function U7($,M){let J=new z$,Q=await aJ($,{config:M.config,cwd:M.cwd,env:M.env,platform:M.platform,arch:M.arch,fileSystem:J});if(!Q)return null;return{projectConfig:Q.projectConfig,systemInfo:Q.systemInfo,toolInstallationRegistry:Q.toolInstallationRegistry,close:()=>{Q.registryDatabase.close()}}}function Q5($){let M=$.indexOf("@track-usage");if(M<0)return null;let J=[],Q="",Y,G;for(let q=2;q<$.length;q+=1){let I=$[q];if(!I)continue;if(I==="@track-usage")continue;if(I==="--config"||I==="--platform"||I==="--arch"){let U=$[q+1];if(!U)continue;if(I==="--config")Q=U;if(I==="--platform")Y=U;if(I==="--arch")G=U;q+=1;continue}if(q>M&&!I.startsWith("-"))J.push(I)}let X=J[0],Z=J[1];if(!X||!Z)return null;return{toolName:X,binaryName:Z,config:Q,platform:Y,arch:G}}async function K7($){let M=Q5($);if(!M)return;let J={getSubLogger:()=>J,trace:()=>{return},debug:()=>{return},info:()=>{return},warn:()=>{return},error:()=>{return},fatal:()=>{return},setPrefix:()=>J},Q=await U7(J,{config:M.config,cwd:process.cwd(),env:process.env,platform:M.platform,arch:M.arch});if(!Q)return;try{await Q.toolInstallationRegistry.recordToolUsage(M.toolName,M.binaryName)}finally{Q.close()}}import H7 from"path";async function _7($,M){let J=$.getSubLogger({name:"populateMemFsForDryRun"}),{sourceFs:Q,targetFs:Y,toolConfigsDir:G,homeDir:X}=M;if(J.trace(R.toolConfigsForDryRun()),!await Q.exists(G)){J.warn(R.fsItemNotFound("Tool configs directory",G));return}let Z=await R7(J,Q,G);J.trace(R.toolConfigsLoaded(G,Z.length));for(let q of Z)await Y5(J,Q,Y,q,X)}async function R7($,M,J){let Q=[];try{let Y=await M.readdir(J);for(let G of Y){let X=H7.join(J,G);try{if((await M.stat(X)).isDirectory()){let q=await R7($,M,X);Q.push(...q)}else Q.push(X)}catch(Z){$.debug(R.fsReadFailed(X),Z)}}}catch(Y){$.debug(R.fsReadFailed(J),Y)}return Q}async function Y5($,M,J,Q,Y){try{let G=await M.readFile(Q,"utf8");await J.ensureDir(H7.dirname(Q)),await J.writeFile(Q,G),$.trace(R.fsWrite("memfs",s(Y,Q)))}catch(G){$.error(R.fsReadFailed(Q),G)}}function O7($){return async(M,J)=>{let Q=$(M,J);if(Q instanceof Promise)return Q;return Q}}async function X5($,M=2000){return new Promise((J)=>{let Q=new G5.Socket,Y=()=>{Q.removeAllListeners(),Q.destroy()};Q.setTimeout(M),Q.on("connect",()=>{Y(),J(!0)}),Q.on("timeout",()=>{Y(),J(!1)}),Q.on("error",()=>{Y(),J(!1)}),Q.connect($,"localhost")})}function Z5($){if(typeof $>"u")return{port:void 0,invalidValue:void 0};let M=$.trim();if(!/^\d+$/.test(M))return{port:void 0,invalidValue:$};let Q=Number.parseInt(M,10);if(!(Q>=1&&Q<=65535))return{port:void 0,invalidValue:$};return{port:Q,invalidValue:void 0}}function W5($,M){let J;if(M)$.trace(R.dryRunEnabled()),J=new $J({});else J=new z$;return $.trace(R.componentInitialized("filesystem"),J.constructor.name),J}function q5($,M,J){if(!J.downloader.cache.enabled){$.info(R.cachingDisabled());return}let Q=K0.join(J.paths.generatedDir,"cache","downloads");return new MM($,M,{enabled:!0,defaultTtl:J.downloader.cache.ttl,cacheDir:Q,storageStrategy:"binary"})}function I5($,M,J,Q){let Y=new f($,M,J,f.createContext("system","shim"),Q),G=new f($,M,J,f.createContext("system","init"),Q),X=new f($,M,J,f.createContext("system","symlink"),Q),Z=new f($,M,J,f.createContext("system","copy"),Q),q=new f($,M,J,f.createContext("system","binary"),Q),I=new f($,M,J,f.createContext("system","catalog"),Q),U=new f($,M,J,f.createContext("system","completion"),Q);return{shimTrackedFs:Y,shellInitTrackedFs:G,symlinkTrackedFs:X,copyTrackedFs:Z,installerTrackedFs:q,catalogTrackedFs:I,completionTrackedFs:U}}async function U5($,M){let J=$.getSubLogger({name:"setupServices"}),{dryRun:Q,env:Y,config:G}=M,X=W5(J,Q),Z=!process.env.BUN_TEST,q=Q&&Z?new z$:X,I=await aJ(J,{config:G,cwd:M.cwd,env:Y,platform:M.platform,arch:M.arch,fileSystem:X,configFileSystem:q,warnOnPlatformArchOverride:!0});if(!I)J.error(R.configNotFound()),process.exit(1);let{projectConfig:U,systemInfo:K,registryPath:H,fileRegistry:_,toolInstallationRegistry:O}=I,B=Y.DEV_PROXY,j=Z5(B),V=j.port;if(typeof j.invalidValue==="string")J.error(R.configParameterInvalid("DEV_PROXY",j.invalidValue,"an integer between 1 and 65535")),process.exit(1);if(typeof V==="number"){if(J.debug(R.proxyCheckingAvailability(V)),!await X5(V))J.error(R.proxyUnavailable(V)),process.exit(1);J.warn(R.proxyEnabled(V))}let D=new MJ(X,U.paths.homeDir);if(Q){let u0=new z$;await _7(J,{sourceFs:u0,targetFs:D,toolConfigsDir:U.paths.toolConfigsDir,homeDir:K.homeDir})}let A=q5($,D,U);$.debug(R.registryInitialized(H));let S=new EQ($,D,void 0,A,typeof V==="number"?{enabled:!0,port:V}:void 0),w=W$(),u=new MM($,D,{enabled:U.github.cache.enabled,defaultTtl:U.github.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","github-api"),storageStrategy:"json"}),i=new RJ($,U,S,u),E=new _J($,U,w,u),g=new MM($,D,{enabled:U.github.cache.enabled,defaultTtl:U.github.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","gitea-api"),storageStrategy:"json"}),$$=new MM($,D,{enabled:U.cargo.cratesIo.cache.enabled,defaultTtl:U.cargo.cratesIo.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","cargo","crates-io"),storageStrategy:"json"}),m=new MM($,D,{enabled:U.cargo.githubRaw.cache.enabled,defaultTtl:U.cargo.githubRaw.cache.ttl,cacheDir:K0.join(U.paths.generatedDir,"cache","cargo","github-raw"),storageStrategy:"json"}),o=new vQ($,U,S,$$,m),{shimTrackedFs:y,shellInitTrackedFs:I$,symlinkTrackedFs:r$,copyTrackedFs:d0,installerTrackedFs:T$,catalogTrackedFs:sJ,completionTrackedFs:h6}=I5($,D,_,U),kM=$.getSubLogger({context:"system"}),m6=new I6(kM,I$,U),rJ=new w6(kM,r$,U,K),g6=new S6(kM,d0,U,K),j7=new F0(kM,w),SM=new tQ($,D,w),_M=new LQ((u0)=>{process.stdout.write(u0)}),X$=new UQ($);X$.register(new cQ(T$,S,i,E,SM,U,_M)),X$.register(new iQ(T$,S,SM,_M,g)),X$.register(new NQ(w)),X$.register(new yQ(T$,S,o,SM,_M,U.cargo.githubRelease.host)),X$.register(new PQ(T$,S,_M,w)),X$.register(new CQ(T$,S,SM,_M,w)),X$.register(new D6(T$,S,_M,w)),X$.register(new hQ(T$,S,SM,_M,w,i,E)),X$.register(new aQ(T$)),X$.register(new A6(w)),X$.register(new L6(T$,w));let V7=X$.getExternallyManagedMethods(),z7=X$.getMissingBinaryMessagesByMethod(),n6=new T6(kM,y,U,K,V7,z7,O),tJ=new eQ(kM,h6,w,j7,{downloader:S,archiveExtractor:SM}),B7=new B6(kM,n6,m6,rJ,g6,tJ,K,U,_,D,h6),D7=new bQ(J,T$,D,U,O,K,X$,rJ,w,_M,tJ),A7=new b6(J,i),E7=new _6,F7=new V6(J,S,O,D,sJ,K0.join(U.paths.generatedDir,"cache","readme"),X$);return{projectConfig:U,fs:D,configService:E7,readmeService:F7,fileRegistry:_,toolInstallationRegistry:O,downloadCache:A,downloader:S,githubApiCache:u,cargoCratesIoCache:$$,cargoGithubRawCache:m,githubApiClient:i,cargoClient:o,shimGenerator:n6,shellInitGenerator:m6,symlinkGenerator:rJ,copyGenerator:g6,completionGenerator:tJ,generatorOrchestrator:B7,installer:D7,archiveExtractor:SM,versionChecker:A7,pluginRegistry:X$,systemInfo:K}}function K5($,M,J){let Q=$.getSubLogger({name:"registerAllCommands"});YG(Q,M,J),eG(Q,M,J),W7(Q,M,J),iG(Q,M,J),UG(Q,M,J),ZG(Q,M,J),G7(Q,M,J),dG(Q,M,J),M7(Q,M,J),rG(Q,M,J),Q7(Q,M,J),PG(Q,M,J),gG(Q,M)}function H5($,M){return $.includes(M)}var _5=new Set(["--config","--log","--platform","--arch"]);function R5($){for(let M=2;M<$.length;M+=1){let J=$[M];if(!J)continue;if(_5.has(J)){M+=1;continue}if(J.startsWith("-"))continue;return J}return}function O5($,M){let J=H5($,"--shim-mode"),Q=M.quiet||J;return KY(M.log,Q,M.verbose)}async function j5($){let M=HG();M.parseOptions($);let J=M.opts(),Q=O5($,J),G=qQ({name:"cli",level:Q,trace:J.trace}).getSubLogger({name:"main"});G.trace(R.cliStarted(),$),K5(G,M,async()=>{return await U5(G,{...J,cwd:process.cwd(),env:process.env})}),await M.parseAsync($)}async function V5($){if(R5($)==="@track-usage"){await K7($);return}await j5($)}V5(process.argv).catch(($)=>{qQ({name:"cli"}).fatal(R.commandExecutionFailed("main",1),$),process.exit(1)});export{U5 as setupServices,V5 as runCliEntrypoint,O5 as resolveLogLevel,K5 as registerAllCommands,j5 as main,O7 as defineTool,w1 as defineConfig,oJ as dedentTemplate,c as dedentString,E$ as Platform,OM as Architecture};
|
|
448
448
|
|
|
449
|
-
//# debugId=
|
|
449
|
+
//# debugId=988E990EE48F48C664756E2164756E21
|