infra-kit 0.3.0 → 0.3.1

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.
Files changed (38) hide show
  1. package/dist/boot-YQAPYAKT.js +2 -0
  2. package/dist/boot-YQAPYAKT.js.map +7 -0
  3. package/dist/chunk-A7FAXZGI.js +2 -0
  4. package/dist/chunk-A7FAXZGI.js.map +7 -0
  5. package/dist/{chunk-KZP2SY37.js → chunk-AVLZBOOA.js} +2 -2
  6. package/dist/{chunk-KZP2SY37.js.map → chunk-AVLZBOOA.js.map} +2 -2
  7. package/dist/{chunk-E2NWNNC6.js → chunk-JPTSUMWI.js} +2 -2
  8. package/dist/{chunk-E2NWNNC6.js.map → chunk-JPTSUMWI.js.map} +1 -1
  9. package/dist/chunk-KAKTWDWJ.js +7 -0
  10. package/dist/chunk-KAKTWDWJ.js.map +7 -0
  11. package/dist/chunk-TL7LO2FF.js +231 -0
  12. package/dist/chunk-TL7LO2FF.js.map +7 -0
  13. package/dist/chunk-UO3FYLPX.js +2 -0
  14. package/dist/chunk-UO3FYLPX.js.map +7 -0
  15. package/dist/{chunk-NC2TIQ3M.js → chunk-V4XK2YEH.js} +2 -2
  16. package/dist/cli.js +10 -9
  17. package/dist/cli.js.map +3 -3
  18. package/dist/dev-server.js +19 -21
  19. package/dist/dev-server.js.map +3 -3
  20. package/dist/dev-wizard-run-2ISRQPGA.js +2 -0
  21. package/dist/dev-wizard-run-2ISRQPGA.js.map +7 -0
  22. package/dist/mcp.js +1 -1
  23. package/dist/mcp.js.map +1 -1
  24. package/dist/update-check.js +1 -1
  25. package/package.json +2 -2
  26. package/dist/boot-MTVHM4N7.js +0 -2
  27. package/dist/boot-MTVHM4N7.js.map +0 -7
  28. package/dist/chunk-4MRYIYJP.js +0 -4
  29. package/dist/chunk-4MRYIYJP.js.map +0 -7
  30. package/dist/chunk-6FU2TRU5.js +0 -2
  31. package/dist/chunk-6FU2TRU5.js.map +0 -7
  32. package/dist/chunk-E2SEBLGJ.js +0 -2
  33. package/dist/chunk-E2SEBLGJ.js.map +0 -7
  34. package/dist/chunk-RLZ5IB2E.js +0 -238
  35. package/dist/chunk-RLZ5IB2E.js.map +0 -7
  36. package/dist/dev-wizard-run-5HQOGE3R.js +0 -2
  37. package/dist/dev-wizard-run-5HQOGE3R.js.map +0 -7
  38. /package/dist/{chunk-NC2TIQ3M.js.map → chunk-V4XK2YEH.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{b as P}from"./chunk-A7FAXZGI.js";import{m as f,q as x}from"./chunk-CHETBZ6M.js";import u from"node:path";var m="infra-kit",g=`${m}@latest`,S=(t,e,n)=>{let r=u.relative(n(u.resolve(t)),u.resolve(e));return r!==""&&!r.startsWith("..")&&!u.isAbsolute(r)},l=(t,e)=>u.resolve(t).split(u.sep).includes(e),z=(t,e)=>{let n=u.resolve(t).split(u.sep),r=n.indexOf("Cellar");return r!==-1&&n[r+1]===e},C=(t,e,n,r)=>{let a=t[e];return a!=null&&a!==""&&S(a,n,r)},H=[{manager:"volta",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"VOLTA_HOME",t,n)||l(t,".volta")||l(t,"volta"),updateCommand:["volta","install",m],canSelfSpawn:!0},{manager:"homebrew",test:({selfRealPath:t})=>z(t,m),updateCommand:["brew","upgrade",m],canSelfSpawn:!1},{manager:"pnpm",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"PNPM_HOME",t,n)||l(t,"pnpm")&&l(t,"global"),updateCommand:["pnpm","add","-g",g],canSelfSpawn:!0},{manager:"bun",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"BUN_INSTALL",t,n)||l(t,".bun"),updateCommand:["bun","add","-g",g],canSelfSpawn:!0},{manager:"yarn",test:({selfRealPath:t})=>l(t,".yarn")||l(t,"yarn")&&l(t,"global"),updateCommand:["yarn","global","add",g],canSelfSpawn:!0},{manager:"npm",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"npm_config_prefix",t,n),updateCommand:["npm","install","-g",g],canSelfSpawn:!0}],E=["npm","install","-g",g],b=t=>{let{selfRealPath:e,env:n,realpath:r,lazyNpmRoot:a}=t,s=H.find(({test:i})=>i({selfRealPath:e,env:n,realpath:r}));if(s)return{manager:s.manager,updateCommand:s.updateCommand,canSelfSpawn:s.canSelfSpawn};let o=a?.();return o!=null&&o!==""&&S(o,e,r)?{manager:"npm",updateCommand:E,canSelfSpawn:!0}:{manager:"unknown",updateCommand:E,canSelfSpawn:!1}},K=(t,e,n)=>l(t,"node_modules")&&S(e,t,n);import{realpathSync as G}from"node:fs";import $ from"node:path";var M=t=>{try{return G(t)}catch{return $.resolve(t)}};import{execFileSync as W}from"node:child_process";import B from"node:process";var Y=3e3,k=()=>{try{let e=W("npm",["root","-g"],{encoding:"utf-8",timeout:Y,stdio:["ignore","pipe","ignore"],shell:B.platform==="win32"}).trim();return e===""?void 0:e}catch{return}};import{spawnSync as de}from"node:child_process";import{homedir as fe}from"node:os";import v from"node:process";import d from"node:fs";import I from"node:path";import Q from"node:process";var X="update-check.lock",Z=1800*1e3,ee=()=>I.join(f(),X),te=(t,e)=>{try{e-d.statSync(t).mtimeMs>Z&&d.rmSync(t,{force:!0})}catch{}},N=(t={})=>{let e=t.nowMs??Date.now(),n=t.lockPath??ee();try{d.mkdirSync(I.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return d.openSync(n,"wx",384)}catch{return null}},a=r();if(a===null&&(te(n,e),a=r()),a===null)return null;try{d.writeFileSync(a,String(Q.pid))}catch{}return()=>{try{d.closeSync(a)}catch{}try{d.rmSync(n,{force:!0})}catch{}}};var ne="https://registry.npmjs.org",re=2500,ae=t=>Object.entries(t).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],oe=t=>{let e=ae(t),n=e!=null&&e!==""?e:ne;for(;n.endsWith("/");)n=n.slice(0,-1);return n},A=async(t,e=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},re);try{let a=await e(`${oe(t)}/${m}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!a.ok)return null;let o=(await a.json())?.version;return typeof o=="string"&&o!==""?o:null}catch{return null}finally{clearTimeout(r)}};var se=/^(\d+)\.(\d+)\.(\d+)$/,R=t=>{let[e=""]=t.trim().split("+"),[n="",...r]=e.split("-"),a=se.exec(n);if(!a)return null;let[s,o,i]=[a[1],a[2],a[3]].map(Number);return{release:[s,o,i],prerelease:r.length>0?r.join("-").split("."):[]}},_=/^\d+$/,le=(t,e)=>{let n=_.test(t),r=_.test(e);return n&&r?Number(t)-Number(e):n!==r?n?-1:1:t<e?-1:1},ie=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n+=1){let r=t[n],a=e[n];if(r===void 0)return-1;if(a===void 0)return 1;if(r!==a)return le(r,a)}return 0},L=(t,e)=>{let n=R(t),r=R(e);if(!n||!r)return!1;for(let o=0;o<3;o+=1){let i=n.release[o],h=r.release[o];if(i!==h)return i>h}let a=n.prerelease.length===0,s=r.prerelease.length===0;return a!==s?a:ie(n.prerelease,r.prerelease)>0};import U from"node:fs";import T from"node:path";var O="update-check.json",ce=1440*60*1e3,ue=()=>T.join(f(),O),pe=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),me=t=>{if(typeof t!="object"||t===null)return!1;let{lastCheckMs:e,latestVersion:n,updateCommand:r}=t;return typeof e=="number"&&Number.isFinite(e)&&(n===null||typeof n=="string")&&(r===null||pe(r))},Ke=(t=e=>U.readFileSync(e,"utf8"))=>{try{let e=JSON.parse(t(ue()));return me(e)?e:null}catch{return null}},F=t=>{let e=f();U.mkdirSync(e,{recursive:!0}),x(T.join(e,O),JSON.stringify(t),384)},Ge=(t,e)=>{if(!t)return!0;let n=e-t.lastCheckMs;return n>=ce||n<0};var ge=200,he=300*1e3,ye=t=>{try{return v.kill(t,0),!0}catch{return!1}},Ce=t=>new Promise(e=>{setTimeout(e,t)}),we=async(t,e)=>{let n=e.clock()+he;for(;e.clock()<n;){if(!e.isProcessAlive(t))return!0;await e.sleep(ge)}return!e.isProcessAlive(t)},rt=async(t,e)=>{let r=(e.acquireLock??N)();if(!r)return"already-running";try{return await Se(t,e)}finally{r()}},Se=async(t,e)=>{let n=e.env??v.env,r=e.nowMs??Date.now(),a=e.fetchLatest??A,s=e.writeCache??F,o=e.isProcessAlive??ye,i=e.sleep??Ce,h=e.clock??Date.now,D=e.lazyNpmRoot??k,V=e.spawnSync??de,c=await a(n),p=(J,q)=>(s({lastCheckMs:r,...q}),J);if(c===null)return p("fetch-failed",{latestVersion:null,updateCommand:null});if(!L(c,t))return p("up-to-date",{latestVersion:c,updateCommand:null});let{canSelfSpawn:j,updateCommand:y}=b({selfRealPath:e.selfRealPath,env:n,realpath:M,lazyNpmRoot:D});if(!j)return p("cannot-self-spawn",{latestVersion:c,updateCommand:y});if(e.parentPid==null)return p("parent-unknown",{latestVersion:c,updateCommand:null});if(s({lastCheckMs:r,latestVersion:c,updateCommand:null}),!await we(e.parentPid,{isProcessAlive:o,sleep:i,clock:h}))return p("parent-still-running",{latestVersion:c,updateCommand:null});let w=V(y[0],y.slice(1),{stdio:"ignore",shell:v.platform==="win32",cwd:fe(),env:P(n),windowsHide:!0});return w.error||w.signal||w.status!==0?p("install-failed",{latestVersion:c,updateCommand:y}):p("installed",{latestVersion:null,updateCommand:null})};export{b as a,K as b,k as c,M as d,L as e,Ke as f,Ge as g,rt as h};
2
+ //# sourceMappingURL=chunk-UO3FYLPX.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/install-manager/install-manager.ts", "../src/lib/install-manager/safe-realpath.ts", "../src/lib/install-manager/npm-root.ts", "../src/lib/update-check/run-update-check.ts", "../src/lib/update-check/lock.ts", "../src/lib/update-check/registry.ts", "../src/lib/update-check/semver.ts", "../src/lib/update-check/update-cache.ts"],
4
+ "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so a self-update advisory can name the one command\n * that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nconst isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nconst hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nconst isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Ordered, first-hit-wins. Order matters: volta and homebrew wrap an npm-shaped layout, so they must be\n * consulted before the generic npm prefix matcher would claim them.\n */\nconst MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see {@link isBrewKegOf}. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * `lazyNpmRoot` is the fallback probe and is invoked at most once, only after every env/path matcher has\n * missed \u2014 a global `npm root -g` subprocess is never paid for a pnpm or volta install. When nothing\n * matches we report `unknown` with an npm command that is a *suggestion only* (`canSelfSpawn: false`):\n * running a guessed global install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const hit = MATCHERS.find(({ test }) => {\n return test({ selfRealPath, env, realpath })\n })\n\n if (hit) return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Shared by `self-update` (interactive) and the background update worker so the two can never disagree\n * about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * The CHILD half of the auto-update, spawned detached by `maybeAutoUpdate`. It outlives the CLI\n * invocation that started it, so it may take its time and it may replace the binary.\n *\n * WHY IT WAITS FOR THE PARENT TO EXIT \u2014 the load-bearing invariant of this whole feature:\n * `scripts/build.js` sets esbuild `splitting: true`, so `dist/cli.js` lazily imports sibling\n * `chunk-*.js` files at runtime (that is how the Ink TUI stays off the fast path). A package manager\n * installing over `dist/` mid-command deletes chunks the parent has not imported yet, and the parent\n * dies on a dynamic import of a file that no longer exists. Waiting for the parent to exit is what\n * makes a silent background install safe rather than a random crash under `infra-kit dev`.\n */\nimport { spawnSync } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport process from 'node:process'\n\nimport { defaultLazyNpmRoot, detectInstallManager, safeRealpath } from 'src/lib/install-manager'\nimport { packageManagerInstallEnv } from 'src/lib/pm-env'\n\nimport { acquireUpdateLock } from './lock'\nimport { fetchLatestVersion } from './registry'\nimport { isNewerVersion } from './semver'\nimport { writeUpdateCache } from './update-cache'\nimport type { UpdateCache } from './update-cache'\n\n/** How often to re-check whether the parent is gone. */\nexport const PARENT_POLL_INTERVAL_MS = 200\n\n/**\n * Give up waiting after this long. A long-lived parent (`infra-kit dev` runs for hours) must not leave\n * an immortal child pinned to a stale version: we simply skip this cycle. `lastCheckMs` is already\n * persisted by then, so the next short-lived command re-checks after the normal 24h window.\n */\nexport const PARENT_WAIT_TIMEOUT_MS = 5 * 60 * 1000\n\nexport interface RunUpdateCheckDeps {\n env?: NodeJS.ProcessEnv\n nowMs?: number\n fetchLatest?: (env: NodeJS.ProcessEnv) => Promise<string | null>\n writeCache?: typeof writeUpdateCache\n isProcessAlive?: (pid: number) => boolean\n sleep?: (ms: number) => Promise<void>\n /** Monotonic-ish source for the parent-wait deadline. Injected so the timeout is testable without real time. */\n clock?: () => number\n /** `npm root -g` probe. Defaults to the real subprocess; this child is detached, so it can afford one. */\n lazyNpmRoot?: () => string | undefined\n /** Single-flight guard. Returns a release fn, or null when another worker already holds the lock. */\n acquireLock?: () => (() => void) | null\n spawnSync?: typeof spawnSync\n /** Realpath of the installed `dist/cli.js`, used to identify the owning package manager. */\n selfRealPath: string\n parentPid?: number\n}\n\n/** Signal 0 performs the permission/existence check without delivering anything. */\nconst defaultIsProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/**\n * Block until `parentPid` exits or {@link PARENT_WAIT_TIMEOUT_MS} elapses. Returns whether the parent\n * is actually gone \u2014 the caller must not install on a timeout.\n */\nconst waitForParentExit = async (\n parentPid: number,\n deps: Required<Pick<RunUpdateCheckDeps, 'isProcessAlive' | 'sleep' | 'clock'>>,\n): Promise<boolean> => {\n const deadline = deps.clock() + PARENT_WAIT_TIMEOUT_MS\n\n while (deps.clock() < deadline) {\n if (!deps.isProcessAlive(parentPid)) return true\n\n await deps.sleep(PARENT_POLL_INTERVAL_MS)\n }\n\n return !deps.isProcessAlive(parentPid)\n}\n\nexport type UpdateCheckOutcome =\n | 'installed'\n | 'install-failed'\n | 'up-to-date'\n | 'fetch-failed'\n | 'cannot-self-spawn'\n | 'parent-still-running'\n | 'parent-unknown'\n | 'already-running'\n\n/**\n * Fetch, decide, and (when safe) install \u2014 returning WHY it did what it did so tests can distinguish\n * \"no update\" from \"could not install\". Never throws.\n *\n * `lastCheckMs` is written from the ATTEMPT, before any early return. If it were written only on\n * success, an offline user would re-spawn a doomed child on every single command.\n *\n * @example\n * await runUpdateCheck('0.1.130', { selfRealPath: '/usr/local/lib/node_modules/infra-kit/dist/cli.js' })\n * // => 'installed'\n */\nexport const runUpdateCheck = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const acquireLock = deps.acquireLock ?? acquireUpdateLock\n\n // Single-flight. N shells launched at once all read the same stale cache and each spawns a worker;\n // the cache throttle cannot stop them because it is only written after the fetch returns. Without\n // this, a pending update means N concurrent `npm install -g` over one global directory.\n const release = acquireLock()\n\n if (!release) return 'already-running'\n\n try {\n return await runUpdateCheckLocked(currentVersion, deps)\n } finally {\n release()\n }\n}\n\nconst runUpdateCheckLocked = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const env = deps.env ?? process.env\n const nowMs = deps.nowMs ?? Date.now()\n const fetchLatest = deps.fetchLatest ?? fetchLatestVersion\n const writeCache = deps.writeCache ?? writeUpdateCache\n const isProcessAlive = deps.isProcessAlive ?? defaultIsProcessAlive\n const sleep = deps.sleep ?? defaultSleep\n const clock = deps.clock ?? Date.now\n const lazyNpmRoot = deps.lazyNpmRoot ?? defaultLazyNpmRoot\n const spawn = deps.spawnSync ?? spawnSync\n\n const latestVersion = await fetchLatest(env)\n\n // Every path below writes the cache EXACTLY once, and always with `lastCheckMs: nowMs` \u2014 the throttle\n // burns on the ATTEMPT, never on success. If it burned only on success, an offline user would respawn\n // a doomed child on every command.\n const finish = (outcome: UpdateCheckOutcome, cache: Omit<UpdateCache, 'lastCheckMs'>): UpdateCheckOutcome => {\n writeCache({ lastCheckMs: nowMs, ...cache })\n\n return outcome\n }\n\n if (latestVersion === null) return finish('fetch-failed', { latestVersion: null, updateCommand: null })\n if (!isNewerVersion(latestVersion, currentVersion))\n return finish('up-to-date', { latestVersion, updateCommand: null })\n\n // `lazyNpmRoot` is what makes the COMMON case work: a plain `npm i -g infra-kit` leaves no\n // `npm_config_prefix` in the user's shell, so every cheap matcher misses and detection would report\n // `unknown` / `canSelfSpawn: false`. Without this probe the auto-update would silently degrade to a\n // notice for the majority of installs. The subprocess is affordable here and nowhere else.\n const { canSelfSpawn, updateCommand } = detectInstallManager({\n selfRealPath: deps.selfRealPath,\n env,\n realpath: safeRealpath,\n lazyNpmRoot,\n })\n\n // Homebrew relinks its prefix and may prompt; an unknown location means the command is a guess.\n // Both stay the user's call, so record the command for `maybeAutoUpdate` to print next invocation.\n if (!canSelfSpawn) return finish('cannot-self-spawn', { latestVersion, updateCommand })\n\n // Fail SAFE. Without a parent to outlive we cannot know whether a live CLI is still lazily importing\n // `chunk-*.js` out of the `dist/` we are about to replace, so we skip the cycle rather than install\n // blind. The real spawn always passes `--parent-pid`; only a hand-run worker lands here.\n if (deps.parentPid == null) return finish('parent-unknown', { latestVersion, updateCommand: null })\n\n // Burn the throttle NOW, before the two unbounded-ish operations below (a 5-minute parent wait, then an\n // install of no fixed duration). Everything after this point can take many minutes, and until the cache\n // is written it still reads as STALE \u2014 so every new shell in that window spawns its own worker, and the\n // single-flight lock becomes the only thing standing between them and concurrent `npm install -g` runs\n // over one global directory. The lock is reaped by mtime (LOCK_STALE_MS), so a slow enough install has\n // its live lock stolen and we get exactly the pile-up the lock exists to prevent.\n //\n // Writing the stamp here makes the throttle \u2014 not the lock \u2014 the primary guard, which is what the cache\n // was always for. `finish()` overwrites this with the real outcome; this is the only path that writes\n // the cache twice, and deliberately so.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null })\n\n const parentGone = await waitForParentExit(deps.parentPid, { isProcessAlive, sleep, clock })\n\n // A long-lived parent (`infra-kit dev`) outlasted the wait. Stay silent and retry next window.\n if (!parentGone) return finish('parent-still-running', { latestVersion, updateCommand: null })\n\n // `shell` on win32 so the `.cmd` shims npm/pnpm/yarn ship as global bins resolve.\n //\n // `packageManagerInstallEnv` strips the inherited npx/dlx markers \u2014 which otherwise make\n // pnpm/portless-style tools believe they were invoked via `npx`/`dlx` and refuse to run \u2014 while KEEPING\n // `npm_config_prefix` and `npm_config_registry`. Using the blunt `withoutPackageManagerEnv` here was a\n // bug: it also erased the prefix that `detectInstallManager` had just matched on, so we would detect a\n // global install at prefix P and then install into the default prefix instead \u2014 silently, forever. See\n // the module doc on `packageManagerInstallEnv`.\n //\n // `cwd` is pinned to the home directory, and this is a SECURITY control, not tidiness: npm resolves\n // `registry=` from an `.npmrc` on disk relative to the cwd. Inheriting the caller's cwd would let any\n // repo containing a hostile `.npmrc` silently redirect this unattended `install -g` to an attacker's\n // registry, executing its lifecycle scripts. Stripping `npm_config_registry` from the env does NOT\n // close that hole, because the redirect lives in a file, not the environment.\n const result = spawn(updateCommand[0] as string, updateCommand.slice(1), {\n stdio: 'ignore',\n shell: process.platform === 'win32',\n cwd: homedir(),\n env: packageManagerInstallEnv(env),\n windowsHide: true,\n })\n\n // Record the manual command so a persistently failing silent install (EACCES on a root-owned global\n // dir, say) still surfaces ONE actionable line, instead of failing invisibly forever.\n if (result.error || result.signal || result.status !== 0) {\n return finish('install-failed', { latestVersion, updateCommand })\n }\n\n // The installed version is now `latestVersion`; clear it so the next run does not re-notify.\n return finish('installed', { latestVersion: null, updateCommand: null })\n}\n", "/**\n * Single-flight lock for the background update worker.\n *\n * Without it, N shells starting at once all read the same stale cache and each spawns a worker \u2014 and\n * once a newer version exists, each of those runs `npm install -g` concurrently, over the same global\n * directory. (Measured: five concurrent `ik` invocations spawn five workers.) The throttle in the cache\n * cannot prevent this: it is only written AFTER the fetch returns, long after the other workers launched.\n *\n * `openSync(path, 'wx')` is the primitive \u2014 an atomic create-if-absent, so exactly one worker wins even\n * if all of them call it in the same millisecond.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { getCacheRoot } from 'src/lib/constants'\n\nexport const LOCK_FILE_NAME = 'update-check.lock'\n\n/**\n * A lock older than this is assumed to belong to a worker that was killed before it could clean up.\n *\n * Must exceed the worker's ENTIRE critical section, and the install is part of it: the lock is held across\n * `fetch` (\u22642.5s) + the parent wait (\u22645min) + `npm install -g`, which has no bound at all \u2014 a cold cache on\n * a slow link can run for many minutes. The previous 10 minutes was budgeted from the wait and the fetch\n * alone, silently omitting the very operation the lock exists to serialise. A slow enough install therefore\n * had its own LIVE lock reaped as stale by the next worker, which then ran a second concurrent\n * `npm install -g` over the same global directory \u2014 precisely the pile-up described above.\n *\n * The throttle, not this timeout, is now the primary guard: `runUpdateCheck` stamps `lastCheckMs` BEFORE\n * the wait and the install, so concurrent shells stop spawning workers at all. This value only has to\n * outlive a plausible install, and is deliberately generous \u2014 the cost of being too large is that a worker\n * killed mid-install delays the next attempt, which the 24h throttle would delay anyway.\n */\nexport const LOCK_STALE_MS = 30 * 60 * 1000\n\nexport const lockFilePath = (): string => {\n return path.join(getCacheRoot(), LOCK_FILE_NAME)\n}\n\nexport interface LockDeps {\n nowMs?: number\n lockPath?: string\n}\n\n/** Delete a lock whose mtime predates the staleness window. Best-effort: losing the race is harmless. */\nconst reapIfStale = (lockPath: string, nowMs: number): void => {\n try {\n if (nowMs - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS) fs.rmSync(lockPath, { force: true })\n } catch {\n // Vanished under us \u2014 another worker reaped it. Nothing to do.\n }\n}\n\n/**\n * Take the lock, or return null when another worker already holds it.\n *\n * Returns a release function rather than a boolean so the caller cannot forget which path releases:\n * there is exactly one handle, and it is the only thing that can unlink the file.\n *\n * @example\n * const release = acquireUpdateLock()\n * if (!release) return 'already-running'\n * try { ... } finally { release() }\n */\nexport const acquireUpdateLock = (deps: LockDeps = {}): (() => void) | null => {\n const nowMs = deps.nowMs ?? Date.now()\n const lockPath = deps.lockPath ?? lockFilePath()\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true })\n } catch {\n return null\n }\n\n const open = (): number | null => {\n try {\n // 'wx' fails with EEXIST if the file is already there: an atomic test-and-set.\n return fs.openSync(lockPath, 'wx', 0o600)\n } catch {\n return null\n }\n }\n\n let fd = open()\n\n if (fd === null) {\n reapIfStale(lockPath, nowMs)\n // One retry only. If a live worker holds the lock, we are the loser and must simply stand down.\n fd = open()\n }\n\n if (fd === null) return null\n\n try {\n fs.writeFileSync(fd, String(process.pid))\n } catch {\n // The pid is a debugging aid, not part of the protocol; the lock is held either way.\n }\n\n return () => {\n try {\n fs.closeSync(fd)\n } catch {\n // Already closed.\n }\n\n try {\n fs.rmSync(lockPath, { force: true })\n } catch {\n // Already gone; a later worker will reap it via LOCK_STALE_MS regardless.\n }\n }\n}\n", "/**\n * Ask the npm registry for the `latest` dist-tag. Node >= 24 (see `engines`), so global `fetch` is\n * available and this needs no dependency.\n */\nimport { PACKAGE_NAME } from 'src/lib/install-manager'\n\nexport const DEFAULT_REGISTRY = 'https://registry.npmjs.org'\n\n/** Bounded so a hanging registry can never keep a detached child alive indefinitely. */\nexport const FETCH_TIMEOUT_MS = 2_500\n\n/**\n * The registry this install actually talks to. A user behind a corporate mirror has `npm_config_registry`\n * set; hitting registry.npmjs.org directly would either fail closed (firewall) or, worse, report a public\n * version they cannot install.\n *\n * @example\n * registryUrl({ npm_config_registry: 'https://nexus.corp/repo/npm/' }) // => 'https://nexus.corp/repo/npm'\n */\n/**\n * `npm_config_registry` in WHICHEVER case the environment spells it.\n *\n * A bare `env.npm_config_registry` reads only the lowercase form, but npm itself matches `/^npm_config_/i`,\n * and POSIX `process.env` is case-SENSITIVE \u2014 so a `NPM_CONFIG_REGISTRY` (the form Dockerfiles and CI\n * images export) was invisible here while npm honoured it. The check then queried the public registry that\n * the install would never touch: the two halves of this feature were exactly inverted.\n */\nconst configuredRegistry = (env: NodeJS.ProcessEnv): string | undefined => {\n const hit = Object.entries(env).find(([key, value]) => {\n return /^npm_config_registry$/i.test(key) && value != null && value !== ''\n })\n\n return hit?.[1]\n}\n\nexport const registryUrl = (env: NodeJS.ProcessEnv): string => {\n const configured = configuredRegistry(env)\n\n let base = configured != null && configured !== '' ? configured : DEFAULT_REGISTRY\n\n // A `/\\/+$/` regex would do this in one line, but its backtracking is super-linear on a hostile input.\n while (base.endsWith('/')) {\n base = base.slice(0, -1)\n }\n\n return base\n}\n\n/**\n * The published `latest` version, or null on ANY failure (offline, timeout, non-200, malformed body).\n * Never throws: a failed check must be indistinguishable from \"no update available\" to every caller.\n *\n * @example\n * await fetchLatestVersion(process.env) // => '0.1.131' | null\n */\nexport const fetchLatestVersion = async (\n env: NodeJS.ProcessEnv,\n fetchFn: typeof fetch = fetch,\n): Promise<string | null> => {\n const controller = new AbortController()\n const timer = setTimeout(() => {\n controller.abort()\n }, FETCH_TIMEOUT_MS)\n\n try {\n const response = await fetchFn(`${registryUrl(env)}/${PACKAGE_NAME}/latest`, {\n signal: controller.signal,\n headers: { accept: 'application/json' },\n })\n\n if (!response.ok) return null\n\n const body: unknown = await response.json()\n const version = (body as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n", "/**\n * Registry-safe version comparison for the auto-update check.\n *\n * Deliberately NOT `src/lib/version-utils`: `parseVersion` there does `versionStr.slice(1)` because it\n * only ever sees `v`-prefixed release tags, so it turns a bare registry version (`0.1.130`) into\n * `[NaN, 1, 130]`. Feeding npm's `dist-tags.latest` through it silently compares NaNs and never fires.\n * These inputs are bare semver from `registry.npmjs.org` and from our own `package.json`.\n */\n\n/** `1.2.3-beta.4+build` \u2192 the `[1, 2, 3]` release triple and the `beta.4` prerelease, or null if unparsable. */\ninterface ParsedVersion {\n release: [number, number, number]\n /** Dot-separated prerelease identifiers, empty when this is a final release. */\n prerelease: string[]\n}\n\nconst RELEASE_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/**\n * Parse bare semver. Returns null (never throws, never NaNs) for anything that is not\n * `major.minor.patch` with optional `-prerelease` and `+build` \u2014 a garbled registry body must read as\n * \"no update\", not as \"update to NaN\".\n *\n * @example\n * parseSemver('0.1.130') // => { release: [0, 1, 130], prerelease: [] }\n * parseSemver('1.0.0-rc.1+abc') // => { release: [1, 0, 0], prerelease: ['rc', '1'] }\n * parseSemver('v1.0.0') // => null\n */\nexport const parseSemver = (version: string): ParsedVersion | null => {\n // Build metadata is ignored entirely by semver precedence rules.\n const [withoutBuild = ''] = version.trim().split('+')\n const [core = '', ...prereleaseParts] = withoutBuild.split('-')\n const match = RELEASE_PATTERN.exec(core)\n\n if (!match) return null\n\n const [major, minor, patch] = [match[1], match[2], match[3]].map(Number) as [number, number, number]\n\n return {\n release: [major, minor, patch],\n // Re-join on '-' so `1.0.0-rc-1` keeps its hyphen inside a single identifier.\n prerelease: prereleaseParts.length > 0 ? prereleaseParts.join('-').split('.') : [],\n }\n}\n\nconst NUMERIC_IDENTIFIER = /^\\d+$/\n\n/** Compare two unequal prerelease identifiers per semver \u00A711. Numeric ones rank below alphanumeric ones. */\nconst compareIdentifier = (left: string, right: string): number => {\n const leftNumeric = NUMERIC_IDENTIFIER.test(left)\n const rightNumeric = NUMERIC_IDENTIFIER.test(right)\n\n if (leftNumeric && rightNumeric) return Number(left) - Number(right)\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1\n\n return left < right ? -1 : 1\n}\n\n/** Compare prerelease identifier lists. A shorter list has lower precedence: `1.0.0-rc` < `1.0.0-rc.1`. */\nconst comparePrerelease = (a: string[], b: string[]): number => {\n for (let index = 0; index < Math.max(a.length, b.length); index += 1) {\n const left = a[index]\n const right = b[index]\n\n if (left === undefined) return -1\n if (right === undefined) return 1\n if (left !== right) return compareIdentifier(left, right)\n }\n\n return 0\n}\n\n/**\n * Is `latest` strictly newer than `current`? False when either is unparsable, so a bad registry\n * response can never trigger an install.\n *\n * The load-bearing case is NUMERIC, not lexical, comparison: `0.1.9` must be older than `0.1.130`.\n * A string compare would order them the other way and pin every user to the older build forever.\n *\n * A final release outranks its own prereleases (`1.0.0` > `1.0.0-rc.1`), so a user on `rc` is offered\n * the release, and a user on the release is never \"downgraded\" to an rc.\n *\n * @example\n * isNewerVersion('0.1.130', '0.1.9') // => true (numeric, not lexical)\n * isNewerVersion('1.0.0', '1.0.0-rc.1') // => true\n * isNewerVersion('0.1.130', '0.1.130') // => false\n * isNewerVersion('garbage', '0.1.0') // => false\n */\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const parsedLatest = parseSemver(latest)\n const parsedCurrent = parseSemver(current)\n\n if (!parsedLatest || !parsedCurrent) return false\n\n for (let index = 0; index < 3; index += 1) {\n const left = parsedLatest.release[index] as number\n const right = parsedCurrent.release[index] as number\n\n if (left !== right) return left > right\n }\n\n const latestIsFinal = parsedLatest.prerelease.length === 0\n const currentIsFinal = parsedCurrent.prerelease.length === 0\n\n if (latestIsFinal !== currentIsFinal) return latestIsFinal\n\n return comparePrerelease(parsedLatest.prerelease, parsedCurrent.prerelease) > 0\n}\n", "/**\n * The throttle + notice state for the auto-update check, at `$cacheRoot/update-check.json`.\n *\n * `getCacheRoot()` \u2014 NOT `getSessionCacheDir()`, which throws unless `INFRA_KIT_SESSION` is set. A user\n * who installed this CLI globally and never ran `infra-kit init` has no session, and the update check\n * must still work for exactly that person.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\nexport const CACHE_FILE_NAME = 'update-check.json'\n\n/** Refresh at most once a day. A background check is cheap, but not once per shell command. */\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000\n\nexport interface UpdateCache {\n /**\n * When the last check was ATTEMPTED \u2014 never \"when it last succeeded\". An offline user whose fetch\n * throws must still burn their 24h window, or every single command spawns another doomed child.\n */\n lastCheckMs: number\n /** Latest version seen on the registry, or null when the last attempt failed. */\n latestVersion: string | null\n /**\n * The command the USER must run, set only when the worker was not allowed to install for them\n * (Homebrew, or an install location it could not identify). Null means \"handled, say nothing\".\n *\n * The worker decides this, not the reader: identifying the owning package manager can cost an\n * `npm root -g` subprocess, and the CLI startup path must never pay for one. The background child\n * already pays it, so it writes the verdict down.\n */\n updateCommand: string[] | null\n}\n\nexport const cacheFilePath = (): string => {\n return path.join(getCacheRoot(), CACHE_FILE_NAME)\n}\n\nconst isStringArray = (value: unknown): value is string[] => {\n return (\n Array.isArray(value) &&\n value.every((entry) => {\n return typeof entry === 'string'\n })\n )\n}\n\nconst isUpdateCache = (value: unknown): value is UpdateCache => {\n if (typeof value !== 'object' || value === null) return false\n\n const { lastCheckMs, latestVersion, updateCommand } = value as Partial<UpdateCache>\n\n return (\n typeof lastCheckMs === 'number' &&\n Number.isFinite(lastCheckMs) &&\n (latestVersion === null || typeof latestVersion === 'string') &&\n (updateCommand === null || isStringArray(updateCommand))\n )\n}\n\n/**\n * Read the cache, or null when it is missing/unreadable/corrupt. A null read means \"stale\" to every\n * caller, so a first run and a hand-mangled file behave identically: check again.\n *\n * @example\n * readUpdateCache() // => { lastCheckMs: 1770000000000, latestVersion: '0.1.131' } | null\n */\nexport const readUpdateCache = (\n readFile: (p: string) => string = (p) => {\n return fs.readFileSync(p, 'utf8')\n },\n): UpdateCache | null => {\n try {\n const parsed: unknown = JSON.parse(readFile(cacheFilePath()))\n\n return isUpdateCache(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\n/**\n * Persist the check result. Creates `$cacheRoot` first: `atomicWriteFileSync` writes a temp file\n * beside the target and renames, so it throws ENOENT on a machine that has never had a `~/.cache/infra-kit`.\n * Without this mkdir the write fails, `lastCheckMs` never lands, and the throttle degrades into a\n * detached-child spawn on every invocation.\n *\n * @example\n * writeUpdateCache({ lastCheckMs: Date.now(), latestVersion: '0.1.131' })\n */\nexport const writeUpdateCache = (cache: UpdateCache): void => {\n const root = getCacheRoot()\n\n fs.mkdirSync(root, { recursive: true })\n atomicWriteFileSync(path.join(root, CACHE_FILE_NAME), JSON.stringify(cache), 0o600)\n}\n\n/**\n * Has the throttle window elapsed? A missing cache is stale by definition (first run).\n *\n * A `lastCheckMs` in the future (clock skew, or a restored backup) also reads as stale rather than\n * locking the user out of updates until their clock catches up.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null }, CHECK_INTERVAL_MS + 1) // => true\n */\nexport const isStale = (cache: UpdateCache | null, nowMs: number): boolean => {\n if (!cache) return true\n\n const elapsed = nowMs - cache.lastCheckMs\n\n return elapsed >= CHECK_INTERVAL_MS || elapsed < 0\n}\n"],
5
+ "mappings": "uFAQA,OAAOA,MAAU,YAGV,IAAMC,EAAe,YAEtBC,EAAS,GAAGD,CAAY,UAoCxBE,EAAW,CAACC,EAAgBC,EAAeC,IAAkC,CACjF,IAAMC,EAAMP,EAAK,SAASM,EAASN,EAAK,QAAQI,CAAM,CAAC,EAAGJ,EAAK,QAAQK,CAAK,CAAC,EAE7E,OAAOE,IAAQ,IAAM,CAACA,EAAI,WAAW,IAAI,GAAK,CAACP,EAAK,WAAWO,CAAG,CACpE,EAGMC,EAAa,CAACC,EAAWC,IACtBV,EAAK,QAAQS,CAAC,EAAE,MAAMT,EAAK,GAAG,EAAE,SAASU,CAAI,EAkBhDC,EAAc,CAACF,EAAWC,IAA0B,CACxD,IAAME,EAAWZ,EAAK,QAAQS,CAAC,EAAE,MAAMT,EAAK,GAAG,EACzCa,EAASD,EAAS,QAAQ,QAAQ,EAExC,OAAOC,IAAW,IAAMD,EAASC,EAAS,CAAC,IAAMH,CACnD,EAGMI,EAAc,CAACC,EAAwBC,EAAaC,EAAsBX,IAAkC,CAChH,IAAMY,EAAMH,EAAIC,CAAG,EAEnB,OAAOE,GAAO,MAAQA,IAAQ,IAAMf,EAASe,EAAKD,EAAcX,CAAQ,CAC1E,EAWMa,EAAsB,CAC1B,CACE,QAAS,QAET,KAAM,CAAC,CAAE,aAAAF,EAAc,IAAAF,EAAK,SAAAT,CAAS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aH,EAAO,cAAAY,EAAe,cAAe,IAAK,CAAC,EAKjE,CAHe,MAAMtB,GAAkBE,EAAK,UAAW,CAAE,eAAAa,EAAgB,MAAAC,EAAO,MAAAC,CAAM,CAAC,EAG1E,OAAOM,EAAO,uBAAwB,CAAE,cAAAD,EAAe,cAAe,IAAK,CAAC,EAgB7F,IAAMS,EAASX,EAAMQ,EAAc,CAAC,EAAaA,EAAc,MAAM,CAAC,EAAG,CACvE,MAAO,SACP,MAAOhC,EAAQ,WAAa,QAC5B,IAAKoC,GAAQ,EACb,IAAKC,EAAyBxB,CAAG,EACjC,YAAa,EACf,CAAC,EAID,OAAIsB,EAAO,OAASA,EAAO,QAAUA,EAAO,SAAW,EAC9CR,EAAO,iBAAkB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAI3DL,EAAO,YAAa,CAAE,cAAe,KAAM,cAAe,IAAK,CAAC,CACzE",
6
+ "names": ["path", "PACKAGE_NAME", "LATEST", "isWithin", "parent", "child", "realpath", "rel", "hasSegment", "p", "name", "isBrewKegOf", "segments", "cellar", "underEnvDir", "env", "key", "selfRealPath", "dir", "MATCHERS", "NPM_UPDATE_COMMAND", "detectInstallManager", "input", "lazyNpmRoot", "hit", "test", "npmRoot", "isLocalNodeModulesInstall", "cwd", "realpathSync", "path", "safeRealpath", "dir", "execFileSync", "process", "NPM_ROOT_TIMEOUT_MS", "defaultLazyNpmRoot", "trimmed", "spawnSync", "homedir", "process", "fs", "path", "process", "LOCK_FILE_NAME", "LOCK_STALE_MS", "lockFilePath", "path", "getCacheRoot", "reapIfStale", "lockPath", "nowMs", "fs", "acquireUpdateLock", "deps", "open", "fd", "process", "DEFAULT_REGISTRY", "FETCH_TIMEOUT_MS", "configuredRegistry", "env", "key", "value", "registryUrl", "configured", "base", "fetchLatestVersion", "fetchFn", "controller", "timer", "response", "PACKAGE_NAME", "version", "RELEASE_PATTERN", "parseSemver", "version", "withoutBuild", "core", "prereleaseParts", "match", "major", "minor", "patch", "NUMERIC_IDENTIFIER", "compareIdentifier", "left", "right", "leftNumeric", "rightNumeric", "comparePrerelease", "a", "b", "index", "isNewerVersion", "latest", "current", "parsedLatest", "parsedCurrent", "latestIsFinal", "currentIsFinal", "fs", "path", "CACHE_FILE_NAME", "CHECK_INTERVAL_MS", "cacheFilePath", "path", "getCacheRoot", "isStringArray", "value", "entry", "isUpdateCache", "lastCheckMs", "latestVersion", "updateCommand", "readUpdateCache", "readFile", "p", "fs", "parsed", "writeUpdateCache", "cache", "root", "atomicWriteFileSync", "isStale", "nowMs", "elapsed", "PARENT_POLL_INTERVAL_MS", "PARENT_WAIT_TIMEOUT_MS", "defaultIsProcessAlive", "pid", "process", "defaultSleep", "ms", "resolve", "waitForParentExit", "parentPid", "deps", "deadline", "runUpdateCheck", "currentVersion", "release", "acquireUpdateLock", "runUpdateCheckLocked", "env", "nowMs", "fetchLatest", "fetchLatestVersion", "writeCache", "writeUpdateCache", "isProcessAlive", "sleep", "clock", "lazyNpmRoot", "defaultLazyNpmRoot", "spawn", "spawnSync", "latestVersion", "finish", "outcome", "cache", "isNewerVersion", "canSelfSpawn", "updateCommand", "detectInstallManager", "safeRealpath", "result", "homedir", "packageManagerInstallEnv"]
7
+ }
@@ -1,4 +1,4 @@
1
- import{a as T}from"./chunk-6FU2TRU5.js";import{O as v,Q as S,c as E,i as C,v as u}from"./chunk-KZP2SY37.js";import W from"node:process";import{$ as w}from"zx";var $=async()=>{try{return await w`cmux --version`.quiet(),!0}catch{return!1}},N=async e=>{let{cwd:t,title:r,layout:n}=e,o=JSON.stringify(n),i=(await w({env:{...W.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${r} --cwd ${t} --focus false --layout ${o}`).stdout;return D(i)},_=async e=>{try{await w`cmux close-workspace --workspace ${e}`.quiet()}catch(t){u.debug({error:t,ref:e},"cmux: skipped closing dev workspace")}},D=e=>{let t=e.match(/workspace:\d+/);if(!t)throw new Error("cmux: could not locate workspace ref in new-workspace output");return t[0]};var I=/\bv(\d+\.\d+\.\d+)\b/g,l=e=>e.trim().replace(/\s+/g," ").replace(I,"$1");import{$ as A}from"zx";var M=async e=>{try{let t=(await A`cmux list-workspaces`.quiet()).stdout,r=B(t,e);if(!r)return;await A`cmux close-workspace --workspace ${r}`.quiet()}catch(t){u.debug({error:t,title:e},"cmux: skipped closing workspace")}},B=(e,t)=>{let r=l(t);for(let n of e.split(`
1
+ import{a as T}from"./chunk-A7FAXZGI.js";import{O as v,Q as S,c as E,i as C,v as u}from"./chunk-AVLZBOOA.js";import W from"node:process";import{$ as w}from"zx";var $=async()=>{try{return await w`cmux --version`.quiet(),!0}catch{return!1}},N=async e=>{let{cwd:t,title:r,layout:n}=e,o=JSON.stringify(n),i=(await w({env:{...W.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${r} --cwd ${t} --focus false --layout ${o}`).stdout;return D(i)},_=async e=>{try{await w`cmux close-workspace --workspace ${e}`.quiet()}catch(t){u.debug({error:t,ref:e},"cmux: skipped closing dev workspace")}},D=e=>{let t=e.match(/workspace:\d+/);if(!t)throw new Error("cmux: could not locate workspace ref in new-workspace output");return t[0]};var I=/\bv(\d+\.\d+\.\d+)\b/g,l=e=>e.trim().replace(/\s+/g," ").replace(I,"$1");import{$ as A}from"zx";var M=async e=>{try{let t=(await A`cmux list-workspaces`.quiet()).stdout,r=B(t,e);if(!r)return;await A`cmux close-workspace --workspace ${r}`.quiet()}catch(t){u.debug({error:t,title:e},"cmux: skipped closing workspace")}},B=(e,t)=>{let r=l(t);for(let n of e.split(`
2
2
  `)){let o=n.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let s=o[1],i=o[2]?.trim()??"";if(l(i)===r)return s}};import{$ as U}from"zx";var F=async()=>{try{let e=(await U`cmux list-workspaces`.quiet()).stdout,t=new Set;for(let r of e.split(`
3
3
  `)){let n=r.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let o=n[1]?.trim();o&&t.add(l(o))}return t}catch(e){return u.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as p}from"zx";var q=async e=>{let{cwd:t,title:r}=e,n=v(await S()),o=(await p`cmux workspace create --cwd ${t}`).stdout,s=J(o),i=(await p`cmux list-pane-surfaces --workspace ${s}`).stdout,c=z(i);await p`cmux new-split right --workspace ${s} --surface ${c}`,n==="three-pane"&&await p`cmux new-split down --workspace ${s} --surface ${c}`,r&&await p`cmux workspace rename --workspace ${s} --title ${r}`},z=e=>{let t=e.match(/surface:\d+/);if(!t)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return t[0]},J=e=>{let t=e.match(/workspace:\d+/);if(!t)throw new Error("cmux: could not locate workspace ref in workspace create output");return t[0]};var j=e=>{let{repoName:t,branch:r}=e,n=E(r),o=n?C(n):r;return`${t} ${o}`};var H=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),R=e=>e instanceof Error&&H.has(e.name),je=e=>{if(R(e))return!0;let t=e?.cause;return R(t)};import{execFile as K}from"node:child_process";import{createHash as Q}from"node:crypto";import{existsSync as V,readFileSync as f}from"node:fs";import G from"node:http";import X from"node:https";import Y from"node:net";import{homedir as Z}from"node:os";import{dirname as k,join as m}from"node:path";import g from"node:process";import ee from"node:tls";import{fileURLToPath as te}from"node:url";import{promisify as re}from"node:util";var oe=re(K),ne=e=>{let t=JSON.parse(f(e,"utf-8")),r=typeof t.bin=="string"?t.bin:t.bin?.portless;return r==null||r===""?null:r},se=()=>{try{let e=k(te(import.meta.url));for(;;){let t=m(e,"node_modules","portless","package.json");if(V(t)){let n=ne(t);return n==null?null:m(k(t),n)}let r=k(e);if(r===e)return null;e=r}}catch{return null}},h,L=()=>(h===void 0&&(h=se()),h),ie=/^[\w@%+=:,./-]+$/,ae="'\\''",ce=e=>ie.test(e)?e:`'${e.replaceAll("'",ae)}'`,it=(e,t)=>{let r=[t.execPath??g.execPath,t.bin,...e];return(t.sudo===!0?"sudo ":"")+r.map(ce).join(" ")},ue=1500,y=1500,le="x-portless",P="127.0.0.1",me="localhost",pe=e=>new Promise(t=>{let r=Y.connect({host:P,port:e}),n=o=>{r.destroy(),t(o)};r.setTimeout(y),r.once("connect",()=>{n(!0)}),r.once("timeout",()=>{n(!1)}),r.once("error",()=>{n(!1)})}),fe=(e,t)=>new Promise(r=>{let o=(t?X.request:G.request)({host:P,port:e,method:"HEAD",path:"/",timeout:y,...t?{rejectUnauthorized:!1,servername:me}:{}},s=>{s.resume(),r(s.headers[le]==="1")});o.on("error",()=>{r(!1)}),o.on("timeout",()=>{o.destroy(),r(!1)}),o.end()}),de=async(e,{timeoutMs:t})=>{let r=L();if(r==null)throw new Error("portless is not installed (not resolvable from node_modules)");await oe(g.execPath,[r,...e],{signal:AbortSignal.timeout(t),encoding:"utf-8",env:T(g.env)})},b=()=>g.env.PORTLESS_STATE_DIR??m(Z(),".portless"),ge="ca.pem",xe="ca.trusted",O=()=>m(b(),ge),at=()=>{try{let e=f(m(b(),xe),"utf-8").trim();return e===""?!1:Q("sha256").update(f(O())).digest("hex")===e.toLowerCase()}catch{return!1}},ct=(e,t)=>new Promise(r=>{let n;try{n=f(O())}catch{r({ok:!1,code:"ENOENT"});return}let o=ee.connect({host:P,port:e,servername:t,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,i=o.authorized;o.destroy(),r(i?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(y),o.once("timeout",()=>{o.destroy(),r({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),r({ok:!1,code:s.code??"UNKNOWN"})})}),ut=()=>{try{let e=JSON.parse(f(m(b(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(t=>{let{hostname:r,port:n}=t??{};return typeof r!="string"||r===""||typeof n!="number"?[]:[{name:r,port:n}]}):[]}catch{return[]}},lt=(e={})=>{let t=e.bin===void 0?L():e.bin,r=e.run??de,n=e.isListening??pe,o=e.isProxyServing??fe,s=e.timeoutMs??ue,i=null,c=async a=>{try{return await r(a,{timeoutMs:s}),!0}catch{return!1}},d=async()=>(i??=await c(["--version"]),i);return{binPath:()=>t,isAvailable:d,isProxyServing:async(a,x)=>!await d()||!await n(a)?!1:o(a,x),registerAlias:async(a,x)=>await d()?c(["alias",a,String(x)]):!1,removeAlias:async a=>{await d()&&await c(["alias","--remove",a])}}};export{se as a,it as b,pe as c,fe as d,O as e,at as f,ct as g,ut as h,lt as i,l as j,M as k,F as l,$ as m,N as n,_ as o,q as p,j as q,je as r};
4
- //# sourceMappingURL=chunk-NC2TIQ3M.js.map
4
+ //# sourceMappingURL=chunk-V4XK2YEH.js.map
package/dist/cli.js CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{$ as At,A as ot,B as rt,C as nt,D as it,E as at,F as st,G as te,H as ct,I as M,J as m,K as lt,L as mt,M as dt,N as pt,O as ut,P as ft,Q as gt,R as ht,S as vt,T as yt,U as wt,V as St,W as kt,X as Rt,Y as oe,Z as Et,_ as xt,a as N,aa as Tt,b as Ne,ba as Ct,c as Le,ca as Pt,d as _e,da as bt,e as De,f as Oe,fa as It,g as _,ga as Nt,h as x,ha as Dt,i as h,j as O,k as qe,l as Ve,m as Je,n as F,o as Ke,p as Be,q as We,r as Ye,s as He,t as Xe,u as Qe,v as Ze,w as Z,x as et,y as tt,z as ee}from"./chunk-RLZ5IB2E.js";import{r as re}from"./chunk-NC2TIQ3M.js";import{a as Lt,b as j,c as _t,d as T,e as ne,f as ie,g as ae}from"./chunk-E2SEBLGJ.js";import{a as ze}from"./chunk-E2NWNNC6.js";import{a as $}from"./chunk-6FU2TRU5.js";import{a as A}from"./chunk-4MRYIYJP.js";import{P as X,Q as L,S as Ie,m as be,v as c}from"./chunk-KZP2SY37.js";import{a as D,b as Fe,d as $e,f as Me,g as je,j as Q,k as Ue,n as v,q as Ge}from"./chunk-CHETBZ6M.js";import jr,{Separator as fo}from"@inquirer/select";import{realpathSync as Ur}from"node:fs";import g from"node:process";import{fileURLToPath as ho}from"node:url";var yo=(e,t)=>{let o=e,r;for(let a of t){if(r=o.find(n=>n.name()===a),!r)return;o=r.commands}return r},Ot=e=>Pt.flatMap(({key:t,label:o})=>It(t).flatMap(r=>{let a=yo(e,r.groupPath);return a?[{name:r.groupPath.join(" "),description:a.description(),group:o}]:[]}));import{Command as tr}from"commander";import I from"node:process";import Ft from"node:process";import{$ as wo}from"zx";var se=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 x(i.path)}))),o=t.at(-1)?.exists===!0,r=await ot(e.userProject,o),a=o?rt(r):"";c.info(`Project name: ${e.projectName}
3
- `),c.info(`Config merge chain (later overrides earlier):
4
- `);for(let i of t){let l=i.exists?" [\u2713]":" [ ]",s=i.path===e.userProject&&a!==""?` ${a}`:"";c.info(`${l} ${i.label.padEnd(22)} ${h(i.path)}${s}`)}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=Ft.env.EDITOR||Ft.env.VISUAL||"vi",o=await Xe(e);o.createdConfig&&c.info(Qe(o)),c.info(`Opening ${h(e.userProject)} in ${t}`),await wo({stdio:"inherit"})`${t} ${e.userProject}`,Ie();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}},U=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 P from"node:process";var So="autoload-warn-misconfig.flag",ko="autoload-warn-fail.flag",Mt="autoload-warn-auth-fail.flag",me="autoload-fail.flag",de="autoload-auth-fail.json",Ro=3e4,jt=async(e=!0)=>{let t;try{t=await L()}catch{return null}let o=t.envAutoLoad;return o?t.environments.includes(o.config)?{trigger:o.trigger,config:o.config,project:t.envManagement.config.name}:(e&&G(`infra-kit: envAutoLoad.config "${o.config}" is not one of environments [${t.environments.join(", ")}] \u2014 env auto-load disabled.`,So),null):null},Ut=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:a,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===a?"skip":"load"},b=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Le})=>{let a=e==="cli-invocation";a&&q();let n=null;try{if(n=await jt(a),!n||Ut({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:To(),force:o})==="skip"||$t()||bo())return null;let l=Co(),s=await Ke({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!$t()&&!Po(l)});return s?(No(),Ao(),s.filePath):null}catch(i){let l=i.message,s=r(i);return Io(),s&&n&&xo({config:n.config,reason:l,at:Date.now()}),a&&s&&n?(G(U(n.config),Mt),c.debug(`env auto-load auth failure: ${l}`)):a?G(`infra-kit: env auto-load failed \u2014 ${l} (will retry later)`,ko):c.debug(`env auto-load skipped: ${l}`),null}},q=()=>{let e=Eo();e&&(G(U(e.config),Mt),c.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},Eo=()=>{try{let e=p.readFileSync(y.join(v(),de),"utf-8");return le(JSON.parse(e))}catch{return null}},xo=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Ge(y.join(t,de),JSON.stringify(e),384)}catch{}},Ao=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},To=()=>({session:P.env[$e],cleared:P.env[Ue],currentConfig:P.env[Me],currentProject:P.env[je],autoLoadedMarker:P.env[Q]}),Co=()=>{try{return p.statSync(y.join(v(),D)).mtimeMs}catch{return null}},Po=e=>{try{let t=y.join(v(),D);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}},$t=()=>{try{let e=v(),t=y.join(e,Fe);if(!p.existsSync(t))return!1;let o=y.join(e,D);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},bo=()=>{try{let e=y.join(v(),me);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Ro:!1}catch{return!1}},Io=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,me),"",{mode:384})}catch{}},No=()=>{try{p.rmSync(y.join(v(),me),{force:!0})}catch{}},G=(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{}c.warn(e)};var pe=async({projectDir:e}={})=>{await b({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Gt="https://dashboard.doppler.com/workplace/projects",Lo=(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}"): ${Gt}/${e}`],ue=async({env:e})=>{let o=!!(await qe())?.envs[e];await Je(e);let r=await F(),a=await _(),n=await O();o?c.info(`Removed the "${e}" service token from ${h(n)}.`):c.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&c.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let l of Lo(a,e))c.warn(l);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Gt}/${a}`};return{content:N(JSON.stringify(i,null,2)),structuredContent:i}};import _o from"@inquirer/password";import J from"node:process";import{$ as V}from"zx";var Do=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Oo(),source:"stdin"};if(t){let r=J.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 _o({message:"Paste the Doppler service token (input is hidden)",mask:!0},{output:J.stderr})).trim(),source:"prompt"}},Oo=async()=>{let e=[];J.stdin.setEncoding("utf8");for await(let t of J.stdin)e.push(t);return e.join("").trim()},fe="DOPPLER_CONFIG",Fo=3e4,$o=async(e,t,o)=>{let r=V.quiet;V.quiet=!0;let a;try{a=(await V({env:We(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(Fo)).stdout}catch(n){throw Mo(n,o)}finally{V.quiet=r}return He(a)},Mo=(e,t)=>{let o=Oe(e)??(e instanceof Error?e.message:String(e));if(_e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=De(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
- `))},jo=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${fe}.`,"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
- `),ge=async({env:e,stdin:t,fromEnv:o,force:r})=>{let{environments:a}=await L();if(!a.includes(e))throw new Error(`Unknown environment "${e}". infra-kit.json \u2192 environments declares: ${a.join(", ")}.`);let n=await _(),{token:i,source:l}=await Do({stdin:t,fromEnv:o});if(!i)throw new Error("No token provided \u2014 nothing was written.");let s=await $o(i,n,e);Ye(s,e);let d=s.some(([k])=>k===fe);if(!d&&!r)throw new Error(jo(e));await Ve(e,i);let u=await F(),f=await O();c.info(`Stored the "${e}" service token (${te(i)}) in ${h(f)} (mode 0600).`),d||c.warn(`Scope was NOT verified (no ${fe} in the payload) \u2014 written because --force was given.`),u.length>0&&c.info(`Purged ${u.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let E={env:e,source:l,redactedToken:te(i),storePath:f,scopeVerified:d,warmCachesPurged:u.length};return A.print(),{content:N(JSON.stringify(E,null,2)),structuredContent:E}};import{spawn as Uo}from"node:child_process";import K from"node:process";import{fileURLToPath as Go}from"node:url";var qo=["SIGINT","SIGTERM"],qt=()=>Go(new URL("./mcp.js",import.meta.url)),he=(e={})=>{let t=e.spawn??Uo,o=e.exit??(i=>K.exit(i)),r=e.env??K.env,a=e.onError??(i=>c.error(i)),n=t(K.execPath,[qt()],{stdio:"inherit",env:$(r)});n.on("error",i=>{a(`failed to launch the MCP server: ${i.message}`),o(1)}),qo.forEach(i=>{K.on(i,()=>{n.kill(i)})}),n.on("exit",(i,l)=>{o(l?1:i??1)})};import{spawnSync as Vo}from"node:child_process";import{realpathSync as Jo}from"node:fs";import ve from"node:process";import{fileURLToPath as Ko}from"node:url";var Bo=()=>Jo(Ko(import.meta.url)),Wo=(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),ye=({dryRun:e},t={})=>{let o=t.spawnSync??Vo,r=t.print??(k=>c.info(k)),a=t.exit??(k=>ve.exit(k)),n=t.env??ve.env,i=t.selfRealPath??Bo(),l=t.lazyNpmRoot??_t,{manager:s,updateCommand:d,canSelfSpawn:u}=Lt({selfRealPath:i,env:n,realpath:T,lazyNpmRoot:l}),f=d.join(" ");if(e){r(`Detected install manager: ${s}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${s}`),r(`Run this yourself: ${f}`),r(s==="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 E=o(d[0],d.slice(1),{stdio:"inherit",shell:ve.platform==="win32",env:$(n)});Wo(E,s,r,a)};import{VENDOR_CONFIG_FILE as Jt}from"@slip-stream-kit/config/internal";import we from"node:fs/promises";import Se from"node:path";import Vt from"node:process";import{pathToFileURL as Yo}from"node:url";var Kt="~/projects",ke=async(e={})=>{if(e.init){await zo(e.cwd);return}await Ho()},Ho=async()=>{let e=Z(),t=await x(e);if(c.info(`Factory config: ${h(e)} ${t?"[\u2713]":"[ ]"}`),!t){c.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Vt.exitCode=1;return}let{workspaceDir:o,targets:r}=await tt(),a=et(o),n=await x(a);c.info(`workspaceDir: ${o} (resolved: ${a}) ${n?"[\u2713 exists]":"[ ] not found"}`),c.info("Targets:");let i=n;for(let l of r){let s=Se.join(a,l),d=await x(s);d||(i=!1);let u=d?"[\u2713]":"[ ]",f=d?"":" (not found \u2014 clone or remove)";c.info(` ${u} ${l} ${h(s)}${f}`)}i||(Vt.exitCode=1)},zo=async e=>{let t=Z();if(await x(t)){c.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await be(),r=await Xo(o);await we.mkdir(Se.dirname(t),{recursive:!0}),await we.writeFile(t,Qo(r),"utf-8"),c.info(`\u2713 Created ${h(t)}`),r.length>0&&c.info(` Seeded ${r.length} target(s) from the source ${Jt}.`),c.info(` Edit \`workspaceDir\` (placeholder: ${Kt}) to point at where your repos live.`),r.length===0&&c.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},Xo=async e=>{try{let t=Se.join(e,Jt),o=await we.stat(t),n=(await import(`${Yo(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let l=i.targets;if(Array.isArray(l)&&l.every(s=>typeof s=="string"))return l}}catch{}return[]},Qo=e=>`${JSON.stringify({workspaceDir:Kt,targets:e},null,2)}
7
- `;var B=(e,t=!0)=>({line:e,reproducible:t});import W from"node:fs";import Zo from"node:os";import er from"node:path";import Ht from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Re=null,Bt=!1,Wt=[],zt=(e=Ht.env)=>{Bt||(Re=e[Y]??null,Bt=!0,delete e[Y])};var Xt=(e,t)=>{if(!Re)return;let o=e.summary??(Wt.length>0?[...Wt]:void 0),r={...e,...o?{summary:o}:{}},a=t?.write??((n,i)=>{W.writeFileSync(n,i)});try{a(Re,JSON.stringify(r))}catch{}},Yt=0,Qt=e=>{let t=e?.tmpdir?.()??Zo.tmpdir(),o=e?.pid??Ht.pid;return Yt+=1,er.join(t,`infra-kit-session-${o}-${Yt}.json`)},Zt=(e,t)=>{if(!(t?.exists??(i=>W.existsSync(i)))(e))return null;let r=t?.read??(i=>W.readFileSync(i,"utf-8")),a=t?.unlink??(i=>W.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{a(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var or=(e,t)=>[...t,e],Ee=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,eo=(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(", ")}.`)}},rr=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=>{m(await mt({all:t.all,confirmedCommand:t.yes}))}),nr=e=>e.description("List all release branches").action(async()=>{m(await ft())}),ir=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".',or,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(gt),a=r.length>0?r:void 0;m(await ht({releases:a,confirmedCommand:t.yes}))}),ar=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=>{m(await vt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),sr=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=>{m(await pt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),cr=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=>{m(await ut({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),lr=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=>{m(await dt({version:t.version,confirmedCommand:t.yes}))}),mr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ct({confirmedCommand:t.yes}))}),dr=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=eo(t.ide,"--ide")??eo(t.cursor,"--cursor");m(await Et({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),pr=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await xt())}),ur=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=>{m(await Tt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),fr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{m(await At())}),gr=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=>{m(await ke({init:t.init}))}),hr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await yt();m(t),t.structuredContent.ok||(I.exitCode=1)}),vr=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 wt({repos:Ee(t.repos)});m(o),o.structuredContent.ok||(I.exitCode=1)}),yr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await se())}),wr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await ce())}),Sr=new Set(["init","doctor","version","dev","self-update","mcp"]),kr=e=>e.startsWith("env-")||Sr.has(e),Rr=new Set(["env-autoload","mcp","version","self-update"]),H=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},xe=()=>{let e=new tr,t=e.command("release").description("Release management commands");rr(t.command("merge-dev")),nr(t.command("list")),ir(t.command("create")),ar(t.command("desc-edit")),sr(t.command("deploy-all")),cr(t.command("deploy-selected")),lr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");dr(o.command("add")),pr(o.command("list")),ur(o.command("remove")),mr(o.command("sync")),fr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");yr(r.command("path")),wr(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 Ne({all:n.all,root:n.root});m(i),i.structuredContent.allPassed||(I.exitCode=1)});let a=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return hr(a.command("check")),a.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=>{m(await kt({confirmedCommand:n.yes,repos:Ee(n.repos)}))}),a.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=>{m(await St({confirmedCommand:!0,repos:Ee(n.repos)}))}),vr(a.command("diff")),gr(a.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=>{m(await nt({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=>{ye({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{he()}),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)").action(async(n,i)=>{let{runDevServerCli:l}=await import("./dev-server.js"),s=!!(I.stdout.isTTY&&I.stdin.isTTY);await l({...i,preset:n},s,M.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await Rt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await st())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{m(await at())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{m(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=>{m(await Be({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=>{m(await it({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)=>{m(await ge({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=>{m(await ct({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=>{m(await ue({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(lt),e.hook("preAction",async(n,i)=>{A.start(H(i)),M.enabled=!!i.optsWithGlobals().json,M.enabled&&(c.level="warn"),Rr.has(H(i))||await Ze(),q(),kr(i.name())||await b({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let l=H(i);if(Nt(l))return;let d=A.snapshot()?.formattedOptions??"",u=d?` ${d}`:"",f=`infra-kit ${l}${u}`;Xt({equivalent:B(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[a])=>Math.max(r,a.length),0);return e.map(([r,a])=>`${r.padEnd(o)}${t}${a}`)};import{spawn as Tr}from"node:child_process";import S from"node:process";var 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."},to={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},oo=e=>`${w.reproPrefix}${e}`,Er=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,xr=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],ro=e=>{let t=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,o=e.ascii===!0?to[e.outcome].ascii:to[e.outcome].unicode,a=[xr(e.outcome,e.findingsCount),Er(e.durationMs)],n=e.summary?.[0];n!=null&&n.length>0&&a.push(n);let i=[`${o} ${a.join(w.sep)}`];return e.showEquivalent!==!1&&i.unshift(`${t}${e.equivalent.line}`),e.envNotice===!0&&i.push(w.envNotice),i.join(`
8
- `)};var Ar=new Set([130,143]),no=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Ar.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import io from"node:process";var R={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},ao=(e,t)=>{let o=t?.write??(n=>{io.stderr.write(n)}),r=t?.stdin??io.stdin,a=[R.saveCursor,R.scrollRegion,R.restoreCursor,R.column,R.sgr,R.cursor,R.wrap];e.entersAltScreen===!0&&a.push(R.primaryBuffer),o(a.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var so=e=>`infra-kit ${e.groupPath.join(" ")}`,Cr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Pr=async(e,t,o)=>{let r=Qt(),a={...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:a});i=await Cr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let l=Zt(r),s=no(i.code,i.signal,l!=null,e.longRunning),d=so(e),u=l?.equivalent??B(d,!0);return ro({equivalent:u,outcome:s,durationMs:t.now()-n,summary:l?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,showEquivalent:!(u.reproducible&&u.line===d)})},br=(e,t)=>{let o=!1,r=!1,a=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},l=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",a),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",l),{dispose:()=>{t.unregister("SIGINT",a),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",l)},childStarted:()=>{o=!1},quitRequested:()=>r}},co=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),lo=async(e,t)=>{let o={spawn:t.spawn??Tr,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),resetTerminal:t.resetTerminal??(s=>{ao(s)})},r=t.write??(s=>S.stderr.write(s)),a=t.signals??{register:(s,d)=>{S.on(s,d)},unregister:(s,d)=>{S.off(s,d)},exit:s=>{S.exit(s)},raise:s=>{S.kill(S.pid,s)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},l=t.installSignals===!1?i:br(()=>n,a);try{for(;;){if(l.quitRequested())return;n=!1;let s=await t.renderPalette(e);if(s==null)return;let d=t.resolveCommand(s);if(!d)continue;let u=oo(so(d));r(`
2
+ import{$ as Ot,A as ee,B as pt,C as j,D as d,E as ft,F as gt,G as ht,H as vt,I as yt,J as wt,K as St,L as kt,M as Rt,N as Et,O as xt,P as Ct,Q as Tt,R as At,S as te,T as bt,U as Pt,V as It,W as Lt,X as Nt,Y as Dt,Z as _t,a as _,aa as $t,b as De,ba as jt,c as Oe,d as $e,e as Fe,f as O,g as Ke,h as M,i as Ye,j as He,k as ze,l as Xe,m as Qe,n as et,o as tt,p as ot,q as Q,r as rt,s as nt,t as Z,u as at,v as ct,w as lt,x as mt,y as dt,z as ut}from"./chunk-TL7LO2FF.js";import{r as oe}from"./chunk-V4XK2YEH.js";import{a as Ft,b as U,c as Mt,d as A,e as re,f as ne,g as ie}from"./chunk-UO3FYLPX.js";import{a as Ze}from"./chunk-JPTSUMWI.js";import{a as it,b as st}from"./chunk-A7FAXZGI.js";import{b as _e,c as C,d as h,e as F,f as Je,g as We,h as Be,i as T}from"./chunk-KAKTWDWJ.js";import{P as z,Q as Le,S as Ne,m as Ie,v as l}from"./chunk-AVLZBOOA.js";import{a as $,b as Me,d as je,f as Ue,g as Ge,j as X,k as qe,n as v,q as Ve}from"./chunk-CHETBZ6M.js";import Zr,{Separator as Ro}from"@inquirer/select";import{realpathSync as en}from"node:fs";import g from"node:process";import{fileURLToPath as xo}from"node:url";var To=(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},Ut=e=>Dt.flatMap(({key:t,label:o})=>Ot(t).flatMap(r=>{let s=To(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as cr}from"commander";import D from"node:process";import Gt from"node:process";import{$ as Ao}from"zx";var se=async()=>{let e=await z(),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 C(i.path)}))),o=t.at(-1)?.exists===!0,r=await at(e.userProject,o),s=o?ct(r):"";l.info(`Project name: ${e.projectName}
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}},ae=async()=>{let e=await z(),t=Gt.env.EDITOR||Gt.env.VISUAL||"vi",o=await et(e);o.createdConfig&&l.info(tt(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await Ao({stdio:"inherit"})`${t} ${e.userProject}`,Ne();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var ce=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 L from"node:process";var bo="autoload-warn-fail.flag",le="autoload-warn-auth-fail.flag",me="autoload-fail.flag",de="autoload-auth-fail.json",Po=3e4,Vt=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 Ke(o.config))return r}catch{return r}return Wt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&G(I(o.config),le),null},Jt=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"},N=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=_e})=>{let s=e==="cli-invocation";s&&q();let n=null;try{if(n=await Vt(s),!n||Jt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:No(),force:o})==="skip"||qt()||Oo())return null;let c=Do(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!qt()&&!_o(c)});return a?(Fo(),Lo(),a.filePath):null}catch(i){let c=i.message,a=r(i);return $o(),a&&n&&Wt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(G(I(n.config),le),l.debug(`env auto-load auth failure: ${c}`)):s?G(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,bo):l.debug(`env auto-load skipped: ${c}`),null}},q=()=>{let e=Io();e&&(G(I(e.config),le),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},Io=()=>{try{let e=p.readFileSync(y.join(v(),de),"utf-8");return ce(JSON.parse(e))}catch{return null}},Wt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Ve(y.join(t,de),JSON.stringify(e),384)}catch{}},Lo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},No=()=>({session:L.env[je],cleared:L.env[qe],currentConfig:L.env[Ue],currentProject:L.env[Ge],autoLoadedMarker:L.env[X]}),Do=()=>{try{return p.statSync(y.join(v(),$)).mtimeMs}catch{return null}},_o=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 ${X}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},qt=()=>{try{let e=v(),t=y.join(e,Me);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}},Oo=()=>{try{let e=y.join(v(),me);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Po:!1}catch{return!1}},$o=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,me),"",{mode:384})}catch{}},Fo=()=>{try{p.rmSync(y.join(v(),me),{force:!0})}catch{}},G=(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 ue=async({projectDir:e}={})=>{await N({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Bt="https://dashboard.doppler.com/workplace/projects",Mo=(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}`],pe=async({env:e})=>{let o=!!(await Je())?.envs[e];await Be(e);let r=await M(),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 Mo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Bt}/${s}`};return{content:_(JSON.stringify(i,null,2)),structuredContent:i}};import jo from"@inquirer/password";import J from"node:process";import{$ as V}from"zx";var Uo=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Go(),source:"stdin"};if(t){let r=J.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return T.setInteractive(),{token:(await jo({message:"Paste the Doppler service token (input is hidden)",mask:!0},{output:J.stderr})).trim(),source:"prompt"}},Go=async()=>{let e=[];J.stdin.setEncoding("utf8");for await(let t of J.stdin)e.push(t);return e.join("").trim()},fe="DOPPLER_CONFIG",qo=3e4,Vo=async(e,t,o)=>{let r=V.quiet;V.quiet=!0;let s;try{s=(await V({env:ze(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(qo)).stdout}catch(n){throw Jo(n,o)}finally{V.quiet=r}return Qe(s)},Jo=(e,t)=>{let o=Fe(e)??(e instanceof Error?e.message:String(e));if(Oe(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=$e(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
+ `))},Wo=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${fe}.`,"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
+ `),ge=async({env:e,stdin:t,fromEnv:o,force:r})=>{let s=await O(),{token:n,source:i}=await Uo({stdin:t,fromEnv:o});if(!n)throw new Error("No token provided \u2014 nothing was written.");let c=await Vo(n,s,e);Xe(c,e);let a=c.some(([k])=>k===fe);if(!a&&!r)throw new Error(Wo(e));await We(e,n);let m=await M(),u=await F();l.info(`Stored the "${e}" service token (${ee(n)}) in ${h(u)} (mode 0600).`),a||l.warn(`Scope was NOT verified (no ${fe} 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:ee(n),storePath:u,scopeVerified:a,warmCachesPurged:m.length};return T.print(),{content:_(JSON.stringify(f,null,2)),structuredContent:f}};import{spawn as Bo}from"node:child_process";import W from"node:process";import{fileURLToPath as Ko}from"node:url";var Yo=["SIGINT","SIGTERM"],Kt=()=>Ko(new URL("./mcp.js",import.meta.url)),he=(e={})=>{let t=e.spawn??Bo,o=e.exit??(i=>W.exit(i)),r=e.env??W.env,s=e.onError??(i=>l.error(i)),n=t(W.execPath,[Kt()],{stdio:"inherit",env:it(r)});n.on("error",i=>{s(`failed to launch the MCP server: ${i.message}`),o(1)}),Yo.forEach(i=>{W.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as Ho}from"node:child_process";import{realpathSync as zo}from"node:fs";import{homedir as Xo}from"node:os";import ve from"node:process";import{fileURLToPath as Qo}from"node:url";var Zo=()=>zo(Qo(import.meta.url)),er=(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),ye=({dryRun:e},t={})=>{let o=t.spawnSync??Ho,r=t.print??(R=>l.info(R)),s=t.exit??(R=>ve.exit(R)),n=t.env??ve.env,i=t.selfRealPath??Zo(),c=t.lazyNpmRoot??Mt,{manager:a,updateCommand:m,canSelfSpawn:u}=Ft({selfRealPath:i,env:n,realpath:A,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:ve.platform==="win32",cwd:Xo(),env:st(n)});er(k,a,r,s)};import{VENDOR_CONFIG_FILE as Ht}from"@slip-stream-kit/config/internal";import we from"node:fs/promises";import Se from"node:path";import Yt from"node:process";import{pathToFileURL as tr}from"node:url";var zt="~/projects",ke=async(e={})=>{if(e.init){await rr(e.cwd);return}await or()},or=async()=>{let e=Q(),t=await C(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 nt(),s=rt(o),n=await C(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=Se.join(s,c),m=await C(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)},rr=async e=>{let t=Q();if(await C(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Ie(),r=await nr(o);await we.mkdir(Se.dirname(t),{recursive:!0}),await we.writeFile(t,ir(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${Ht}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${zt}) 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.")},nr=async e=>{try{let t=Se.join(e,Ht),o=await we.stat(t),n=(await import(`${tr(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[]},ir=e=>`${JSON.stringify({workspaceDir:zt,targets:e},null,2)}
7
+ `;var B=(e,t=!0)=>({line:e,reproducible:t});import K from"node:fs";import sr from"node:os";import ar from"node:path";import eo from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Re=null,Xt=!1,Qt=[],to=(e=eo.env)=>{Xt||(Re=e[Y]??null,Xt=!0,delete e[Y])};var oo=(e,t)=>{if(!Re)return;let o=e.summary??(Qt.length>0?[...Qt]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{K.writeFileSync(n,i)});try{s(Re,JSON.stringify(r))}catch{}},Zt=0,ro=e=>{let t=e?.tmpdir?.()??sr.tmpdir(),o=e?.pid??eo.pid;return Zt+=1,ar.join(t,`infra-kit-session-${o}-${Zt}.json`)},no=(e,t)=>{if(!(t?.exists??(i=>K.existsSync(i)))(e))return null;let r=t?.read??(i=>K.readFileSync(i,"utf-8")),s=t?.unlink??(i=>K.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var lr=(e,t)=>[...t,e],Ee=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,io=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&te.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${te.join(", ")}.`)}},mr=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 gt({all:t.all,confirmedCommand:t.yes}))}),dr=e=>e.description("List all release branches").action(async()=>{d(await wt())}),ur=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".',lr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(St),s=r.length>0?r:void 0;d(await kt({releases:s,confirmedCommand:t.yes}))}),pr=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 Rt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),fr=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 vt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),gr=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 yt({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),hr=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 ht({version:t.version,confirmedCommand:t.yes}))}),vr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await Nt({confirmedCommand:t.yes}))}),yr=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=io(t.ide,"--ide")??io(t.cursor,"--cursor");d(await bt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),wr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await Pt())}),Sr=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}))}),kr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{d(await It())}),Rr=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 ke({init:t.init}))}),Er=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Et();d(t),t.structuredContent.ok||(D.exitCode=1)}),xr=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 xt({repos:Ee(t.repos)});d(o),o.structuredContent.ok||(D.exitCode=1)}),Cr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await se())}),Tr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ae())}),Ar=new Set(["init","doctor","version","dev","self-update","mcp"]),br=e=>e.startsWith("env-")||Ar.has(e),Pr=new Set(["env-autoload","mcp","version","self-update"]),H=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},xe=()=>{let e=new cr,t=e.command("release").description("Release management commands");mr(t.command("merge-dev")),dr(t.command("list")),ur(t.command("create")),pr(t.command("desc-edit")),fr(t.command("deploy-all")),gr(t.command("deploy-selected")),hr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");yr(o.command("add")),wr(o.command("list")),Sr(o.command("remove")),vr(o.command("sync")),kr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");Cr(r.command("path")),Tr(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||(D.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return Er(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 Tt({confirmedCommand:n.yes,repos:Ee(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 Ct({confirmedCommand:!0,repos:Ee(n.repos)}))}),xr(s.command("diff")),Rr(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 lt({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=>{ye({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{he()}),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)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(D.stdout.isTTY&&D.stdin.isTTY);await c({...i,preset:n},a,j.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await At())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(await ut())}),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 dt())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await Z())}),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 He({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 mt({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 ge({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 pt({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 pe({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 ue({projectDir:n.projectDir})}),e.commands.forEach(ft),e.hook("preAction",async(n,i)=>{T.start(H(i)),j.enabled=!!i.optsWithGlobals().json,j.enabled&&(l.level="warn"),Pr.has(H(i))||await ot(),q(),br(i.name())||await N({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=H(i);if($t(c))return;let m=T.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;oo({equivalent:B(f,!0)})}),e};var Ce=(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 Mr}from"chalk";import{spawn as jr}from"node:child_process";import S from"node:process";import{Chalk as Ir}from"chalk";var b=new Ir({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."},so={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},ao={unicode:"\u2500",ascii:"-"},Lr=3,Te=e=>e,Nr={ok:e=>b.green(e),findings:e=>b.yellow(e),failed:e=>b.red(e),cancelled:e=>b.gray(e)},lo=e=>e?{dim:t=>b.dim(t),bold:t=>b.bold(t)}:{dim:Te,bold:Te},Dr=(e,t)=>e?Nr[t]:Te,co=e=>[...e].length,mo=(e,t={})=>{let o=lo(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`,Or=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],$r=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Lr?"":` ${r(o.repeat(s))}`},uo=e=>{let t=e.color===!0,o=lo(t),r=Dr(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?so[e.outcome].ascii:so[e.outcome].unicode,c=Or(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=co(u)+co(f),R=$r(k,e.width,s?ao.ascii:ao.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 Fr=new Set([130,143]),po=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Fr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import fo 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"},go=(e,t)=>{let o=t?.write??(n=>{fo.stderr.write(n)}),r=t?.stdin??fo.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 ho=e=>`infra-kit ${e.groupPath.join(" ")}`,Ur=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},Gr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),qr=async(e,t,o)=>{let r=ro(),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 Gr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=no(r),a=po(i.code,i.signal,c!=null,e.longRunning),m=ho(e),u=c?.equivalent??B(m,!0);return uo({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)})},Vr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){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}},vo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),yo=async(e,t)=>{let o={spawn:t.spawn??jr,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??Mr.level>0,columns:t.columns??Ur,resetTerminal:t.resetTerminal??(a=>{go(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)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Vr(()=>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=mo(ho(m),{color:o.color});r(`
9
10
  ${u}
10
- `),l.childStarted();let f=await Pr(d,o,()=>{n=!0});r(`
11
+ `),c.childStarted();let f=await qr(m,o,()=>{n=!0});r(`
11
12
  ${f}
12
- `)}}finally{l.dispose()}};import{spawn as Lr}from"node:child_process";import po from"node:fs";import C from"node:process";import{fileURLToPath as uo}from"node:url";var mo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Ir=new Set(["mcp","self-update"]),Nr=e=>e[2]!=null&&Ir.has(e[2]),Te=e=>{let{argv:t,env:o,isTty:r,selfRealPath:a,cwd:n,realpath:i}=e;return mo.some(s=>{let d=o[s];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":Nr(t)?"own-command":r?j(a,n,i)?"local-install":null:"not-a-tty"};var _r=e=>{Lr(C.execPath,[e,"--parent-pid",String(C.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Dr=()=>uo(new URL("./update-check.js",import.meta.url)),Or=()=>po.realpathSync(uo(new URL("./cli.js",import.meta.url))),Fr=/^[\w@./+-]+$/i,$r=e=>Fr.test(e),Mr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every($r)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Ce=(e,t={})=>{try{let o=t.argv??C.argv,r=t.env??C.env,a=t.isTty??!!C.stdout.isTTY,n=t.cwd??C.cwd(),i=t.nowMs??Date.now(),l=t.selfRealPath??Or(),s=t.readCache??ie,d=t.spawnChild??_r,u=t.fileExists??(z=>po.existsSync(z)),f=t.notify??(z=>{c.info(z)});if(Te({argv:o,env:r,isTty:a,selfRealPath:l,cwd:n,realpath:T})!==null)return;let E=s();if(Mr(E,e,f),!ae(E,i))return;let k=t.childPath??Dr();if(!u(k))return;d(k)}catch{}};Dt();zt();var Pe=xe(),go=async e=>{try{e?await Pe.parseAsync(e):await Pe.parseAsync()}catch(t){re(t)&&(c.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);c.error(o),g.exit(1)}},Gr=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;j(Ur(ho(import.meta.url)),g.cwd(),T)&&c.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};Gr();Ce(ze.version);var vo=()=>Ot(Pe.commands),qr=async()=>{let e=vo(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-MTVHM4N7.js");t=await o(e)}else{let o=Ae(e.map(a=>[a.name,a.description])),r=e.flatMap((a,n)=>[...e[n-1]?.group===a.group?[]:[new fo(" "),new fo(`\u2014 ${a.group} \u2014`)],{name:o[n]??a.name,value:a.name}]);t=await jr({message:"Select a command to run",choices:r},{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},Vr=async()=>{let{runCommandPalette:e}=await import("./boot-MTVHM4N7.js"),t=ho(import.meta.url),o=new Map(bt.map(r=>[r.groupPath.join(" "),r]));await lo(vo(),{renderPalette:e,resolveCommand:r=>{let a=o.get(r);return a?{groupPath:a.groupPath,entersAltScreen:a.entersAltScreen,sessionEnvNotice:a.sessionEnvNotice,longRunning:a.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(co(g.env,e))await Vr();else{let t=await qr();t&&await go(["node","infra-kit",...t.split(" ")])}}else await go();
13
+ `)}}finally{c.dispose()}};import{spawn as Br}from"node:child_process";import So from"node:fs";import P from"node:process";import{fileURLToPath as ko}from"node:url";var wo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Jr=new Set(["mcp","self-update"]),Wr=e=>e[2]!=null&&Jr.has(e[2]),Ae=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return wo.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Wr(t)?"own-command":r?U(s,n,i)?"local-install":null:"not-a-tty"};var Kr=e=>{Br(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Yr=()=>ko(new URL("./update-check.js",import.meta.url)),Hr=()=>So.realpathSync(ko(new URL("./cli.js",import.meta.url))),zr=/^[\w@./+-]+$/i,Xr=e=>zr.test(e),Qr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||re(e.latestVersion,t)&&e.updateCommand.every(Xr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},be=(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??Hr(),a=t.readCache??ne,m=t.spawnChild??Kr,u=t.fileExists??(x=>So.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(Ae({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:A})!==null)return;let k=a();if(Qr(k,e,f),!ie(k,i))return;let R=t.childPath??Yr();if(!u(R))return;m(R)}catch{}};jt();to();var Pe=xe(),Eo=async e=>{try{e?await Pe.parseAsync(e):await Pe.parseAsync()}catch(t){oe(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},tn=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;U(en(xo(import.meta.url)),g.cwd(),A)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};tn();be(Ze.version);var Co=()=>Ut(Pe.commands),on=async()=>{let e=Co(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-YQAPYAKT.js");t=await o(e)}else{let o=Ce(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new Ro(" "),new Ro(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await Zr({message:"Select a command to run",choices:r},{output:g.stderr})}}catch(o){if(!oe(o))throw o}return t},rn=async()=>{let{runCommandPalette:e}=await import("./boot-YQAPYAKT.js"),t=xo(import.meta.url),o=new Map(_t.map(r=>[r.groupPath.join(" "),r]));await yo(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(vo(g.env,e))await rn();else{let t=await on();t&&await Eo(["node","infra-kit",...t.split(" ")])}}else await Eo();
13
14
  //# sourceMappingURL=cli.js.map