infra-kit 0.1.133 → 0.1.134

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.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/command-echo/confirm-or-exit.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 * @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 command ran off the CLI (an MCP tool), where a `pnpm exec` line would be\n * nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be 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 confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { logger } from 'src/lib/logger'\n\nimport { commandEcho } from './command-echo'\n\n/**\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise it prompts the user, marks the echo as interactive, and\n * exits cleanly if the user declines.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nexport const confirmOrExit = async (confirmedCommand: boolean | undefined, message: string): Promise<void> => {\n const answer = confirmedCommand ? true : await confirm({ message })\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n"],
5
+ "mappings": "wCAOA,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,EAOA,UAAUE,EAAcC,EAA0C,CAChEJ,EAAQ,KAAK,CAAE,KAAAG,EAAM,MAAAC,CAAM,CAAC,CAC9B,EAKA,eAAwB,CACtB,OAAOJ,EACJ,IAAKK,GACA,OAAOA,EAAI,OAAU,UAChBA,EAAI,MAAQA,EAAI,KAAO,GAG5B,MAAM,QAAQA,EAAI,KAAK,EAClB,GAAGA,EAAI,IAAI,KAAKA,EAAI,MAAM,KAAK,IAAI,CAAC,IAGtC,GAAGA,EAAI,IAAI,KAAKA,EAAI,KAAK,GACjC,EACA,OAAO,OAAO,EACd,KAAK,GAAG,CACb,EAOA,UAAgD,CAC9C,OAAIL,EAAQ,SAAW,EACd,KAGF,CAAE,iBAAkB,KAAK,cAAc,CAAE,CAClD,EASA,OAAc,CACR,CAACC,GAAiBD,EAAQ,SAAW,GAAK,CAACD,GAI/CO,EAAO,KAAK;AAAA,sBAAgDP,CAAO,IAAI,KAAK,cAAc,CAAC;AAAA,CAAI,CACjG,EAKA,OAAc,CACZA,EAAU,GACVC,EAAU,CAAC,EACXC,EAAgB,EAClB,CACF,CACF,EAGaM,EAAcT,EAAkB,EC1G7C,OAAOU,MAAa,oBACpB,OAAOC,MAAa,eAoBb,IAAMC,EAAgB,MAAOC,EAAuCC,IAAmC,CAC5G,IAAMC,EAASF,EAAmB,GAAO,MAAMG,EAAQ,CAAE,QAAAF,CAAQ,CAAC,EAE7DD,GACHI,EAAY,eAAe,EAGxBF,IACHG,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,EAElB",
6
+ "names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "confirm", "process", "confirmOrExit", "confirmedCommand", "message", "answer", "confirm", "commandEcho", "logger", "process"]
7
+ }
@@ -1,2 +1,2 @@
1
1
  import{a as v,b as x,c as y}from"./chunk-LTKR3F4N.js";import{Buffer as K}from"node:buffer";import{execFileSync as L}from"node:child_process";import g from"node:fs";import O from"node:net";import u from"node:path";import p from"node:process";import{pathToFileURL as _}from"node:url";import{z as l}from"zod";import{z as i}from"zod";var P=i.strictObject({requiredScripts:i.array(i.string().min(1)).optional(),requiredFiles:i.array(i.string().min(1)).optional(),turbo:i.strictObject({requiredTasks:i.array(i.string().min(1)).optional()}).optional(),dev:i.strictObject({proxy:i.strictObject({templates:i.strictObject({local:i.string().min(1),cloud:i.string().min(1)}),routes:i.record(i.string().min(1),i.strictObject({packageName:i.string().min(1),from:i.array(i.enum(["local","cloud"])).min(1),default:i.enum(["local","cloud"]).optional()}).refine(e=>e.from.length<=1||e.default!==void 0,{message:"default is required when `from` has more than one source"}).refine(e=>e.default===void 0||e.from.includes(e.default),{message:"default must be listed in `from`"}))}).optional()}).optional()});var R="INFRA_KIT_ENV",k="infra-kit.config.ts",N=u.join(".infra-kit","dev-context"),T=u.join(".infra-kit","dev-context.json"),D=l.object({package:l.string(),port:l.number(),pid:l.number().optional(),writtenAt:l.number().optional(),release:l.string().optional(),alias:l.string().optional(),proxyPort:l.number().optional(),origin:l.string().optional()}),j=(e,t)=>{let r=t?.username??e.E2E__BASIC_AUTH_USERNAME,n=t?.password??e.E2E__BASIC_AUTH_PASSWORD;return!r||!n?void 0:`Basic ${K.from(`${r}:${n}`).toString("base64")}`};var b=(e,t)=>e.replaceAll("<release>",t.release).replaceAll("<packageName>",t.packageName).replaceAll("<env>",t.env),C=80,F="127.0.0.1",S=(e,t)=>{if(t==null||t===C)return e;let r;try{r=new URL(e)}catch{throw new Error(`infra-kit/vite: dev.proxy templates.local resolved to "${e}", which is not a valid URL, so the proxy port ${t} cannot be applied.`)}if(r.port!=="")return e;r.port=String(t);let n=r.toString();return!e.endsWith("/")&&n.endsWith("/")?n.slice(0,-1):n},U=1024,V=(e,t)=>t!=null&&t>=U?S(e.replace(/^https:\/\//iu,"http://"),t):S(e,t),M=e=>{let{route:t,templates:r,env:n,getRelease:a,info:o}=e;if(o?.origin)return o.origin;let s=b(r.local,{release:o?.release??a(),packageName:v(t.packageName),env:n??""});return V(s,o?.proxyPort)},H=(e,t)=>{let r=e.default??e.from[0];return e.from.includes("local")&&t.has(e.packageName)?"local":r},$=new Set(["localhost","127.0.0.1","::1"]),B=e=>{let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}let r=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t;return r.endsWith(".localhost")||$.has(r)},W=({routePath:e,route:t,templates:r,localSet:n,env:a,getRelease:o,localInfo:s})=>{if(H(t,n)==="local"){let f=M({route:t,templates:r,env:a,getRelease:o,info:s?.get(t.packageName)});return B(f)?{target:f,changeOrigin:!0,secure:!1}:{target:f,changeOrigin:!0}}if(!a)throw new Error(`infra-kit/vite: proxy route "${e}" resolves to a cloud backend but ${R} is not set. Source an environment from Doppler first (e.g. \`infra-kit env-load -c dev\`).`);return{target:b(r.cloud,{release:"",packageName:t.packageName,env:a}),changeOrigin:!0,secure:!1,cookieDomainRewrite:"localhost"}},J=({proxy:e,localSet:t,env:r,getRelease:n,authHeader:a,localInfo:o})=>{let s={},c=a?{Authorization:a}:void 0;for(let[d,f]of Object.entries(e.routes)){let m=W({routePath:d,route:f,templates:e.templates,localSet:t,env:r,getRelease:n,localInfo:o});s[d]=c?{...m,headers:c}:m}return s},G=e=>{let t;return()=>(t??={value:e()},t.value)},q=async e=>{let t=u.join(e,k);if(!g.existsSync(t))return;let r=g.statSync(t),o=(await import(`${_(t).href}?mtime=${Number(r.mtimeMs)}`)).default;if(o===void 0)return;let s=typeof o=="function"?await o():o,c=P.safeParse(s);if(!c.success)throw new Error(`infra-kit/vite: invalid ${k} at ${t}: ${l.prettifyError(c.error)}`);return c.data.dev},z=e=>{if(Array.isArray(e))return e.filter(t=>typeof t=="string");if(e!==null&&typeof e=="object"){let t=e.packages??e.localPackages;if(Array.isArray(t))return t.filter(r=>typeof r=="string")}return[]},I=(e,t)=>{let r=u.resolve(e);for(;;){let n=u.join(r,t);if(g.existsSync(n))return n;let a=u.dirname(r);if(a===r)return;r=a}},h=()=>({packages:new Set,info:new Map}),X=e=>{if(e==null)return!0;try{return p.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Y=e=>{let t;try{t=g.readdirSync(e)}catch{return h()}let r=new Set,n=new Map;for(let a of t)if(a.endsWith(".json"))try{let o=D.safeParse(JSON.parse(g.readFileSync(u.join(e,a),"utf-8")));if(!o.success||!X(o.data.pid))continue;r.add(o.data.package),n.set(o.data.package,{port:o.data.port,origin:o.data.origin,release:o.data.release,alias:o.data.alias,proxyPort:o.data.proxyPort})}catch{continue}return{packages:r,info:n}},Q=e=>{let t=I(e,N);if(t)return Y(t);let r=I(e,T);if(!r)return h();try{return{packages:new Set(z(JSON.parse(g.readFileSync(r,"utf-8")))),info:new Map}}catch{return h()}};var Z=e=>L("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf-8"}).trim(),ee=()=>new Promise((e,t)=>{let r=O.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),a=typeof n=="object"&&n!==null?n.port:0;r.close(()=>e(a))})}),te="INFRA_KIT_UI_PORTS",re=e=>{try{let t=JSON.parse(g.readFileSync(u.join(e,"package.json"),"utf-8"));return typeof t.name=="string"?t.name:null}catch{return null}},ne=e=>{let t=p.env[te];if(t==null||t==="")return null;let r=re(e);if(r==null)return null;try{let n=JSON.parse(t)[r];if(typeof n=="number")return{port:n};if(n===null||typeof n!="object")return null;let{port:a,alias:o}=n;return typeof a!="number"?null:{port:a,alias:typeof o=="string"?o:void 0}}catch{return null}},oe=443,ae=async(e={})=>{let t=e.cwd??p.cwd();if(e.command==="build")return{proxy:{}};let r=e.port==null?ne(t):null,n=e.port??r?.port??await ee(),a=r!=null,o=e.host??F,s=r?.alias==null?void 0:{protocol:"wss",host:r.alias,clientPort:oe},c={port:n,host:o,...a?{strictPort:a}:{},...s?{hmr:s}:{}},d=await q(t);if(!d?.proxy)return{...c,proxy:{}};let{packages:f,info:m}=Q(t),w=p.env[R],A=j(p.env,e.basicAuth),E=G(()=>{try{return x(Z(t))||y}catch{return y}});return{...c,proxy:J({proxy:d.proxy,localSet:f,env:w,getRelease:E,authHeader:A,localInfo:m})}},ve=async(e={})=>(await ae(e)).proxy;export{P as a,J as b,q as c,ae as d,ve as e};
2
- //# sourceMappingURL=chunk-6EPRH34O.js.map
2
+ //# sourceMappingURL=chunk-TUVUKM4K.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/vite/vite.ts", "../src/lib/package-config/package-config-schema.ts"],
4
+ "sourcesContent": ["import { Buffer } from 'node:buffer'\nimport { execFileSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport net from 'node:net'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { pathToFileURL } from 'node:url'\nimport { z } from 'zod'\n\nimport type {\n InfraKitDev,\n InfraKitDevProxy,\n InfraKitDevProxyRoute,\n InfraKitDevProxySource,\n} from '../package-config/package-config'\nimport { packageConfigSchema } from '../package-config/package-config-schema'\nimport { DEFAULT_RELEASE_SLUG, slugifyHostLabel, slugifyRelease } from '../release-slug/release-slug'\n\n/**\n * Env-name handle read at vite-config time to fill the `<env>` placeholder in a\n * cloud proxy target. Inlined (not imported from `src/lib/constants`) to keep the\n * `infra-kit/vite` bundle's import graph tiny \u2014 see the module header. Kept\n * byte-identical to `INFRA_KIT_ENV_VAR` in `src/lib/constants/constants.ts`.\n */\nconst INFRA_KIT_ENV = 'INFRA_KIT_ENV'\n\n/** Per-package config filename, mirrored from the CLI's `PACKAGE_CONFIG_FILE`. */\nconst PACKAGE_CONFIG_FILE = 'infra-kit.config.ts'\n\n/**\n * Repo-relative dev-context fragment DIRECTORY, searched upward from cwd. Each\n * runner (single-process or cmux pane) writes its OWN `<app>.json` fragment here\n * recording its real bound port + release; the helper merges them (see\n * {@link readLocalContext}). This is the current source of truth.\n */\nconst DEV_CONTEXT_DIR = path.join('.infra-kit', 'dev-context')\n\n/**\n * Legacy single-file dev-context manifest, searched upward from cwd. Read only as\n * a transitional back-compat path when {@link DEV_CONTEXT_DIR} is absent (the\n * directory wins per-package when both exist).\n */\nconst DEV_CONTEXT_FILE = path.join('.infra-kit', 'dev-context.json')\n\n/**\n * One `.infra-kit/dev-context/<app>.json` fragment. `package` is the load-bearing\n * field the helper reads (\u2192 localSet); `origin` is **the authoritative local target** \u2014\n * the exact origin the runner registered, obeyed verbatim by {@link resolveLocalTarget}.\n * The runner is the only party that knows the scheme and port its alias is really served\n * on, so the helper never re-derives them when `origin` is present.\n *\n * `release`, `alias` and `proxyPort` are the LEGACY inputs, read only when `origin` is\n * absent \u2014 which can only happen when an OLD CLI wrote the fragment (a CLI-only rollback).\n * `port` is no longer a proxy target (the direct `127.0.0.1:<port>` branch is gone) \u2014 it\n * survives as diagnostic provenance. `pid` is the staleness guard: {@link readFragmentDir}\n * drops a fragment whose writer is no longer alive, so a crashed runner cannot keep a\n * package pinned `local` at a dead alias. `writtenAt` is provenance only.\n *\n * Kept lenient (not `.strict()`) so extra writer fields never reject a valid fragment, and\n * deliberately un-`refine`d: a rejected fragment would drop a started package to `cloud`\n * instead of falling into legacy mode, which is what makes the rollback path work.\n */\nconst devContextFragmentSchema = z.object({\n package: z.string(),\n port: z.number(),\n pid: z.number().optional(),\n writtenAt: z.number().optional(),\n release: z.string().optional(),\n alias: z.string().optional(),\n proxyPort: z.number().optional(),\n origin: z.string().optional(),\n})\n\n/**\n * A single Vite `server.proxy` entry. `changeOrigin` is always set. `cookieDomainRewrite` is cloud-only\n * (it keeps an HTTPS cloud BE's cookies usable from a local FE). `secure: false` appears on BOTH sources\n * but for different reasons: a cloud target may serve a cert the local store rejects, and a local target\n * is served by portless from its own private CA \u2014 set there only for a loopback host (see\n * {@link isLoopbackTarget}). `headers` is present only when HTTP Basic Auth is injected (see\n * {@link buildBasicAuthHeader}) \u2014 it carries the `Authorization` header applied\n * uniformly to every route so upstream environments behind auth (e2e/staging)\n * stay reachable.\n */\nexport interface InfraKitViteProxyEntry {\n target: string\n changeOrigin: true\n secure?: false\n cookieDomainRewrite?: 'localhost'\n headers?: Record<string, string>\n}\n\n/** A Vite `server.proxy`-shaped map: path-prefix \u2192 proxy entry. */\nexport type InfraKitViteProxy = Record<string, InfraKitViteProxyEntry>\n\n/** Explicit HTTP Basic Auth credentials, overriding the `E2E__BASIC_AUTH_*` env vars. */\nexport interface InfraKitBasicAuth {\n username: string\n password: string\n}\n\nexport interface InfraKitDevOptions {\n /** Package dir whose `infra-kit.config.ts` is loaded. Defaults to `process.cwd()`. */\n cwd?: string\n /**\n * Explicit HTTP Basic Auth credentials injected into every proxy route as an\n * `Authorization` header. Takes precedence over the `E2E__BASIC_AUTH_USERNAME`\n * / `E2E__BASIC_AUTH_PASSWORD` env vars. Omit to use the env-based default.\n */\n basicAuth?: InfraKitBasicAuth\n /**\n * Vite's `command`. Pass it (`defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))`)\n * so `build` is a no-op: `server` is irrelevant to a build and proxy resolution would otherwise\n * fail-fast on a cloud route with no sourced env. Omit (or `'serve'`) for the dev-server config.\n */\n command?: 'build' | 'serve'\n /**\n * Explicit dev-server port. Omit for a **per-worktree dynamic** free port (a fresh OS-assigned\n * port) so N simultaneous git worktrees never collide on Vite's default `5173`; Vite prints the\n * chosen URL. Pass a fixed number only when an external contract pins the port.\n */\n port?: number\n /**\n * Interface the dev server binds. Defaults to {@link LOOPBACK_V4} so a portless alias can reach it\n * (Vite's own `localhost` default binds `[::1]` only, which the proxy cannot dial). Override when\n * the dev server must be reachable off the loopback \u2014 `'0.0.0.0'` or `true` inside a container, on\n * a LAN, or for an e2e runner on another host.\n */\n host?: string | boolean\n}\n\n/**\n * Build the `Authorization: Basic <base64(user:pass)>` header value. Credentials\n * come from `override` when given, else from `E2E__BASIC_AUTH_USERNAME` /\n * `E2E__BASIC_AUTH_PASSWORD` (NOTE: double underscore). Returns `undefined` when\n * either half is missing, so callers add no `headers` key at all.\n */\nconst buildBasicAuthHeader = (env: NodeJS.ProcessEnv, override?: InfraKitBasicAuth): string | undefined => {\n const username = override?.username ?? env.E2E__BASIC_AUTH_USERNAME\n const password = override?.password ?? env.E2E__BASIC_AUTH_PASSWORD\n\n if (!username || !password) return undefined\n\n const encoded = Buffer.from(`${username}:${password}`).toString('base64')\n\n return `Basic ${encoded}`\n}\n\n/**\n * Re-exported from the shared, dependency-light `lib/release-slug` module so the\n * published `infra-kit/vite` surface (`entry/vite.ts:7`) is unchanged while the\n * dev-server's fragment writer derives `<release>` from the SAME implementation\n * (no slug drift). See {@link slugifyRelease}.\n */\nexport { slugifyRelease }\n\n/** Fill the `<release>`/`<packageName>`/`<env>` placeholders in a URL template. */\nconst interpolate = (template: string, values: { release: string; packageName: string; env: string }): string => {\n return template\n .replaceAll('<release>', values.release)\n .replaceAll('<packageName>', values.packageName)\n .replaceAll('<env>', values.env)\n}\n\n/** The port a bare `http://` target implies, and the proxy's default \u2014 never spelled out in a URL. */\nconst DEFAULT_HTTP_PORT = 80\n\n/**\n * The interface the vite dev server binds. Pinned to IPv4 loopback because portless dials its routes\n * on `127.0.0.1`, while vite's default `host: 'localhost'` combined with its\n * `dns.setDefaultResultOrder('verbatim')` binds `[::1]` ONLY \u2014 the alias then resolves, the proxy\n * connects, and the connection is refused, surfacing as a 502 on every UI request. Backends never hit\n * this because `ServerlessLocalRun` already binds `127.0.0.1`. Still loopback-only: this narrows the\n * address family, it does not expose the dev server to the network.\n */\nconst LOOPBACK_V4 = '127.0.0.1'\n\n/**\n * Graft the proxy's listen port onto an interpolated local target. The `dev.proxy` local template is\n * written port-free (`https://<release>.<packageName>.localhost`) because the proxy serves TLS on `:443`,\n * the only port a port-free HTTPS URL can come from. A consumer who trades the clean URL for a zero-sudo\n * unprivileged port still needs the frontend to reach it, so the runner records the port it actually bound\n * and we append it here. A template that already pins its own port keeps it.\n */\nconst withProxyPort = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort == null || proxyPort === DEFAULT_HTTP_PORT) return target\n\n let url: URL\n\n try {\n url = new URL(target)\n } catch {\n throw new Error(\n `infra-kit/vite: dev.proxy templates.local resolved to \"${target}\", which is not a valid URL, so the proxy port ${proxyPort} cannot be applied.`,\n )\n }\n\n if (url.port !== '') return target\n url.port = String(proxyPort)\n\n // `URL.toString()` synthesizes a `/` pathname for an authority-only URL, so the common port-free\n // template would come back as `\u2026localhost:1355/`. Strip that ONLY when the template had no trailing\n // slash of its own \u2014 a template ending in `/` (e.g. `\u2026localhost/base/`) means it, and silently\n // trimming it would change the path the frontend proxies to.\n const grafted = url.toString()\n\n return !target.endsWith('/') && grafted.endsWith('/') ? grafted.slice(0, -1) : grafted\n}\n\n/**\n * The lowest port a daemon can bind without root. An origin-less fragment recording a port AT OR ABOVE\n * this was written by an old CLI whose `spawnDaemon` always passed `--no-tls`, so infra-kit itself could\n * only ever have put PLAIN HTTP there. Below it (80/443) the daemon was installed out-of-band, where\n * portless defaults to TLS ON \u2014 which is precisely why the legacy scheme is left alone down there.\n */\nconst LEGACY_SELF_SPAWNED_PORT_FLOOR = 1024\n\n/**\n * Legacy target resolution \u2014 reached ONLY for an origin-less fragment, i.e. one written by an OLD CLI\n * (a CLI-only rollback). It must reproduce the old helper rather than reject anything, because that is\n * what lets the CLI be reverted without touching a single consumer repo.\n *\n * `proxyPort >= 1024`: force the scheme to `http`. **Mitigation, not a proof** \u2014 infra-kit's own\n * `spawnDaemon` always passed `--no-tls`, so an unprivileged daemon *infra-kit created* was always plain\n * HTTP; a HAND-STARTED TLS daemon on such a port (portless's own default is TLS) would be wrongly\n * downgraded here. That corner is accepted: forcing `http` reproduces what the old CLI + old helper\n * already emitted, so it regresses nothing that worked.\n *\n * `proxyPort < 1024` (80/443) or absent: the daemon was installed out-of-band and may well be TLS, and we\n * cannot know. Reproduce the old helper verbatim and NEVER rewrite the scheme \u2014 forcing `http` on a `:443`\n * fragment would emit `http://<alias>:443`, plain HTTP into a TLS listener, the exact silent failure this\n * design exists to remove.\n */\nconst resolveLegacyTarget = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort != null && proxyPort >= LEGACY_SELF_SPAWNED_PORT_FLOOR) {\n return withProxyPort(target.replace(/^https:\\/\\//iu, 'http://'), proxyPort)\n }\n\n return withProxyPort(target, proxyPort)\n}\n\n/**\n * The proxy target for a route resolved to `local`. The runner PUBLISHES the contract and the helper OBEYS\n * it: when the fragment carries an `origin`, that string is the target verbatim \u2014 the runner is the only\n * party that knows the scheme and port the alias it registered is actually served on, and this helper ships\n * on its own release cadence, so any re-derivation here is a guess that can silently disagree.\n *\n * `templates.local` is consulted ONLY in legacy mode (see {@link resolveLegacyTarget}).\n *\n * The target proxies to a stable HOSTNAME, and the runner re-points that alias at the freshly-bound port\n * on every `--watch` restart, so it self-heals without Vite reloading its config.\n */\nconst resolveLocalTarget = (args: {\n route: InfraKitDevProxyRoute\n templates: InfraKitDevProxy['templates']\n env: string | undefined\n getRelease: () => string\n info: LocalPackageInfo | undefined\n}): string => {\n const { route, templates, env, getRelease, info } = args\n\n if (info?.origin) return info.origin\n\n const target = interpolate(templates.local, {\n // Prefer THIS package's runner-recorded release slug (R4) over the single global git derivation,\n // so cross-branch FE/BE pairings don't drift the emitted `<release>` from the segment the runner\n // aliased. Fall back to the global git slug only when the fragment carried no release.\n release: info?.release ?? getRelease(),\n // The local template resolves to a `<release>.<packageName>.localhost` alias the dev-server\n // registered with portless \u2014 which slugifies the package name to a legal DNS label. Slugify\n // identically here or a scoped name (`@hulyo/client-ui`) emits a target that no alias backs.\n packageName: slugifyHostLabel(route.packageName),\n env: env ?? '',\n })\n\n return resolveLegacyTarget(target, info?.proxyPort)\n}\n\n/**\n * Pick the effective source for a route: `local` when the route lists `local` as\n * a capability AND its packageName is in the local dev set; otherwise the fallback\n * \u2014 the declared `default` for a multi-source route, or the sole `from` entry for\n * a single-source one. Always resolves (the schema guarantees a usable fallback).\n */\nconst pickSource = (route: InfraKitDevProxyRoute, localSet: ReadonlySet<string>): InfraKitDevProxySource => {\n // `from` is guaranteed non-empty by the schema, so `from[0]` is always present.\n const fallback = route.default ?? route.from[0]!\n\n return route.from.includes('local') && localSet.has(route.packageName) ? 'local' : fallback\n}\n\ninterface ResolveRouteArgs {\n routePath: string\n route: InfraKitDevProxyRoute\n templates: InfraKitDevProxy['templates']\n localSet: ReadonlySet<string>\n env: string | undefined\n getRelease: () => string\n /** Per-package runtime data (recorded release/port) from the dev-context merge. */\n localInfo?: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/** Hostnames that can only be this machine \u2014 the only ones a private-CA cert is allowed to go unchecked on. */\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1'])\n\n/**\n * Is `target` unambiguously on this machine? Only then may {@link resolveRoute} disable cert validation:\n * `templates.local` is an unconstrained string in a consumer-authored config, so an unconditional\n * `secure: false` in a PUBLISHED helper would silently switch off validation for whatever URL a consumer\n * wrote there. Scoping it to `.localhost`/loopback is what makes \"no MITM surface\" true by construction.\n * An unparseable target is NOT local (the caller then leaves `secure` unset \u2014 fail closed).\n */\nconst isLoopbackTarget = (target: string): boolean => {\n let hostname: string\n\n try {\n hostname = new URL(target).hostname.toLowerCase()\n } catch {\n return false\n }\n\n // `URL.hostname` brackets an IPv6 literal (`[::1]`); compare the bare address.\n const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname\n\n return bare.endsWith('.localhost') || LOOPBACK_HOSTNAMES.has(bare)\n}\n\n/** Resolve one route into a Vite proxy entry (or throw an actionable error). */\nconst resolveRoute = ({\n routePath,\n route,\n templates,\n localSet,\n env,\n getRelease,\n localInfo,\n}: ResolveRouteArgs): InfraKitViteProxyEntry => {\n const source = pickSource(route, localSet)\n\n if (source === 'local') {\n const target = resolveLocalTarget({ route, templates, env, getRelease, info: localInfo?.get(route.packageName) })\n\n // The local target is now HTTPS, served with a cert minted by portless's own private CA. Node's\n // http-proxy validates the upstream chain against the system store, which does not contain that CA,\n // so every proxied request fails with SELF_SIGNED_CERT_IN_CHAIN (confirmed empirically \u2014 see\n // `.omc/research/portless-https-spike.md`). Only a loopback target earns the exemption.\n return isLoopbackTarget(target) ? { target, changeOrigin: true, secure: false } : { target, changeOrigin: true }\n }\n\n if (!env) {\n throw new Error(\n `infra-kit/vite: proxy route \"${routePath}\" resolves to a cloud backend but ${INFRA_KIT_ENV} is not set. Source an environment from Doppler first (e.g. \\`infra-kit env-load -c dev\\`).`,\n )\n }\n\n const target = interpolate(templates.cloud, { release: '', packageName: route.packageName, env })\n\n return { target, changeOrigin: true, secure: false, cookieDomainRewrite: 'localhost' }\n}\n\ninterface ResolveProxyArgs {\n proxy: InfraKitDevProxy\n localSet: ReadonlySet<string>\n env: string | undefined\n getRelease: () => string\n /** Pre-computed `Authorization` header value applied uniformly to every route. */\n authHeader?: string\n /** Per-package runtime data (recorded release/port) from the dev-context merge. */\n localInfo?: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/**\n * Pure resolver: turn a `dev.proxy` config + resolved inputs (local set, env,\n * lazy release) into a Vite `server.proxy` map. Side-effect-free so the\n * resolution shape is fully unit-testable. When `authHeader` is set, every route\n * entry gets a matching `headers.Authorization`; otherwise no `headers` key.\n */\nexport const resolveProxyConfig = ({\n proxy,\n localSet,\n env,\n getRelease,\n authHeader,\n localInfo,\n}: ResolveProxyArgs): InfraKitViteProxy => {\n const result: InfraKitViteProxy = {}\n const headers = authHeader ? { Authorization: authHeader } : undefined\n\n for (const [routePath, route] of Object.entries(proxy.routes)) {\n const entry = resolveRoute({ routePath, route, templates: proxy.templates, localSet, env, getRelease, localInfo })\n\n result[routePath] = headers ? { ...entry, headers } : entry\n }\n\n return result\n}\n\n/** Memoize a zero-arg thunk so `<release>` git resolution runs at most once. */\nconst once = <T>(fn: () => T): (() => T) => {\n let cached: { value: T } | undefined\n\n return () => {\n cached ??= { value: fn() }\n\n return cached.value\n }\n}\n\n/**\n * Load a package's `infra-kit.config.ts` and return its `dev` block, or\n * `undefined` when the config or the `dev` key is absent. The `.ts` config is\n * evaluated via Node's native type stripping (Node >= 24) \u2014 the same mechanism\n * the CLI's config loader uses. Cache-busted by mtime so repeated dev-server\n * reloads pick up edits.\n */\nexport const loadDev = async (cwd: string): Promise<InfraKitDev | undefined> => {\n const configPath = path.join(cwd, PACKAGE_CONFIG_FILE)\n\n if (!fs.existsSync(configPath)) return undefined\n\n const stat = fs.statSync(configPath)\n const moduleUrl = `${pathToFileURL(configPath).href}?mtime=${Number(stat.mtimeMs)}`\n\n const imported = (await import(moduleUrl)) as { default?: unknown }\n const rawExport = imported.default\n\n if (rawExport === undefined) return undefined\n\n const resolved = typeof rawExport === 'function' ? await (rawExport as () => unknown)() : rawExport\n\n const parsed = packageConfigSchema.safeParse(resolved)\n\n if (!parsed.success) {\n throw new Error(`infra-kit/vite: invalid ${PACKAGE_CONFIG_FILE} at ${configPath}: ${z.prettifyError(parsed.error)}`)\n }\n\n return parsed.data.dev\n}\n\n/** Coerce a parsed dev-context.json into the set of locally-running package names. */\nconst extractPackages = (parsed: unknown): string[] => {\n if (Array.isArray(parsed)) {\n return parsed.filter((v): v is string => {\n return typeof v === 'string'\n })\n }\n\n if (parsed !== null && typeof parsed === 'object') {\n const candidate = (parsed as Record<string, unknown>).packages ?? (parsed as Record<string, unknown>).localPackages\n\n if (Array.isArray(candidate)) {\n return candidate.filter((v): v is string => {\n return typeof v === 'string'\n })\n }\n }\n\n return []\n}\n\n/** Search upward from `start` for `relative`, returning the first hit or undefined. */\nconst findUp = (start: string, relative: string): string | undefined => {\n let dir = path.resolve(start)\n\n for (;;) {\n const candidate = path.join(dir, relative)\n\n if (fs.existsSync(candidate)) return candidate\n\n const parent = path.dirname(dir)\n\n if (parent === dir) return undefined\n\n dir = parent\n }\n}\n\n/** Per-package runtime data merged from the dev-context fragment directory. */\nexport interface LocalPackageInfo {\n /** The real bound port the runner recorded. Provenance only \u2014 the proxy target is the alias host. */\n port: number\n /**\n * The authoritative local target (`https://<release>.<packageName>.localhost`), published by the\n * runner. Present \u2192 {@link resolveLocalTarget} uses it verbatim and consults no template. Absent \u2192\n * the fragment came from an old CLI and the legacy template path runs.\n */\n origin?: string\n /** LEGACY (no `origin`): the runner-recorded release slug, preferred over the helper's git derivation. */\n release?: string\n /** LEGACY (no `origin`): `<release>.<packageName>.localhost`, present only when an alias was registered. */\n alias?: string\n /** LEGACY (no `origin`): the port {@link alias} resolves on. `80` (the default) is implicit in the template. */\n proxyPort?: number\n}\n\n/**\n * The locally-running package set plus a `package \u2192 { port, release }` map merged\n * from the dev-context fragments. `packages` feeds `pickSource`; `info` lets a\n * `local` route emit the per-package recorded release (see {@link resolveRoute}).\n */\nexport interface LocalContext {\n packages: ReadonlySet<string>\n info: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/** An empty {@link LocalContext} (frontend-only / dev-context absent). */\nconst emptyLocalContext = (): LocalContext => {\n return { packages: new Set(), info: new Map() }\n}\n\n/**\n * Is the runner that wrote a fragment still alive? Signal `0` performs the permission and existence\n * checks without delivering anything. `ESRCH` is the one answer that means \"gone\"; `EPERM` means the\n * pid exists under another uid, which is still a live process. A fragment with no `pid` predates the\n * field and is trusted (back-compat) rather than dropped.\n */\nconst isFragmentWriterAlive = (pid: number | undefined): boolean => {\n if (pid == null) return true\n\n try {\n process.kill(pid, 0)\n\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/**\n * Merge every `<app>.json` fragment in the dev-context directory into a\n * {@link LocalContext}. Two DISTINCT failure branches (do NOT collapse them into\n * one directory-wide catch):\n * - `readdir`-ENOENT (directory vanished mid-race) \u2192 empty context, matching the\n * dir-absent back-compat behaviour.\n * - a single corrupt/truncated/invalid `<app>.json` \u2192 that ONE fragment is\n * SKIPPED (per-fragment `safeParse` isolation); the rest still merge, so one bad\n * fragment never collapses the whole localSet to empty (which would silently\n * drop a started package to cloud).\n */\nconst readFragmentDir = (dir: string): LocalContext => {\n let entries: string[]\n\n try {\n entries = fs.readdirSync(dir)\n } catch {\n return emptyLocalContext()\n }\n\n const packages = new Set<string>()\n const info = new Map<string, LocalPackageInfo>()\n\n for (const name of entries) {\n if (!name.endsWith('.json')) continue\n\n try {\n const parsed = devContextFragmentSchema.safeParse(JSON.parse(fs.readFileSync(path.join(dir, name), 'utf-8')))\n\n if (!parsed.success) continue\n\n // A runner killed with SIGKILL (or crashed) leaves its fragment AND its portless alias behind.\n // Trusting it would route this package's `/api` at an alias nothing serves \u2014 a silent 502 with\n // no diagnostic. The writer already stamps its pid; honour it.\n if (!isFragmentWriterAlive(parsed.data.pid)) continue\n\n packages.add(parsed.data.package)\n info.set(parsed.data.package, {\n port: parsed.data.port,\n origin: parsed.data.origin,\n release: parsed.data.release,\n alias: parsed.data.alias,\n proxyPort: parsed.data.proxyPort,\n })\n } catch {\n // Corrupt/truncated fragment (JSON.parse / read failure): skip ONLY this one.\n continue\n }\n }\n\n return { packages, info }\n}\n\n/**\n * Read the locally-running package context, searched upward from `cwd`. Prefers\n * the `.infra-kit/dev-context/` fragment DIRECTORY (merged via\n * {@link readFragmentDir}); when it is absent, falls back to the legacy single\n * `.infra-kit/dev-context.json` file (read as before \u2014 no per-package release);\n * when neither exists \u2192 empty context (frontend-only, every route resolves cloud).\n */\nexport const readLocalContext = (cwd: string): LocalContext => {\n const dir = findUp(cwd, DEV_CONTEXT_DIR)\n\n if (dir) return readFragmentDir(dir)\n\n const legacy = findUp(cwd, DEV_CONTEXT_FILE)\n\n if (!legacy) return emptyLocalContext()\n\n try {\n return { packages: new Set(extractPackages(JSON.parse(fs.readFileSync(legacy, 'utf-8')))), info: new Map() }\n } catch {\n return emptyLocalContext()\n }\n}\n\n/**\n * Read the set of locally-running packages (searched upward from `cwd`). Thin\n * wrapper over {@link readLocalContext} preserving the historical `Set`-returning\n * contract. Absent dev-context \u2192 empty set (frontend-only cloud resolution).\n */\nexport const readLocalSet = (cwd: string): ReadonlySet<string> => {\n return readLocalContext(cwd).packages\n}\n\n/** Current git branch of `cwd` (raw, un-slugified). */\nconst readGitBranch = (cwd: string): string => {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, encoding: 'utf-8' }).trim()\n}\n\n/**\n * An OS-assigned free TCP port on 127.0.0.1 \u2014 the per-worktree dev-server port (mirrors the\n * backend's `listen(0)`). This probes then releases the port, so there is a small TOCTOU window\n * before Vite binds it; Vite's default `strictPort: false` absorbs a lost race by stepping to the\n * next free port. Only a consumer that sets `strictPort: true` would hard-fail on the rare collision.\n */\nconst getFreePort = (): Promise<number> => {\n return new Promise((resolve, reject) => {\n const srv = net.createServer()\n\n srv.unref()\n srv.on('error', reject)\n srv.listen(0, '127.0.0.1', () => {\n const address = srv.address()\n const port = typeof address === 'object' && address !== null ? address.port : 0\n\n srv.close(() => {\n return resolve(port)\n })\n })\n })\n}\n\n/** Env var carrying the runner-assigned `{ \"<ui-package>\": <port> }` map (Layer B). */\nconst UI_PORTS_ENV = 'INFRA_KIT_UI_PORTS'\n\n/** This package's `package.json` `name`, or `null` (unreadable / nameless). */\nconst readPackageName = (cwd: string): string | null => {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8')) as { name?: unknown }\n\n return typeof parsed.name === 'string' ? parsed.name : null\n } catch {\n return null\n }\n}\n\n/**\n * What the runner assigned THIS UI. `alias` is present only in the widened record form, i.e. only when the\n * runner both assigned the port AND registered the hostname \u2014 which is exactly the condition for pointing\n * HMR at that hostname. The legacy bare-number form yields no alias.\n */\ninterface ManagedUi {\n port: number\n alias?: string\n}\n\n/**\n * What `infra-kit dev` assigned THIS UI via `INFRA_KIT_UI_PORTS` (Layer B), or `null` when the map is\n * absent / this package isn't in it / it's malformed. Present \u2192 the helper binds the port with\n * `strictPort` so vite lands on exactly the port the runner already aliased. Absent (a standalone\n * `vite dev`) \u2192 the caller falls back to a free port, byte-identical to today.\n *\n * Accepts BOTH the widened `{ port, alias }` record and the legacy bare `<port>` number an older runner\n * writes \u2014 a new helper paired with an old CLI must still bind the assigned port.\n */\nconst resolveManagedUi = (cwd: string): ManagedUi | null => {\n const raw = process.env[UI_PORTS_ENV]\n\n if (raw == null || raw === '') return null\n\n const name = readPackageName(cwd)\n\n if (name == null) return null\n\n try {\n const entry = (JSON.parse(raw) as Record<string, unknown>)[name]\n\n if (typeof entry === 'number') return { port: entry }\n\n if (entry === null || typeof entry !== 'object') return null\n\n const { port, alias } = entry as { port?: unknown; alias?: unknown }\n\n if (typeof port !== 'number') return null\n\n return { port, alias: typeof alias === 'string' ? alias : undefined }\n } catch {\n return null\n }\n}\n\n/** The port an `https://` alias is served on \u2014 never spelled out in a URL, and what the HMR client dials. */\nconst HTTPS_PORT = 443\n\n/**\n * Vite's `server.hmr` override, pointing the HMR client at the alias instead of at the raw dev-server port.\n * The page is loaded over `https://<alias>`, so its websocket must be `wss://` on the same origin or the\n * browser blocks it as mixed content; `clientPort` is the proxy's implicit `:443`, not vite's bound port.\n */\nexport interface InfraKitViteHmr {\n protocol: 'wss'\n host: string\n clientPort: number\n}\n\n/**\n * Resolve a package's `dev` block into a ready-made Vite `server` config: a per-worktree dev-server\n * `port` plus the `proxy` map. Loads the package's `infra-kit.config.ts`, merges the local dev set\n * from the `.infra-kit/dev-context/` fragment directory, and interpolates the local/cloud templates.\n * `<env>` comes from `INFRA_KIT_ENV`; `<release>` from each package's runner-recorded fragment when\n * present, else the slugified git branch (computed lazily, only when a local route needs it).\n *\n * `port` defaults to a fresh OS-assigned free port so simultaneous git worktrees never collide on\n * Vite's `5173` (override via `options.port`). `host` defaults to {@link LOOPBACK_V4} so the portless\n * alias can actually reach it (override via `options.host` for containers/LAN). `hmr` is emitted only\n * when `infra-kit dev` registered an alias for this UI, so a bare `vite dev` keeps vite's own HMR\n * defaults. Pass `command` so `build` is a no-op (empty proxy, no port) \u2014 a build ignores `server` and\n * proxy resolution would otherwise fail-fast on a cloud route with no sourced env.\n *\n * @example\n * // vite.config.ts \u2014 the whole `server` field is the helper's output\n * import { infraKitDev } from 'infra-kit/vite'\n * export default defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))\n */\nexport const infraKitDev = async (\n options: InfraKitDevOptions = {},\n): Promise<{\n port?: number\n host?: string | boolean\n strictPort?: boolean\n hmr?: InfraKitViteHmr\n proxy: InfraKitViteProxy\n}> => {\n const cwd = options.cwd ?? process.cwd()\n\n // A build ignores `server`; skip the port + proxy work (proxy resolution would fail-fast on a\n // cloud route with no sourced env).\n if (options.command === 'build') return { proxy: {} }\n\n // Port precedence: explicit `options.port` > the runner-assigned Layer-B port (bound `strictPort` so\n // vite lands on exactly the aliased port) > a fresh free port (today's default; the portless-off path).\n const managed = options.port == null ? resolveManagedUi(cwd) : null\n const port = options.port ?? managed?.port ?? (await getFreePort())\n const strictPort = managed != null\n const host = options.host ?? LOOPBACK_V4\n\n // Override HMR ONLY when the runner handed us the alias it registered. A bare `vite dev` (no runner)\n // has no alias, and a computable hostname is not a registered one \u2014 pointing the HMR client at a\n // hostname nothing resolves would break hot reload on a path that works today.\n const hmr: InfraKitViteHmr | undefined =\n managed?.alias == null ? undefined : { protocol: 'wss', host: managed.alias, clientPort: HTTPS_PORT }\n const server = { port, host, ...(strictPort ? { strictPort } : {}), ...(hmr ? { hmr } : {}) }\n const dev = await loadDev(cwd)\n\n if (!dev?.proxy) return { ...server, proxy: {} }\n\n const { packages: localSet, info: localInfo } = readLocalContext(cwd)\n const env = process.env[INFRA_KIT_ENV]\n const authHeader = buildBasicAuthHeader(process.env, options.basicAuth)\n const getRelease = once(() => {\n // Mirrors the dev-server's `readAppRelease`: outside a git repo both sides must land on the SAME\n // label, or this target names a host the runner never aliased.\n try {\n return slugifyRelease(readGitBranch(cwd)) || DEFAULT_RELEASE_SLUG\n } catch {\n return DEFAULT_RELEASE_SLUG\n }\n })\n\n return {\n ...server,\n proxy: resolveProxyConfig({ proxy: dev.proxy, localSet, env, getRelease, authHeader, localInfo }),\n }\n}\n\n/**\n * Convenience wrapper returning just the proxy map (for spreading into\n * `server.proxy` directly). Equivalent to `(await infraKitDev(options)).proxy`.\n */\nexport const infraKitProxy = async (options: InfraKitDevOptions = {}): Promise<InfraKitViteProxy> => {\n return (await infraKitDev(options)).proxy\n}\n", "import { z } from 'zod'\n\n/**\n * Schema for the resolved (post-factory) package config object. `strictObject`\n * rejects unknown keys so typos in `infra-kit.config.ts` surface as validation\n * errors instead of being silently ignored.\n *\n * Kept in its own module \u2014 separate from the public `defineConfig`/types entry \u2014\n * so the published `infra-kit` type surface stays free of a `zod` import.\n */\nexport const packageConfigSchema = z.strictObject({\n requiredScripts: z.array(z.string().min(1)).optional(),\n requiredFiles: z.array(z.string().min(1)).optional(),\n turbo: z\n .strictObject({\n requiredTasks: z.array(z.string().min(1)).optional(),\n })\n .optional(),\n dev: z\n .strictObject({\n proxy: z\n .strictObject({\n templates: z.strictObject({\n local: z.string().min(1),\n cloud: z.string().min(1),\n }),\n routes: z.record(\n z.string().min(1),\n z\n .strictObject({\n packageName: z.string().min(1),\n from: z.array(z.enum(['local', 'cloud'])).min(1),\n default: z.enum(['local', 'cloud']).optional(),\n })\n .refine(\n (route) => {\n return route.from.length <= 1 || route.default !== undefined\n },\n {\n message: 'default is required when `from` has more than one source',\n },\n )\n .refine(\n (route) => {\n return route.default === undefined || route.from.includes(route.default)\n },\n {\n message: 'default must be listed in `from`',\n },\n ),\n ),\n })\n .optional(),\n })\n .optional(),\n})\n"],
5
+ "mappings": "sDAAA,OAAS,UAAAA,MAAc,cACvB,OAAS,gBAAAC,MAAoB,qBAC7B,OAAOC,MAAQ,UACf,OAAOC,MAAS,WAChB,OAAOC,MAAU,YACjB,OAAOC,MAAa,eACpB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,KAAAC,MAAS,MCPlB,OAAS,KAAAC,MAAS,MAUX,IAAMC,EAAsBD,EAAE,aAAa,CAChD,gBAAiBA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,C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EAAM,GAAID,EAAa,CAAE,WAAAA,CAAW,EAAI,CAAC,EAAI,GAAIG,EAAM,CAAE,IAAAA,CAAI,EAAI,CAAC,CAAG,EACtFE,EAAM,MAAMC,EAAQ9B,CAAG,EAE7B,GAAI,CAAC6B,GAAK,MAAO,MAAO,CAAE,GAAGD,EAAQ,MAAO,CAAC,CAAE,EAE/C,GAAM,CAAE,SAAUG,EAAU,KAAMC,CAAU,EAAIC,EAAiBjC,CAAG,EAC9DkC,EAAMlB,EAAQ,IAAImB,CAAa,EAC/BC,EAAaC,EAAqBrB,EAAQ,IAAKM,EAAQ,SAAS,EAChEgB,EAAaC,EAAK,IAAM,CAG5B,GAAI,CACF,OAAOC,EAAezC,EAAcC,CAAG,CAAC,GAAKyC,CAC/C,MAAQ,CACN,OAAOA,CACT,CACF,CAAC,EAED,MAAO,CACL,GAAGb,EACH,MAAOc,EAAmB,CAAE,MAAOb,EAAI,MAAO,SAAAE,EAAU,IAAAG,EAAK,WAAAI,EAAY,WAAAF,EAAY,UAAAJ,CAAU,CAAC,CAClG,CACF,EAMaW,GAAgB,MAAOrB,EAA8B,CAAC,KACzD,MAAMD,GAAYC,CAAO,GAAG",
6
+ "names": ["Buffer", "execFileSync", "fs", "net", "path", "process", "pathToFileURL", "z", "z", "packageConfigSchema", "route", "INFRA_KIT_ENV", "PACKAGE_CONFIG_FILE", "DEV_CONTEXT_DIR", "path", "DEV_CONTEXT_FILE", "devContextFragmentSchema", "z", "buildBasicAuthHeader", "env", "override", "username", "password", "Buffer", "interpolate", "template", "values", "DEFAULT_HTTP_PORT", "LOOPBACK_V4", "withProxyPort", "target", "proxyPort", "url", "grafted", "LEGACY_SELF_SPAWNED_PORT_FLOOR", "resolveLegacyTarget", "resolveLocalTarget", "args", "route", "templates", "env", "getRelease", "info", "slugifyHostLabel", "pickSource", "localSet", "fallback", "LOOPBACK_HOSTNAMES", "isLoopbackTarget", "hostname", "bare", "resolveRoute", "routePath", "localInfo", "INFRA_KIT_ENV", "resolveProxyConfig", "proxy", "authHeader", "result", "headers", "entry", "once", "fn", "cached", "loadDev", "cwd", "configPath", "path", "PACKAGE_CONFIG_FILE", "fs", "stat", "rawExport", "pathToFileURL", "resolved", "parsed", "packageConfigSchema", "z", "extractPackages", "v", "candidate", "findUp", "start", "relative", "dir", "parent", "emptyLocalContext", "isFragmentWriterAlive", "pid", "process", "error", "readFragmentDir", "entries", "packages", "name", "devContextFragmentSchema", "readLocalContext", "DEV_CONTEXT_DIR", "legacy", "DEV_CONTEXT_FILE", "readGitBranch", "cwd", "execFileSync", "getFreePort", "resolve", "reject", "srv", "net", "address", "port", "UI_PORTS_ENV", "readPackageName", "parsed", "fs", "path", "resolveManagedUi", "raw", "process", "name", "entry", "alias", "HTTPS_PORT", "infraKitDev", "options", "managed", "strictPort", "host", "LOOPBACK_V4", "hmr", "server", "dev", "loadDev", "localSet", "localInfo", "readLocalContext", "env", "INFRA_KIT_ENV", "authHeader", "buildBasicAuthHeader", "getRelease", "once", "slugifyRelease", "DEFAULT_RELEASE_SLUG", "resolveProxyConfig", "infraKitProxy"]
7
+ }
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{A as Ye,B as We,C as He,D as ze,E as Xe,F as Qe,G as Ze,H as et,I as H,J as tt,K as ot,L as rt,M as nt,N as it,O as D,P as at,R as M,S as st,a as we,b as x,c as S,d as Ee,e as xe,f as Ce,g as B,h as ke,i as Pe,j as J,k as Te,l as Ae,m as De,n as Me,o as Oe,p as je,q as Ue,r as Fe,s as _,t as m,u as Ge,v as Ve,w as qe,x as Ke,y as Be,z as Je}from"./chunk-WSO6DN6Q.js";import{a as $e}from"./chunk-RXEMP3VI.js";import{q as z}from"./chunk-RSF5XAQJ.js";import{P as K,Q as ye,S as Se,m as he,v as l}from"./chunk-V37MZDFR.js";import{e as W}from"./chunk-Z6KTUVIC.js";import{a as ct,b as O,c as lt,d as P,e as X,f as Q,g as Z}from"./chunk-3OMHS5RE.js";import{a as Re}from"./chunk-6FDGBQGX.js";import{a as L}from"./chunk-6FU2TRU5.js";import{a as N,b as be,d as Ie,f as Le,g as Ne,j as Y,k as _e,n as w}from"./chunk-CHETBZ6M.js";import"./chunk-6EPRH34O.js";import"./chunk-LTKR3F4N.js";import er,{Separator as ro}from"@inquirer/select";import{realpathSync as tr}from"node:fs";import u from"node:process";import{fileURLToPath as io}from"node:url";var mt=e=>{let t=new Map(e.map(o=>[o.name(),o]));return D.flatMap(({key:o,label:r})=>M(o).flatMap(a=>{let i=t.get(a);return i?[{name:a,description:i.description(),group:r}]:[]}))};import{Command as _o}from"commander";import I from"node:process";import dt from"node:process";import{$ as so}from"zx";var ee=async()=>{let e=await K(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async n=>({...n,exists:await x(n.path)}))),o=t.at(-1)?.exists===!0,r=await Te(e.userProject,o),a=o?Ae(r):"";l.info(`Project name: ${e.projectName}
2
+ import{A as qe,B as Ke,C as Je,D as Ye,E as Be,F as We,G as He,H as ze,I as Y,J as Xe,K as Qe,L as Ze,M as et,N as tt,O as ot,P as rt,R as nt,S as it,a as he,b as E,c as y,d as Se,e as we,f as Re,g as G,h as Ee,i as xe,j as V,k as Ce,l as Pe,m as Le,n as Ne,o as _e,p as De,q as Oe,r as Me,s as N,t as m,u as je,v as $e,w as Ue,x as Fe,y as Ge,z as Ve}from"./chunk-2YHPK2VY.js";import{a as K}from"./chunk-TFHVQOVF.js";import{r as B}from"./chunk-27PDA2PN.js";import{P as F,Q as ge,S as ve,m as fe,v as l}from"./chunk-3F7XYJWY.js";import{e as J}from"./chunk-Z6KTUVIC.js";import{a as at,b as _,c as st,d as P,e as W,f as H,g as z}from"./chunk-3OMHS5RE.js";import{a as ye}from"./chunk-DOG3OPNW.js";import{a as I}from"./chunk-6FU2TRU5.js";import{a as L,b as Te,d as ke,f as Ae,g as be,j as q,k as Ie,n as S}from"./chunk-CHETBZ6M.js";import"./chunk-TUVUKM4K.js";import"./chunk-LTKR3F4N.js";import Zo,{Separator as $t}from"@inquirer/select";import{realpathSync as er}from"node:fs";import u from"node:process";import{fileURLToPath as Ft}from"node:url";var Vt=(e,t)=>{let o=e,r;for(let a of t){if(r=o.find(n=>n.name()===a),!r)return;o=r.commands}return r},ct=e=>ot.flatMap(({key:t,label:o})=>nt(t).flatMap(r=>{let a=Vt(e,r.groupPath);return a?[{name:r.groupPath.join(" "),description:a.description(),group:o}]:[]}));import{Command as go}from"commander";import b from"node:process";import lt from"node:process";import{$ as qt}from"zx";var X=async()=>{let e=await F(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await E(i.path)}))),o=t.at(-1)?.exists===!0,r=await Ce(e.userProject,o),a=o?Pe(r):"";l.info(`Project name: ${e.projectName}
3
3
  `),l.info(`Config merge chain (later overrides earlier):
4
- `);for(let n of t){let s=n.exists?" [\u2713]":" [ ]",c=n.path===e.userProject&&a!==""?` ${a}`:"";l.info(`${s} ${n.label.padEnd(22)} ${S(n.path)}${c}`)}let i={projectName:e.projectName,layers:t.map(n=>({label:n.label,path:n.path,exists:n.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(i,null,2)}],structuredContent:i}},te=async()=>{let e=await K(),t=dt.env.EDITOR||dt.env.VISUAL||"vi",o=await Ee(e);o.createdConfig&&l.info(xe(o)),l.info(`Opening ${S(e.userProject)} in ${t}`),await so({stdio:"inherit"})`${t} ${e.userProject}`,Se();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};import p from"node:fs";import R from"node:path";import A from"node:process";var co="autoload-warn-misconfig.flag",lo="autoload-warn-fail.flag",oe="autoload-fail.flag",mo=3e4,ut=async(e=!0)=>{let t;try{t=await ye()}catch{return null}let o=t.envAutoLoad;return o?t.environments.includes(o.config)?{trigger:o.trigger,config:o.config,project:t.envManagement.config.name}:(e&&gt(`infra-kit: envAutoLoad.config "${o.config}" is not one of environments [${t.environments.join(", ")}] \u2014 env auto-load disabled.`,co),null):null},ft=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:a,env:i,force:n}=e;return t!==o||!i.session||i.cleared||i.currentConfig&&!i.autoLoadedMarker||!n&&i.autoLoadedMarker&&i.currentConfig===r&&i.currentProject===a?"skip":"load"},b=async({expectedTrigger:e,projectDir:t,force:o})=>{let r=e==="cli-invocation";try{let a=await ut(r);if(!a||ft({trigger:a.trigger,expectedTrigger:e,targetConfig:a.config,targetProject:a.project,env:po(),force:o})==="skip"||pt()||go())return null;let n=uo(),s=await je({config:a.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!pt()&&!fo(n)});return s?(ho(),s.filePath):null}catch(a){let i=a.message;return vo(),r?gt(`infra-kit: env auto-load failed \u2014 ${i} (will retry later)`,lo):l.debug(`env auto-load skipped: ${i}`),null}},po=()=>({session:A.env[Ie],cleared:A.env[_e],currentConfig:A.env[Le],currentProject:A.env[Ne],autoLoadedMarker:A.env[Y]}),uo=()=>{try{return p.statSync(R.join(w(),N)).mtimeMs}catch{return null}},fo=e=>{try{let t=R.join(w(),N);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Y}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},pt=()=>{try{let e=w(),t=R.join(e,be);if(!p.existsSync(t))return!1;let o=R.join(e,N);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},go=()=>{try{let e=R.join(w(),oe);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<mo:!1}catch{return!1}},vo=()=>{try{let e=w();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(R.join(e,oe),"",{mode:384})}catch{}},ho=()=>{try{p.rmSync(R.join(w(),oe),{force:!0})}catch{}},gt=(e,t)=>{try{let o=w(),r=R.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var re=async({projectDir:e}={})=>{await b({expectedTrigger:"shell-startup",projectDir:e,force:!0})};import{spawn as yo}from"node:child_process";import $ from"node:process";import{fileURLToPath as So}from"node:url";var wo=["SIGINT","SIGTERM"],vt=()=>So(new URL("./mcp.js",import.meta.url)),ne=(e={})=>{let t=e.spawn??yo,o=e.exit??(n=>$.exit(n)),r=e.env??$.env,a=e.onError??(n=>l.error(n)),i=t($.execPath,[vt()],{stdio:"inherit",env:L(r)});i.on("error",n=>{a(`failed to launch the MCP server: ${n.message}`),o(1)}),wo.forEach(n=>{$.on(n,()=>{i.kill(n)})}),i.on("exit",(n,s)=>{o(s?1:n??1)})};import{spawnSync as Ro}from"node:child_process";import{realpathSync as Eo}from"node:fs";import ie from"node:process";import{fileURLToPath as xo}from"node:url";var Co=()=>Eo(xo(import.meta.url)),ko=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),ae=({dryRun:e},t={})=>{let o=t.spawnSync??Ro,r=t.print??(k=>l.info(k)),a=t.exit??(k=>ie.exit(k)),i=t.env??ie.env,n=t.selfRealPath??Co(),s=t.lazyNpmRoot??lt,{manager:c,updateCommand:d,canSelfSpawn:f}=ct({selfRealPath:n,env:i,realpath:P,lazyNpmRoot:s}),v=d.join(" ");if(e){r(`Detected install manager: ${c}`),r(`Would run: ${v}`);return}if(!f){r(`Detected install manager: ${c}`),r(`Run this yourself: ${v}`),r(c==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let C=o(d[0],d.slice(1),{stdio:"inherit",shell:ie.platform==="win32",env:L(i)});ko(C,c,r,a)};import se from"node:fs/promises";import ce from"node:path";import ht from"node:process";import{pathToFileURL as Po}from"node:url";var yt="~/projects",le=async(e={})=>{if(e.init){await Ao(e.cwd);return}await To()},To=async()=>{let e=B(),t=await x(e);if(l.info(`Factory config: ${S(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor-config --init` to scaffold it."),ht.exitCode=1;return}let{workspaceDir:o,targets:r}=await Pe(),a=ke(o),i=await x(a);l.info(`workspaceDir: ${o} (resolved: ${a}) ${i?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let n=i;for(let s of r){let c=ce.join(a,s),d=await x(c);d||(n=!1);let f=d?"[\u2713]":"[ ]",v=d?"":" (not found \u2014 clone or remove)";l.info(` ${f} ${s} ${S(c)}${v}`)}n||(ht.exitCode=1)},Ao=async e=>{let t=B();if(await x(t)){l.info(`Factory config already exists at ${S(t)} \u2014 leaving it untouched.`);return}let o=e??await he(),r=await bo(o);await se.mkdir(ce.dirname(t),{recursive:!0}),await se.writeFile(t,Io(r),"utf-8"),l.info(`\u2713 Created ${S(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${W}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${yt}) to point at where your repos live.`),r.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},bo=async e=>{try{let t=ce.join(e,W),o=await se.stat(t),i=(await import(`${Po(t).href}?mtime=${Number(o.mtimeMs)}`)).default,n=typeof i=="function"?await i():i;if(n&&typeof n=="object"&&"targets"in n){let s=n.targets;if(Array.isArray(s)&&s.every(c=>typeof c=="string"))return s}}catch{}return[]},Io=e=>`${JSON.stringify({workspaceDir:yt,targets:e},null,2)}
5
- `;var j=(e,t=!0)=>({line:e,reproducible:t});import U from"node:fs";import Lo from"node:os";import No from"node:path";import Et from"node:process";var F="INFRA_KIT_SESSION_REPORT",me=null,St=!1,wt=[],xt=(e=Et.env)=>{St||(me=e[F]??null,St=!0,delete e[F])};var Ct=(e,t)=>{if(!me)return;let o=e.summary??(wt.length>0?[...wt]:void 0),r={...e,...o?{summary:o}:{}},a=t?.write??((i,n)=>{U.writeFileSync(i,n)});try{a(me,JSON.stringify(r))}catch{}},Rt=0,kt=e=>{let t=e?.tmpdir?.()??Lo.tmpdir(),o=e?.pid??Et.pid;return Rt+=1,No.join(t,`infra-kit-session-${o}-${Rt}.json`)},Pt=(e,t)=>{if(!(t?.exists??(n=>U.existsSync(n)))(e))return null;let r=t?.read??(n=>U.readFileSync(n,"utf-8")),a=t?.unlink??(n=>U.unlinkSync(n)),i;try{i=r(e)}catch{return null}finally{try{a(e)}catch{}}try{return JSON.parse(i)}catch{return null}};var Do=(e,t)=>[...t,e],de=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,Tt=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&H.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${H.join(", ")}.`)}},G={value:!1},g=(e,t)=>e.hook("preAction",()=>{G.value||l.warn(`"${e.name()}" is a deprecated alias; use "${t}" instead.`)}),At=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ve({all:t.all,confirmedCommand:t.yes}))}),bt=e=>e.description("List all release branches").action(async()=>{m(await Je())}),It=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',Do,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(Ye),a=r.length>0?r:void 0;m(await We({releases:a,confirmedCommand:t.yes}))}),Lt=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await He({version:t.version,description:t.description,confirmedCommand:t.yes}))}),Nt=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ke({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),_t=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Be({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),Dt=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await qe({version:t.version,confirmedCommand:t.yes}))}),Mt=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await it({confirmedCommand:t.yes}))}),Ot=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=Tt(t.ide,"--ide")??Tt(t.cursor,"--cursor");m(await tt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),$t=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await ot())}),jt=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{m(await nt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Ut=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{m(await rt())}),Ft=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{m(await le({init:t.init}))}),Gt=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await ze();m(t),t.structuredContent.ok||(I.exitCode=1)}),Vt=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await Xe({repos:de(t.repos)});m(o),o.structuredContent.ok||(I.exitCode=1)}),qt=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await ee())}),Kt=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await te())}),Mo=new Set(["init","doctor","version","dev","self-update","mcp"]),Oo=e=>e.startsWith("env-")||Mo.has(e),$o=new Set(["env-autoload","mcp","version","self-update"]),pe=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},ue=()=>{let e=new _o,t=e.command("release").description("Release management commands");At(t.command("merge-dev")),bt(t.command("list")),It(t.command("create")),Lt(t.command("desc-edit")),Nt(t.command("deploy-all")),_t(t.command("deploy-selected")),Dt(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");Ot(o.command("add")),$t(o.command("list")),jt(o.command("remove")),Mt(o.command("sync")),Ut(o.command("reload")),g(At(e.command("merge-dev")),"release merge-dev"),g(bt(e.command("release-list")),"release list"),g(It(e.command("release-create")),"release create"),g(Lt(e.command("release-desc-edit")),"release desc-edit"),g(Nt(e.command("release-deploy-all")),"release deploy-all"),g(_t(e.command("release-deploy-selected")),"release deploy-selected"),g(Dt(e.command("release-deliver")),"release deliver"),g(Ot(e.command("worktrees-add")),"worktrees add"),g($t(e.command("worktrees-list")),"worktrees list"),g(jt(e.command("worktrees-remove")),"worktrees remove"),g(Mt(e.command("worktrees-sync")),"worktrees sync"),g(Ut(e.command("worktrees-reload")),"worktrees reload");let r=e.command("config").description("Manage infra-kit configuration files");qt(r.command("path")),Kt(r.command("edit")),qt(e.command("config-path",{hidden:!0})),Kt(e.command("config-edit",{hidden:!0})),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async i=>{let n=await we({all:i.all,root:i.root});m(n),n.structuredContent.allPassed||(I.exitCode=1)});let a=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return Gt(a.command("check")),a.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async i=>{m(await Ze({confirmedCommand:i.yes,repos:de(i.repos)}))}),a.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async i=>{m(await Qe({confirmedCommand:!0,repos:de(i.repos)}))}),Vt(a.command("diff")),Ft(a.command("config")),g(Ft(e.command("vendor-config")),"vendor config"),Gt(e.command("vendor-check",{hidden:!0})),Vt(e.command("vendor-diff",{hidden:!0})),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{m(await De())}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(i=>{ae({dryRun:!!i.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ne()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").action(async(i,n)=>{let{runDevServerCli:s}=await import("./dev-server.js"),c=!!(I.stdout.isTTY&&I.stdin.isTTY);await s({...n,preset:i},c,_.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await et())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Fe())}),e.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{m(await Oe())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{m(await J())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async i=>{m(await Ue({config:i.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async i=>{m(await Me({purge:!!i.purge}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async i=>{await re({projectDir:i.projectDir})}),e.commands.forEach(Ge),e.hook("preAction",async(i,n)=>{_.enabled=!!n.optsWithGlobals().json,_.enabled&&(l.level="warn"),$o.has(pe(n))||await Ce(),Oo(n.name())||await b({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(i,n)=>{let s=pe(n);if(st(s))return;let d=$e.snapshot()?.formattedOptions??"",f=d?` ${d}`:"",v=`infra-kit ${s}${f}`;Ct({equivalent:j(v,!0)})}),e};var fe=(e,t=" ")=>{let o=e.reduce((r,[a])=>Math.max(r,a.length),0);return e.map(([r,a])=>`${r.padEnd(o)}${t}${a}`)};import{spawn as Go}from"node:child_process";import y from"node:process";var h={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},Bt={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Jt=e=>`${h.reproPrefix}${e}`,jo=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,Uo=(e,t)=>e==="findings"?t!=null?`${t} ${h.findingsSuffix}`:h.findingsPlain:{ok:h.ok,failed:h.failed,cancelled:h.cancelled}[e],Yt=e=>{let t=e.equivalent.reproducible?h.reproPrefix:h.nonReproPrefix,o=e.ascii===!0?Bt[e.outcome].ascii:Bt[e.outcome].unicode,a=[Uo(e.outcome,e.findingsCount),jo(e.durationMs)],i=e.summary?.[0];i!=null&&i.length>0&&a.push(i);let n=[`${o} ${a.join(h.sep)}`];return e.showEquivalent!==!1&&n.unshift(`${t}${e.equivalent.line}`),e.envNotice===!0&&n.push(h.envNotice),n.join(`
6
- `)};var Fo=new Set([130,143]),Wt=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Fo.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import Ht from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},zt=(e,t)=>{let o=t?.write??(i=>{Ht.stderr.write(i)}),r=t?.stdin??Ht.stdin,a=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&a.push(E.primaryBuffer),o(a.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var Xt=e=>`infra-kit ${e.groupPath.join(" ")}`,Vo=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),qo=async(e,t,o)=>{let r=kt(),a={...t.env,[F]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},i=t.now(),n={code:1,signal:null};o(!0);try{let v=t.spawn(y.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:a});n=await Vo(v)}catch{n={code:1,signal:null}}finally{o(!1),t.resetTerminal({entersAltScreen:e.entersAltScreen})}let s=Pt(r),c=Wt(n.code,n.signal,s!=null,e.longRunning),d=Xt(e),f=s?.equivalent??j(d,!0);return Yt({equivalent:f,outcome:c,durationMs:t.now()-i,summary:s?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,showEquivalent:!(f.reproducible&&f.line===d)})},Ko=(e,t)=>{let o=!1,r=!1,a=()=>{if(e()){o=!0;return}t.exit(0)},i=()=>{if(!e()){t.exit(0);return}o||(r=!0)},n=()=>{t.exit(129)},s=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",a),t.register("SIGTERM",i),t.register("SIGHUP",n),t.register("SIGTSTP",s),{dispose:()=>{t.unregister("SIGINT",a),t.unregister("SIGTERM",i),t.unregister("SIGHUP",n),t.unregister("SIGTSTP",s)},childStarted:()=>{o=!1},quitRequested:()=>r}},Qt=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),Zt=async(e,t)=>{let o={spawn:t.spawn??Go,now:t.now??(()=>Date.now()),env:t.env??y.env,cliPath:t.cliPath,ascii:t.ascii??!(y.stdout.isTTY&&y.env.TERM!=="dumb"),resetTerminal:t.resetTerminal??(c=>{zt(c)})},r=t.write??(c=>y.stderr.write(c)),a=t.signals??{register:(c,d)=>{y.on(c,d)},unregister:(c,d)=>{y.off(c,d)},exit:c=>{y.exit(c)},raise:c=>{y.kill(y.pid,c)}},i=!1,n={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},s=t.installSignals===!1?n:Ko(()=>i,a);try{for(;;){let c=await t.renderPalette(e);if(c==null)return;let d=t.resolveCommand(c);if(!d)continue;let f=Jt(Xt(d));r(`
4
+ `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",s=i.path===e.userProject&&a!==""?` ${a}`:"";l.info(`${c} ${i.label.padEnd(22)} ${y(i.path)}${s}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},Q=async()=>{let e=await F(),t=lt.env.EDITOR||lt.env.VISUAL||"vi",o=await Se(e);o.createdConfig&&l.info(we(o)),l.info(`Opening ${y(e.userProject)} in ${t}`),await qt({stdio:"inherit"})`${t} ${e.userProject}`,ve();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};import p from"node:fs";import w from"node:path";import k from"node:process";var Kt="autoload-warn-misconfig.flag",Jt="autoload-warn-fail.flag",Z="autoload-fail.flag",Yt=3e4,dt=async(e=!0)=>{let t;try{t=await ge()}catch{return null}let o=t.envAutoLoad;return o?t.environments.includes(o.config)?{trigger:o.trigger,config:o.config,project:t.envManagement.config.name}:(e&&ut(`infra-kit: envAutoLoad.config "${o.config}" is not one of environments [${t.environments.join(", ")}] \u2014 env auto-load disabled.`,Kt),null):null},pt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:a,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===a?"skip":"load"},A=async({expectedTrigger:e,projectDir:t,force:o})=>{let r=e==="cli-invocation";try{let a=await dt(r);if(!a||pt({trigger:a.trigger,expectedTrigger:e,targetConfig:a.config,targetProject:a.project,env:Bt(),force:o})==="skip"||mt()||zt())return null;let i=Wt(),c=await De({config:a.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!mt()&&!Ht(i)});return c?(Qt(),c.filePath):null}catch(a){let n=a.message;return Xt(),r?ut(`infra-kit: env auto-load failed \u2014 ${n} (will retry later)`,Jt):l.debug(`env auto-load skipped: ${n}`),null}},Bt=()=>({session:k.env[ke],cleared:k.env[Ie],currentConfig:k.env[Ae],currentProject:k.env[be],autoLoadedMarker:k.env[q]}),Wt=()=>{try{return p.statSync(w.join(S(),L)).mtimeMs}catch{return null}},Ht=e=>{try{let t=w.join(S(),L);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${q}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},mt=()=>{try{let e=S(),t=w.join(e,Te);if(!p.existsSync(t))return!1;let o=w.join(e,L);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},zt=()=>{try{let e=w.join(S(),Z);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Yt:!1}catch{return!1}},Xt=()=>{try{let e=S();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(w.join(e,Z),"",{mode:384})}catch{}},Qt=()=>{try{p.rmSync(w.join(S(),Z),{force:!0})}catch{}},ut=(e,t)=>{try{let o=S(),r=w.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var ee=async({projectDir:e}={})=>{await A({expectedTrigger:"shell-startup",projectDir:e,force:!0})};import{spawn as Zt}from"node:child_process";import D from"node:process";import{fileURLToPath as eo}from"node:url";var to=["SIGINT","SIGTERM"],ft=()=>eo(new URL("./mcp.js",import.meta.url)),te=(e={})=>{let t=e.spawn??Zt,o=e.exit??(i=>D.exit(i)),r=e.env??D.env,a=e.onError??(i=>l.error(i)),n=t(D.execPath,[ft()],{stdio:"inherit",env:I(r)});n.on("error",i=>{a(`failed to launch the MCP server: ${i.message}`),o(1)}),to.forEach(i=>{D.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as oo}from"node:child_process";import{realpathSync as ro}from"node:fs";import oe from"node:process";import{fileURLToPath as no}from"node:url";var io=()=>ro(no(import.meta.url)),ao=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),re=({dryRun:e},t={})=>{let o=t.spawnSync??oo,r=t.print??(C=>l.info(C)),a=t.exit??(C=>oe.exit(C)),n=t.env??oe.env,i=t.selfRealPath??io(),c=t.lazyNpmRoot??st,{manager:s,updateCommand:d,canSelfSpawn:f}=at({selfRealPath:i,env:n,realpath:P,lazyNpmRoot:c}),g=d.join(" ");if(e){r(`Detected install manager: ${s}`),r(`Would run: ${g}`);return}if(!f){r(`Detected install manager: ${s}`),r(`Run this yourself: ${g}`),r(s==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let x=o(d[0],d.slice(1),{stdio:"inherit",shell:oe.platform==="win32",env:I(n)});ao(x,s,r,a)};import ne from"node:fs/promises";import ie from"node:path";import gt from"node:process";import{pathToFileURL as so}from"node:url";var vt="~/projects",ae=async(e={})=>{if(e.init){await lo(e.cwd);return}await co()},co=async()=>{let e=G(),t=await E(e);if(l.info(`Factory config: ${y(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),gt.exitCode=1;return}let{workspaceDir:o,targets:r}=await xe(),a=Ee(o),n=await E(a);l.info(`workspaceDir: ${o} (resolved: ${a}) ${n?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=n;for(let c of r){let s=ie.join(a,c),d=await E(s);d||(i=!1);let f=d?"[\u2713]":"[ ]",g=d?"":" (not found \u2014 clone or remove)";l.info(` ${f} ${c} ${y(s)}${g}`)}i||(gt.exitCode=1)},lo=async e=>{let t=G();if(await E(t)){l.info(`Factory config already exists at ${y(t)} \u2014 leaving it untouched.`);return}let o=e??await fe(),r=await mo(o);await ne.mkdir(ie.dirname(t),{recursive:!0}),await ne.writeFile(t,po(r),"utf-8"),l.info(`\u2713 Created ${y(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${J}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${vt}) to point at where your repos live.`),r.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},mo=async e=>{try{let t=ie.join(e,J),o=await ne.stat(t),n=(await import(`${so(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let c=i.targets;if(Array.isArray(c)&&c.every(s=>typeof s=="string"))return c}}catch{}return[]},po=e=>`${JSON.stringify({workspaceDir:vt,targets:e},null,2)}
5
+ `;var O=(e,t=!0)=>({line:e,reproducible:t});import M from"node:fs";import uo from"node:os";import fo from"node:path";import wt from"node:process";var j="INFRA_KIT_SESSION_REPORT",se=null,ht=!1,yt=[],Rt=(e=wt.env)=>{ht||(se=e[j]??null,ht=!0,delete e[j])};var Et=(e,t)=>{if(!se)return;let o=e.summary??(yt.length>0?[...yt]:void 0),r={...e,...o?{summary:o}:{}},a=t?.write??((n,i)=>{M.writeFileSync(n,i)});try{a(se,JSON.stringify(r))}catch{}},St=0,xt=e=>{let t=e?.tmpdir?.()??uo.tmpdir(),o=e?.pid??wt.pid;return St+=1,fo.join(t,`infra-kit-session-${o}-${St}.json`)},Ct=(e,t)=>{if(!(t?.exists??(i=>M.existsSync(i)))(e))return null;let r=t?.read??(i=>M.readFileSync(i,"utf-8")),a=t?.unlink??(i=>M.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{a(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var vo=(e,t)=>[...t,e],ce=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,Pt=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Y.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${Y.join(", ")}.`)}},ho=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await $e({all:t.all,confirmedCommand:t.yes}))}),yo=e=>e.description("List all release branches").action(async()=>{m(await Ve())}),So=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',vo,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(qe),a=r.length>0?r:void 0;m(await Ke({releases:a,confirmedCommand:t.yes}))}),wo=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Je({version:t.version,description:t.description,confirmedCommand:t.yes}))}),Ro=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Fe({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),Eo=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ge({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),xo=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ue({version:t.version,confirmedCommand:t.yes}))}),Co=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await tt({confirmedCommand:t.yes}))}),Po=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=Pt(t.ide,"--ide")??Pt(t.cursor,"--cursor");m(await Xe({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),To=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await Qe())}),ko=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{m(await et({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Ao=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{m(await Ze())}),bo=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{m(await ae({init:t.init}))}),Io=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ye();m(t),t.structuredContent.ok||(b.exitCode=1)}),Lo=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await Be({repos:ce(t.repos)});m(o),o.structuredContent.ok||(b.exitCode=1)}),No=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await X())}),_o=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await Q())}),Do=new Set(["init","doctor","version","dev","self-update","mcp"]),Oo=e=>e.startsWith("env-")||Do.has(e),Mo=new Set(["env-autoload","mcp","version","self-update"]),$=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},le=()=>{let e=new go,t=e.command("release").description("Release management commands");ho(t.command("merge-dev")),yo(t.command("list")),So(t.command("create")),wo(t.command("desc-edit")),Ro(t.command("deploy-all")),Eo(t.command("deploy-selected")),xo(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");Po(o.command("add")),To(o.command("list")),ko(o.command("remove")),Co(o.command("sync")),Ao(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");No(r.command("path")),_o(r.command("edit")),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async n=>{let i=await he({all:n.all,root:n.root});m(i),i.structuredContent.allPassed||(b.exitCode=1)});let a=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return Io(a.command("check")),a.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{m(await He({confirmedCommand:n.yes,repos:ce(n.repos)}))}),a.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{m(await We({confirmedCommand:!0,repos:ce(n.repos)}))}),Lo(a.command("diff")),bo(a.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{m(await Le())}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{re({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{te()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),s=!!(b.stdout.isTTY&&b.stdin.isTTY);await c({...i,preset:n},s,N.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await ze())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Me())}),e.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{m(await _e())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{m(await V())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async n=>{m(await Oe({config:n.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async n=>{m(await Ne({purge:!!n.purge}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async n=>{await ee({projectDir:n.projectDir})}),e.commands.forEach(je),e.hook("preAction",async(n,i)=>{K.start($(i)),N.enabled=!!i.optsWithGlobals().json,N.enabled&&(l.level="warn"),Mo.has($(i))||await Re(),Oo(i.name())||await A({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=$(i);if(it(c))return;let d=K.snapshot()?.formattedOptions??"",f=d?` ${d}`:"",g=`infra-kit ${c}${f}`;Et({equivalent:O(g,!0)})}),e};var me=(e,t=" ")=>{let o=e.reduce((r,[a])=>Math.max(r,a.length),0);return e.map(([r,a])=>`${r.padEnd(o)}${t}${a}`)};import{spawn as Fo}from"node:child_process";import h from"node:process";var v={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},Tt={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},kt=e=>`${v.reproPrefix}${e}`,jo=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$o=(e,t)=>e==="findings"?t!=null?`${t} ${v.findingsSuffix}`:v.findingsPlain:{ok:v.ok,failed:v.failed,cancelled:v.cancelled}[e],At=e=>{let t=e.equivalent.reproducible?v.reproPrefix:v.nonReproPrefix,o=e.ascii===!0?Tt[e.outcome].ascii:Tt[e.outcome].unicode,a=[$o(e.outcome,e.findingsCount),jo(e.durationMs)],n=e.summary?.[0];n!=null&&n.length>0&&a.push(n);let i=[`${o} ${a.join(v.sep)}`];return e.showEquivalent!==!1&&i.unshift(`${t}${e.equivalent.line}`),e.envNotice===!0&&i.push(v.envNotice),i.join(`
6
+ `)};var Uo=new Set([130,143]),bt=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Uo.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import It from"node:process";var R={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Lt=(e,t)=>{let o=t?.write??(n=>{It.stderr.write(n)}),r=t?.stdin??It.stdin,a=[R.saveCursor,R.scrollRegion,R.restoreCursor,R.column,R.sgr,R.cursor,R.wrap];e.entersAltScreen===!0&&a.push(R.primaryBuffer),o(a.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var Nt=e=>`infra-kit ${e.groupPath.join(" ")}`,Go=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Vo=async(e,t,o)=>{let r=xt(),a={...t.env,[j]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o(!0);try{let g=t.spawn(h.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:a});i=await Go(g)}catch{i={code:1,signal:null}}finally{o(!1),t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=Ct(r),s=bt(i.code,i.signal,c!=null,e.longRunning),d=Nt(e),f=c?.equivalent??O(d,!0);return At({equivalent:f,outcome:s,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,showEquivalent:!(f.reproducible&&f.line===d)})},qo=(e,t)=>{let o=!1,r=!1,a=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",a),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",a),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},_t=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),Dt=async(e,t)=>{let o={spawn:t.spawn??Fo,now:t.now??(()=>Date.now()),env:t.env??h.env,cliPath:t.cliPath,ascii:t.ascii??!(h.stdout.isTTY&&h.env.TERM!=="dumb"),resetTerminal:t.resetTerminal??(s=>{Lt(s)})},r=t.write??(s=>h.stderr.write(s)),a=t.signals??{register:(s,d)=>{h.on(s,d)},unregister:(s,d)=>{h.off(s,d)},exit:s=>{h.exit(s)},raise:s=>{h.kill(h.pid,s)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:qo(()=>n,a);try{for(;;){let s=await t.renderPalette(e);if(s==null)return;let d=t.resolveCommand(s);if(!d)continue;let f=kt(Nt(d));r(`
7
7
  ${f}
8
- `),s.childStarted();let v=await qo(d,o,C=>{i=C});if(r(`
9
- ${v}
10
- `),s.quitRequested())return}}finally{s.dispose()}};import{spawn as Yo}from"node:child_process";import to from"node:fs";import T from"node:process";import{fileURLToPath as oo}from"node:url";var eo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Bo=new Set(["mcp","self-update"]),Jo=e=>e[2]!=null&&Bo.has(e[2]),ge=e=>{let{argv:t,env:o,isTty:r,selfRealPath:a,cwd:i,realpath:n}=e;return eo.some(c=>{let d=o[c];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":Jo(t)?"own-command":r?O(a,i,n)?"local-install":null:"not-a-tty"};var Wo=e=>{Yo(T.execPath,[e,"--parent-pid",String(T.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Ho=()=>oo(new URL("./update-check.js",import.meta.url)),zo=()=>to.realpathSync(oo(new URL("./cli.js",import.meta.url))),Xo=/^[\w@./+-]+$/i,Qo=e=>Xo.test(e),Zo=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||X(e.latestVersion,t)&&e.updateCommand.every(Qo)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},ve=(e,t={})=>{try{let o=t.argv??T.argv,r=t.env??T.env,a=t.isTty??!!T.stdout.isTTY,i=t.cwd??T.cwd(),n=t.nowMs??Date.now(),s=t.selfRealPath??zo(),c=t.readCache??Q,d=t.spawnChild??Wo,f=t.fileExists??(q=>to.existsSync(q)),v=t.notify??(q=>{l.info(q)});if(ge({argv:o,env:r,isTty:a,selfRealPath:s,cwd:i,realpath:P})!==null)return;let C=c();if(Zo(C,e,v),!Z(C,n))return;let k=t.childPath??Ho();if(!f(k))return;d(k)}catch{}};xt();var V=ue(),no=async e=>{try{e?await V.parseAsync(e):await V.parseAsync()}catch(t){z(t)&&(l.info("Operation cancelled."),u.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),u.exit(1)}},or=()=>{try{if(u.env.INFRA_KIT_NO_LOCATION_WARN||u.argv.includes("--json")||u.argv[2]==="mcp")return;O(tr(io(import.meta.url)),u.cwd(),P)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};or();ve(Re.version);var rr=()=>new Map(V.commands.map(e=>[e.name(),e])),ao=()=>mt(V.commands),nr=async()=>{let e=rr(),t=ao(),o=null;try{if(u.stdout.isTTY&&u.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-YCABHUPP.js");o=await r(t)}else{let r=fe(t.map(n=>[n.name,n.description])),a=new Map;t.forEach((n,s)=>{a.set(n.name,r[s]??n.name)});let i=n=>n.filter(s=>e.has(s)).map(s=>({name:a.get(s)??s,value:s}));o=await er({message:"Select a command to run",choices:D.flatMap(({key:n,label:s})=>{let c=i(M(n));return c.length===0?[]:[new ro(" "),new ro(`\u2014 ${s} \u2014`),...c]})},{output:u.stderr})}}catch(r){if(!z(r))throw r}return o},ir=async()=>{let{runCommandPalette:e}=await import("./boot-YCABHUPP.js"),t=io(import.meta.url),o=new Map(at.map(r=>[r.cliName,r]));await Zt(ao(),{renderPalette:e,resolveCommand:r=>{let a=o.get(r);return a?{groupPath:a.groupPath,entersAltScreen:a.entersAltScreen,sessionEnvNotice:a.sessionEnvNotice,longRunning:a.longRunning}:void 0},cliPath:t})};if(u.argv.length<=2){let e={stdoutIsTTY:!!u.stdout.isTTY,stdinIsTTY:!!u.stdin.isTTY,stderrIsTTY:!!u.stderr.isTTY};if(Qt(u.env,e))await ir();else{let t=await nr();t&&(G.value=!0,await no(["node","infra-kit",t]))}}else await no();
8
+ `),c.childStarted();let g=await Vo(d,o,x=>{n=x});if(r(`
9
+ ${g}
10
+ `),c.quitRequested())return}}finally{c.dispose()}};import{spawn as Yo}from"node:child_process";import Mt from"node:fs";import T from"node:process";import{fileURLToPath as jt}from"node:url";var Ot=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Ko=new Set(["mcp","self-update"]),Jo=e=>e[2]!=null&&Ko.has(e[2]),de=e=>{let{argv:t,env:o,isTty:r,selfRealPath:a,cwd:n,realpath:i}=e;return Ot.some(s=>{let d=o[s];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":Jo(t)?"own-command":r?_(a,n,i)?"local-install":null:"not-a-tty"};var Bo=e=>{Yo(T.execPath,[e,"--parent-pid",String(T.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Wo=()=>jt(new URL("./update-check.js",import.meta.url)),Ho=()=>Mt.realpathSync(jt(new URL("./cli.js",import.meta.url))),zo=/^[\w@./+-]+$/i,Xo=e=>zo.test(e),Qo=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||W(e.latestVersion,t)&&e.updateCommand.every(Xo)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},pe=(e,t={})=>{try{let o=t.argv??T.argv,r=t.env??T.env,a=t.isTty??!!T.stdout.isTTY,n=t.cwd??T.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??Ho(),s=t.readCache??H,d=t.spawnChild??Bo,f=t.fileExists??(U=>Mt.existsSync(U)),g=t.notify??(U=>{l.info(U)});if(de({argv:o,env:r,isTty:a,selfRealPath:c,cwd:n,realpath:P})!==null)return;let x=s();if(Qo(x,e,g),!z(x,i))return;let C=t.childPath??Wo();if(!f(C))return;d(C)}catch{}};Rt();var ue=le(),Ut=async e=>{try{e?await ue.parseAsync(e):await ue.parseAsync()}catch(t){B(t)&&(l.info("Operation cancelled."),u.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),u.exit(1)}},tr=()=>{try{if(u.env.INFRA_KIT_NO_LOCATION_WARN||u.argv.includes("--json")||u.argv[2]==="mcp")return;_(er(Ft(import.meta.url)),u.cwd(),P)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};tr();pe(ye.version);var Gt=()=>ct(ue.commands),or=async()=>{let e=Gt(),t=null;try{if(u.stdout.isTTY&&u.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-YCABHUPP.js");t=await o(e)}else{let o=me(e.map(a=>[a.name,a.description])),r=e.flatMap((a,n)=>[...e[n-1]?.group===a.group?[]:[new $t(" "),new $t(`\u2014 ${a.group} \u2014`)],{name:o[n]??a.name,value:a.name}]);t=await Zo({message:"Select a command to run",choices:r},{output:u.stderr})}}catch(o){if(!B(o))throw o}return t},rr=async()=>{let{runCommandPalette:e}=await import("./boot-YCABHUPP.js"),t=Ft(import.meta.url),o=new Map(rt.map(r=>[r.groupPath.join(" "),r]));await Dt(Gt(),{renderPalette:e,resolveCommand:r=>{let a=o.get(r);return a?{groupPath:a.groupPath,entersAltScreen:a.entersAltScreen,sessionEnvNotice:a.sessionEnvNotice,longRunning:a.longRunning}:void 0},cliPath:t})};if(u.argv.length<=2){let e={stdoutIsTTY:!!u.stdout.isTTY,stdinIsTTY:!!u.stdin.isTTY,stderrIsTTY:!!u.stderr.isTTY};if(_t(u.env,e))await rr();else{let t=await or();t&&await Ut(["node","infra-kit",...t.split(" ")])}}else await Ut();
11
11
  //# sourceMappingURL=cli.js.map