infra-kit 0.3.7 → 0.3.8

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/dist/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{$ as $t,A as te,B as ft,C as U,D as d,E as gt,F as ht,G as vt,H as yt,I as wt,J as St,K as kt,L as Rt,M as Et,N as oe,O as xt,P as Tt,Q as At,R as bt,S as Ct,T as Pt,U as It,V as Nt,W as Lt,X as _t,Y as Dt,Z as Ot,a as D,aa as Ft,b as De,ba as Ut,c as $e,d as Fe,e as Me,f as O,g as He,h as j,i as Ye,j as ze,k as Xe,l as Qe,m as Ze,n as tt,o as ot,p as rt,q as Z,r as nt,s as it,t as ee,u as ct,v as lt,w as mt,x as dt,y as ut,z as pt}from"./chunk-IURGCRSN.js";import{t as re}from"./chunk-XTRPE4SX.js";import{a as Mt,b as G,c as jt,d as b,e as ne,f as ie,g as se}from"./chunk-KAWDTA5H.js";import{a as et}from"./chunk-N6ML3SBF.js";import{a as st,b as at}from"./chunk-LKKKDB6V.js";import{b as Oe,c as T,d as h,e as F,f as We,g as Ke,h as Be,i as A,l as M}from"./chunk-7DL27USH.js";import{P as X,Q as Le,S as _e,n as Ne,v as l}from"./chunk-PZU6BLQR.js";import{a as $,b as je,d as Ue,f as Ge,g as qe,j as Q,k as Ve,n as v,q as Je}from"./chunk-CHETBZ6M.js";import"./chunk-X46DP23W.js";import en,{Separator as Eo}from"@inquirer/select";import{realpathSync as tn}from"node:fs";import g from"node:process";import{fileURLToPath as To}from"node:url";var bo=(e,t)=>{let o=e,r;for(let s of t){if(r=o.find(n=>n.name()===s),!r)return;o=r.commands}return r},Gt=e=>Dt.flatMap(({key:t,label:o})=>$t(t).flatMap(r=>{let s=bo(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as lr}from"commander";import _ from"node:process";import qt from"node:process";import{$ as Co}from"zx";var ae=async()=>{let e=await X(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await T(i.path)}))),o=t.at(-1)?.exists===!0,r=await ct(e.userProject,o),s=o?lt(r):"";l.info(`Project name: ${e.projectName}
2
+ import{A as ft,B as te,C as gt,D as I,E as d,F as ht,G as vt,H as yt,I as wt,J as St,K as kt,L as Rt,M as Et,N as xt,O as oe,P as Tt,Q as At,R as Ct,S as bt,T as Pt,U as It,V as Nt,W as Lt,X as Dt,Y as _t,Z as Ot,_ as $t,a as O,aa as Ft,b as _e,ba as Mt,c as $e,ca as Gt,d as Fe,e as Me,f as $,g as He,h as U,i as Ye,j as ze,k as Xe,l as Qe,m as Ze,n as tt,o as ot,p as rt,q as Z,r as nt,s as it,t as ee,u as ct,v as lt,w as mt,x as dt,y as ut,z as pt}from"./chunk-RDRJX6TT.js";import{t as re}from"./chunk-XTRPE4SX.js";import{a as jt,b as G,c as Ut,d as C,e as ne,f as ie,g as se}from"./chunk-KAWDTA5H.js";import{a as et}from"./chunk-3LPUAYWA.js";import{a as st,b as at}from"./chunk-LKKKDB6V.js";import{b as Oe,c as T,d as h,e as M,f as We,g as Be,h as Ke,i as A,l as j}from"./chunk-7DL27USH.js";import{P as X,Q as Le,S as De,n as Ne,v as l}from"./chunk-PZU6BLQR.js";import{a as F,b as je,d as Ue,f as Ge,g as qe,j as Q,k as Ve,n as v,q as Je}from"./chunk-CHETBZ6M.js";import"./chunk-X46DP23W.js";import tn,{Separator as xo}from"@inquirer/select";import{realpathSync as on}from"node:fs";import g from"node:process";import{fileURLToPath as Ao}from"node:url";var bo=(e,t)=>{let o=e,r;for(let s of t){if(r=o.find(n=>n.name()===s),!r)return;o=r.commands}return r},qt=e=>Ot.flatMap(({key:t,label:o})=>Ft(t).flatMap(r=>{let s=bo(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as mr}from"commander";import _ from"node:process";import Vt from"node:process";import{$ as Po}from"zx";var ae=async()=>{let e=await X(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await T(i.path)}))),o=t.at(-1)?.exists===!0,r=await ct(e.userProject,o),s=o?lt(r):"";l.info(`Project name: ${e.projectName}
3
3
  `),l.info(`Config merge chain (later overrides earlier):
4
- `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",a=i.path===e.userProject&&s!==""?` ${s}`:"";l.info(`${c} ${i.label.padEnd(22)} ${h(i.path)}${a}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ce=async()=>{let e=await X(),t=qt.env.EDITOR||qt.env.VISUAL||"vi",o=await tt(e);o.createdConfig&&l.info(ot(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await Co({stdio:"inherit"})`${t} ${e.userProject}`,_e();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var le=e=>{if(typeof e!="object"||e===null)return null;let{config:t,reason:o,at:r}=e;return typeof t!="string"||t.length===0||typeof o!="string"||typeof r!="number"||!Number.isFinite(r)?null:{config:t,reason:o,at:r}},I=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import p from"node:fs";import y from"node:path";import N from"node:process";var Po="autoload-warn-fail.flag",me="autoload-warn-auth-fail.flag",de="autoload-fail.flag",ue="autoload-auth-fail.json",Io=3e4,Jt=async(e=!0)=>{let t;try{t=await Le()}catch{return null}let o=t.envAutoLoad;if(!o)return null;let r={trigger:o.trigger,config:o.config,project:t.envManagement.config.name};try{if(await He(o.config))return r}catch{return r}return Kt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&q(I(o.config),me),null},Wt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:s,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===s?"skip":"load"},L=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Oe})=>{let s=e==="cli-invocation";s&&V();let n=null;try{if(n=await Jt(s),!n||Wt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:_o(),force:o})==="skip"||Vt()||$o())return null;let c=Do(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!Vt()&&!Oo(c)});return a?(Mo(),Lo(),a.filePath):null}catch(i){let c=i.message,a=r(i);return Fo(),a&&n&&Kt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(q(I(n.config),me),l.debug(`env auto-load auth failure: ${c}`)):s?q(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,Po):l.debug(`env auto-load skipped: ${c}`),null}},V=()=>{let e=No();e&&(q(I(e.config),me),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},No=()=>{try{let e=p.readFileSync(y.join(v(),ue),"utf-8");return le(JSON.parse(e))}catch{return null}},Kt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Je(y.join(t,ue),JSON.stringify(e),384)}catch{}},Lo=()=>{try{p.rmSync(y.join(v(),ue),{force:!0})}catch{}},_o=()=>({session:N.env[Ue],cleared:N.env[Ve],currentConfig:N.env[Ge],currentProject:N.env[qe],autoLoadedMarker:N.env[Q]}),Do=()=>{try{return p.statSync(y.join(v(),$)).mtimeMs}catch{return null}},Oo=e=>{try{let t=y.join(v(),$);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Q}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},Vt=()=>{try{let e=v(),t=y.join(e,je);if(!p.existsSync(t))return!1;let o=y.join(e,$);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},$o=()=>{try{let e=y.join(v(),de);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Io:!1}catch{return!1}},Fo=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,de),"",{mode:384})}catch{}},Mo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},q=(e,t)=>{try{let o=v(),r=y.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var pe=async({projectDir:e}={})=>{await L({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Bt="https://dashboard.doppler.com/workplace/projects",jo=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${Bt}/${e}`],fe=async({env:e})=>{let o=!!(await We())?.envs[e];await Be(e);let r=await j(),s=await O(),n=await F();o?l.info(`Removed the "${e}" service token from ${h(n)}.`):l.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let c of jo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Bt}/${s}`};return{content:D(JSON.stringify(i,null,2)),structuredContent:i}};import Uo from"@inquirer/password";import W from"node:process";import{$ as J}from"zx";var Go=async({stdin:e,fromEnv:t})=>{if(e)return{token:await qo(),source:"stdin"};if(t){let r=W.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return A.setInteractive(),{token:(await M(r=>Uo({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:W.stderr})).trim(),source:"prompt"}},qo=async()=>{let e=[];W.stdin.setEncoding("utf8");for await(let t of W.stdin)e.push(t);return e.join("").trim()},ge="DOPPLER_CONFIG",Vo=3e4,Jo=async(e,t,o)=>{let r=J.quiet;J.quiet=!0;let s;try{s=(await J({env:Xe(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(Vo)).stdout}catch(n){throw Wo(n,o)}finally{J.quiet=r}return Ze(s)},Wo=(e,t)=>{let o=Me(e)??(e instanceof Error?e.message:String(e));if($e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=Fe(o)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${r}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
4
+ `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",a=i.path===e.userProject&&s!==""?` ${s}`:"";l.info(`${c} ${i.label.padEnd(22)} ${h(i.path)}${a}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ce=async()=>{let e=await X(),t=Vt.env.EDITOR||Vt.env.VISUAL||"vi",o=await tt(e);o.createdConfig&&l.info(ot(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await Po({stdio:"inherit"})`${t} ${e.userProject}`,De();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var le=e=>{if(typeof e!="object"||e===null)return null;let{config:t,reason:o,at:r}=e;return typeof t!="string"||t.length===0||typeof o!="string"||typeof r!="number"||!Number.isFinite(r)?null:{config:t,reason:o,at:r}},N=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import p from"node:fs";import y from"node:path";import L from"node:process";var Io="autoload-warn-fail.flag",me="autoload-warn-auth-fail.flag",de="autoload-fail.flag",ue="autoload-auth-fail.json",No=3e4,Wt=async(e=!0)=>{let t;try{t=await Le()}catch{return null}let o=t.envAutoLoad;if(!o)return null;let r={trigger:o.trigger,config:o.config,project:t.envManagement.config.name};try{if(await He(o.config))return r}catch{return r}return Kt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&q(N(o.config),me),null},Bt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:s,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===s?"skip":"load"},D=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Oe})=>{let s=e==="cli-invocation";s&&V();let n=null;try{if(n=await Wt(s),!n||Bt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:_o(),force:o})==="skip"||Jt()||Fo())return null;let c=Oo(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!Jt()&&!$o(c)});return a?(jo(),Do(),a.filePath):null}catch(i){let c=i.message,a=r(i);return Mo(),a&&n&&Kt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(q(N(n.config),me),l.debug(`env auto-load auth failure: ${c}`)):s?q(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,Io):l.debug(`env auto-load skipped: ${c}`),null}},V=()=>{let e=Lo();e&&(q(N(e.config),me),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},Lo=()=>{try{let e=p.readFileSync(y.join(v(),ue),"utf-8");return le(JSON.parse(e))}catch{return null}},Kt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Je(y.join(t,ue),JSON.stringify(e),384)}catch{}},Do=()=>{try{p.rmSync(y.join(v(),ue),{force:!0})}catch{}},_o=()=>({session:L.env[Ue],cleared:L.env[Ve],currentConfig:L.env[Ge],currentProject:L.env[qe],autoLoadedMarker:L.env[Q]}),Oo=()=>{try{return p.statSync(y.join(v(),F)).mtimeMs}catch{return null}},$o=e=>{try{let t=y.join(v(),F);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Q}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},Jt=()=>{try{let e=v(),t=y.join(e,je);if(!p.existsSync(t))return!1;let o=y.join(e,F);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},Fo=()=>{try{let e=y.join(v(),de);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<No:!1}catch{return!1}},Mo=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,de),"",{mode:384})}catch{}},jo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},q=(e,t)=>{try{let o=v(),r=y.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var pe=async({projectDir:e}={})=>{await D({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Ht="https://dashboard.doppler.com/workplace/projects",Uo=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${Ht}/${e}`],fe=async({env:e})=>{let o=!!(await We())?.envs[e];await Ke(e);let r=await U(),s=await $(),n=await M();o?l.info(`Removed the "${e}" service token from ${h(n)}.`):l.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let c of Uo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Ht}/${s}`};return{content:O(JSON.stringify(i,null,2)),structuredContent:i}};import Go from"@inquirer/password";import W from"node:process";import{$ as J}from"zx";var qo=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Vo(),source:"stdin"};if(t){let r=W.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return A.setInteractive(),{token:(await j(r=>Go({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:W.stderr})).trim(),source:"prompt"}},Vo=async()=>{let e=[];W.stdin.setEncoding("utf8");for await(let t of W.stdin)e.push(t);return e.join("").trim()},ge="DOPPLER_CONFIG",Jo=3e4,Wo=async(e,t,o)=>{let r=J.quiet;J.quiet=!0;let s;try{s=(await J({env:Xe(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(Jo)).stdout}catch(n){throw Bo(n,o)}finally{J.quiet=r}return Ze(s)},Bo=(e,t)=>{let o=Me(e)??(e instanceof Error?e.message:String(e));if($e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=Fe(o)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${r}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
5
5
  `))},Ko=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${ge}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
6
- `),he=async({env:e,stdin:t,fromEnv:o,force:r})=>{let s=await O(),{token:n,source:i}=await Go({stdin:t,fromEnv:o});if(!n)throw new Error("No token provided \u2014 nothing was written.");let c=await Jo(n,s,e);Qe(c,e);let a=c.some(([k])=>k===ge);if(!a&&!r)throw new Error(Ko(e));await Ke(e,n);let m=await j(),u=await F();l.info(`Stored the "${e}" service token (${te(n)}) in ${h(u)} (mode 0600).`),a||l.warn(`Scope was NOT verified (no ${ge} in the payload) \u2014 written because --force was given.`),m.length>0&&l.info(`Purged ${m.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let f={env:e,source:i,redactedToken:te(n),storePath:u,scopeVerified:a,warmCachesPurged:m.length};return A.print(),{content:D(JSON.stringify(f,null,2)),structuredContent:f}};import{spawn as Bo}from"node:child_process";import K from"node:process";import{fileURLToPath as Ho}from"node:url";var Yo=["SIGINT","SIGTERM"],Ht=()=>Ho(new URL("./mcp.js",import.meta.url)),ve=(e={})=>{let t=e.spawn??Bo,o=e.exit??(i=>K.exit(i)),r=e.env??K.env,s=e.onError??(i=>l.error(i)),n=t(K.execPath,[Ht()],{stdio:"inherit",env:st(r)});n.on("error",i=>{s(`failed to launch the MCP server: ${i.message}`),o(1)}),Yo.forEach(i=>{K.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as zo}from"node:child_process";import{realpathSync as Xo}from"node:fs";import{homedir as Qo}from"node:os";import ye from"node:process";import{fileURLToPath as Zo}from"node:url";var er=()=>Xo(Zo(import.meta.url)),tr=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),we=({dryRun:e},t={})=>{let o=t.spawnSync??zo,r=t.print??(R=>l.info(R)),s=t.exit??(R=>ye.exit(R)),n=t.env??ye.env,i=t.selfRealPath??er(),c=t.lazyNpmRoot??jt,{manager:a,updateCommand:m,canSelfSpawn:u}=Mt({selfRealPath:i,env:n,realpath:b,lazyNpmRoot:c}),f=m.join(" ");if(e){r(`Detected install manager: ${a}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${a}`),r(`Run this yourself: ${f}`),r(a==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let k=o(m[0],m.slice(1),{stdio:"inherit",shell:ye.platform==="win32",cwd:Qo(),env:at(n)});tr(k,a,r,s)};import{VENDOR_CONFIG_FILE as zt}from"@slip-stream-kit/config/internal";import Se from"node:fs/promises";import ke from"node:path";import Yt from"node:process";import{pathToFileURL as or}from"node:url";var Xt="~/projects",Re=async(e={})=>{if(e.init){await nr(e.cwd);return}await rr()},rr=async()=>{let e=Z(),t=await T(e);if(l.info(`Factory config: ${h(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Yt.exitCode=1;return}let{workspaceDir:o,targets:r}=await it(),s=nt(o),n=await T(s);l.info(`workspaceDir: ${o} (resolved: ${s}) ${n?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=n;for(let c of r){let a=ke.join(s,c),m=await T(a);m||(i=!1);let u=m?"[\u2713]":"[ ]",f=m?"":" (not found \u2014 clone or remove)";l.info(` ${u} ${c} ${h(a)}${f}`)}i||(Yt.exitCode=1)},nr=async e=>{let t=Z();if(await T(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Ne(),r=await ir(o);await Se.mkdir(ke.dirname(t),{recursive:!0}),await Se.writeFile(t,sr(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${zt}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${Xt}) to point at where your repos live.`),r.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},ir=async e=>{try{let t=ke.join(e,zt),o=await Se.stat(t),n=(await import(`${or(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let c=i.targets;if(Array.isArray(c)&&c.every(a=>typeof a=="string"))return c}}catch{}return[]},sr=e=>`${JSON.stringify({workspaceDir:Xt,targets:e},null,2)}
7
- `;var B=(e,t=!0)=>({line:e,reproducible:t});import H from"node:fs";import ar from"node:os";import cr from"node:path";import to from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Ee=null,Qt=!1,Zt=[],oo=(e=to.env)=>{Qt||(Ee=e[Y]??null,Qt=!0,delete e[Y])};var ro=(e,t)=>{if(!Ee)return;let o=e.summary??(Zt.length>0?[...Zt]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{H.writeFileSync(n,i)});try{s(Ee,JSON.stringify(r))}catch{}},eo=0,no=e=>{let t=e?.tmpdir?.()??ar.tmpdir(),o=e?.pid??to.pid;return eo+=1,cr.join(t,`infra-kit-session-${o}-${eo}.json`)},io=(e,t)=>{if(!(t?.exists??(i=>H.existsSync(i)))(e))return null;let r=t?.read??(i=>H.readFileSync(i,"utf-8")),s=t?.unlink??(i=>H.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var mr=(e,t)=>[...t,e],xe=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,so=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&oe.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${oe.join(", ")}.`)}},dr=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await ht({all:t.all,confirmedCommand:t.yes}))}),ur=e=>e.description("List all release branches").action(async()=>{d(await St())}),pr=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',mr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(kt),s=r.length>0?r:void 0;d(await Rt({releases:s,confirmedCommand:t.yes}))}),fr=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await Et({version:t.version,description:t.description,confirmedCommand:t.yes}))}),gr=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await yt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),hr=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await wt({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),vr=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await vt({version:t.version,confirmedCommand:t.yes}))}),yr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await _t({confirmedCommand:t.yes}))}),wr=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=so(t.ide,"--ide")??so(t.cursor,"--cursor");d(await It({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Sr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await Nt())}),kr=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{d(await Lt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Rr=e=>e.description("Reopen editor + cmux windows for every active worktree in the current project (additive, idempotent)").option("--all","Reopen across every discovered infra-kit project (Stage 3 \u2014 not yet implemented)").option("--project <names...>","Restrict --all to these project names").option("--root <paths...>","Discovery roots for --all (repeatable)").option("--release-only","Restrict to release worktrees (reproduces the legacy worktrees-reload scope)").option("--force","Close each cmux workspace first, then reopen (the legacy worktrees-reload behaviour)").option("--dry-run","Print the plan (paths + cmux titles) and spawn nothing").action(async t=>{d(await xt({all:t.all,project:t.project,root:t.root,releaseOnly:t.releaseOnly,force:t.force,dryRun:t.dryRun}))}),Er=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{d(await Re({init:t.init}))}),xr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Tt();d(t),t.structuredContent.ok||(_.exitCode=1)}),Tr=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await At({repos:xe(t.repos)});d(o),o.structuredContent.ok||(_.exitCode=1)}),Ar=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await ae())}),br=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ce())}),Cr=new Set(["init","doctor","version","dev","self-update","mcp"]),Pr=e=>e.startsWith("env-")||Cr.has(e),Ir=new Set(["env-autoload","mcp","version","self-update"]),z=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Te=()=>{let e=new lr,t=e.command("release").description("Release management commands");dr(t.command("merge-dev")),ur(t.command("list")),pr(t.command("create")),fr(t.command("desc-edit")),gr(t.command("deploy-all")),hr(t.command("deploy-selected")),vr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");wr(o.command("add")),Sr(o.command("list")),kr(o.command("remove")),yr(o.command("sync")),Rr(e.command("reopen"));let r=e.command("config").description("Manage infra-kit configuration files");Ar(r.command("path")),br(r.command("edit")),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async n=>{let i=await De({all:n.all,root:n.root});d(i),i.structuredContent.allPassed||(_.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return xr(s.command("check")),s.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Ct({confirmedCommand:n.yes,repos:xe(n.repos)}))}),s.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await bt({confirmedCommand:!0,repos:xe(n.repos)}))}),Tr(s.command("diff")),Er(s.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").action(async n=>{d(await mt({fix:!!n.fix}))}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{we({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ve()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(_.stdout.isTTY&&_.stdin.isTTY);await c({...i,preset:n},a,U.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await Pt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(await pt())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{d(await ut())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await ee())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async n=>{d(await ze({config:n.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async n=>{d(await dt({purge:!!n.purge}))}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(n,i)=>{d(await he({env:n,stdin:i.stdin,fromEnv:i.fromEnv,force:i.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async n=>{d(await ft({check:!!n.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async n=>{d(await fe({env:n}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async n=>{await pe({projectDir:n.projectDir})}),e.commands.forEach(gt),e.hook("preAction",async(n,i)=>{A.start(z(i)),U.enabled=!!i.optsWithGlobals().json,U.enabled&&(l.level="warn"),Ir.has(z(i))||await rt(),V(),Pr(i.name())||await L({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=z(i);if(Ft(c))return;let m=A.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;ro({equivalent:B(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>`${r.padEnd(o)}${t}${s}`)};import{chalkStderr as jr}from"chalk";import{spawn as Ur}from"node:child_process";import S from"node:process";import{Chalk as Nr}from"chalk";var C=new Nr({level:1}),w={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},ao={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},co={unicode:"\u2500",ascii:"-"},Lr=3,be=e=>e,_r={ok:e=>C.green(e),findings:e=>C.yellow(e),failed:e=>C.red(e),cancelled:e=>C.gray(e)},mo=e=>e?{dim:t=>C.dim(t),bold:t=>C.bold(t)}:{dim:be,bold:be},Dr=(e,t)=>e?_r[t]:be,lo=e=>[...e].length,uo=(e,t={})=>{let o=mo(t.color===!0);return`${o.dim(w.reproPrefix.trim())} ${o.bold(e)}`},Or=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$r=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],Fr=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Lr?"":` ${r(o.repeat(s))}`},po=e=>{let t=e.color===!0,o=mo(t),r=Dr(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?ao[e.outcome].ascii:ao[e.outcome].unicode,c=$r(e.outcome,e.findingsCount),a=[Or(e.durationMs)],m=e.summary?.[0]?.split(`
8
- `)[0];m!=null&&m.length>0&&a.push(m);let u=`${i} ${c}`,f=`${w.sep}${a.join(w.sep)}`,k=lo(u)+lo(f),R=Fr(k,e.width,s?co.ascii:co.unicode,o.dim),x=[`${r(u)}${o.dim(f)}${R}`];return e.showEquivalent!==!1&&x.unshift(`${o.dim(n.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&x.push(o.dim(w.envNotice)),x.join(`
9
- `)};var Mr=new Set([130,143]),fo=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Mr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import go from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},ho=(e,t)=>{let o=t?.write??(n=>{go.stderr.write(n)}),r=t?.stdin??go.stdin,s=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&s.push(E.primaryBuffer),o(s.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var vo=e=>`infra-kit ${e.groupPath.join(" ")}`,Gr=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},qr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Vr=async(e,t,o)=>{let r=no(),s={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o();try{let f=t.spawn(S.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:s});i=await qr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=io(r),a=fo(i.code,i.signal,c!=null,e.longRunning),m=vo(e),u=c?.equivalent??B(m,!0);return po({equivalent:u,outcome:a,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===m)})},Jr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.resetTerminal(),t.exit(0)},n=()=>{if(!e()){t.resetTerminal(),t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",s),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",s),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},yo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),wo=async(e,t)=>{let o={spawn:t.spawn??Ur,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),color:t.color??jr.level>0,columns:t.columns??Gr,resetTerminal:t.resetTerminal??(a=>{ho(a)})},r=t.write??(a=>S.stderr.write(a)),s=t.signals??{register:(a,m)=>{S.on(a,m)},unregister:(a,m)=>{S.off(a,m)},exit:a=>{S.exit(a)},raise:a=>{S.kill(S.pid,a)},resetTerminal:()=>{o.resetTerminal({entersAltScreen:!1})}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Jr(()=>n,s);try{for(;;){if(c.quitRequested())return;n=!1;let a=await t.renderPalette(e);if(a==null)return;let m=t.resolveCommand(a);if(!m)continue;let u=uo(vo(m),{color:o.color});r(`
6
+ `),he=async({env:e,stdin:t,fromEnv:o,force:r})=>{let s=await $(),{token:n,source:i}=await qo({stdin:t,fromEnv:o});if(!n)throw new Error("No token provided \u2014 nothing was written.");let c=await Wo(n,s,e);Qe(c,e);let a=c.some(([k])=>k===ge);if(!a&&!r)throw new Error(Ko(e));await Be(e,n);let m=await U(),u=await M();l.info(`Stored the "${e}" service token (${te(n)}) in ${h(u)} (mode 0600).`),a||l.warn(`Scope was NOT verified (no ${ge} in the payload) \u2014 written because --force was given.`),m.length>0&&l.info(`Purged ${m.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let f={env:e,source:i,redactedToken:te(n),storePath:u,scopeVerified:a,warmCachesPurged:m.length};return A.print(),{content:O(JSON.stringify(f,null,2)),structuredContent:f}};import{spawn as Ho}from"node:child_process";import B from"node:process";import{fileURLToPath as Yo}from"node:url";var zo=["SIGINT","SIGTERM"],Yt=()=>Yo(new URL("./mcp.js",import.meta.url)),ve=(e={})=>{let t=e.spawn??Ho,o=e.exit??(i=>B.exit(i)),r=e.env??B.env,s=e.onError??(i=>l.error(i)),n=t(B.execPath,[Yt()],{stdio:"inherit",env:st(r)});n.on("error",i=>{s(`failed to launch the MCP server: ${i.message}`),o(1)}),zo.forEach(i=>{B.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as Xo}from"node:child_process";import{realpathSync as Qo}from"node:fs";import{homedir as Zo}from"node:os";import ye from"node:process";import{fileURLToPath as er}from"node:url";var tr=()=>Qo(er(import.meta.url)),or=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),we=({dryRun:e},t={})=>{let o=t.spawnSync??Xo,r=t.print??(R=>l.info(R)),s=t.exit??(R=>ye.exit(R)),n=t.env??ye.env,i=t.selfRealPath??tr(),c=t.lazyNpmRoot??Ut,{manager:a,updateCommand:m,canSelfSpawn:u}=jt({selfRealPath:i,env:n,realpath:C,lazyNpmRoot:c}),f=m.join(" ");if(e){r(`Detected install manager: ${a}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${a}`),r(`Run this yourself: ${f}`),r(a==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let k=o(m[0],m.slice(1),{stdio:"inherit",shell:ye.platform==="win32",cwd:Zo(),env:at(n)});or(k,a,r,s)};import{VENDOR_CONFIG_FILE as Xt}from"@slip-stream-kit/config/internal";import Se from"node:fs/promises";import ke from"node:path";import zt from"node:process";import{pathToFileURL as rr}from"node:url";var Qt="~/projects",Re=async(e={})=>{if(e.init){await ir(e.cwd);return}await nr()},nr=async()=>{let e=Z(),t=await T(e);if(l.info(`Factory config: ${h(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),zt.exitCode=1;return}let{workspaceDir:o,targets:r}=await it(),s=nt(o),n=await T(s);l.info(`workspaceDir: ${o} (resolved: ${s}) ${n?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=n;for(let c of r){let a=ke.join(s,c),m=await T(a);m||(i=!1);let u=m?"[\u2713]":"[ ]",f=m?"":" (not found \u2014 clone or remove)";l.info(` ${u} ${c} ${h(a)}${f}`)}i||(zt.exitCode=1)},ir=async e=>{let t=Z();if(await T(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Ne(),r=await sr(o);await Se.mkdir(ke.dirname(t),{recursive:!0}),await Se.writeFile(t,ar(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${Xt}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${Qt}) to point at where your repos live.`),r.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},sr=async e=>{try{let t=ke.join(e,Xt),o=await Se.stat(t),n=(await import(`${rr(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let c=i.targets;if(Array.isArray(c)&&c.every(a=>typeof a=="string"))return c}}catch{}return[]},ar=e=>`${JSON.stringify({workspaceDir:Qt,targets:e},null,2)}
7
+ `;var K=(e,t=!0)=>({line:e,reproducible:t});import H from"node:fs";import cr from"node:os";import lr from"node:path";import oo from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Ee=null,Zt=!1,eo=[],ro=(e=oo.env)=>{Zt||(Ee=e[Y]??null,Zt=!0,delete e[Y])};var no=(e,t)=>{if(!Ee)return;let o=e.summary??(eo.length>0?[...eo]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{H.writeFileSync(n,i)});try{s(Ee,JSON.stringify(r))}catch{}},to=0,io=e=>{let t=e?.tmpdir?.()??cr.tmpdir(),o=e?.pid??oo.pid;return to+=1,lr.join(t,`infra-kit-session-${o}-${to}.json`)},so=(e,t)=>{if(!(t?.exists??(i=>H.existsSync(i)))(e))return null;let r=t?.read??(i=>H.readFileSync(i,"utf-8")),s=t?.unlink??(i=>H.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var dr=(e,t)=>[...t,e],xe=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,ao=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&oe.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${oe.join(", ")}.`)}},ur=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await vt({all:t.all,confirmedCommand:t.yes}))}),pr=e=>e.description("List all release branches").action(async()=>{d(await kt())}),fr=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',dr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(Rt),s=r.length>0?r:void 0;d(await Et({releases:s,confirmedCommand:t.yes}))}),gr=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await xt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),hr=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await wt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),vr=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await St({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),yr=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await yt({version:t.version,confirmedCommand:t.yes}))}),wr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await _t({confirmedCommand:t.yes}))}),Sr=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=ao(t.ide,"--ide")??ao(t.cursor,"--cursor");d(await Nt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),kr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await Lt())}),Rr=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{d(await Dt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Er=e=>e.description("Reopen editor + cmux windows for every active worktree in the current project (additive, idempotent)").option("--all","Reopen across every discovered infra-kit project (Stage 3 \u2014 not yet implemented)").option("--project <names...>","Restrict --all to these project names").option("--root <paths...>","Discovery roots for --all (repeatable)").option("--release-only","Restrict to release worktrees (reproduces the legacy worktrees-reload scope)").option("--force","Close each cmux workspace first, then reopen (the legacy worktrees-reload behaviour)").option("--dry-run","Print the plan (paths + cmux titles) and spawn nothing").action(async t=>{d(await Tt({all:t.all,project:t.project,root:t.root,releaseOnly:t.releaseOnly,force:t.force,dryRun:t.dryRun}))}),xr=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{d(await Re({init:t.init}))}),Tr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await At();d(t),t.structuredContent.ok||(_.exitCode=1)}),Ar=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await Ct({repos:xe(t.repos)});d(o),o.structuredContent.ok||(_.exitCode=1)}),Cr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await ae())}),br=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ce())}),Pr=new Set(["init","doctor","version","dev","self-update","mcp"]),Ir=e=>e.startsWith("env-")||Pr.has(e),Nr=new Set(["env-autoload","mcp","version","self-update"]),z=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Te=()=>{let e=new mr,t=e.command("release").description("Release management commands");ur(t.command("merge-dev")),pr(t.command("list")),fr(t.command("create")),gr(t.command("desc-edit")),hr(t.command("deploy-all")),vr(t.command("deploy-selected")),yr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");Sr(o.command("add")),kr(o.command("list")),Rr(o.command("remove")),wr(o.command("sync")),Er(e.command("reopen"));let r=e.command("config").description("Manage infra-kit configuration files");Cr(r.command("path")),br(r.command("edit")),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async n=>{let i=await _e({all:n.all,root:n.root});d(i),i.structuredContent.allPassed||(_.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return Tr(s.command("check")),s.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Pt({confirmedCommand:n.yes,repos:xe(n.repos)}))}),s.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await bt({confirmedCommand:!0,repos:xe(n.repos)}))}),Ar(s.command("diff")),xr(s.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async n=>{let i=await mt({fix:!!n.fix});I.enabled||dt(i.structuredContent.checks,{ascii:!!n.ascii}),d(i)}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{we({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ve()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(_.stdout.isTTY&&_.stdin.isTTY);await c({...i,preset:n},a,I.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await It())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(await ft())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{d(await pt())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await ee())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async n=>{d(await ze({config:n.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async n=>{d(await ut({purge:!!n.purge}))}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(n,i)=>{d(await he({env:n,stdin:i.stdin,fromEnv:i.fromEnv,force:i.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async n=>{d(await gt({check:!!n.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async n=>{d(await fe({env:n}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async n=>{await pe({projectDir:n.projectDir})}),e.commands.forEach(ht),e.hook("preAction",async(n,i)=>{A.start(z(i)),I.enabled=!!i.optsWithGlobals().json,I.enabled&&(l.level="warn"),Nr.has(z(i))||await rt(),V(),Ir(i.name())||await D({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=z(i);if(Mt(c))return;let m=A.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;no({equivalent:K(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>`${r.padEnd(o)}${t}${s}`)};import{chalkStderr as Ur}from"chalk";import{spawn as Gr}from"node:child_process";import S from"node:process";import{Chalk as Lr}from"chalk";var b=new Lr({level:1}),w={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},co={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},lo={unicode:"\u2500",ascii:"-"},Dr=3,Ce=e=>e,_r={ok:e=>b.green(e),findings:e=>b.yellow(e),failed:e=>b.red(e),cancelled:e=>b.gray(e)},uo=e=>e?{dim:t=>b.dim(t),bold:t=>b.bold(t)}:{dim:Ce,bold:Ce},Or=(e,t)=>e?_r[t]:Ce,mo=e=>[...e].length,po=(e,t={})=>{let o=uo(t.color===!0);return`${o.dim(w.reproPrefix.trim())} ${o.bold(e)}`},$r=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,Fr=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],Mr=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Dr?"":` ${r(o.repeat(s))}`},fo=e=>{let t=e.color===!0,o=uo(t),r=Or(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?co[e.outcome].ascii:co[e.outcome].unicode,c=Fr(e.outcome,e.findingsCount),a=[$r(e.durationMs)],m=e.summary?.[0]?.split(`
8
+ `)[0];m!=null&&m.length>0&&a.push(m);let u=`${i} ${c}`,f=`${w.sep}${a.join(w.sep)}`,k=mo(u)+mo(f),R=Mr(k,e.width,s?lo.ascii:lo.unicode,o.dim),x=[`${r(u)}${o.dim(f)}${R}`];return e.showEquivalent!==!1&&x.unshift(`${o.dim(n.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&x.push(o.dim(w.envNotice)),x.join(`
9
+ `)};var jr=new Set([130,143]),go=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&jr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import ho from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},vo=(e,t)=>{let o=t?.write??(n=>{ho.stderr.write(n)}),r=t?.stdin??ho.stdin,s=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&s.push(E.primaryBuffer),o(s.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var yo=e=>`infra-kit ${e.groupPath.join(" ")}`,qr=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},Vr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Jr=async(e,t,o)=>{let r=io(),s={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o();try{let f=t.spawn(S.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:s});i=await Vr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=so(r),a=go(i.code,i.signal,c!=null,e.longRunning),m=yo(e),u=c?.equivalent??K(m,!0);return fo({equivalent:u,outcome:a,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===m)})},Wr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.resetTerminal(),t.exit(0)},n=()=>{if(!e()){t.resetTerminal(),t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",s),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",s),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},wo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),So=async(e,t)=>{let o={spawn:t.spawn??Gr,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),color:t.color??Ur.level>0,columns:t.columns??qr,resetTerminal:t.resetTerminal??(a=>{vo(a)})},r=t.write??(a=>S.stderr.write(a)),s=t.signals??{register:(a,m)=>{S.on(a,m)},unregister:(a,m)=>{S.off(a,m)},exit:a=>{S.exit(a)},raise:a=>{S.kill(S.pid,a)},resetTerminal:()=>{o.resetTerminal({entersAltScreen:!1})}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Wr(()=>n,s);try{for(;;){if(c.quitRequested())return;n=!1;let a=await t.renderPalette(e);if(a==null)return;let m=t.resolveCommand(a);if(!m)continue;let u=po(yo(m),{color:o.color});r(`
10
10
  ${u}
11
- `),c.childStarted();let f=await Vr(m,o,()=>{n=!0});r(`
11
+ `),c.childStarted();let f=await Jr(m,o,()=>{n=!0});r(`
12
12
  ${f}
13
- `)}}finally{c.dispose()}};import{spawn as Br}from"node:child_process";import ko from"node:fs";import P from"node:process";import{fileURLToPath as Ro}from"node:url";var So=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Wr=new Set(["mcp","self-update"]),Kr=e=>e[2]!=null&&Wr.has(e[2]),Ce=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return So.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Kr(t)?"own-command":r?G(s,n,i)?"local-install":null:"not-a-tty"};var Hr=e=>{Br(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Yr=()=>Ro(new URL("./update-check.js",import.meta.url)),zr=()=>ko.realpathSync(Ro(new URL("./cli.js",import.meta.url))),Xr=/^[\w@./+-]+$/i,Qr=e=>Xr.test(e),Zr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every(Qr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Pe=(e,t={})=>{try{let o=t.argv??P.argv,r=t.env??P.env,s=t.isTty??!!P.stdout.isTTY,n=t.cwd??P.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??zr(),a=t.readCache??ie,m=t.spawnChild??Hr,u=t.fileExists??(x=>ko.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(Ce({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:b})!==null)return;let k=a();if(Zr(k,e,f),!se(k,i))return;let R=t.childPath??Yr();if(!u(R))return;m(R)}catch{}};Ut();oo();var Ie=Te(),xo=async e=>{try{e?await Ie.parseAsync(e):await Ie.parseAsync()}catch(t){re(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},on=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;G(tn(To(import.meta.url)),g.cwd(),b)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};on();Pe(et.version);var Ao=()=>Gt(Ie.commands),rn=async()=>{let e=Ao(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-HP5ORQEX.js");t=await o(e)}else{let o=Ae(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new Eo(" "),new Eo(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await M(s=>en({message:"Select a command to run",choices:r},s),{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},nn=async()=>{let{runCommandPalette:e}=await import("./boot-HP5ORQEX.js"),t=To(import.meta.url),o=new Map(Ot.map(r=>[r.groupPath.join(" "),r]));await wo(Ao(),{renderPalette:e,resolveCommand:r=>{let s=o.get(r);return s?{groupPath:s.groupPath,entersAltScreen:s.entersAltScreen,sessionEnvNotice:s.sessionEnvNotice,longRunning:s.longRunning}:void 0},cliPath:t})};if(g.argv.length<=2){let e={stdoutIsTTY:!!g.stdout.isTTY,stdinIsTTY:!!g.stdin.isTTY,stderrIsTTY:!!g.stderr.isTTY};if(yo(g.env,e))await nn();else{let t=await rn();t&&await xo(["node","infra-kit",...t.split(" ")])}}else await xo();
13
+ `)}}finally{c.dispose()}};import{spawn as Hr}from"node:child_process";import Ro from"node:fs";import P from"node:process";import{fileURLToPath as Eo}from"node:url";var ko=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Br=new Set(["mcp","self-update"]),Kr=e=>e[2]!=null&&Br.has(e[2]),be=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return ko.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Kr(t)?"own-command":r?G(s,n,i)?"local-install":null:"not-a-tty"};var Yr=e=>{Hr(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},zr=()=>Eo(new URL("./update-check.js",import.meta.url)),Xr=()=>Ro.realpathSync(Eo(new URL("./cli.js",import.meta.url))),Qr=/^[\w@./+-]+$/i,Zr=e=>Qr.test(e),en=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every(Zr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Pe=(e,t={})=>{try{let o=t.argv??P.argv,r=t.env??P.env,s=t.isTty??!!P.stdout.isTTY,n=t.cwd??P.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??Xr(),a=t.readCache??ie,m=t.spawnChild??Yr,u=t.fileExists??(x=>Ro.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(be({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:C})!==null)return;let k=a();if(en(k,e,f),!se(k,i))return;let R=t.childPath??zr();if(!u(R))return;m(R)}catch{}};Gt();ro();var Ie=Te(),To=async e=>{try{e?await Ie.parseAsync(e):await Ie.parseAsync()}catch(t){re(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},rn=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;G(on(Ao(import.meta.url)),g.cwd(),C)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};rn();Pe(et.version);var Co=()=>qt(Ie.commands),nn=async()=>{let e=Co(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-HP5ORQEX.js");t=await o(e)}else{let o=Ae(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new xo(" "),new xo(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await j(s=>tn({message:"Select a command to run",choices:r},s),{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},sn=async()=>{let{runCommandPalette:e}=await import("./boot-HP5ORQEX.js"),t=Ao(import.meta.url),o=new Map($t.map(r=>[r.groupPath.join(" "),r]));await So(Co(),{renderPalette:e,resolveCommand:r=>{let s=o.get(r);return s?{groupPath:s.groupPath,entersAltScreen:s.entersAltScreen,sessionEnvNotice:s.sessionEnvNotice,longRunning:s.longRunning}:void 0},cliPath:t})};if(g.argv.length<=2){let e={stdoutIsTTY:!!g.stdout.isTTY,stdinIsTTY:!!g.stdin.isTTY,stderrIsTTY:!!g.stderr.isTTY};if(wo(g.env,e))await sn();else{let t=await nn();t&&await To(["node","infra-kit",...t.split(" ")])}}else await To();
14
14
  //# sourceMappingURL=cli.js.map