infra-kit 0.4.0 → 0.5.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.
- package/dist/chunk-6GWRKIZ7.js +2 -0
- package/dist/chunk-6GWRKIZ7.js.map +7 -0
- package/dist/{chunk-CHETBZ6M.js → chunk-D4UYDBN5.js} +2 -2
- package/dist/{chunk-CHETBZ6M.js.map → chunk-D4UYDBN5.js.map} +2 -2
- package/dist/chunk-HXBIE4JP.js +7 -0
- package/dist/{chunk-D7QNBU5A.js.map → chunk-HXBIE4JP.js.map} +3 -3
- package/dist/{chunk-PVMF4FH7.js → chunk-Q23IJP6D.js} +2 -2
- package/dist/chunk-Q4HKBLQG.js +7 -0
- package/dist/chunk-Q4HKBLQG.js.map +7 -0
- package/dist/chunk-X2POR5VH.js +422 -0
- package/dist/chunk-X2POR5VH.js.map +7 -0
- package/dist/{chunk-7POMR4QK.js → chunk-XJOY7J3G.js} +1 -1
- package/dist/chunk-XJOY7J3G.js.map +7 -0
- package/dist/chunk-Y3FV2BRI.js +2 -0
- package/dist/chunk-Y3FV2BRI.js.map +7 -0
- package/dist/cli.js +12 -12
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +2 -2
- package/dist/dev-server.js.map +1 -1
- package/dist/{dev-wizard-run-YMH3L7GE.js → dev-wizard-run-FNMMYTDX.js} +2 -2
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/dist/update-check.js.map +1 -1
- package/package.json +11 -11
- package/readme.md +36 -33
- package/dist/chunk-7POMR4QK.js.map +0 -7
- package/dist/chunk-D7QNBU5A.js +0 -7
- package/dist/chunk-NKXTDKWV.js +0 -2
- package/dist/chunk-NKXTDKWV.js.map +0 -7
- package/dist/chunk-NS5KIBXS.js +0 -2
- package/dist/chunk-NS5KIBXS.js.map +0 -7
- package/dist/chunk-QRY6BS6K.js +0 -249
- package/dist/chunk-QRY6BS6K.js.map +0 -7
- package/dist/chunk-Z2SKAHP4.js +0 -6
- package/dist/chunk-Z2SKAHP4.js.map +0 -7
- /package/dist/{chunk-PVMF4FH7.js.map → chunk-Q23IJP6D.js.map} +0 -0
- /package/dist/{dev-wizard-run-YMH3L7GE.js.map → dev-wizard-run-FNMMYTDX.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var r=t=>Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("npm_")&&e!=="PNPM_SCRIPT_SRC_DIR")),o=/^npm_config_(?:prefix|registry)$/i,a=t=>{let e=r(t);for(let[n,s]of Object.entries(t))o.test(n)&&(e[n]=s);return e};export{r as a,a as b};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-XJOY7J3G.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/pm-env/pm-env.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install:\n * the whole `npm_*` block plus `PNPM_SCRIPT_SRC_DIR`. The result makes the child look exactly like\n * a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\n// Any child we launch through `node <bin>` (the portless driver, the update worker, the mcp launcher)\n// inherits our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm\n// dlx` and refuse to work. portless is the motivating case; its guard (cli.js `main()`) is:\n//\n// isNpx = npm_command === 'exec' && !npm_lifecycle_event\n// isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n// if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) -> abort\n//\n// `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n// transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is\n// live. `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event, so `isNpx`\n// holds, every portless call exits 1, `isAvailable()` is false, and `ensureProxy` aborts the whole\n// dev boot with \"portless is not installed\", on a machine where it plainly is.\n//\n// `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n// `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n// `npm_*` removes that suppressor and creates an abort for the script-style invocation that\n// previously worked. Both markers go, or neither is safe.\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config\n * kept \u2014 specifically `npm_config_prefix` and `npm_config_registry`.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\n// `withoutPackageManagerEnv` is deliberately a blunt `npm_*` prefix filter, and it is the\n// right tool for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it\n// also drops the two variables that tell the package manager where, and from where, to install:\n//\n// - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and\n// we detect a global install rooted at prefix P, then run the install with P erased \u2014 so it\n// lands in the DEFAULT prefix instead. That is either a permanent EACCES, or a second global\n// copy that is not the one on PATH. Nothing notices: the install exits 0, we report\n// `installed`, the version on PATH never moves, and the whole cycle repeats every window\n// forever. `export npm_config_prefix=~/.npm-global` is npm's own documented EACCES workaround,\n// so this is a mainstream layout, not an exotic one.\n// - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it\n// here means we decide against a corporate mirror and then install from somewhere else.\n//\n// Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`,\n// `npm_lifecycle_event` and `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm config, and all of which\n// remain stripped.\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
|
|
5
|
+
"mappings": "AAuBO,IAAMA,EAA4BC,GAChC,OAAO,YACZ,OAAO,QAAQA,CAAG,EAAE,OAAO,CAAC,CAACC,CAAG,IACvB,CAACA,EAAI,WAAW,MAAM,GAAKA,IAAQ,qBAC3C,CACH,EASIC,EAAyB,oCA2BlBC,EAA4BH,GAA8C,CACrF,IAAMI,EAAYL,EAAyBC,CAAG,EAE9C,OAAW,CAACC,EAAKI,CAAK,IAAK,OAAO,QAAQL,CAAG,EACvCE,EAAuB,KAAKD,CAAG,IAAGG,EAAUH,CAAG,EAAII,GAGzD,OAAOD,CACT",
|
|
6
|
+
"names": ["withoutPackageManagerEnv", "env", "key", "NPM_CONFIG_TO_PRESERVE", "packageManagerInstallEnv", "sanitised", "value"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as k,g as w,i as P,j as b}from"./chunk-6GWRKIZ7.js";import{b as y}from"./chunk-XJOY7J3G.js";import{m as p,q as C}from"./chunk-D4UYDBN5.js";import{spawnSync as Z}from"node:child_process";import{homedir as ee}from"node:os";import h from"node:process";import l from"node:fs";import S from"node:path";import O from"node:process";var V="update-check.lock",j=1800*1e3,D=()=>S.join(p(),V),q=(t,e)=>{try{e-l.statSync(t).mtimeMs>j&&l.rmSync(t,{force:!0})}catch{}},E=(t={})=>{let e=t.nowMs??Date.now(),n=t.lockPath??D();try{l.mkdirSync(S.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return l.openSync(n,"wx",384)}catch{return null}},o=r();if(o===null&&(q(n,e),o=r()),o===null)return null;try{l.writeFileSync(o,String(O.pid))}catch{}return()=>{try{l.closeSync(o)}catch{}try{l.rmSync(n,{force:!0})}catch{}}};var J="https://registry.npmjs.org",$=5e3,z=t=>Object.entries(t).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],G=t=>{let e=z(t),n=e!=null&&e!==""?e:J;for(;n.endsWith("/");)n=n.slice(0,-1);return n},U=async(t,e=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},$);try{let o=await e(`${G(t)}/${k}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let s=(await o.json())?.version;return typeof s=="string"&&s!==""?s:null}catch{return null}finally{clearTimeout(r)}};var H=/^(\d+)\.(\d+)\.(\d+)$/,v=t=>{let[e=""]=t.trim().split("+"),[n="",...r]=e.split("-"),o=H.exec(n);if(!o)return null;let[i,s,u]=[o[1],o[2],o[3]].map(Number);return{release:[i,s,u],prerelease:r.length>0?r.join("-").split("."):[]}},x=/^\d+$/,K=(t,e)=>{let n=x.test(t),r=x.test(e);return n&&r?Number(t)-Number(e):n!==r?n?-1:1:t<e?-1:1},W=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n+=1){let r=t[n],o=e[n];if(r===void 0)return-1;if(o===void 0)return 1;if(r!==o)return K(r,o)}return 0},N=(t,e)=>{let n=v(t),r=v(e);if(!n||!r)return!1;for(let s=0;s<3;s+=1){let u=n.release[s],m=r.release[s];if(u!==m)return u>m}let o=n.prerelease.length===0,i=r.prerelease.length===0;return o!==i?o:W(n.prerelease,r.prerelease)>0};import L from"node:fs";import M from"node:path";var A="update-check.json",B=1200*1e3,Y=()=>M.join(p(),A),Q=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),X=t=>{if(typeof t!="object"||t===null)return!1;let{lastCheckMs:e,latestVersion:n,updateCommand:r,outcome:o}=t;return typeof e=="number"&&Number.isFinite(e)&&(n===null||typeof n=="string")&&(r===null||Q(r))&&(o==null||typeof o=="string")},ke=(t=e=>L.readFileSync(e,"utf8"))=>{try{let e=JSON.parse(t(Y()));return X(e)?e:null}catch{return null}},R=t=>{let e=p();L.mkdirSync(e,{recursive:!0}),C(M.join(e,A),JSON.stringify(t),384)},we=(t,e)=>{if(!t)return!0;let n=e-t.lastCheckMs;return n<0?!0:n>=B};var te=200,ne=300*1e3,re=t=>{try{return h.kill(t,0),!0}catch{return!1}},oe=t=>new Promise(e=>{setTimeout(e,t)}),se=async(t,e)=>{let n=e.clock()+ne;for(;e.clock()<n;){if(!e.isProcessAlive(t))return!0;await e.sleep(te)}return!e.isProcessAlive(t)},Ae=async(t,e)=>{let r=(e.acquireLock??E)();if(!r)return"already-running";try{return await ae(t,e)}finally{r()}},ae=async(t,e)=>{let n=e.env??h.env,r=e.nowMs??Date.now(),o=e.fetchLatest??U,i=e.writeCache??R,s=e.isProcessAlive??re,u=e.sleep??oe,m=e.clock??Date.now,_=e.lazyNpmRoot??P,I=e.spawnSync??Z,a=await o(n),c=(g,F)=>(i({lastCheckMs:r,...F,outcome:g}),g);if(a===null)return c("fetch-failed",{latestVersion:null,updateCommand:null});if(!N(a,t))return c("up-to-date",{latestVersion:a,updateCommand:null});let{canSelfSpawn:T,updateCommand:f}=w({selfRealPath:e.selfRealPath,env:n,realpath:b,lazyNpmRoot:_});if(!T)return c("cannot-self-spawn",{latestVersion:a,updateCommand:f});if(e.parentPid==null)return c("parent-unknown",{latestVersion:a,updateCommand:null});if(i({lastCheckMs:r,latestVersion:a,updateCommand:null,outcome:"installing"}),!await se(e.parentPid,{isProcessAlive:s,sleep:u,clock:m}))return c("parent-still-running",{latestVersion:a,updateCommand:null});let d=I(f[0],f.slice(1),{stdio:"ignore",shell:h.platform==="win32",cwd:ee(),env:y(n),windowsHide:!0});return d.error||d.signal||d.status!==0?c("install-failed",{latestVersion:a,updateCommand:f}):c("installed",{latestVersion:null,updateCommand:null})};export{N as a,ke as b,we as c,Ae as d};
|
|
2
|
+
//# sourceMappingURL=chunk-Y3FV2BRI.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../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 * 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 throttle 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 = (\n outcome: UpdateCheckOutcome,\n cache: Omit<UpdateCache, 'lastCheckMs' | 'outcome'>,\n ): UpdateCheckOutcome => {\n // `outcome` is recorded on EVERY write: it is what lets a reader (human or `isStale`) tell a settled\n // `installed`/`up-to-date` from a transient `fetch-failed`, all of which otherwise write an identical\n // `{latestVersion:null}`. See `UpdateCache.outcome`.\n writeCache({ lastCheckMs: nowMs, ...cache, outcome })\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 //\n // `outcome: 'installing'` marks a mid-install checkpoint: if the worker is killed here (machine sleeps,\n // SIGKILL) and never reaches `finish()`, this stamp is what the next run reads, and the cache says so\n // rather than looking like a settled result. It does not shorten the next window \u2014 see CHECK_INTERVAL_MS.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null, outcome: 'installing' })\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 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/**\n * Bounded so a hanging registry can never keep a detached child alive indefinitely. 5s, not a tighter\n * bound: the abbreviated `/pkg/latest` endpoint is usually ~20-900ms, but a cold TLS/DNS handshake in a\n * freshly-spawned worker can spike past a 2.5s cap \u2014 and a single trip used to cost a `fetch-failed` that\n * pushed the next check a full window out. A detached child that lingers a few extra seconds harms nothing.\n */\nexport const FETCH_TIMEOUT_MS = 5_000\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 setup` 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/**\n * The ONE re-check window, whatever the last outcome was. A background check is cheap \u2014 one\n * detached child and a single registry fetch bounded by `FETCH_TIMEOUT_MS` \u2014 but not once per\n * shell command, which is the storm this throttle exists to stop.\n *\n * MUST stay above a full worker cycle: `runUpdateCheck` stamps `lastCheckMs` BEFORE waiting up to\n * `PARENT_WAIT_TIMEOUT_MS` (5min) for the parent to exit and THEN installing.\n */\n// There is deliberately no shorter \"retry after a transient failure\" window. One used to exist\n// because this interval was 24h, and burning a whole day on a single network blip locked out\n// exactly the publisher pushing a release mid-window. At 20 minutes that gap is gone: a blip costs\n// one window, so a second window buys nothing and cannot pay for what it costs.\n//\n// What it would cost: go below a full worker cycle and the cache reads stale while the first worker\n// is still legitimately working, so the next shell spawns a worker that dies on the live\n// single-flight lock and returns WITHOUT writing \u2014 leaving the cache stale for every command until\n// `LOCK_STALE_MS` (30min) reaps the lock. That is the per-command spawn storm this throttle exists\n// to prevent, and it is why a 5-minute retry window is not an option.\nexport const CHECK_INTERVAL_MS = 20 * 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 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 * The last check's terminal outcome (`installed`, `fetch-failed`, `up-to-date`, \u2026), or absent on a\n * cache written before this field existed.\n *\n * Diagnostic ONLY \u2014 nothing branches on it, {@link isStale} included. It earns its keep by being the\n * one thing that makes this file legible: a successful `installed` and a failed `fetch-failed` both\n * write a byte-identical `{latestVersion:null, updateCommand:null}`, so without this the cache cannot\n * say which happened, and a silent auto-update leaves no other trace of what it did.\n */\n outcome?: 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, outcome } = 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 (outcome === undefined || outcome === null || typeof outcome === 'string')\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 * The window does NOT depend on `outcome`: every last outcome, transient or settled, is re-checked\n * after {@link CHECK_INTERVAL_MS}. See that constant for why a shorter transient-failure window is not\n * worth its cost here.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null, updateCommand: 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 if (elapsed < 0) return true\n\n return elapsed >= CHECK_INTERVAL_MS\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["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", "outcome", "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
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{$ as
|
|
2
|
+
import{$ as Kt,A as kt,B as Rt,C as Pt,D as te,E as xt,F as D,G as m,H as Ct,I as bt,J as At,K as Tt,L as Dt,M as It,N as Lt,O as _t,P as Nt,Q as Ot,R as Mt,S as Ft,T as $t,U as jt,V as oe,W as Ut,X as qt,Y as Gt,Z as Wt,_ as Vt,a as N,aa as Ht,b as Ue,ba as Jt,c as qe,ca as Bt,da as Yt,e as We,ea as zt,f as Ve,g as He,ga as Xt,h as Je,ha as Qt,i as O,ia as Zt,j as rt,k as j,l as st,m as at,n as ct,o as lt,p as dt,q as ut,r as mt,s as pt,t as ee,u as ft,v as gt,w as ht,x as vt,y as wt,z as St}from"./chunk-X2POR5VH.js";import{y as re}from"./chunk-Q23IJP6D.js";import{a as ne,b as ie,c as se}from"./chunk-Y3FV2BRI.js";import{a as Fe,f as yt,h as U,j as q}from"./chunk-6GWRKIZ7.js";import{a as Ge}from"./chunk-XJOY7J3G.js";import{a as Et}from"./chunk-TVG47UHG.js";import{b as Ke,c as E,d as h,e as F,f as et,g as tt,h as ot,i as P,k as $}from"./chunk-HXBIE4JP.js";import{L as l,a as Oe,ea as Q,fa as $e,ha as je,r as Me}from"./chunk-Q4HKBLQG.js";import{a as M,b as Be,d as Ye,f as ze,g as Xe,j as Z,k as Qe,n as w,q as Ze}from"./chunk-D4UYDBN5.js";import{a as nt,b as it}from"./chunk-QWVLAZ6N.js";import In,{Separator as Go}from"@inquirer/select";import{realpathSync as Ln}from"node:fs";import g from"node:process";import{fileURLToPath as Vo}from"node:url";var Ho=(e,t)=>{let o=e,r;for(let n of t){if(r=o.find(s=>s.name()===n),!r)return;o=r.commands}return r},eo=e=>Yt.flatMap(({key:t,label:o})=>Xt(t).flatMap(r=>{let n=Ho(e,r.groupPath);return n?[{name:r.groupPath.join(" "),description:n.description(),group:o}]:[]}));import{Command as Rr}from"commander";import b from"node:process";import to from"node:process";import{$ as Jo}from"zx";var ae=async()=>{let e=await Q(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async a=>({...a,exists:await E(a.path)}))),o=t.at(-1)?.exists===!0,r=await ht(e.userProject,o),n=o?vt(r):"";l.info(`Project name: ${e.projectName}
|
|
3
3
|
`),l.info(`Config merge chain (later overrides earlier):
|
|
4
|
-
`);for(let a of t){let i=a.exists?" [\u2713]":" [ ]",c=a.path===e.userProject&&n!==""?` ${n}`:"";l.info(`${i} ${a.label.padEnd(22)} ${
|
|
5
|
-
`))},
|
|
6
|
-
`),
|
|
7
|
-
`;var Y=(e,t=!0)=>({line:e,reproducible:t});import z from"node:fs";import Tr from"node:os";import Ir from"node:path";import yo from"node:process";var X="INFRA_KIT_SESSION_REPORT",Ae=null,go=!1,ho=[],So=(e=yo.env)=>{go||(Ae=e[X]??null,go=!0,delete e[X])};var wo=(e,t)=>{if(!Ae)return;let o=e.summary??(ho.length>0?[...ho]:void 0),r={...e,...o?{summary:o}:{}},n=t?.write??((s,a)=>{z.writeFileSync(s,a)});try{n(Ae,JSON.stringify(r))}catch{}},vo=0,ko=e=>{let t=e?.tmpdir?.()??Tr.tmpdir(),o=e?.pid??yo.pid;return vo+=1,Ir.join(t,`infra-kit-session-${o}-${vo}.json`)},Ro=(e,t)=>{if(!(t?.exists??(a=>z.existsSync(a)))(e))return null;let r=t?.read??(a=>z.readFileSync(a,"utf-8")),n=t?.unlink??(a=>z.unlinkSync(a)),s;try{s=r(e)}catch{return null}finally{try{n(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Nr=(e,t)=>[...t,e],Po=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&ne.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${ne.join(", ")}.`)}},Lr=e=>e.description("Merge dev branch into every release branch").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("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").action(async t=>{let o=await It(()=>Dt({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,confirmedCommand:t.yes}));m(o),o.structuredContent.failedMerges>0&&(A.exitCode=1)}),_r=e=>e.description("List all release branches").action(async()=>{m(await Ft())}),Or=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".',Nr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(kt),n=r.length>0?r:void 0;m(await qt({releases:n,confirmedCommand:t.yes}))}),$r=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 Gt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),xo=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Lt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),Mr=e=>xo(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{m(await ke({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Fr=e=>xo(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{m(await Re({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),jr=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 Nt({version:t.version,confirmedCommand:t.yes}))}),Ur=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Yt({confirmedCommand:t.yes}))}),qr=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=Po(t.ide,"--ide")??Po(t.cursor,"--cursor");m(await Ht({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Gr=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await Bt())}),Wr=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 Jt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Kr=e=>e.description("Reopen editor + cmux windows for every active worktree in the current project (additive, idempotent)").option("--all","Reopen across every discovered infra-kit project (Stage 3 \u2014 not yet implemented)").option("--project <names...>","Restrict --all to these project names").option("--root <paths...>","Discovery roots for --all (repeatable)").option("--release-only","Restrict to release worktrees (reproduces the legacy worktrees-reload scope)").option("--force","Close each cmux workspace first, then reopen (the legacy worktrees-reload behaviour)").option("--dry-run","Print the plan (paths + cmux titles) and spawn nothing").action(async t=>{m(await Wt({all:t.all,project:t.project,root:t.root,releaseOnly:t.releaseOnly,force:t.force,dryRun:t.dryRun}))}),Vr=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 be({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 Kt();m(t),t.structuredContent.ok||(A.exitCode=1)}),Br=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await le())}),Jr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await de())}),Yr=new Set(["init","doctor","version","dev","self-update","mcp"]),zr=e=>e.startsWith("env-")||Yr.has(e),Xr=new Set(["env-autoload","mcp","version","self-update"]),Q=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Te=()=>{let e=new Dr,t=e.command("release").description("Release management commands");Lr(t.command("merge-dev")),_r(t.command("list")),Or(t.command("create")),$r(t.command("desc-edit")),Mr(t.command("deploy-all")),Fr(t.command("deploy-selected")),jr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");qr(o.command("add")),Gr(o.command("list")),Wr(o.command("remove")),Ur(o.command("sync")),Kr(e.command("reopen"));let r=e.command("config").description("Manage infra-kit configuration files");Br(r.command("path")),Jr(r.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{m(await Ke())});let n=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=i=>i.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(n.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async i=>{m(await J({env:i.env,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"all"))}),s(n.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async i=>{m(await J({env:i.env,services:i.service,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"selected"))}),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)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async i=>{if(i.design&&!i.fix){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),A.exitCode=1;return}let c=await We({all:i.all,root:i.root,fix:i.fix,design:i.design});m(c);let{allPassed:u,fixed:d}=c.structuredContent,p=(d??[]).some(g=>g.action==="failed");(!u||p)&&(A.exitCode=1)});let a=e.command("vendor").description("Verify the mirrored vendor/ tree");return Hr(a.command("check")),Vr(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.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async i=>{let c=await Rt({fix:!!i.fix});D.enabled||Pt(c.structuredContent.checks,{ascii:!!i.ascii}),m(c)}),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(i=>{xe({dryRun:!!i.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{Se()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(i,c)=>{let{runDevServerCli:u}=await import("./dev-server.js"),d=!!(A.stdout.isTTY&&A.stdin.isTTY);await u({...c,preset:i},d,D.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{m(await Be())}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await Vt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Ct())}),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 Et())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{m(await oe())}),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 i=>{m(await dt({config:i.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 i=>{m(await xt({purge:!!i.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(i,c)=>{m(await ye({env:i,stdin:c.stdin,fromEnv:c.fromEnv,force:c.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 i=>{m(await bt({check:!!i.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 i=>{m(await he({env:i}))}),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 i=>{await ge({projectDir:i.projectDir})}),e.commands.forEach(At),e.hook("preAction",async(i,c)=>{P.start(Q(c)),D.enabled=!!c.optsWithGlobals().json,D.enabled&&(l.level="warn"),Xr.has(Q(c))||await ht(),K(),zr(c.name())||await _({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(i,c)=>{let u=Q(c);if(Zt(u))return;let p=P.snapshot()?.formattedOptions??"",g=p?` ${p}`:"",S=`infra-kit ${u}${g}`;wo({equivalent:Y(S,!0)})}),e};var Ie=(e,t=" ")=>{let o=e.reduce((r,[n])=>Math.max(r,n.length),0);return e.map(([r,n])=>`${r.padEnd(o)}${t}${n}`)};import{chalkStderr as Sn}from"chalk";import{spawn as wn}from"node:child_process";import y from"node:process";import{Chalk as Qr}from"chalk";var T=new Qr({level:1}),R={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."},Zr={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},Eo={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Co={unicode:"\u2500",ascii:"-"},en=3,De=e=>e,tn={ok:e=>T.green(e),findings:e=>T.yellow(e),failed:e=>T.red(e),cancelled:e=>T.gray(e)},Le=e=>e?{dim:t=>T.dim(t),bold:t=>T.bold(t)}:{dim:De,bold:De},on=(e,t)=>e?tn[t]:De,Ne=e=>[...e].length,rn=(e,t)=>{if(t==null)return e;let o=Math.max(0,t-1);return Ne(e)<=o?e:[...e].slice(0,o).join("")},bo=e=>{let t=Le(e.color===!0).dim,o=Zr[e.canSuspend?"suspend":"plain"],r=e.ascii===!0?o.ascii:o.unicode;return t(rn(r,e.width))},Ao=(e,t={})=>{let o=Le(t.color===!0);return`${o.dim(R.reproPrefix.trim())} ${o.bold(e)}`},nn=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,sn=(e,t)=>e==="findings"?t!=null?`${t} ${R.findingsSuffix}`:R.findingsPlain:{ok:R.ok,failed:R.failed,cancelled:R.cancelled}[e],an=(e,t,o,r)=>{if(t==null)return"";let n=t-2-e;return n<en?"":` ${r(o.repeat(n))}`},To=e=>{let t=e.color===!0,o=Le(t),r=on(t,e.outcome),n=e.ascii===!0,s=e.equivalent.reproducible?R.reproPrefix:R.nonReproPrefix,a=n?Eo[e.outcome].ascii:Eo[e.outcome].unicode,i=sn(e.outcome,e.findingsCount),c=[nn(e.durationMs)],u=e.summary?.[0]?.split(`
|
|
8
|
-
`)[0];u!=null&&u.length>0&&c.push(u);let d=`${a} ${i}`,p=`${
|
|
9
|
-
`)};var
|
|
10
|
-
`,
|
|
11
|
-
${
|
|
12
|
-
`),i.childStarted();let
|
|
13
|
-
${
|
|
14
|
-
`),await u(c)==="quit")return}}finally{i.dispose()}};import{spawn as
|
|
4
|
+
`);for(let a of t){let i=a.exists?" [\u2713]":" [ ]",c=a.path===e.userProject&&n!==""?` ${n}`:"";l.info(`${i} ${a.label.padEnd(22)} ${h(a.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(a=>({label:a.label,path:a.path,exists:a.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},ce=async()=>{let e=await Q(),t=to.env.EDITOR||to.env.VISUAL||"vi",o=await ut(e);o.createdConfig&&l.info(mt(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await Jo({stdio:"inherit"})`${t} ${e.userProject}`,je();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var le=e=>{if(typeof e!="object"||e===null)return null;let{config:t,reason:o,at:r}=e;return typeof t!="string"||t.length===0||typeof o!="string"||typeof r!="number"||!Number.isFinite(r)?null:{config:t,reason:o,at:r}},I=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import f from"node:fs";import S from"node:path";import L from"node:process";var Bo="autoload-warn-fail.flag",de="autoload-warn-auth-fail.flag",ue="autoload-fail.flag",me="autoload-auth-fail.json",Yo=3e4,ro=async(e=!0)=>{let t;try{t=await $e()}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 rt(o.config))return r}catch{return r}return io({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&G(I(o.config),de),null},no=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:n,env:s,force:a}=e;return t!==o||!s.session||s.cleared||s.currentConfig&&!s.autoLoadedMarker||!a&&s.autoLoadedMarker&&s.currentConfig===r&&s.currentProject===n?"skip":"load"},_=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Ke})=>{let n=e==="cli-invocation";n&&W();let s=null;try{if(s=await ro(n),!s||no({trigger:s.trigger,expectedTrigger:e,targetConfig:s.config,targetProject:s.project,env:Qo(),force:o})==="skip"||oo()||tr())return null;let i=Zo(),c=await st({config:s.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!oo()&&!er(i)});return c?(rr(),Xo(),c.filePath):null}catch(a){let i=a.message,c=r(a);return or(),c&&s&&io({config:s.config,reason:i,at:Date.now()}),n&&c&&s?(G(I(s.config),de),l.debug(`env auto-load auth failure: ${i}`)):n?G(`infra-kit: env auto-load failed \u2014 ${i} (will retry later)`,Bo):l.debug(`env auto-load skipped: ${i}`),null}},W=()=>{let e=zo();e&&(G(I(e.config),de),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},zo=()=>{try{let e=f.readFileSync(S.join(w(),me),"utf-8");return le(JSON.parse(e))}catch{return null}},io=e=>{try{let t=w();f.mkdirSync(t,{recursive:!0,mode:448}),Ze(S.join(t,me),JSON.stringify(e),384)}catch{}},Xo=()=>{try{f.rmSync(S.join(w(),me),{force:!0})}catch{}},Qo=()=>({session:L.env[Ye],cleared:L.env[Qe],currentConfig:L.env[ze],currentProject:L.env[Xe],autoLoadedMarker:L.env[Z]}),Zo=()=>{try{return f.statSync(S.join(w(),M)).mtimeMs}catch{return null}},er=e=>{try{let t=S.join(w(),M);if(!f.existsSync(t))return!1;let o=f.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Z}$`,"m").test(f.readFileSync(t,"utf-8"))}catch{return!1}},oo=()=>{try{let e=w(),t=S.join(e,Be);if(!f.existsSync(t))return!1;let o=S.join(e,M);return f.existsSync(o)?f.statSync(t).mtimeMs>=f.statSync(o).mtimeMs:!0}catch{return!1}},tr=()=>{try{let e=S.join(w(),ue);return f.existsSync(e)?Date.now()-f.statSync(e).mtimeMs<Yo:!1}catch{return!1}},or=()=>{try{let e=w();f.mkdirSync(e,{recursive:!0,mode:448}),f.writeFileSync(S.join(e,ue),"",{mode:384})}catch{}},rr=()=>{try{f.rmSync(S.join(w(),ue),{force:!0})}catch{}},G=(e,t)=>{try{let o=w(),r=S.join(o,t);if(f.existsSync(r))return;f.mkdirSync(o,{recursive:!0,mode:448}),f.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var pe=async({projectDir:e}={})=>{await _({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var so="https://dashboard.doppler.com/workplace/projects",nr=(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}"): ${so}/${e}`],fe=async({env:e})=>{let o=!!(await et())?.envs[e];await ot(e);let r=await j(),n=await O(),s=await F();o?l.info(`Removed the "${e}" service token from ${h(s)}.`):l.info(`No "${e}" service token was stored in ${h(s)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let i of nr(n,e))l.warn(i);let a={env:e,removed:o,storePath:s,warmCachesPurged:r.length,revokeUrl:`${so}/${n}`};return{content:N(JSON.stringify(a,null,2)),structuredContent:a}};import ir from"@inquirer/password";import K from"node:process";import{$ as V}from"zx";var sr=async({stdin:e,fromEnv:t})=>{if(e)return{token:await ar(),source:"stdin"};if(t){let r=K.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return P.setInteractive(),{token:(await $(r=>ir({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:K.stderr})).trim(),source:"prompt"}},ar=async()=>{let e=[];K.stdin.setEncoding("utf8");for await(let t of K.stdin)e.push(t);return e.join("").trim()},ge="DOPPLER_CONFIG",cr=3e4,lr=async(e,t,o)=>{let r=V.quiet;V.quiet=!0;let n;try{n=(await V({env:ct(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(cr)).stdout}catch(s){throw dr(s,o)}finally{V.quiet=r}return dt(n)},dr=(e,t)=>{let o=Oe(e)??(e instanceof Error?e.message:String(e));if(He(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=Je(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
|
+
`))},ur=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${ge}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
|
|
6
|
+
`),he=async({env:e,stdin:t,fromEnv:o,force:r})=>{let n=await O(),{token:s,source:a}=await sr({stdin:t,fromEnv:o});if(!s)throw new Error("No token provided \u2014 nothing was written.");let i=await lr(s,n,e);lt(i,e);let c=i.some(([y])=>y===ge);if(!c&&!r)throw new Error(ur(e));await tt(e,s);let u=await j(),d=await F();l.info(`Stored the "${e}" service token (${te(s)}) in ${h(d)} (mode 0600).`),c||l.warn(`Scope was NOT verified (no ${ge} in the payload) \u2014 written because --force was given.`),u.length>0&&l.info(`Purged ${u.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let p={env:e,source:a,redactedToken:te(s),storePath:d,scopeVerified:c,warmCachesPurged:u.length};return P.print(),{content:N(JSON.stringify(p,null,2)),structuredContent:p}};import{spawn as mr}from"node:child_process";import H from"node:process";import{fileURLToPath as pr}from"node:url";var fr=["SIGINT","SIGTERM"],ao=()=>pr(new URL("./mcp.js",import.meta.url)),ve=(e={})=>{let t=e.spawn??mr,o=e.exit??(a=>H.exit(a)),r=e.env??H.env,n=e.onError??(a=>l.error(a)),s=t(H.execPath,[ao()],{stdio:"inherit",env:Ge(r)});s.on("error",a=>{n(`failed to launch the MCP server: ${a.message}`),o(1)}),fr.forEach(a=>{H.on(a,()=>{s.kill(a)})}),s.on("exit",(a,i)=>{o(i?1:a??1)})};var ye=async(e,t,o=!0)=>{let{from:r,version:n,env:s,services:a,skipTerraform:i,yes:c,dryRun:u,printEnv:d}=e,p=await Lt(r);return o&&P.addOption("--from",p),It(p,{"--version":n,"--skip-terraform":i,"--dry-run":u,"--print-env":d}),p==="local"?t==="all"?Mt({env:s,confirmedCommand:c,dryRun:u,printEnv:d}):Ft({env:s,service:a,confirmedCommand:c,dryRun:u,printEnv:d}):t==="all"?_t({version:n,env:s,skipTerraform:i,confirmedCommand:c}):Nt({version:n,env:s,services:a,skipTerraform:i,confirmedCommand:c})},we=async e=>ye(e,"all"),Se=async e=>ye(e,"selected"),J=async(e,t)=>{let o=`release deploy-${t} --from local`;return l.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${o}\` instead.`),ye({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as lo}from"@slip-stream-kit/config/internal";import ke from"node:fs/promises";import Re from"node:path";import co from"node:process";import{pathToFileURL as gr}from"node:url";var uo="~/projects",Pe=async(e={})=>{if(e.init){await vr(e.cwd);return}await hr()},hr=async()=>{let e=ee(),t=await E(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."),co.exitCode=1;return}let{workspaceDir:o,targets:r}=await gt(),n=ft(o),s=await E(n);l.info(`workspaceDir: ${o} (resolved: ${n}) ${s?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let a=s;for(let i of r){let c=Re.join(n,i),u=await E(c);u||(a=!1);let d=u?"[\u2713]":"[ ]",p=u?"":" (not found \u2014 clone or remove)";l.info(` ${d} ${i} ${h(c)}${p}`)}a||(co.exitCode=1)},vr=async e=>{let t=ee();if(await E(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Me(),r=await yr(o);await ke.mkdir(Re.dirname(t),{recursive:!0}),await ke.writeFile(t,wr(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${lo}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${uo}) 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.")},yr=async e=>{try{let t=Re.join(e,lo),o=await ke.stat(t),s=(await import(`${gr(t).href}?mtime=${Number(o.mtimeMs)}`)).default,a=typeof s=="function"?await s():s;if(a&&typeof a=="object"&&"targets"in a){let i=a.targets;if(Array.isArray(i)&&i.every(c=>typeof c=="string"))return i}}catch{}return[]},wr=e=>`${JSON.stringify({workspaceDir:uo,targets:e},null,2)}
|
|
7
|
+
`;var B=(e,t=!0)=>({line:e,reproducible:t});import Y from"node:fs";import Sr from"node:os";import kr from"node:path";import go from"node:process";var z="INFRA_KIT_SESSION_REPORT",xe=null,mo=!1,po=[],ho=(e=go.env)=>{mo||(xe=e[z]??null,mo=!0,delete e[z])};var vo=(e,t)=>{if(!xe)return;let o=e.summary??(po.length>0?[...po]:void 0),r={...e,...o?{summary:o}:{}},n=t?.write??((s,a)=>{Y.writeFileSync(s,a)});try{n(xe,JSON.stringify(r))}catch{}},fo=0,yo=e=>{let t=e?.tmpdir?.()??Sr.tmpdir(),o=e?.pid??go.pid;return fo+=1,kr.join(t,`infra-kit-session-${o}-${fo}.json`)},wo=(e,t)=>{if(!(t?.exists??(a=>Y.existsSync(a)))(e))return null;let r=t?.read??(a=>Y.readFileSync(a,"utf-8")),n=t?.unlink??(a=>Y.unlinkSync(a)),s;try{s=r(e)}catch{return null}finally{try{n(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Ce=e=>{e.options.some(o=>o.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Ce)};var Pr=(e,t)=>[...t,e],So=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&oe.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${oe.join(", ")}.`)}},xr=e=>e.description("Merge dev branch into every release branch").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("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").action(async t=>{let o=await bt(()=>At({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,confirmedCommand:t.yes}));m(o),o.structuredContent.failedMerges>0&&(b.exitCode=1)}),Cr=e=>e.description("List all release branches").action(async()=>{m(await Ot())}),Er=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".',Pr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(wt),n=r.length>0?r:void 0;m(await $t({releases:n,confirmedCommand:t.yes}))}),br=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 jt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),ko=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Dt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),Ar=e=>ko(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{m(await we({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Tr=e=>ko(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{m(await Se({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Dr=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 Tt({version:t.version,confirmedCommand:t.yes}))}),Ir=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ut({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),Lr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Bt({confirmedCommand:t.yes}))}),_r=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=So(t.ide,"--ide")??So(t.cursor,"--cursor");m(await Kt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Nr=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await Ht())}),Or=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 Jt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Mr=e=>e.description("Reopen editor + cmux windows for every active worktree in the current project (additive, idempotent)").option("--all","Reopen across every discovered infra-kit project (Stage 3 \u2014 not yet implemented)").option("--project <names...>","Restrict --all to these project names").option("--root <paths...>","Discovery roots for --all (repeatable)").option("--release-only","Restrict to release worktrees (reproduces the legacy worktrees-reload scope)").option("--force","Close each cmux workspace first, then reopen (the legacy worktrees-reload behaviour)").option("--dry-run","Print the plan (paths + cmux titles) and spawn nothing").action(async t=>{m(await qt({all:t.all,project:t.project,root:t.root,releaseOnly:t.releaseOnly,force:t.force,dryRun:t.dryRun}))}),Fr=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 Pe({init:t.init}))}),$r=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Wt();m(t),t.structuredContent.ok||(b.exitCode=1)}),jr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await ae())}),Ur=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await ce())}),qr=new Set(["setup","doctor","version","dev","mcp"]),Gr=e=>e.startsWith("env-")||qr.has(e),Wr=new Set(["env-autoload","mcp","version"]),X=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Ee=()=>{let e=new Rr,t=e.command("release").description("Release management commands");xr(t.command("merge-dev")),Cr(t.command("list")),Er(t.command("create")),br(t.command("desc-edit")),Ar(t.command("deploy-all")),Tr(t.command("deploy-selected")),Dr(t.command("deliver")),Ir(t.command("remove"));let o=e.command("worktrees").description("Git worktree management commands");_r(o.command("add")),Nr(o.command("list")),Or(o.command("remove")),Lr(o.command("sync")),Mr(e.command("reopen"));let r=e.command("config").description("Manage infra-kit configuration files");jr(r.command("path")),Ur(r.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{m(await qe())});let n=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=i=>i.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(n.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async i=>{m(await J({env:i.env,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"all"))}),s(n.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async i=>{m(await J({env:i.env,services:i.service,yes:i.yes,dryRun:i.dryRun,printEnv:i.printEnv},"selected"))}),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)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async i=>{if(i.design&&!i.fix){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),b.exitCode=1;return}let c=await Ue({all:i.all,root:i.root,fix:i.fix,design:i.design});m(c);let{allPassed:u,fixed:d}=c.structuredContent,p=(d??[]).some(y=>y.action==="failed");(!u||p)&&(b.exitCode=1)});let a=e.command("vendor").description("Verify the mirrored vendor/ tree");return $r(a.command("check")),Fr(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.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async i=>{let c=await St({fix:!!i.fix});D.enabled||Ve(c.structuredContent.checks,{ascii:!!i.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(b.exitCode=1),m(c)}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ve()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(i,c)=>{let{runDevServerCli:u}=await import("./dev-server.js"),d=!!(b.stdout.isTTY&&b.stdin.isTTY);await u({...c,preset:i},d,D.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{m(await We())}),e.command("setup").description("Set this machine up: shell integration, agent files, MCP server, then the external tools").option("--tools <ids...>","Limit to these tools (brew, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").action(async i=>{m(await Gt({tools:i.tools,update:i.update,skipTools:i.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await Vt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Pt())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{m(await Rt())}),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 i=>{m(await at({config:i.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 i=>{m(await kt({purge:!!i.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(i,c)=>{m(await he({env:i,stdin:c.stdin,fromEnv:c.fromEnv,force:c.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 i=>{m(await xt({check:!!i.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 i=>{m(await fe({env:i}))}),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 i=>{await pe({projectDir:i.projectDir})}),e.commands.forEach(Ct),Ce(e),e.hook("preAction",async(i,c)=>{P.start(X(c)),D.enabled=!!c.optsWithGlobals().json,D.enabled&&(l.level="warn"),Wr.has(X(c))||await pt(),W(),Gr(c.name())||await _({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(i,c)=>{let u=X(c);if(Qt(u))return;let p=P.snapshot()?.formattedOptions??"",y=p?` ${p}`:"",R=`infra-kit ${u}${y}`;vo({equivalent:B(R,!0)})}),e};var be=(e,t=" ")=>{let o=e.reduce((r,[n])=>Math.max(r,n.length),0);return e.map(([r,n])=>`${r.padEnd(o)}${t}${n}`)};import{chalkStderr as un}from"chalk";import{spawn as mn}from"node:child_process";import v from"node:process";import{Chalk as Vr}from"chalk";var A=new Vr({level:1}),k={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."},Kr={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},Ro={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Po={unicode:"\u2500",ascii:"-"},Hr=3,Ae=e=>e,Jr={ok:e=>A.green(e),findings:e=>A.yellow(e),failed:e=>A.red(e),cancelled:e=>A.gray(e)},De=e=>e?{dim:t=>A.dim(t),bold:t=>A.bold(t)}:{dim:Ae,bold:Ae},Br=(e,t)=>e?Jr[t]:Ae,Te=e=>[...e].length,Yr=(e,t)=>{if(t==null)return e;let o=Math.max(0,t-1);return Te(e)<=o?e:[...e].slice(0,o).join("")},xo=e=>{let t=De(e.color===!0).dim,o=Kr[e.canSuspend?"suspend":"plain"],r=e.ascii===!0?o.ascii:o.unicode;return t(Yr(r,e.width))},Co=(e,t={})=>{let o=De(t.color===!0);return`${o.dim(k.reproPrefix.trim())} ${o.bold(e)}`},zr=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,Xr=(e,t)=>e==="findings"?t!=null?`${t} ${k.findingsSuffix}`:k.findingsPlain:{ok:k.ok,failed:k.failed,cancelled:k.cancelled}[e],Qr=(e,t,o,r)=>{if(t==null)return"";let n=t-2-e;return n<Hr?"":` ${r(o.repeat(n))}`},Eo=e=>{let t=e.color===!0,o=De(t),r=Br(t,e.outcome),n=e.ascii===!0,s=e.equivalent.reproducible?k.reproPrefix:k.nonReproPrefix,a=n?Ro[e.outcome].ascii:Ro[e.outcome].unicode,i=Xr(e.outcome,e.findingsCount),c=[zr(e.durationMs)],u=e.summary?.[0]?.split(`
|
|
8
|
+
`)[0];u!=null&&u.length>0&&c.push(u);let d=`${a} ${i}`,p=`${k.sep}${c.join(k.sep)}`,y=Te(d)+Te(p),R=Qr(y,e.width,n?Po.ascii:Po.unicode,o.dim),C=[`${r(d)}${o.dim(p)}${R}`];return e.showEquivalent!==!1&&C.unshift(`${o.dim(s.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&C.push(o.dim(k.envNotice)),C.join(`
|
|
9
|
+
`)};var Zr=new Set([130,143]),bo=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Zr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import en from"node:process";var tn={3:"quit",4:"quit",26:"suspend",27:"quit"},on=e=>{if(e.length!==1)return"continue";let t=typeof e=="string"?e.charCodeAt(0):e[0];return t===void 0||Number.isNaN(t)?"continue":tn[t]??"continue"},rn=150,nn="\r\x1B[2K",sn=`\r
|
|
10
|
+
`,Ao=(e,t)=>{To(e),e.stdin.on("data",t),e.listener=t},To=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Do=(e,t)=>{nt(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Ao(e,t)},Io=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(nn)),To(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),it()},an=e=>{e.settled||(e.settled=!0,Io(e))},Lo=(e,t)=>{let o=xo({canSuspend:e.deps.suspend!==void 0,ascii:e.deps.ascii,color:e.deps.color,width:e.deps.columns()});e.deps.write(t+o),e.hintOnScreen=!0},cn=async e=>{await new Promise(t=>{setTimeout(t,e)})},ln=(e,t,o)=>{Io(e),t(),Do(e,o),Lo(e,sn)},dn=async e=>new Promise(t=>{let o=r=>{let n=on(r),s=e.deps.suspend;if(n==="quit"){t("quit");return}if(n==="suspend"&&s!==void 0){ln(e,s,o);return}t("palette")};Ao(e,o),Lo(e,"")}),_o=async(e,t)=>{if(e.quitRequested())return"quit";let o=t.stdin??en.stdin;if(o.isTTY!==!0)return"palette";let r={deps:t,stdin:o,listener:null,hintOnScreen:!1,settled:!1};try{return Do(r,()=>{}),e.armed(),await cn(t.drainMs??rn),await dn(r)}finally{an(r)}};import No from"node:process";var x={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Oo=(e,t)=>{let o=t?.write??(s=>{No.stderr.write(s)}),r=t?.stdin??No.stdin,n=[x.saveCursor,x.scrollRegion,x.restoreCursor,x.column,x.sgr,x.cursor,x.wrap];e.entersAltScreen===!0&&n.push(x.primaryBuffer),o(n.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var Mo=e=>`infra-kit ${e.groupPath.join(" ")}`,pn=()=>{fn();let e=v.stderr.columns;return e!=null&&e>0?e:void 0},fn=()=>{let e=v.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},gn=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),hn=async(e,t,o)=>{let r=yo(),n={...t.env,[z]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),a={code:1,signal:null};o();try{let p=t.spawn(v.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:n});a=await gn(p)}catch{a={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let i=wo(r),c=bo(a.code,a.signal,i!=null,e.longRunning),u=Mo(e),d=i?.equivalent??B(u,!0);return Eo({equivalent:d,outcome:c,durationMs:t.now()-s,summary:i?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===u)})},vn=1e3,yn=(e,t)=>e!=null&&t-e<=vn,Ie=e=>{e.resetTerminal(),e.exit(0)},wn=(e,t)=>{let o=null,r=!1,n=()=>{let c=e();if(c==="child"){o=t.now();return}c!=="pause"&&Ie(t)},s=()=>{let c=e();if(c==="palette"){Ie(t);return}if(!yn(o,t.now())){if(c==="pause"){Ie(t);return}r=!0}},a=()=>{t.exit(129)},i=()=>{e()==="child"&&t.raise("SIGSTOP")};return t.register("SIGINT",n),t.register("SIGTERM",s),t.register("SIGHUP",a),t.register("SIGTSTP",i),{dispose:()=>{t.unregister("SIGINT",n),t.unregister("SIGTERM",s),t.unregister("SIGHUP",a),t.unregister("SIGTSTP",i)},childStarted:()=>{o=null},quitRequested:()=>r}},Fo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),Sn=v.platform==="win32"?void 0:()=>{Et()},kn=(e,t)=>o=>_o(o,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:Sn}),$o=async(e,t)=>{let o={spawn:t.spawn??mn,now:t.now??(()=>Date.now()),env:t.env??v.env,cliPath:t.cliPath,ascii:t.ascii??!(v.stdout.isTTY&&v.env.TERM!=="dumb"),color:t.color??un.level>0,columns:t.columns??pn,resetTerminal:t.resetTerminal??(d=>{Oo(d)})},r=t.write??(d=>v.stderr.write(d)),n="palette",s=t.signals??{register:(d,p)=>{v.on(d,p)},unregister:(d,p)=>{v.off(d,p)},exit:d=>{v.exit(d)},raise:d=>{v.kill(v.pid,d)},now:()=>Date.now(),resetTerminal:()=>{n==="pause"&&r("\r\x1B[2K"),o.resetTerminal({entersAltScreen:!1})}},a={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},i=t.installSignals===!1?a:wn(()=>n,s),c={armed:()=>{n="pause"},quitRequested:()=>i.quitRequested()},u=t.afterRun??kn(r,o);try{for(;;){if(i.quitRequested())return;n="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let y=Co(Mo(p),{color:o.color});r(`
|
|
11
|
+
${y}
|
|
12
|
+
`),i.childStarted();let R=await hn(p,o,()=>{n="child"});if(r(`
|
|
13
|
+
${R}
|
|
14
|
+
`),await u(c)==="quit")return}}finally{i.dispose()}};import{spawn as xn}from"node:child_process";import Uo from"node:fs";import T from"node:process";import{fileURLToPath as qo}from"node:url";var jo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Rn=new Set(["mcp"]),Pn=e=>e[2]!=null&&Rn.has(e[2]),Le=e=>{let{argv:t,env:o,isTty:r,selfRealPath:n,cwd:s,realpath:a}=e;return jo.some(c=>{let u=o[c];return u!=null&&u!==""})?"opt-out":t.includes("--json")?"json":Pn(t)?"own-command":r?U(n,s,a)?"local-install":null:"not-a-tty"};var Cn=e=>{xn(T.execPath,[e,"--parent-pid",String(T.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},En=()=>qo(new URL("./update-check.js",import.meta.url)),bn=()=>Uo.realpathSync(qo(new URL("./cli.js",import.meta.url))),An=/^[\w@./+ -]+$/i,Tn=e=>An.test(e),Dn=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every(Tn)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${yt(e.updateCommand)}`)},_e=(e,t={})=>{try{let o=t.argv??T.argv,r=t.env??T.env,n=t.isTty??!!T.stdout.isTTY,s=t.cwd??T.cwd(),a=t.nowMs??Date.now(),i=t.selfRealPath??bn(),c=t.readCache??ie,u=t.spawnChild??Cn,d=t.fileExists??(C=>Uo.existsSync(C)),p=t.notify??(C=>{l.info(C)});if(Le({argv:o,env:r,isTty:n,selfRealPath:i,cwd:s,realpath:q})!==null)return;let y=c();if(Dn(y,e,p),!se(y,a))return;let R=t.childPath??En();if(!d(R))return;u(R)}catch{}};Zt();ho();var Ne=Ee(),Wo=async e=>{try{e?await Ne.parseAsync(e):await Ne.parseAsync()}catch(t){re(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},_n=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;U(Ln(Vo(import.meta.url)),g.cwd(),q)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};_n();_e(Fe.version);var Ko=()=>eo(Ne.commands),Nn=async()=>{let e=Ko(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-AJLBGRED.js");t=await o(e)}else{let o=be(e.map(n=>[n.name,n.description])),r=e.flatMap((n,s)=>[...e[s-1]?.group===n.group?[]:[new Go(" "),new Go(`\u2014 ${n.group} \u2014`)],{name:o[s]??n.name,value:n.name}]);t=await $(n=>In({message:"Select a command to run",choices:r},n),{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},On=async()=>{let{runCommandPalette:e}=await import("./boot-AJLBGRED.js"),t=Vo(import.meta.url),o=new Map(zt.map(r=>[r.groupPath.join(" "),r]));await $o(Ko(),{renderPalette:e,resolveCommand:r=>{let n=o.get(r);return n?{groupPath:n.groupPath,entersAltScreen:n.entersAltScreen,sessionEnvNotice:n.sessionEnvNotice,longRunning:n.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(Fo(g.env,e))await On();else{let t=await Nn();t&&await Wo(["node","infra-kit",...t.split(" ")])}}else await Wo();
|
|
15
15
|
//# sourceMappingURL=cli.js.map
|