infra-kit 0.14.0 → 0.15.0
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-MFHYIQ7B.js → chunk-3UE375II.js} +2 -2
- package/dist/{chunk-MFHYIQ7B.js.map → chunk-3UE375II.js.map} +1 -1
- package/dist/chunk-4RZM53X7.js +7 -0
- package/dist/{chunk-DW2SQ2XU.js.map → chunk-4RZM53X7.js.map} +3 -3
- package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
- package/dist/chunk-DVXTZPQ5.js.map +7 -0
- package/dist/{chunk-FRBNA6VH.js → chunk-EZ4DIT5A.js} +3 -3
- package/dist/{chunk-FRBNA6VH.js.map → chunk-EZ4DIT5A.js.map} +1 -1
- package/dist/chunk-I23MDR4X.js +5 -0
- package/dist/chunk-I23MDR4X.js.map +7 -0
- package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
- package/dist/chunk-IT6XJWTW.js.map +7 -0
- package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
- package/dist/chunk-PP3ZZKB3.js +12 -0
- package/dist/chunk-PP3ZZKB3.js.map +7 -0
- package/dist/{chunk-EAUGQ3ZU.js → chunk-ZTAUGYJF.js} +2 -2
- package/dist/cli.js +117 -109
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +21 -21
- package/dist/dev-server.js.map +3 -3
- package/dist/{dev-wizard-run-3DNKOVPD.js → dev-wizard-run-6PLC5YEW.js} +2 -2
- package/dist/env-load-NURS7WNH.js +2 -0
- package/dist/mcp-proxy.js +7 -7
- package/dist/mcp-proxy.js.map +3 -3
- package/dist/{persistent-ink-dev-ui-P65EJCC6.js → persistent-ink-dev-ui-ZSOS3CF4.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +5 -2
- package/dist/chunk-CMF7HEVU.js.map +0 -7
- package/dist/chunk-DW2SQ2XU.js +0 -7
- package/dist/chunk-QSTGO43H.js +0 -4
- package/dist/chunk-QSTGO43H.js.map +0 -7
- package/dist/chunk-UD6VVXUY.js +0 -10
- package/dist/chunk-UD6VVXUY.js.map +0 -7
- package/dist/chunk-VDBJ73LS.js.map +0 -7
- package/dist/env-load-MF26WMDL.js +0 -2
- /package/dist/{chunk-BQPSXIH2.js.map → chunk-MH37P7W4.js.map} +0 -0
- /package/dist/{chunk-EAUGQ3ZU.js.map → chunk-ZTAUGYJF.js.map} +0 -0
- /package/dist/{dev-wizard-run-3DNKOVPD.js.map → dev-wizard-run-6PLC5YEW.js.map} +0 -0
- /package/dist/{env-load-MF26WMDL.js.map → env-load-NURS7WNH.js.map} +0 -0
- /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i={name:"infra-kit",type:"module",version:"0.
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var i={name:"infra-kit",type:"module",version:"0.15.0",repository:{type:"git",url:"git+https://github.com/ArthurSaenz/infra-kit.git",directory:"apps/infra-kit/cli"},files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js","ik-mcp":"dist/mcp-proxy.js"},engines:{node:">=24.x"},scripts:{build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build","infra-kit-check":"pnpm exec infra-kit audit","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only","qa:pty":"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@aws-lambda-powertools/logger":"^2.35.0","@inquirer/checkbox":"^5.2.5","@inquirer/confirm":"^6.3.2","@inquirer/input":"^5.1.6","@inquirer/password":"^5.2.2","@inquirer/select":"^5.2.5","@slip-stream-kit/config":"workspace:^",chalk:"^6.0.0",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"^5.12.5",ink:"^7.1.1",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.6",react:"19.3.0",yaml:"^2.9.1",zod:"^4.6.5",zx:"^8.8.5"},devDependencies:{"@slip-stream-kit/eslint-plugin":"workspace:*","@types/aws-lambda":"catalog:","@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.2","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
|
|
2
|
+
//# sourceMappingURL=chunk-3UE375II.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../package.json"],
|
|
4
|
-
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.
|
|
4
|
+
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.15.0\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/ArthurSaenz/infra-kit.git\",\n \"directory\": \"apps/infra-kit/cli\"\n },\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\",\n \"ik-mcp\": \"dist/mcp-proxy.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.35.0\",\n \"@inquirer/checkbox\": \"^5.2.5\",\n \"@inquirer/confirm\": \"^6.3.2\",\n \"@inquirer/input\": \"^5.1.6\",\n \"@inquirer/password\": \"^5.2.2\",\n \"@inquirer/select\": \"^5.2.5\",\n \"@slip-stream-kit/config\": \"workspace:^\",\n \"chalk\": \"^6.0.0\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"^5.12.5\",\n \"ink\": \"^7.1.1\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.6\",\n \"react\": \"19.3.0\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^4.6.5\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@slip-stream-kit/eslint-plugin\": \"workspace:*\",\n \"@types/aws-lambda\": \"catalog:\",\n \"@types/react\": \"catalog:\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.2\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n"],
|
|
5
5
|
"mappings": "AAAA,IAAAA,EAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,SACX,WAAc,CACZ,KAAQ,MACR,IAAO,mDACP,UAAa,oBACf,EACA,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,cACN,SAAU,mBACZ,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,MAAS,sDACT,QAAW,iBACX,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,oEAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,SAAU,qMACV,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,kBAAmB,SACnB,qBAAsB,SACtB,mBAAoB,SACpB,0BAA2B,cAC3B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,UACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,iCAAkC,cAClC,oBAAqB,WACrB,eAAgB,WAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF",
|
|
6
6
|
"names": ["package_default"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{P as p,S as w,ca as C,d as f,f as u,ga as g}from"./chunk-EZ4DIT5A.js";import{p as b}from"./chunk-I23MDR4X.js";import{a as A,b as D}from"./chunk-QWVLAZ6N.js";var H=()=>{let e="",t=[],r=!1;return{start(n){e=n,t=[],r=!1},setInteractive(){r=!0},addOption(n,o){t.push({flag:n,value:o})},formatOptions(){return t.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ")},snapshot(){return t.length===0?null:{formattedOptions:this.formatOptions()}},print(){!r||t.length===0||!e||p.info(`\u{1F4DF} Equivalent command:
|
|
2
|
+
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
3
|
+
`)},reset(){e="",t=[],r=!1}}},x=H();import{isAbsolute as $,resolve as I}from"node:path";import M from"node:process";var E=null,y=null,K=e=>{E=[...e],y=M.cwd()},q=new Set(["--yes","-y"]),B=(e,t)=>{let r=[...e];for(let[n,o]of r.entries())o==="-C"&&r[n+1]!==void 0&&!$(r[n+1])?r[n+1]=I(t,r[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!$(o.slice(2))&&(r[n]=`-C${I(t,o.slice(2))}`);return r},T=()=>{if(E===null||y===null)return["--yes"];let e=B(E.slice(2),y);return e.some(r=>q.has(r))?e:[...e,"--yes"]};import _ from"node:process";var J=27,L=e=>e===null?"an interactive prompt was reached under --json, which never prompts":`an interactive prompt was reached in agent mode (${e==="flag"?"--agent":"INFRA_KIT_AGENT / CLAUDECODE"}), where there is no human to answer it`,W=e=>`${e===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${e}`} on the re-run`,z=e=>{if(typeof e=="object"&&"value"in e)return e.value;let t=typeof e=="object"?e.refuse:void 0,{source:r}=f;throw new g(t===void 0?{status:"refused",agentMode:r}:{status:"argument_required",argument:t,agentMode:r},2,{operation:"interactive prompt",remediation:W(t),stderrExcerpt:L(r)})},j=async(e,t)=>{let r=new AbortController,{whenHeadless:n="refuse",...o}=t??{},i={...o,signal:r.signal};if(u())return z(n);if(!_.stdin.isTTY)return e(i);let m=_.stdin,P=d=>{d.length===1&&d[0]===J&&r.abort()};A();try{let d=e(i);return m.isPaused()&&m.resume(),m.on("data",P),await d}finally{m.removeListener("data",P),D()}};import U from"@inquirer/confirm";import Y from"node:process";var a=class extends Error{constructor(t="Operation cancelled by the operator"){super(t),this.name="CommandDeclinedError"}},fe=e=>e instanceof a;var N=(e,t,r=T())=>{let{source:n}=f;throw new g({status:"confirmation_required",message:e,plan:t,rerun:r,agentMode:n},2,{operation:"confirm before running",remediation:n===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${r.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},G=async(e,t,r={})=>{!e&&u()&&N(t,r.plan,r.rerun);let n=e?!0:await j(o=>U({message:t},o),{whenHeadless:"refuse"});if(e||x.setInteractive(),!n){if(r.throwOnDecline)throw new a;p.info("Operation cancelled. Exiting..."),Y.exit(0)}};import h from"node:fs/promises";import l from"node:path";import{z as s}from"zod";var c=class extends Error{env;constructor(t,r=null){super(t),this.name="EnvAuthError",this.env=r}};var V="tokens.json",v=1,R=384,F=448,Q=s.object({version:s.literal(v).default(v),envs:s.record(s.string().min(1),s.string().min(1))}).strict(),k=async()=>{let e=await C();return l.join(l.dirname(e.userProject),V)},S=async()=>{let e=await k(),t;try{t=await h.readFile(e,"utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch(o){throw new c(`Invalid JSON in the token store at ${w(e)}: ${o.message}
|
|
4
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=Q.safeParse(r);if(!n.success)throw new c(`Invalid token store at ${w(e)}: ${s.prettifyError(n.error)}
|
|
5
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},O=async e=>{let t=await k(),r=l.dirname(t),n=l.dirname(r),o=l.dirname(n);for(let i of[o,n,r])await h.mkdir(i,{recursive:!0,mode:F}),await h.chmod(i,F);b(t,`${JSON.stringify(e,null,2)}
|
|
6
|
+
`,R),await h.chmod(t,R)};var X=async e=>{let t=await S();await O({version:v,envs:{...t?.envs,...e}})},Z=async e=>{let t=await S();if(!t||!(e in t.envs))return;let r={...t.envs};delete r[e],await O({version:v,envs:r})};export{x as a,fe as b,K as c,T as d,j as e,N as f,G as g,c as h,k as i,S as j,X as k,Z as l};
|
|
7
|
+
//# sourceMappingURL=chunk-4RZM53X7.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts", "../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts"],
|
|
4
|
-
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, [env]: token },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "rerun", "rerunArgv", "source", "agentMode", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process", "fs", "path", "z", "EnvAuthError", "message", "env", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "
|
|
4
|
+
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n await setTokens({ [env]: token })\n}\n\n/**\n * Add or replace several environments' tokens in ONE read-modify-write, so a bulk import never leaves\n * the store half-written between two of its entries.\n *\n * @example\n * await setTokens({ dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' })\n * // tokens.json => { version: 1, envs: { \u2026existing, dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' } }\n */\nexport const setTokens = async (tokens: Record<string, string>): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, ...tokens },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
+
"mappings": "oKAOA,IAAMA,EAAoB,IAAM,CAC9B,IAAIC,EAAU,GACVC,EAA2B,CAAC,EAC5BC,EAAgB,GAEpB,MAAO,CAWL,MAAMC,EAAoB,CACxBH,EAAUG,EACVF,EAAU,CAAC,EACXC,EAAgB,EAClB,EAMA,gBAAuB,CACrBA,EAAgB,EAClB,EAQA,UAAUE,EAAcC,EAA0C,CAChEJ,EAAQ,KAAK,CAAE,KAAAG,EAAM,MAAAC,CAAM,CAAC,CAC9B,EAKA,eAAwB,CACtB,OAAOJ,EACJ,IAAKK,GACA,OAAOA,EAA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CAAU,EACrCE,EAAgBd,EAAK,QAAQa,CAAW,EAE9C,QAAWE,IAAO,CAACD,EAAeD,EAAaD,CAAU,EACvD,MAAMR,EAAG,MAAMW,EAAK,CAAE,UAAW,GAAM,KAAMrB,CAAe,CAAC,EAC7D,MAAMU,EAAG,MAAMW,EAAKrB,CAAc,EAGpCsB,EAAoBd,EAAW,GAAG,KAAK,UAAUS,EAAO,KAAM,CAAC,CAAC;AAAA,EAAMlB,CAAe,EAIrF,MAAMW,EAAG,MAAMF,EAAWT,CAAe,CAC3C,EAsBO,IAAMwB,EAAY,MAAOC,GAAkD,CAChF,IAAMC,EAAW,MAAMC,EAAe,EAEtC,MAAMC,EAAgB,CACpB,QAASC,EACT,KAAM,CAAE,GAAGH,GAAU,KAAM,GAAGD,CAAO,CACvC,CAAC,CACH,EAYaK,EAAc,MAAOC,GAA+B,CAC/D,IAAML,EAAW,MAAMC,EAAe,EAEtC,GAAI,CAACD,GAAY,EAAEK,KAAOL,EAAS,MAAO,OAE1C,IAAMM,EAAO,CAAE,GAAGN,EAAS,IAAK,EAEhC,OAAOM,EAAKD,CAAG,EAEf,MAAMH,EAAgB,CACpB,QAASC,EACT,KAAAG,CACF,CAAC,CACH",
|
|
6
|
+
"names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "rerun", "rerunArgv", "source", "agentMode", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process", "fs", "path", "z", "EnvAuthError", "message", "env", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setTokens", "tokens", "existing", "readTokenStore", "writeTokenStore", "TOKEN_STORE_VERSION", "removeToken", "env", "envs"]
|
|
7
7
|
}
|
|
@@ -3,4 +3,4 @@ import h from"node:process";var p=["\u280B","\u2819","\u2839","\u2838","\u283C",
|
|
|
3
3
|
`),this.paintSpinner();return}this.deps.write(`${t}
|
|
4
4
|
`)}log(t,e="info",r={}){(e!=="debug"||this.deps.verbose)&&this.emit(t),r.tee!==!1&&this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=p[this.spinnerFrame%p.length];this.deps.write(`${d}${this.color(s.teal,t)} ${this.color(s.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
|
|
5
5
|
`);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},f),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(d)}errorCount(t){let e=`\u26A0 ${t}`;return t>0?this.color(`${s.bold}${s.red}`,e):this.color(s.dim,e)}tagCell(t,e,r){return this.color((r??0)>0?s.red:s.teal,t.padEnd(e))}healthDot(t){switch(t){case"ok":return this.color(s.green,"\u25CF ok");case"down":return this.color(s.red,"\u25CF down");case"starting":return this.color(s.dim,"\u25CC starting");case"unverified":return this.color(s.dim,"\u25CD ?");default:return""}}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let r of e)this.emit(r),this.tee(r,"info")}tagWidth(t){return[...t.endpoints.map(r=>r.tag),...t.uiRefs.map(r=>r.tag),...(t.failed??[]).map(r=>r.tag),...(t.degraded??[]).map(r=>`${r.tag} ${r.route}`)].reduce((r,i)=>Math.max(r,i.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(a=>!!a).join(" \xB7 "),r=t.failed?.length??0,i=v(t.elapsedMs),n=r>0?this.color(s.red,`${r} failed \xB7 started in ${i}`):this.color(s.green,`ready in ${i}`);return` ${this.color(s.bold,"infra-kit dev")} ${this.color(s.dim,e)} ${n}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",r=this.hyperlink(t.logHref,t.logPath),i=`${e} logs \u2192 ${r}`,n="\u2500".repeat(60);return[` ${this.color(s.dim,i)}`,` ${this.color(s.dim,n)}`]}uiRefLine(t,e,r){let i=r==null?"":` ${this.errorCount(r)}`;return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.dim,"no managed port (vite prints its own URL)")}${i}`}statusFields(t){let e=[];return t.uptimeMs!=null&&e.push(this.color(s.dim,`up ${c(t.uptimeMs)}`)),t.rpm!=null&&t.rpm>0&&e.push(this.color(s.dim,`${t.rpm}/min`)),t.restarts!=null&&t.restarts>0&&e.push(this.color(s.dim,`\u21BA${t.restarts}`)),t.errors!=null&&e.push(this.errorCount(t.errors)),e.join(" ")}endpointLine(t,e,r){let i=r?this.healthDot(t.health):"",n=this.statusFields(t),a=[i,n].filter(Boolean).join(" ");return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.blue,t.url)}${a?` ${a}`:""}`}failedLine(t,e){return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.red,"\u25CF failed")} ${this.color(s.dim,t.reason)}`}degradedLine(t,e){let r=`${t.tag} ${t.route}`,i=t.fallback==="cloud"?"\u25CF cloud (local backend down)":"\u25CF dead alias (local backend down)",n=t.target?` ${this.color(s.dim,t.target)}`:"";return` ${this.color(s.red,"\u26A0")} ${this.color(s.teal,r.padEnd(e))} ${this.color(s.red,i)}${n}`}proxyLines(t){if(t.length===0)return[];let e=Math.max(...t.map(r=>r.route.length));return t.map((r,i)=>{let n=i===t.length-1?"\u2514":"\u251C",a=r.source==="local"?this.color(s.green,"\u25CF"):this.color(s.dim,"\u25CB"),l=r.target?` ${this.color(s.blue,r.target)}`:"";return` ${this.color(s.dim,n)} ${this.color(s.teal,r.route.padEnd(e))} ${a} ${this.color(s.dim,r.source)}${l}`})}formatLines(t,{withHealthDot:e}){let r=this.tagWidth(t),i=["",this.titleLine(t),""];for(let n of t.endpoints)i.push(this.endpointLine(n,r,e)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.failed??[])i.push(this.failedLine(n,r));for(let n of t.uiRefs)i.push(this.uiRefLine(n,r,n.errors)),n.proxies&&i.push(...this.proxyLines(n.proxies));for(let n of t.degraded??[])i.push(this.degradedLine(n,r));return i.push("",...this.legendLines(t)),i}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t),r=t.endpoints.map(i=>{let n=this.healthDot(i.health),a=this.statusFields(i),l=[n,a].filter(Boolean).join(" ");return` ${this.tagCell(i.tag,e,i.errors)} ${l}`});for(let i of t.uiRefs)i.errors!=null&&r.push(` ${this.tagCell(i.tag,e,i.errors)} ${this.errorCount(i.errors)}`);for(let i of t.degraded??[])r.push(this.degradedLine(i,e));if(t.sessionUptimeMs!=null){let i=`up ${c(t.sessionUptimeMs)}`;r.push(` ${this.color(s.dim,i)}`)}return r}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}};export{R as a,g as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-DVXTZPQ5.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dev/render.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Terminal renderer for `infra-kit dev` \u2014 a calm-print layer (never a full-screen TUI).\n *\n * The boot collapses into a single transient spinner; the final screen is a STATUS PANEL, one row per\n * server, carrying health, uptime, requests/min, restarts and an error count. There is no log tail:\n * every line \u2014 framework output, request logs, a handler's own `console.log` \u2014 is written to that\n * service's file under `<cacheRoot>/<session>/dev/<pid>/` and never printed. What still appears above\n * the panel is only what the RUNNER says: a restart, an unhealthy app, a dead engine.\n *\n * The panel's live fields are the reason it is a status surface and not a screenshot. With nothing\n * scrolling beside it, a panel whose numbers never move cannot be told apart from a hung process.\n *\n * All I/O is injected (`write` / `appendLog` / `isTTY` / `now`) so every frame is snapshot-testable and\n * the spinner is deterministically disabled in tests (`isTTY: false`).\n */\nimport process from 'node:process'\n\nimport type { DevUi } from './dev-ui.js'\n\nexport type LogLevel = 'info' | 'warn' | 'error' | 'debug'\n\n/**\n * Per-call options for {@link DevRenderer.log}.\n *\n * `tee: false` exists for exactly one caller: `DevServerRunner.reportFault`, which files the fault into the\n * sink ITSELF (at `error` level \u2014 that is what turns the panel row red) and then prints it. Without this\n * opt-out the print tees a SECOND copy into the same `runner.log`, so every fault is filed twice \u2014 a\n * literal 2\u00D7 amplifier sitting at the centre of the loop that wrote 455 GB.\n */\nexport interface LogOptions {\n /** Also append the line to the log file. Default `true`; `false` prints without filing. */\n tee?: boolean\n}\n\n/**\n * A row's liveness, as the runner's probe state machine resolved it.\n *\n * Five arms, not a boolean, because a probe has three outcomes and a row has a history. The two that\n * are neither `ok` nor `down` are the honest ones: a UI that has never answered yet is `starting`\n * (vite is spawned after the ready frame, so red would be a lie for the first seconds), and a port that\n * answers something OTHER than vite's ping is `unverified` \u2014 a squatter, a shadowing proxy, or a future\n * vite that dropped the endpoint are all consistent with that, and only one of them is broken. Red must\n * stay a PROOF of failure, so `unverified` renders a question mark and never a red dot.\n */\nexport type HealthState = 'ok' | 'down' | 'starting' | 'unverified' | 'unknown'\n\n/** Injected I/O seams. Defaults wire to the real stdout + a caller-provided file appender. */\nexport interface DevRendererDeps {\n /** Terminal sink (default: `process.stdout.write`). */\n write: (text: string) => void\n /** File tee \u2014 always receives full detail (default: no-op; the runner passes its log appender). */\n appendLog: (text: string) => void\n /** Whether the terminal is a TTY. Gates the spinner + ANSI color; false in CI / when piped. */\n isTTY: boolean\n /** Clock seam (default: `() => new Date()`), so timestamps + `ready in Xs` are testable. */\n now: () => Date\n /** When true, boot narration reaches the terminal; otherwise it is file-only. */\n verbose: boolean\n}\n\n/**\n * One resolved proxy route on a frontend, painted as an indented line under that app's row: which route,\n * where it lands, and whether it is the local backend or the shared cloud one. This is the \"all proxies \u2014\n * which one and where\" surface: unlike a {@link DegradedRow} it reports the happy path too, so a frontend\n * that proxies `/api` local and `/media` cloud shows both, and nobody has to guess where a route points.\n */\nexport interface ProxyRouteRow {\n /** Route path (e.g. `/api`). */\n route: string\n /** Where the route resolves this run \u2014 the local backend or the shared cloud origin. */\n source: 'local' | 'cloud'\n /**\n * The origin the route lands on. Omitted when it is not knowable (a `local` route whose backend is not\n * up \u2014 a dead alias the degraded row already owns \u2014 or a `cloud` route with no `<env>` sourced).\n */\n target?: string\n}\n\n/**\n * One server's row on the status panel.\n *\n * The live fields below are what make the panel a STATUS surface rather than a screenshot. The terminal\n * no longer carries a log tail, so a static row would leave \"quiet\" indistinguishable from \"hung\" \u2014 the\n * moving numbers are the liveness tell, and they are not decoration.\n */\nexport interface EndpointRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** The app's `.localhost` alias URL \u2014 the only form, since an app that cannot be aliased never starts. */\n url: string\n /** Liveness, as {@link HealthState} defines it; `unknown` renders no dot at all (nothing to probe). */\n health: HealthState\n /** Milliseconds since this server last (re)started. Omitted on the boot frame. */\n uptimeMs?: number\n /** Watch-triggered restarts so far this session. */\n restarts?: number\n /** Requests served in the last 60s. */\n rpm?: number\n /**\n * Errors this service has declared since boot \u2014 a 5xx, a `console.error`, a framework failure line.\n * This is the ONLY error signal the user gets now that nothing prints, so a row that cannot count is\n * a row that lies. A COUNT, never a classification: it is incremented from the level the emitter\n * declared, never from anything read out of the line's text.\n */\n errors?: number\n /**\n * Resolved proxy routes for a frontend row (a `<app>/ui` endpoint), painted as an indented list under\n * it. Absent on backend rows \u2014 a `<app>/api` endpoint proxies nothing \u2014 and on a frontend with no\n * `dev.proxy` block.\n */\n proxies?: ProxyRouteRow[]\n}\n\n/**\n * A UI app whose URL the runner does not own, so it streams its own below \u2014 referenced, never given a\n * (fabricated) endpoint row. The fallback case only: a UI whose port the runner pre-assigned is an\n * {@link EndpointRow}, proxy or no proxy.\n */\nexport interface UiRef {\n /** Stream tag, e.g. `client/ui`. */\n tag: string\n /**\n * Errors this UI has declared since boot. Present for the same reason an {@link EndpointRow} has one:\n * with nothing printing, a row that cannot count is a row that lies \u2014 and this row belongs to the app\n * whose vite config never wired `infraKitDev()`, i.e. the one most likely to be misconfigured.\n */\n errors?: number\n /** Resolved proxy routes for this frontend, painted as an indented list under its reference line. */\n proxies?: ProxyRouteRow[]\n}\n\n/**\n * An app that was asked for but never came up. It has no URL and no health \u2014 but it MUST still get a\n * row: the header is a report of what the user asked for, and an app that silently vanishes from it\n * reads as \"not requested\" rather than \"broken\".\n */\nexport interface FailedRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** One-line reason, e.g. `config is missing field: 'connectionURL'`. */\n reason: string\n}\n\n/**\n * A route that wanted a local backend and is falling back to cloud because that backend failed to start.\n *\n * It gets a row of its own \u2014 not a footnote on the failed backend's row \u2014 because the two facts land on\n * different people. `client/api \u25CF failed` says a server is down, which reads as \"that half is broken\".\n * It does NOT say the frontend beside it came up healthy and is now sending every `/api` request to the\n * shared cloud backend. That second fact is the one that gets you writing to the cloud dev database\n * while you believe you are on localhost, and it is invisible everywhere else on the screen: the vite\n * proxy resolved cleanly, so nothing else has anything to complain about.\n *\n * Only rendered under `--watch` \u2014 without it the run is refused outright (see `local-pairing.ts`).\n */\nexport interface DegradedRow {\n /** Route path (e.g. `/api`). */\n route: string\n /** Stream tag of the frontend serving it, e.g. `client/ui`. */\n tag: string\n /**\n * Where the route ACTUALLY resolves now. Not always `cloud`: the helper falls back to\n * `route.default ?? route.from[0]`, so a single-source `from: ['local']` route with no `default` falls\n * back to `local` \u2014 at an alias nothing registered, i.e. a 502 on every request. The row must name the\n * real destination, or it is doing the same lying-by-omission it exists to prevent.\n */\n fallback: 'local' | 'cloud'\n /** The cloud origin it now resolves to. Only ever set when `fallback` is `cloud` and it is knowable. */\n target?: string\n}\n\n/** Everything {@link DevRenderer.ready} needs to paint the final header in one shot. */\nexport interface ReadySummary {\n /** Resolved preset / target label (e.g. `client`, `*`). */\n target: string\n watch: boolean\n /** Slugified release for the header meta; omitted outside a git repo. */\n release?: string\n /** Backend readiness time in ms (UI is fire-and-forget, so this is BE-only \u2014 labeled honestly). */\n elapsedMs: number\n /** Real backend endpoint rows (owned ports + pre-probed health). */\n endpoints: EndpointRow[]\n /** UI apps that print their own URL below. */\n uiRefs: UiRef[]\n /**\n * Apps that failed to start. Optional only so the (many) existing summaries need not restate an\n * empty list; a non-empty one downgrades the title from a green `ready` to an honest `N failed`.\n */\n failed?: FailedRow[]\n /**\n * Routes silently demoted from local to cloud by a backend that failed to start. Recomputed on every\n * repaint, so a route CLEARS from the panel the moment `--watch` gets its backend up (see\n * {@link DegradedRow}).\n */\n degraded?: DegradedRow[]\n /** Human watch summary, e.g. `1 app \u00B7 5 packages`; omitted when not watching. */\n watchSummary?: string\n /**\n * Compact, human-readable log path shown as the `logs \u2192 \u2026` label. A DIRECTORY, not a file\n * (e.g. `~/.cache/infra-kit/<session>/dev/<pid>`): there is one log per service, so a single path\n * would have to pick a favourite.\n */\n logPath: string\n /** Absolute log path backing the clickable OSC-8 hyperlink (wrapped as `file://<logHref>`). */\n logHref: string\n /**\n * Milliseconds since the session became ready \u2014 the panel's HEARTBEAT.\n *\n * Every other live field belongs to a backend: uptime, req/min, restarts. A UI-only session has no\n * backend, so its rows have nothing that moves \u2014 and Ink does not repaint an identical frame, so the\n * screen would sit perfectly still while the session ran. With no log tail left to prove otherwise,\n * a motionless panel is indistinguishable from a hung process. This is the one field that ticks for\n * EVERY session shape. Omitted on the boot frame, where nothing has elapsed yet.\n */\n sessionUptimeMs?: number\n}\n\nconst SPINNER_FRAMES = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F']\nconst SPINNER_INTERVAL_MS = 80\n\nconst ANSI = {\n reset: '\\x1B[0m',\n dim: '\\x1B[2m',\n bold: '\\x1B[1m',\n teal: '\\x1B[36m',\n green: '\\x1B[32m',\n blue: '\\x1B[34m',\n red: '\\x1B[31m',\n} as const\n\n/** Erase the current line and return the cursor to column 0 (used to clear the spinner). */\nconst CLEAR_LINE = '\\r\\x1B[2K'\n\n/**\n * SGR color codes (`ESC [ \u2026 m`) and OSC-8 hyperlink wrappers (`ESC ] 8 ; ; \u2026 ESC \\`), non-greedy.\n * Matching the ESC control character is the whole point here \u2014 this pattern exists to remove it.\n */\n// eslint-disable-next-line sonarjs/no-control-regex, no-control-regex\nconst ANSI_PATTERN = /\\x1B\\[[0-9;]*m|\\x1B\\]8;;.*?\\x1B\\\\/g\n\n/**\n * Strip SGR colors + OSC-8 hyperlink escapes, keeping the hyperlink's visible label. Applied at the\n * file-tee seam so `logs.txt` stays greppable plain text even though the terminal frames it renders\n * from are colored + hyperlinked (both renderers format once, for a TTY, and tee the same string).\n */\nexport const stripAnsi = (s: string): string => {\n return s.replace(ANSI_PATTERN, '')\n}\n\n/** Zero-pad to 2 digits for `HH:MM:SS`. */\nconst pad2 = (n: number): string => {\n return String(n).padStart(2, '0')\n}\n\n/** `2.4s` for the `ready in \u2026` header. */\nexport const formatElapsed = (ms: number): string => {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * `47s` / `4m12s` / `2h03m` \u2014 the panel's liveness tell.\n *\n * With no log tail on screen, a panel whose numbers never move is indistinguishable from a hung\n * process. This is the field that proves the session is alive even when nothing is happening, so it is\n * always rendered and always advancing.\n */\nexport const formatUptime = (ms: number): string => {\n const total = Math.max(0, Math.floor(ms / 1000))\n const hours = Math.floor(total / 3600)\n const minutes = Math.floor((total % 3600) / 60)\n const seconds = total % 60\n\n if (hours > 0) return `${hours}h${pad2(minutes)}m`\n if (minutes > 0) return `${minutes}m${pad2(seconds)}s`\n\n return `${seconds}s`\n}\n\n/**\n * Resolve the endpoint URL for an app: `https://<alias><prefix>`, where `alias` is the portless hostname\n * the runner registered (e.g. `feat-x.backend-api.hulyo-monorepo.localhost`). The runner refuses to start an app it could\n * not alias, so there is no port-form to fall back to.\n *\n * There is no port and no scheme choice, by construction. The proxy serves TLS on 443 \u2014 the implicit HTTPS\n * port \u2014 so the URL is byte-identical to the `dev.proxy` local template that `infra-kit/vite` proxies to,\n * and what the table prints cannot drift from what the frontend calls. Any port suffix here would mean the\n * proxy is not on 443, which `ensureProxy` has already refused to start.\n */\nexport const resolveEndpointUrl = (input: { prefixUrl: string; alias: string }): string => {\n return `https://${input.alias}${input.prefixUrl}`\n}\n\nexport class DevRenderer implements DevUi {\n private readonly deps: DevRendererDeps\n private spinnerTimer: ReturnType<typeof setInterval> | null = null\n private spinnerPhase = ''\n private spinnerFrame = 0\n\n constructor(deps: Partial<DevRendererDeps> = {}) {\n this.deps = {\n write:\n deps.write ??\n ((text: string): void => {\n process.stdout.write(text)\n }),\n appendLog: deps.appendLog ?? ((): void => {}),\n isTTY: deps.isTTY ?? Boolean(process.stdout.isTTY),\n now:\n deps.now ??\n ((): Date => {\n return new Date()\n }),\n verbose: deps.verbose ?? false,\n }\n }\n\n /** Wrap `s` in an ANSI color on a TTY; return it untouched when piped (deterministic snapshots). */\n private color(code: string, s: string): string {\n return this.deps.isTTY ? `${code}${s}${ANSI.reset}` : s\n }\n\n /**\n * Wrap `label` in an OSC-8 terminal hyperlink to `href` (a filesystem path \u2192 `file://` URI) so the\n * log path is cmd/ctrl-clickable. Returns the bare `label` when piped (deterministic snapshots) or\n * when `href` is empty \u2014 terminals without OSC-8 support silently ignore the escapes anyway.\n */\n private hyperlink(href: string, label: string): string {\n if (!this.deps.isTTY || href === '') return label\n\n // `encodeURI` escapes spaces / non-ASCII but leaves `#` and `?`, which a file URI reads as a\n // fragment / query \u2014 encode those too so a path containing them still resolves to the real file.\n const uri = encodeURI(href).replace(/[#?]/g, (c) => {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n\n return `\\x1B]8;;file://${uri}\\x1B\\\\${label}\\x1B]8;;\\x1B\\\\`\n }\n\n /**\n * Append one line to the log file ONLY \u2014 the canonical `[iso] [LEVEL] msg` shape, no terminal write.\n * The single source of the file-tee format: the private {@link tee} and the Ink boot UI both route\n * here, so the log file stays identical whichever renderer is live.\n */\n teeOnly(message: string, level: LogLevel): void {\n this.deps.appendLog(`[${this.deps.now().toISOString()}] [${level.toUpperCase()}] ${stripAnsi(message)}\\n`)\n }\n\n /** File tee for a line that is ALSO written to the terminal; delegates the format to {@link teeOnly}. */\n private tee(message: string, level: LogLevel): void {\n this.teeOnly(message, level)\n }\n\n /**\n * No-op for the plain renderer: it owns no Ink / raw-mode terminal state to release. Present to\n * satisfy {@link DevUi} so the runner can call `dispose()` uniformly. Idempotent by construction.\n */\n dispose(): void {\n // Nothing to release \u2014 the plain renderer never seizes the terminal.\n }\n\n /**\n * Write one terminal line spinner-safely: if the spinner is live on a TTY, erase it, print the\n * line, then repaint the spinner, so a mid-boot message never shreds the `\\r`-based spinner.\n */\n private emit(line: string): void {\n if (this.spinnerTimer != null && this.deps.isTTY) {\n this.deps.write(`${CLEAR_LINE}${line}\\n`)\n this.paintSpinner()\n\n return\n }\n\n this.deps.write(`${line}\\n`)\n }\n\n /** A general message routed by level (terminal + file tee). Debug is terminal-only in verbose. */\n log(message: string, level: LogLevel = 'info', options: LogOptions = {}): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n if (options.tee !== false) {\n this.tee(message, level)\n }\n }\n\n /** A boot-narration step: terminal only when `--verbose`, but always tee'd to the log. */\n narrate(message: string): void {\n if (this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, 'info')\n }\n\n /** `LogFn`-shaped adapter for the build runner seam (which passes `(msg, level)`). */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot spinner -------------------------------------------------------\n\n /** Paint the current spinner frame in place (TTY only). */\n private paintSpinner(): void {\n const frame = SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length]!\n\n this.deps.write(`${CLEAR_LINE}${this.color(ANSI.teal, frame)} ${this.color(ANSI.dim, this.spinnerPhase)}`)\n }\n\n /**\n * Update the boot phase. On a TTY this drives a single transient spinner line; when piped it\n * prints one plain phase line (no ANSI, deterministic). Always tee'd to the log.\n */\n bootStep(phase: string): void {\n this.tee(phase, 'info')\n this.spinnerPhase = phase\n\n if (!this.deps.isTTY) {\n this.deps.write(`${phase}\\n`)\n\n return\n }\n\n if (this.spinnerTimer == null) {\n this.spinnerTimer = setInterval(() => {\n this.spinnerFrame += 1\n this.paintSpinner()\n }, SPINNER_INTERVAL_MS)\n // Never keep the event loop alive for the spinner alone.\n this.spinnerTimer.unref?.()\n }\n this.paintSpinner()\n }\n\n /** Stop + erase the spinner line (idempotent). Called before the ready header prints. */\n stopSpinner(): void {\n if (this.spinnerTimer != null) {\n clearInterval(this.spinnerTimer)\n this.spinnerTimer = null\n }\n if (this.deps.isTTY) {\n this.deps.write(CLEAR_LINE)\n }\n }\n\n // ---- the ready header ---------------------------------------------------\n\n /**\n * The error counter, shared by endpoint rows and UI reference rows.\n *\n * Zero is rendered, not omitted: with nothing else printing, this is the only failure signal on the\n * screen, so a dim `\u26A0 0` is a claim worth making.\n *\n * Non-zero is BOLD red, and that is not decoration. A frontend that fails to compile still serves and\n * still answers vite's ping, so its dot stays green \u2014 the dot is liveness, and the app IS alive. This\n * counter is the only thing on the screen that says the app is nevertheless broken, so it has to win a\n * glance against a green dot sitting two columns away.\n */\n private errorCount(errors: number): string {\n const text = `\u26A0 ${errors}`\n\n return errors > 0 ? this.color(`${ANSI.bold}${ANSI.red}`, text) : this.color(ANSI.dim, text)\n }\n\n /**\n * The padded tag gutter for a PANEL row \u2014 red once the row has declared an error, teal otherwise.\n *\n * Footer only, never {@link formatHeaderLines}. The header is committed once through Ink's `<Static>`,\n * so a tag reddened there would be a photograph of the boot: it could never turn red later, and \u2014 far\n * worse \u2014 could never turn back. The panel repaints, so the color tracks the fact.\n */\n private tagCell(tag: string, tagWidth: number, errors: number | undefined): string {\n return this.color((errors ?? 0) > 0 ? ANSI.red : ANSI.teal, tag.padEnd(tagWidth))\n }\n\n /** Format the health dot for an endpoint row \u2014 one arm per {@link HealthState}; `unknown` prints nothing. */\n private healthDot(health: HealthState): string {\n switch (health) {\n case 'ok':\n return this.color(ANSI.green, '\u25CF ok')\n case 'down':\n return this.color(ANSI.red, '\u25CF down')\n case 'starting':\n return this.color(ANSI.dim, '\u25CC starting')\n // Answering, but not with vite's ping. Dim, never red: a non-204 is equally consistent with a\n // broken squatter and a perfectly healthy vite behind something that shadows the ping, and a red\n // dot on a coin-flip is how a dot stops being read at all.\n case 'unverified':\n return this.color(ANSI.dim, '\u25CD ?')\n default:\n return ''\n }\n }\n\n /**\n * Collapse the boot and print the final header in one shot: title line, one endpoint row per\n * backend server (with health dot), a reference line per UI app, the watch line, the clickable\n * log path, and a separator rule. Synchronous \u2014 health is pre-probed by the caller.\n */\n ready(summary: ReadySummary): void {\n this.stopSpinner()\n\n const lines = this.formatReadyLines(summary)\n\n for (const line of lines) {\n this.emit(line)\n this.tee(line, 'info')\n }\n }\n\n /** Column width for the aligned `tag` gutter \u2014 the widest endpoint/UI/failed tag. */\n private tagWidth(summary: ReadySummary): number {\n const tags = [\n ...summary.endpoints.map((e) => {\n return e.tag\n }),\n ...summary.uiRefs.map((u) => {\n return u.tag\n }),\n ...(summary.failed ?? []).map((f) => {\n return f.tag\n }),\n // A degraded row's gutter is `<tag> <route>`, which is wider than any bare tag \u2014 measure the label\n // it actually prints or its `\u25CF cloud \u2026` cell would sit out of column with every row above it.\n ...(summary.degraded ?? []).map((d) => {\n return `${d.tag} ${d.route}`\n }),\n ]\n\n return tags.reduce((w, t) => {\n return Math.max(w, t.length)\n }, 0)\n }\n\n /**\n * The `infra-kit dev \u00B7 <meta> ready in Xs` title line.\n *\n * A green `ready` is a claim about the whole session, so it is spent only when the whole session\n * is up. With anything in `failed` the status turns red and counts the casualties instead \u2014 the\n * boot time alone, next to a green word, is exactly how a half-dead session used to pass for a\n * healthy one.\n */\n private titleLine(summary: ReadySummary): string {\n const meta = [summary.target, summary.watch ? 'watch' : null, summary.release]\n .filter((s): s is string => {\n return Boolean(s)\n })\n .join(' \u00B7 ')\n\n const failedCount = summary.failed?.length ?? 0\n const elapsed = formatElapsed(summary.elapsedMs)\n const status =\n failedCount > 0\n ? this.color(ANSI.red, `${failedCount} failed \u00B7 started in ${elapsed}`)\n : this.color(ANSI.green, `ready in ${elapsed}`)\n\n return ` ${this.color(ANSI.bold, 'infra-kit dev')} ${this.color(ANSI.dim, meta)} ${status}`\n }\n\n /** The static legend tail: watch line + clickable log path, then a separator rule. */\n private legendLines(summary: ReadySummary): string[] {\n const watchText = summary.watch && summary.watchSummary ? `watching ${summary.watchSummary}` : 'watch off'\n const logLink = this.hyperlink(summary.logHref, summary.logPath)\n const watchLine = `${watchText} logs \u2192 ${logLink}`\n const rule = '\u2500'.repeat(60)\n\n return [` ${this.color(ANSI.dim, watchLine)}`, ` ${this.color(ANSI.dim, rule)}`]\n }\n\n /**\n * A UI reference row \u2014 used when infra-kit could not claim the UI's port, so it has no URL to print.\n *\n * It STILL carries an error count. That is the whole point: this row is exactly the misconfigured app\n * (its vite config never wired `infraKitDev()`), which is the app most likely to be broken \u2014 and with\n * no log tail on screen, a row with no error field is a row that cannot report the breakage. It used\n * to be a bare reference line, so its errors were counted into a file nobody had a reason to open.\n */\n private uiRefLine(ref: UiRef, tagWidth: number, errors: number | undefined): string {\n const errText = errors == null ? '' : ` ${this.errorCount(errors)}`\n\n return ` ${this.color(ANSI.teal, ref.tag.padEnd(tagWidth))} ${this.color(\n ANSI.dim,\n 'no managed port (vite prints its own URL)',\n )}${errText}`\n }\n\n /**\n * The live half of an endpoint row: `up 4m12s 18/min \u21BA2 \u26A0 3`.\n *\n * Empty on the boot frame (no field is set yet). Each field is omitted individually when absent \u2014 a\n * server with no restarts should not have to say so.\n */\n private statusFields(endpoint: ReadySummary['endpoints'][number]): string {\n const parts: string[] = []\n\n if (endpoint.uptimeMs != null) parts.push(this.color(ANSI.dim, `up ${formatUptime(endpoint.uptimeMs)}`))\n if (endpoint.rpm != null && endpoint.rpm > 0) parts.push(this.color(ANSI.dim, `${endpoint.rpm}/min`))\n if (endpoint.restarts != null && endpoint.restarts > 0) parts.push(this.color(ANSI.dim, `\u21BA${endpoint.restarts}`))\n // Errors are the exception to \"omit when zero\" \u2014 see {@link errorCount}.\n if (endpoint.errors != null) {\n parts.push(this.errorCount(endpoint.errors))\n }\n\n return parts.join(' ')\n }\n\n /** One endpoint row (`client/api https://\u2026 \u25CF ok up 4m12s 18/min \u26A0 0`). */\n private endpointLine(endpoint: ReadySummary['endpoints'][number], tagWidth: number, withHealthDot: boolean): string {\n const dot = withHealthDot ? this.healthDot(endpoint.health) : ''\n const status = this.statusFields(endpoint)\n const suffix = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.color(ANSI.teal, endpoint.tag.padEnd(tagWidth))} ${this.color(ANSI.blue, endpoint.url)}${\n suffix ? ` ${suffix}` : ''\n }`\n }\n\n /** One failed row (`client/api \u25CF failed <reason>`) \u2014 no URL, because there is nothing listening. */\n private failedLine(failed: FailedRow, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, failed.tag.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n '\u25CF failed',\n )} ${this.color(ANSI.dim, failed.reason)}`\n }\n\n /**\n * One degraded-route row (`\u26A0 /api \u25CF cloud (local backend failed) https://dev.hulyo.co.il`).\n *\n * Tagged by ROUTE, not by app, and deliberately so: the app rows above already say what is up and what\n * is down, and neither of them can say \"the frontend that came up healthy is talking to cloud\". The\n * route is the thing that got redirected, so the route is what the row is about.\n */\n private degradedLine(row: DegradedRow, tagWidth: number): string {\n const label = `${row.tag} ${row.route}`\n // A `local` fallback is not a cloud proxy \u2014 it is a dead alias that 502s. Saying \"cloud\" there would\n // name a destination the traffic never reaches.\n const state = row.fallback === 'cloud' ? '\u25CF cloud (local backend down)' : '\u25CF dead alias (local backend down)'\n const target = row.target ? ` ${this.color(ANSI.dim, row.target)}` : ''\n\n return ` ${this.color(ANSI.red, '\u26A0')} ${this.color(ANSI.teal, label.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n state,\n )}${target}`\n }\n\n /**\n * The indented proxy lines painted under a frontend's row: ` \u251C /api \u25CF local https://\u2026`. One per\n * resolved route, so \"which one and where\" is answered inline instead of left to guess. A filled dot is\n * the local backend, a hollow one the shared cloud origin \u2014 the same local=\u25CF/cloud=\u25CB language the rest\n * of the panel uses. The last route gets a `\u2514` elbow so the group reads as one block belonging to the\n * app above it. Empty when the frontend declares no routes.\n */\n private proxyLines(proxies: ProxyRouteRow[]): string[] {\n if (proxies.length === 0) return []\n\n const routeWidth = Math.max(\n ...proxies.map((p) => {\n return p.route.length\n }),\n )\n\n return proxies.map((p, i) => {\n const elbow = i === proxies.length - 1 ? '\u2514' : '\u251C'\n const dot = p.source === 'local' ? this.color(ANSI.green, '\u25CF') : this.color(ANSI.dim, '\u25CB')\n const where = p.target ? ` ${this.color(ANSI.blue, p.target)}` : ''\n\n return ` ${this.color(ANSI.dim, elbow)} ${this.color(ANSI.teal, p.route.padEnd(routeWidth))} ${dot} ${this.color(\n ANSI.dim,\n p.source,\n )}${where}`\n })\n }\n\n /**\n * Shared header layout: blank, title line, blank, one endpoint row per backend, a reference row per\n * UI app, then the watch/log legend. `withHealthDot` is the ONLY difference between the static Ink\n * header (false \u2014 health is live, the footer owns it) and the ready/boot frame (true).\n */\n private formatLines(summary: ReadySummary, { withHealthDot }: { withHealthDot: boolean }): string[] {\n const tagWidth = this.tagWidth(summary)\n const lines: string[] = ['', this.titleLine(summary), '']\n\n for (const e of summary.endpoints) {\n lines.push(this.endpointLine(e, tagWidth, withHealthDot))\n // A frontend's proxy routes hang directly off its own row, so \"where does /api go\" reads as a\n // property of the app rather than a footnote somewhere below it.\n if (e.proxies) lines.push(...this.proxyLines(e.proxies))\n }\n // Failures sit with the live rows, not in the scrollback above: the log line announcing the crash\n // is metres up the terminal by now, and the header is the only thing the user actually reads.\n for (const f of summary.failed ?? []) {\n lines.push(this.failedLine(f, tagWidth))\n }\n for (const u of summary.uiRefs) {\n lines.push(this.uiRefLine(u, tagWidth, u.errors))\n if (u.proxies) lines.push(...this.proxyLines(u.proxies))\n }\n // Below the app rows, because it is a consequence of one of them \u2014 a `\u25CF failed` backend is WHY a\n // route went to cloud, and the two read as cause and effect only in that order.\n for (const d of summary.degraded ?? []) {\n lines.push(this.degradedLine(d, tagWidth))\n }\n\n lines.push('', ...this.legendLines(summary))\n\n return lines\n }\n\n /**\n * Static reference lines for the persistent Ink header, committed ONCE via `<Static>`: title,\n * endpoint URLs WITHOUT the health dot (health is live \u2192 the footer owns it), UI reference rows,\n * watch line, clickable log path, separator. Pure; colors follow `isTTY`.\n */\n formatHeaderLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: false })\n }\n\n /**\n * The live status rows \u2014 THE PANEL. Re-rendered in place on every tick; never committed to `<Static>`.\n *\n * This is the only part of the screen that can change after `ready`, and that makes it the only place\n * live fields can live. The header is committed once through `<Static>`, so anything painted there is\n * a photograph: an uptime or an error count rendered into the header would be frozen at its boot value\n * for the whole session, looking live and being a lie. (It was: the live fields went into the shared\n * endpoint line first, the header picked them up, the footer kept printing a bare health dot, and a\n * real run showed a panel with no uptime, no req/min and no error count at all. No unit test saw it \u2014\n * only the rendered terminal did.)\n *\n * Every row is rendered, including an endpoint that was never probed and a UI with no backend at all:\n * with no log tail on screen this panel is the entire signal, and a row that is absent cannot report\n * that its service is broken.\n */\n formatFooterLines(summary: ReadySummary): string[] {\n const tagWidth = this.tagWidth(summary)\n const rows = summary.endpoints.map((e) => {\n const dot = this.healthDot(e.health)\n const status = this.statusFields(e)\n const cells = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.tagCell(e.tag, tagWidth, e.errors)} ${cells}`\n })\n\n // A UI whose port infra-kit could not claim has no endpoint row \u2014 but its errors still have to land\n // somewhere the user can see, and it is precisely the app most likely to be misconfigured.\n for (const ref of summary.uiRefs) {\n if (ref.errors == null) continue\n rows.push(` ${this.tagCell(ref.tag, tagWidth, ref.errors)} ${this.errorCount(ref.errors)}`)\n }\n\n // Degraded routes live in the PANEL, not only in the header. The header is committed once through\n // `<Static>` \u2014 a photograph \u2014 so a degraded row painted only there would still be on screen after\n // `--watch` brought the backend back and the route went local again: a permanent warning about a\n // condition that has been fixed, which trains the user to ignore it. The caller re-derives this list\n // from the running set on every tick, so the row survives exactly as long as the problem does.\n for (const d of summary.degraded ?? []) {\n rows.push(this.degradedLine(d, tagWidth))\n }\n\n // The heartbeat. Without it a UI-only session \u2014 whose rows carry no backend uptime and no req/min \u2014\n // would render an identical frame every tick, and Ink does not repaint an identical frame. The panel\n // would be genuinely, verifiably alive and look exactly like a hung process.\n if (summary.sessionUptimeMs != null) {\n const beat = `up ${formatUptime(summary.sessionUptimeMs)}`\n\n rows.push(` ${this.color(ANSI.dim, beat)}`)\n }\n\n return rows\n }\n\n /**\n * Build the ready-header lines with NO side effects (no terminal write, no tee), so both\n * {@link ready} (which writes + tees them) and the Ink boot UI (which commits them via `<Static>`\n * and tee-only's them) share one layout. Colors follow `isTTY` exactly like every other line.\n */\n formatReadyLines(summary: ReadySummary): string[] {\n return this.formatL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AK,IAAI,EAErD,MAAO,KAAK,KAAK,QAAQT,EAAE,IAAKJ,EAAUI,EAAE,MAAM,CAAC,KAAK+B,CAAK,EAC/D,CAAC,EAID,QAAWjB,KAAOhB,EAAQ,OACpBgB,EAAI,QAAU,MAClBgB,EAAK,KAAK,KAAK,KAAK,QAAQhB,EAAI,IAAKlB,EAAUkB,EAAI,MAAM,CAAC,KAAK,KAAK,WAAWA,EAAI,MAAM,CAAC,EAAE,EAQ9F,QAAWX,KAAKL,EAAQ,UAAY,CAAC,EACnCgC,EAAK,KAAK,KAAK,aAAa3B,EAAGP,CAAQ,CAAC,EAM1C,GAAIE,EAAQ,iBAAmB,KAAM,CACnC,IAAMkC,EAAO,MAAM1D,EAAawB,EAAQ,eAAe,CAAC,GAExDgC,EAAK,KAAK,KAAK,KAAK,MAAMjE,EAAK,IAAKmE,CAAI,CAAC,EAAE,CAC7C,CAEA,OAAOF,CACT,CAOA,iBAAiBhC,EAAiC,CAChD,OAAO,KAAK,YAAYA,EAAS,CAAE,cAAe,EAAK,CAAC,CAC1D,CACF",
|
|
6
|
+
"names": ["process", "SPINNER_FRAMES", "SPINNER_INTERVAL_MS", "ANSI", "CLEAR_LINE", "ANSI_PATTERN", "stripAnsi", "s", "pad2", "n", "formatElapsed", "ms", "formatUptime", "total", "hours", "minutes", "seconds", "resolveEndpointUrl", "input", "DevRenderer", "deps", "text", "code", "href", "label", "c", "message", "level", "line", "options", "frame", "phase", "errors", "tag", "tagWidth", "health", "summary", "lines", "e", "u", "f", "d", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "ref", "errText", "endpoint", "parts", "withHealthDot", "dot", "suffix", "failed", "row", "state", "target", "proxies", "routeWidth", "p", "elbow", "where", "rows", "cells", "beat"]
|
|
7
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ie}from"./chunk-MFAFQVTW.js";import{a as ne}from"./chunk-
|
|
1
|
+
import{a as ie}from"./chunk-MFAFQVTW.js";import{a as ne}from"./chunk-3UE375II.js";import{e as N,q as re,s as oe}from"./chunk-I23MDR4X.js";import Fe from"node:process";import De from"node:process";var S={enabled:!1},We=(e,t=r=>{De.stdout.write(r)})=>(S.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
|
|
2
2
|
`),e),se=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(se)};var ae={source:null},w=()=>ae.source!==null,qe=()=>w()||S.enabled,_=()=>!!Fe.env.CI,Ge=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let o=e.INFRA_KIT_AGENT;return o==="1"||e.CLAUDECODE!==void 0&&!t&&o!=="0"?"env":null};var x=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:o,stderrExcerpt:n}=r;if(typeof o=="string"&&o.length>0)return o;if(typeof n=="string"&&n.length>0)return n;r=r.cause}},Be=(e,t)=>{let r=t.stderrExcerpt??x(e),o=[`failed to ${t.operation}`];return r&&o.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&o.push(`try: ${t.remediation}`),o.join(" \u2014 ")},u=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(Be(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??x(t)}};import k from"node:path";import le from"node:process";import{$ as m}from"zx";var ze=/^v?(\d+)\.(\d+)\.(\d+)$/,Ue=/^(\d+)\.(\d+)\.(\d+)$/,He=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,I="release/",T="release/v",ce="refs/heads/",Ve="next";var ue=new Set(["dev","main","next","hotfix","regular","release"]),g=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},h=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},pe=e=>e.startsWith(ce)?e.slice(ce.length):e,de=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),L=e=>{if(e.length===0)throw new g('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new g(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!He.test(e))throw new g(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(ue.has(e))throw new g(`Release name "${e}" is reserved. Reserved names: ${[...ue].join(", ")}.`)},K=e=>{let t=pe(e.trim());if(!t.startsWith(I))return null;if(t.startsWith(T)){let o=t.slice(T.length),n=Ue.exec(o);if(n)return de(Number(n[1]),Number(n[2]),Number(n[3]))}let r=t.slice(I.length);try{L(r)}catch{return null}return{kind:"name",name:r,raw:r}},Je=e=>{let t=e.trim();if(pe(t).startsWith(I)){let n=K(t);if(!n)throw new h(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=ze.exec(t);if(o)return de(Number(o[1]),Number(o[2]),Number(o[3]));if(t.toLowerCase()===Ve)throw new h('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');if(t.includes("@"))throw new h(`Cannot parse "${e}" as a release ref: the \`@date\` suffix belongs to \`release create\`; pass the version alone here and use \`--release-date\` on \`release edit\``);try{L(t)}catch(n){let s=n instanceof Error?n.message:String(n);throw new h(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:t,raw:t}},Xe=e=>e.kind==="version"?`${T}${e.raw}`:`${I}${e.name}`,Ye=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ze=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Qe=e=>e.kind==="version"?`v${e.raw}`:e.name,et=e=>e.raw,D=e=>e==null?!1:K(e)!==null,me=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},tt=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let o=me(r?.a),n=me(r?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<t.name?-1:e.name>t.name?1:0};var fe=async e=>{let t=await m({cwd:e})`git worktree list --porcelain`,r=[],o=null;for(let n of t.stdout.split(`
|
|
3
3
|
`)){if(n.startsWith("worktree ")){o&&r.push(o),o={path:n.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}o&&(n.startsWith("branch ")?o.branch=n.slice(7).replace(/^refs\/heads\//,""):n==="detached"?o.detached=!0:n==="bare"?o.bare=!0:n==="locked"||n.startsWith("locked ")?o.locked=!0:(n==="prunable"||n.startsWith("prunable "))&&(o.prunable=!0))}return o&&r.push(o),r},rt=async e=>{let t=await fe(le.cwd()),r=o=>e==="release"?D(o):o.startsWith("feature/");return t.map(o=>o.branch).filter(o=>o!==null&&r(o))},ot=e=>{let t=x(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},nt=({hasStderr:e})=>{if(w())return"infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},R=async()=>{try{return(await m({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=ot(e)??x(e);throw new u(e,{operation:`resolve the project root from ${le.cwd()}`,stderrExcerpt:t,remediation:nt({hasStderr:t!==void 0})})}},W=async e=>{let t=e??await R(),r=(await m({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),o=k.resolve(t,r);return o.includes(`${k.sep}.git${k.sep}modules${k.sep}`)?t:k.dirname(o)},ge=async()=>(await m`git rev-parse --abbrev-ref HEAD`).stdout.trim(),he=async()=>(await m`git status --porcelain`).stdout.split(`
|
|
4
4
|
`).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),it=async()=>(await he()).length===0,st=async()=>{let e=await R(),[t,r]=await Promise.all([m({cwd:e})`git rev-parse --absolute-git-dir`,m({cwd:e})`git rev-parse --git-common-dir`]),o=t.stdout.trim(),n=k.resolve(e,r.stdout.trim());return o!==n};var at=async e=>(await m`git branch --list ${e}`).stdout.trim().length>0,ct=async e=>{(await m`git branch --list ${e}`).stdout.trim().length!==0&&await ge()!==e&&await m`git branch -D ${e}`},ut=async e=>{(await m`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await m`git push origin --delete ${e}`};import{$ as P}from"zx";var mt=async(e,t)=>{let r=`${t}^{commit}`;try{return(await P({cwd:e,quiet:!0})`git rev-parse --verify --quiet ${r}`).stdout.trim()||null}catch{return null}},pt=async(e,t,r)=>{try{return await P({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(o){if(o.exitCode===1)return!1;throw new u(o,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},dt=async(e,t)=>{let o=(await P({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
|
|
@@ -9,5 +9,5 @@ A retired key on this branch \u2014 run \`infra-kit setup --skip-tools\` in this
|
|
|
9
9
|
`),hr=e=>[`"vendorSource" is not allowed in ${e.label} (${e.path}): only the committed project file may mark a repository as the \`vendor sync\` source. In the machine-wide file it would make every repository on this machine a source; in a per-project override it would make this machine disagree with every other clone.`,"Move the block to the source repository's own infra-kit.json and commit it there."].join(`
|
|
10
10
|
`),yr=e=>[`"audit" is not allowed in ${e.label} (${e.path}): the root audit gates CI, so a per-machine copy would make this machine pass or fail a different check list than CI.`,"Move the block to the project infra-kit.json and commit it there."].join(`
|
|
11
11
|
`),wr={mcp:gr,vendorSource:hr,audit:yr},kr=(e,t)=>{for(let[r,o]of Object.entries(wr))if(r in t)throw new Error(o(e))},Y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vr=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
|
|
12
|
-
`);var Ke=class extends u{structuredContent;exitCode;constructor(t,r,o){super(void 0,o),this.name="StructuredRefusalError",this.structuredContent=t,this.exitCode=r}};export{S as a,We as b,se as c,ae as d,w as e,qe as f,Ge as g,x as h,u as i,g as j,L as k,K as l,Je as m,Xe as n,Ye as o,Ze as p,Qe as q,et as r,D as s,tt as t,fe as u,rt as v,R as w,W as x,ge as y,he as z,it as A,st as B,at as C,ct as D,ut as E,mt as F,pt as G,dt as H,lt as I,we as J,ft as K,G as L,gt as M,ht as N,yt as O,B as P,z as Q,It as R,H as S,j as T,$ as U,_t as V,je as W,sr as
|
|
13
|
-
//# sourceMappingURL=chunk-
|
|
12
|
+
`);var Ke=class extends u{structuredContent;exitCode;constructor(t,r,o){super(void 0,o),this.name="StructuredRefusalError",this.structuredContent=t,this.exitCode=r}};export{S as a,We as b,se as c,ae as d,w as e,qe as f,Ge as g,x as h,u as i,g as j,L as k,K as l,Je as m,Xe as n,Ye as o,Ze as p,Qe as q,et as r,D as s,tt as t,fe as u,rt as v,R as w,W as x,ge as y,he as z,it as A,st as B,at as C,ct as D,ut as E,mt as F,pt as G,dt as H,lt as I,we as J,ft as K,G as L,gt as M,ht as N,yt as O,B as P,z as Q,It as R,H as S,j as T,$ as U,_t as V,je as W,ee as X,sr as Y,$e as Z,Z as _,ar as $,cr as aa,_e as ba,Te as ca,ur as da,mr as ea,pr as fa,Ke as ga};
|
|
13
|
+
//# sourceMappingURL=chunk-EZ4DIT5A.js.map
|