var F=Object.defineProperty;var k=(e,r)=>F(e,"name",{value:r,configurable:!0});import{createRequire as B}from"node:module";import{d as U,R as v,a8 as W,n as b,y as K,al as G,am as Y,an as X,ao as Q}from"../packem_chunks/bin.js";const D=B(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,$=k(e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[r,a]=w.versions.node.split(".").map(Number);if(r>22||r===22&&a>=3||r===20&&a>=16)return w.getBuiltinModule(e)}return D(e)},"__cjs_getBuiltinModule"),{spawn:J,execFileSync:E}=$("node:child_process"),{existsSync:j}=$("node:fs"),{platform:z,homedir:M}=$("node:os"),{join:g}=$("node:path"),Z=/v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/,ee=5e3,re=1e4,te=3e5,ae=4096,T=z()==="win32",x=["amp","claude","codex","copilot","crush","cursor","droid","gemini","kimi","opencode","qwen"];var ne=Object.defineProperty,ie=k((e,r)=>ne(e,"name",{value:r,configurable:!0}),"O"),oe=Object.defineProperty,m=ie((e,r)=>oe(e,"name",{value:r,configurable:!0}),"a"),se=Object.defineProperty,ce=m((e,r)=>se(e,"name",{value:r,configurable:!0}),"a$6");const le={alternateCommands:[],buildArgs:ce((e,r,a)=>["-x",e,"--dangerously-allow-all"],"buildArgs"),command:"amp",defaultModel:"",envVariable:"AMP_PATH"};var ue=Object.defineProperty,de=m((e,r)=>ue(e,"name",{value:r,configurable:!0}),"t$8");const me={alternateCommands:[],buildArgs:de((e,r,a)=>["--dangerously-skip-permissions","--model",r,"--output-format","text","-p",e],"buildArgs"),command:"claude",defaultModel:"claude-sonnet-4-20250514",envVariable:"CLAUDE_PATH"};var pe=Object.defineProperty,ge=m((e,r)=>pe(e,"name",{value:r,configurable:!0}),"a$4");const fe={alternateCommands:["openai-codex"],buildArgs:ge((e,r,a)=>[e,"--approval-mode","full-auto","--quiet","--model",r,"--max-tokens",String(a)],"buildArgs"),command:"codex",defaultModel:"o3",envVariable:"CODEX_PATH"};var he=Object.defineProperty,ve=m((e,r)=>he(e,"name",{value:r,configurable:!0}),"l");const ye={alternateCommands:[],buildArgs:ve((e,r,a)=>{const t=["-p",e,"--allow-all-tools"];return r&&t.push("--model",r),t},"buildArgs"),command:"copilot",defaultModel:"",envVariable:"COPILOT_PATH"};var be=Object.defineProperty,ke=m((e,r)=>be(e,"name",{value:r,configurable:!0}),"n$2");const we={alternateCommands:[],buildArgs:ke((e,r,a)=>{const t=["run","--yolo"];return r&&t.push("-m",r),t.push(e),t},"buildArgs"),command:"crush",defaultModel:"",envVariable:"CRUSH_PATH"};var Ae=Object.defineProperty,$e=m((e,r)=>Ae(e,"name",{value:r,configurable:!0}),"t$5");const Se={alternateCommands:["cursor"],buildArgs:$e((e,r,a)=>{const t=["-p","--force","--output-format","text"];return r&&t.push("--model",r),t.push(e),t},"buildArgs"),command:"agent",defaultModel:"",envVariable:"CURSOR_PATH"};var Pe=Object.defineProperty,Te=m((e,r)=>Pe(e,"name",{value:r,configurable:!0}),"i");const Ce={alternateCommands:[],buildArgs:Te((e,r,a)=>{const t=[e,"--skip-permissions-unsafe","-o","text"];return r&&t.push("-m",r),t},"buildArgs"),command:"droid",defaultModel:"",envVariable:"DROID_PATH"};var je=Object.defineProperty,Oe=m((e,r)=>je(e,"name",{value:r,configurable:!0}),"o$1");const Re={alternateCommands:["gemini-cli"],buildArgs:Oe((e,r,a)=>["--sandbox","--model",r,"--max-output-tokens",String(a),"-p",e],"buildArgs"),command:"gemini",defaultModel:"gemini-2.5-pro",envVariable:"GEMINI_PATH"};var Ee=Object.defineProperty,Me=m((e,r)=>Ee(e,"name",{value:r,configurable:!0}),"o");const xe={alternateCommands:[],buildArgs:Me((e,r,a)=>{const t=["--quiet","-p",e];return r&&t.push("-m",r),t},"buildArgs"),command:"kimi",defaultModel:"",envVariable:"KIMI_PATH"};var Ie=Object.defineProperty,_e=m((e,r)=>Ie(e,"name",{value:r,configurable:!0}),"r");const Ne={alternateCommands:[],buildArgs:_e((e,r,a)=>{const t=["run",e];return r&&t.push("-m",r),t},"buildArgs"),command:"opencode",defaultModel:"anthropic/claude-sonnet-4",envVariable:"OPENCODE_PATH"};var Le=Object.defineProperty,qe=m((e,r)=>Le(e,"name",{value:r,configurable:!0}),"n");const Ve={alternateCommands:["qwen-code"],buildArgs:qe((e,r,a)=>["-p",e,"--yolo","-o","text"],"buildArgs"),command:"qwen",defaultModel:"",envVariable:"QWEN_PATH"};var He=Object.defineProperty,f=m((e,r)=>He(e,"name",{value:r,configurable:!0}),"s");const I={amp:le,claude:me,codex:fe,copilot:ye,crush:we,cursor:Se,droid:Ce,gemini:Re,kimi:xe,opencode:Ne,qwen:Ve},O=f(e=>e==="~"||e.startsWith("~/")||T&&e.startsWith("~\\")?g(M(),e.slice(2)):e,"resolveHome"),Fe=f(e=>{try{const r=E(T?"where":"which",[e],{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:ee}).trim().split(`
`)[0]?.trim();return r&&r.length>0?r:void 0}catch{return}},"whichCommand"),Be=f(e=>{const r=M();if(T){const a=process.env.APPDATA??"",t=process.env.LOCALAPPDATA??"",n=process.env.ProgramFiles??"";return[g(a,"npm",`${e}.cmd`),g(a,"npm",e),g(t,"Programs",e,`${e}.exe`),g(n,e,`${e}.exe`),g(r,".npm-global","bin",`${e}.cmd`)]}return[`/opt/homebrew/bin/${e}`,`/usr/local/bin/${e}`,g(r,".npm-global","bin",e),g(r,".local","bin",e),g(r,".cargo","bin",e)]},"getKnownPaths"),S=f(e=>{try{const r=E(e,["--version"],{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:re}),a=Z.exec(r);return a?a[1]:void 0}catch{return}},"detectVersion"),_=f(e=>{const r=I[e],a={available:!1,name:e},t=process.env[r.envVariable];if(t&&j(O(t))){const i=O(t);return{...a,available:!0,detectionMethod:"envvar",path:i,version:S(i)}}const n=[r.command,...r.alternateCommands];for(const i of n){const o=Fe(i);if(o)return{...a,available:!0,detectionMethod:"which",path:o,version:S(o)}}for(const i of n)for(const o of Be(i))if(j(o))return{...a,available:!0,detectionMethod:"known-path",path:o,version:S(o)};return a},"detectProvider"),De=f(()=>x.map(e=>_(e)),"detectAllProviders"),Je=f(()=>De().filter(e=>e.available),"detectAvailableProviders"),ze=f((e,r,a={})=>{const t=I[e],n=a.model??t.defaultModel,i=a.maxTokens!==void 0&&Number.isFinite(a.maxTokens)?a.maxTokens:ae;return t.buildArgs(r,n,i)},"buildCliArgs"),Ue=f(async(e,r,a={})=>{if(!e.available||!e.path)throw new Error(`AI provider "${e.name}" is not available.`);const t=ze(e.name,r,a),n=a.timeoutMs!==void 0&&Number.isFinite(a.timeoutMs)?a.timeoutMs:te;return new Promise((i,o)=>{const p={env:{...process.env,FORCE_COLOR:"0",NO_COLOR:"1"},stdio:["pipe","pipe","pipe"]},s=J(e.path,t,p);s.stdin.end();let c="",d="",u=!1,y;const C=setTimeout(()=>{u=!0,s.kill("SIGTERM"),y=setTimeout(()=>s.kill("SIGKILL"),5e3),o(new Error(`${e.name} CLI timed out after ${String(n)}ms`))},n);s.stdout.on("data",h=>{c+=h.toString("utf8")}),s.stderr.on("data",h=>{d+=h.toString("utf8")}),s.on("close",h=>{clearTimeout(C),clearTimeout(y),!u&&(h===0?i({provider:e.name,stderr:d,stdout:c}):o(new Error(`${e.name} CLI exited with code ${String(h)}: ${d||c}`)))}),s.on("error",h=>{clearTimeout(C),clearTimeout(y),u||o(new Error(`Failed to spawn ${e.name} CLI: ${h.message}`))})})},"runProvider");var We=Object.defineProperty,N=k((e,r)=>We(e,"name",{value:r,configurable:!0}),"i");const Ke=12e4,Ge=2,Ye=1e3,Xe=N(e=>new Promise(r=>{setTimeout(r,e)}),"sleep"),L=N(async(e,r,a=Ge)=>{let t;for(let n=0;n<=a;n+=1)try{return(await Ue(e,r,{timeoutMs:Ke})).stdout}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t.message.includes("timed out"))throw t;if(n<a){const o=Ye*2**n;await Xe(o)}}throw t??new Error("AI request failed after retries")},"runWithRetry");var Qe=Object.defineProperty,l=k((e,r)=>Qe(e,"name",{value:r,configurable:!0}),"c");const Ze={amp:30,claude:80,codex:60,copilot:50,crush:35,cursor:40,droid:20,gemini:100,kimi:25,opencode:35,qwen:30},er=l(e=>{if(e?.provider){if(!x.includes(e.provider))return;const t=_(e.provider);return t.available?t:void 0}const r=Je();if(r.length===0)return;const a={...Ze,...e?.priority};return r.toSorted((t,n)=>(a[n.name]??0)-(a[t.name]??0))[0]},"resolveProvider"),rr=new Set(["defer","review","skip","update"]),tr=new Set(["critical","high","low","medium"]),ar=new Set(["high","low","medium"]),nr=50,P=30,ir=l(e=>e.map(r=>{const a=r.vulnerabilities&&r.vulnerabilities.length>0?` [VULNERABILITIES: ${r.vulnerabilities.map(n=>`${n.severity} ${n.id}`).join(", ")}]`:"";let t="";if(r.socketReport){const n=Math.round(r.socketReport.score.overall*100),i=[`score:${String(n)}%`];if(r.socketReport.alerts.length>0){const o={};for(const s of r.socketReport.alerts)o[s.severity]=(o[s.severity]??0)+1;const p=Object.entries(o).map(([s,c])=>`${String(c)} ${s}`).join(", ");i.push(`alerts: ${p}`)}i.push(`supply-chain:${String(Math.round(r.socketReport.score.supplyChain*100))}%`),i.push(`quality:${String(Math.round(r.socketReport.score.quality*100))}%`),t=` [SOCKET.DEV: ${i.join(", ")}]`}return`- ${r.packageName}: ${r.currentRange} → ${r.newRange} (${r.updateType})${a}${t}`}).join(`
`),"buildPackageList"),A=`Respond ONLY with valid JSON in this exact structure:
{
  "summary": "Brief overall summary",
  "recommendations": [
    {
      "package": "package-name",
      "action": "update|skip|review|defer",
      "reason": "explanation",
      "riskLevel": "low|medium|high|critical",
      "breakingChanges": ["change1"],
      "effort": "low|medium|high"
    }
  ],
  "warnings": ["warning1"]
}`,or={compatibility:l(e=>`Analyze the compatibility of these package updates:

${e}

For each package:
1. Check peer dependency compatibility
2. Identify potential conflicts with other packages in the list
3. Assess API compatibility between current and target versions
4. Check for deprecated features being removed
5. Evaluate Node.js version requirements

${A}`,"compatibility"),impact:l(e=>`Analyze the impact of updating these npm packages:

${e}

For each package, provide:
1. Risk level (low/medium/high/critical)
2. Recommended action (update/skip/review/defer)
3. Reason for recommendation
4. Known breaking changes (if any)
5. Estimated migration effort (low/medium/high)

${A}`,"impact"),recommend:l(e=>`Provide smart recommendations for updating these packages:

${e}

Consider:
1. Update priority based on security, features, and stability
2. Grouping related packages for atomic updates
3. Best practices for the specific package ecosystem
4. Risk vs. benefit analysis
5. Suggested update order
6. If Socket.dev scores are provided, prioritize packages with low supply chain or quality scores

${A}`,"recommend"),security:l(e=>`Analyze the security implications of these package updates:

${e}

For each package:
1. Check if the update fixes known vulnerabilities (use the vulnerability data above)
2. Assess if the new version introduces security risks
3. Evaluate if this is a security-sensitive package (auth, crypto, session, etc.)
4. Recommend urgency of the update based on vulnerability severity
5. Flag any packages where skipping the update poses security risk
6. If Socket.dev scores are provided, factor in supply chain and quality scores — low scores indicate higher risk

${A}`,"security")},sr=new Set(["compatibility","impact","recommend","security"]),br=l(e=>sr.has(e)?e:"impact","validateAnalysisType"),q=l((e,r="impact")=>{const a=ir(e);return or[r](a)},"buildAnalysisPrompt"),cr=/```(?:json)?\s*([\s\S]*?)```/,lr=/\{[\s\S]*\}/,ur=l(e=>{try{return JSON.parse(e)}catch{}const r=cr.exec(e);if(r?.[1])try{return JSON.parse(r[1])}catch{}const a=lr.exec(e);if(a?.[0])try{return JSON.parse(a[0])}catch{}},"extractJson"),dr=l(e=>({action:rr.has(e.action)?e.action:"review",breakingChanges:Array.isArray(e.breakingChanges)?e.breakingChanges:[],effort:ar.has(e.effort)?e.effort:"medium",package:typeof e.package=="string"?e.package:"",reason:typeof e.reason=="string"?e.reason:"",riskLevel:tr.has(e.riskLevel)?e.riskLevel:"medium"}),"normalizeRecommendation"),V=l((e,r,a)=>{const t=ur(e);if(!t||typeof t!="object")return{analysisType:a,provider:r,recommendations:[],summary:"Failed to parse AI response.",warnings:["AI response was not valid JSON."]};const n=t,i=Array.isArray(n.recommendations)?n.recommendations:[];return{analysisType:a,provider:r,recommendations:i.map(o=>dr(o)),summary:typeof n.summary=="string"?n.summary:"",warnings:Array.isArray(n.warnings)?n.warnings:[]}},"parseAiResponse"),mr={eslint:["ESLint 9.0: Flat config required","ESLint 8.0+: New rule formats"],next:["Next.js 13+: App router changes","Next.js 14+: Server components default"],react:["React 17 to 18: Concurrent features","React 18+: Strict mode changes"],typescript:["TypeScript 5.0: New decorators","TypeScript 4.7+: ESM changes"],vite:["Vite 5: Node.js 18+ required"],vue:["Vue 3: Composition API","Vue 3: Breaking template changes"],webpack:["Webpack 5: Node.js polyfills removed"]},pr=new Set(["bcrypt","cors","crypto-js","express-session","helmet","jose","jsonwebtoken","node-forge","oauth","passport"]),R=l((e,r)=>{const a=e.map(t=>{const n=t.vulnerabilities&&t.vulnerabilities.length>0,i=pr.has(t.packageName),o=mr[t.packageName]??[];let p="low",s="update",c="low",d="Patch/minor update, safe to apply.";return t.updateType==="major"?(p="high",s=o.length>0?"review":"update",c="medium",d=o.length>0?`Major update with known breaking changes: ${o[0]}`:"Major version update, review changelog before applying."):t.updateType==="minor"&&(p="medium",d="Minor update, generally safe."),n&&(p="high",s="update",d="Security update — current version has known vulnerabilities."),i&&t.updateType==="major"&&(s="review",d="Security-sensitive package with major update, careful review needed.",c="high"),{action:s,breakingChanges:o,effort:c,package:t.packageName,reason:d,riskLevel:p}});return{analysisType:r,provider:"rule-engine",recommendations:a,summary:`Rule-based ${r} analysis for ${String(e.length)} packages.`,warnings:["No AI provider available — using built-in rule engine."]}},"ruleBasedAnalysis"),gr=l(async(e,r,a)=>{const t=q(r,a),n=await L(e,t);return V(n,e.name,a)},"analyzeChunk"),fr=l((e,r,a)=>{const t=[],n=[],i=[];for(const o of e)t.push(...o.recommendations),n.push(...o.warnings),o.summary&&i.push(o.summary);return{analysisType:a,provider:r,recommendations:t,summary:i.length===1?i[0]??"":`Analyzed ${String(t.length)} packages in ${String(e.length)} batches.`,warnings:[...new Set(n)]}},"mergeResults"),H={compatibility:"Compatibility",impact:"Impact",recommend:"Recommendations",security:"Security"},kr=l(e=>{const r=`${H[e.analysisType]??e.analysisType} Analysis (${e.provider})`,a=e.recommendations.flatMap(n=>{const i=[{action:n.action,effort:n.effort,package:n.package,reason:n.reason,risk:n.riskLevel}];return n.breakingChanges.length>0&&i.push({action:"",effort:"",package:"",reason:`Breaking: ${n.breakingChanges.join("; ")}`,risk:""}),i}),t=process.stdout.columns||80;return U(v.createElement(W,{borderStyle:"round",flexDirection:"column",paddingLeft:1,paddingRight:1},v.createElement(b,{bold:!0},r),v.createElement(b,null,""),v.createElement(b,null,e.summary),v.createElement(b,null,""),v.createElement(K,{borderStyle:"none",data:a}),...e.warnings.length>0?[v.createElement(b,null,""),...e.warnings.map((n,i)=>v.createElement(b,{dimColor:!0,key:String(i)},`  ${n}`))]:[]),{columns:t})},"formatAiAnalysis");l(e=>JSON.stringify(e,void 0,2),"formatAiAnalysisJson");const wr=l(async(e,r,a,t="impact")=>{const n=er(a);if(!n)return r.info(`No AI CLI tool found, using rule-based analysis.
`),R(e,t);const i=G(n.name,t,e),o=Y(i);if(o)return r.info(`Using cached ${t} analysis from ${o.provider}.
`),o;const p=H[t]??t;r.info(`Running ${p.toLowerCase()} analysis with ${n.name}...
`);try{let s;if(e.length>nr){r.info(`Splitting ${String(e.length)} packages into batches of ${String(P)}...
`);const c=[];for(let u=0;u<e.length;u+=P)c.push(e.slice(u,u+P));const d=[];for(let u=0;u<c.length;u+=1){r.info(`  Batch ${String(u+1)}/${String(c.length)}...`);const y=c[u];y&&d.push(await gr(n,y,t))}s=fr(d,n.name,t)}else{const c=await L(n,q(e,t));s=V(c,n.name,t)}return X(i,s,Q(t,a?.cacheTtl)),s}catch(s){const c=s instanceof Error?s.message:String(s);return r.warn(`AI analysis failed (${c}), falling back to rule engine.
`),R(e,t)}},"runAiAnalysis");export{br as H,Ze as R,kr as Z,De as _,er as b,wr as e,Ue as h,L as r,ur as w};
