infra-kit 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/boot-HP5ORQEX.js +2 -0
  2. package/dist/boot-HP5ORQEX.js.map +7 -0
  3. package/dist/chunk-7DL27USH.js +7 -0
  4. package/dist/{chunk-GZNE5CBQ.js.map → chunk-7DL27USH.js.map} +3 -3
  5. package/dist/chunk-IURGCRSN.js +231 -0
  6. package/dist/chunk-IURGCRSN.js.map +7 -0
  7. package/dist/chunk-KAWDTA5H.js +2 -0
  8. package/dist/chunk-KAWDTA5H.js.map +7 -0
  9. package/dist/{chunk-A7FAXZGI.js → chunk-LKKKDB6V.js} +1 -1
  10. package/dist/{chunk-A7FAXZGI.js.map → chunk-LKKKDB6V.js.map} +1 -1
  11. package/dist/{chunk-OS5Z2WME.js → chunk-N6ML3SBF.js} +2 -2
  12. package/dist/{chunk-OS5Z2WME.js.map → chunk-N6ML3SBF.js.map} +1 -1
  13. package/dist/chunk-PZU6BLQR.js +4 -0
  14. package/dist/{chunk-IVWPZEMC.js.map → chunk-PZU6BLQR.js.map} +3 -3
  15. package/dist/chunk-X46DP23W.js +2 -0
  16. package/dist/chunk-X46DP23W.js.map +7 -0
  17. package/dist/chunk-XTRPE4SX.js +2 -0
  18. package/dist/chunk-XTRPE4SX.js.map +7 -0
  19. package/dist/cli.js +6 -6
  20. package/dist/cli.js.map +3 -3
  21. package/dist/dev-server.js +3 -3
  22. package/dist/dev-server.js.map +2 -2
  23. package/dist/dev-wizard-run-KIOSJM4D.js +2 -0
  24. package/dist/dev-wizard-run-KIOSJM4D.js.map +7 -0
  25. package/dist/mcp.js +1 -1
  26. package/dist/mcp.js.map +1 -1
  27. package/dist/update-check.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/boot-EEEVHAMO.js +0 -2
  30. package/dist/boot-EEEVHAMO.js.map +0 -7
  31. package/dist/chunk-GZNE5CBQ.js +0 -7
  32. package/dist/chunk-IVWPZEMC.js +0 -4
  33. package/dist/chunk-K46DOODL.js +0 -231
  34. package/dist/chunk-K46DOODL.js.map +0 -7
  35. package/dist/chunk-S45AAYXO.js +0 -4
  36. package/dist/chunk-S45AAYXO.js.map +0 -7
  37. package/dist/chunk-UO3FYLPX.js +0 -2
  38. package/dist/chunk-UO3FYLPX.js.map +0 -7
  39. package/dist/dev-wizard-run-5ST3BJ4L.js +0 -2
  40. package/dist/dev-wizard-run-5ST3BJ4L.js.map +0 -7
@@ -0,0 +1,2 @@
1
+ import{f as C,i as f,l as g}from"./chunk-7DL27USH.js";import{I as x,Q as v,v as u,w as b,x as y,y as k}from"./chunk-PZU6BLQR.js";import{e as w}from"./chunk-CHETBZ6M.js";import"./chunk-X46DP23W.js";import O from"@inquirer/checkbox";import _ from"@inquirer/confirm";import j,{Separator as I}from"@inquirer/select";import{loadDev as K}from"@slip-stream-kit/config/internal";import U from"node:path";import m from"node:process";var W=e=>e.split("/")[0],A=e=>new Map(e.apps.map(r=>[r.name,r])),D=e=>e.localCapable&&e.cloudCapable,N=(e,r,t)=>D(r)?t[`${e} ${r.path}`]??(r.cloudCapable?"cloud":"local"):r.localCapable?"local":"cloud",$=(e,r,t)=>{let a=new Set,o=new Map;for(let n of e){let s=r.get(W(n));for(let c of s?.backends??[]){o.set(c.packageName,c.ownerApp);for(let l of c.routes)N(n,l,t)==="local"&&a.add(c.packageName)}}return{localPkgs:a,ownerByPkg:o}},B=(e,r)=>{let t={},a=!1;for(let o of e?.backends??[]){let n=r.has(o.packageName);for(let s of o.routes){let c=s.localCapable&&n?"local":"cloud";t[s.path]=c,c==="cloud"&&(a=!0)}}return{overrides:t,anyCloud:a}},z=(e,r)=>{let t=A(r),a=e.targets.filter(p=>p.endsWith("/ui")),o=e.targets.filter(p=>p.endsWith("/api")),{localPkgs:n,ownerByPkg:s}=$(a,t,e.sources),c={},l=!1;for(let p of a){let{overrides:d,anyCloud:i}=B(t.get(W(p)),n);i&&(l=!0),c[p]=Object.keys(d).length>0?{proxy:d}:{}}for(let p of o)c[p]??={};for(let p of n){let d=s.get(p);d!=null&&(c[`${d}/api`]??={})}return{presetDef:{apps:c,cmux:e.cmux},anyCloudRoute:l,targetKeys:Object.keys(c).sort()}},M=(e,r)=>{let t=[`--target=${e.targetKeys.join(",")}`];return r.watch&&t.push("--watch"),r.cmux&&t.push("--cmux"),{flags:t.join(" ")}};var h={output:m.stderr,clearPromptOnDone:!0},q={select:e=>g(r=>j({message:e.message,choices:e.choices,default:e.default},r),h),checkbox:e=>g(r=>O({message:e.message,choices:e.choices},r),h),confirm:e=>g(r=>_({message:e.message,default:e.default},r),h)},E=(e,r)=>{let t=new Map;for(let[a,o]of Object.entries(e)){let n={path:a,localCapable:o.from.includes("local"),cloudCapable:o.from.includes("cloud"),default:o.default},s=t.get(o.packageName);s?(s.routes.push(n),s.localCapable=s.localCapable||n.localCapable,s.cloudCapable=s.cloudCapable||n.cloudCapable):t.set(o.packageName,{packageName:o.packageName,routes:[n],localCapable:n.localCapable,cloudCapable:n.cloudCapable,ownerApp:r.get(o.packageName)})}return[...t.values()]},T=async(e,r,t)=>{try{let a=(await K(e))?.proxy?.routes;return a?E(a,t):[]}catch(a){return u.warn(`\u26A0\uFE0F Skipping ${r}: its dev config failed to load \u2014 ${a instanceof Error?a.message:String(a)}`),[]}},V=async e=>{let r=y(e),t=k(e),a=await v(),o=new Map(r.map(i=>[i.packageName,i.name])),n=new Map(r.map(i=>[i.name,i.packageName])),s=new Set(t.map(i=>i.name)),c=new Set(r.map(i=>i.name)),l=[...new Set([...c,...s])].sort(),p=await Promise.all(l.map(async i=>{let P=s.has(i);return{name:i,hasApi:c.has(i),hasUi:P,apiPackage:n.get(i),backends:P?await T(U.join(e,"apps",i,"ui"),i,o):[]}})),d=await C();return{apps:p,presets:Object.keys(a.devServersPresets??{}),environments:Object.keys(d?.envs??{}).sort()}},F=e=>{let r=[];for(let t of e.apps){if(t.hasUi){let a=t.backends.flatMap(n=>n.routes.map(s=>s.path)),o=a.length>0?`frontend \u2014 proxies ${[...a].sort().join(", ")}`:"frontend";r.push({name:`${t.name}/ui`,value:`${t.name}/ui`,description:o})}t.hasApi&&!t.hasUi&&r.push({name:`${t.name}/api`,value:`${t.name}/api`,description:"backend"})}return r},L=e=>{let r={api:e.apps.filter(o=>o.hasApi).map(o=>o.name),ui:e.apps.filter(o=>o.hasUi).map(o=>o.name)},t={},a=new Map;for(let o of e.apps){o.apiPackage!=null&&(t[o.name]=o.apiPackage);for(let n of o.backends)for(let s of n.routes)a.set(`${o.name} ${s.path}`,n.packageName)}return{discovered:r,apiPkgByApp:t,routePkg:(o,n)=>a.get(`${o} ${n}`)}},X=(e,r)=>x({__wizard__:e},L(r)).map(t=>t.message),Z="INFRA_KIT_DEV_WIZARD_CMUX",H=()=>m.env[Z]==="1",G=async(e,r,t)=>{let a=new Map(r.apps.map(n=>[n.name,n])),o={};for(let n of t){let s=a.get(n.split("/")[0]);for(let c of s?.backends??[])for(let l of c.routes){if(!l.localCapable||!l.cloudCapable)continue;let p=await e.select({message:`\u{1F500} ${n} ${l.path} \u2192 local or cloud?`,choices:[{name:"local (this machine)",value:"local"},{name:"cloud",value:"cloud"}],default:l.default??"local"});o[`${n} ${l.path}`]=p}}return o},J=(e,r,t)=>e.apps.find(a=>a.name===r)?.backends.flatMap(a=>a.routes).find(a=>a.path===t),Q=(e,r)=>{let t=[];for(let[a,o]of Object.entries(e.presetDef.apps??{})){if(!a.endsWith("/ui")||!o.proxy)continue;let n=a.split("/")[0];for(let[s,c]of Object.entries(o.proxy)){let l=J(r,n,s),p=l&&l.localCapable&&l.cloudCapable?"":" (only option)";t.push(` ${a} ${s} \u2192 ${c}${p}`)}}if(t.length!==0){u.info("Resolved routes:");for(let a of[...t].sort())u.info(a)}},R=async(e,r)=>{if(r.apps.length===0)return u.warn("No apps discovered to run."),null;let t=await e.checkbox({message:"\u{1F4E6} Which packages?",choices:F(r)});if(t.length===0)return u.warn("No packages selected."),null;let a=t.filter(i=>i.endsWith("/ui")),o=await G(e,r,a),n=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!1}),s=H()?await e.confirm({message:"\u{1F9E9} Run each app in its own cmux pane?",default:!1}):!1,c={targets:t,sources:o,watch:n,cmux:s},l=z(c,r);if(l.anyCloudRoute){if(r.environments.length===0)return u.warn("\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded."),u.warn(" Run `infra-kit env-load` to add one, then re-run the wizard."),null;c.env=await e.select({message:"\u2601\uFE0F Point cloud routes at which environment?",choices:r.environments.map(i=>({name:i,value:i}))}),m.env[w]=c.env}let p=X(l.presetDef,r);if(p.length>0){u.warn("\u26A0\uFE0F Proxy audit found issues with this selection:");for(let i of p)u.warn(` \u2022 ${i}`);return null}Q(l,r),Y(l,c);let d=l.targetKeys.filter(i=>i.endsWith("/api")).map(i=>i.split("/")[0]);return s&&d.length>0?{include:d,presetDef:l.presetDef,watch:n,cmux:!0}:(s&&u.info("\u2139\uFE0F cmux needs at least one local backend (panes are backend-only) \u2014 running in-process instead."),{presetDef:l.presetDef,watch:n,cmux:!1})},Y=(e,r)=>{f.setInteractive();let t=M(e,r);f.addOption(t.flags,!0),f.print(),u.info("\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.")},ee=async(e,r)=>{let t=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!1});return f.setInteractive(),f.addOption(r,!0),t&&f.addOption("--watch",!0),f.print(),{preset:r,watch:t,cmux:!1}},S=" manual",re=async(e,r)=>{if(r.presets.length===0)return R(e,r);let t=await e.select({message:"\u{1F680} Start from a preset, or configure manually?",choices:[...r.presets.map(a=>({name:a,value:a})),new I(" "),{name:"Manual (custom)\u2026",value:S}]});return t===S?R(e,r):ee(e,t)},be=async(e=q,r=b(m.cwd()))=>re(e,await V(r));export{S as MANUAL_CHOICE,Z as WIZARD_CMUX_VAR,X as auditManualPlan,q as defaultPrompts,V as gatherWizardModel,T as loadBackends,be as runDevWizard,re as runWizardFlow};
2
+ //# sourceMappingURL=dev-wizard-run-KIOSJM4D.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/dev-wizard-run.ts", "../src/dev/dev-wizard.ts"],
4
+ "sourcesContent": ["/**\n * Impure driver for the interactive `infra-kit dev` wizard: filesystem/config discovery, the inquirer\n * prompt flow (step-0 preset-or-manual, then the manual matrix), the pre-flight proxy audit, and the\n * `commandEcho` teaching line. The pure answer\u2192plan mapping lives in {@link file://./dev-wizard.ts}.\n *\n * Prompts are behind the injectable {@link WizardPrompts} seam so the flow is testable without a TTY.\n * This module is reached ONLY from the bare-invocation TTY branch of the entry point; every flagged /\n * non-TTY / `--json` / MCP invocation bypasses it entirely.\n */\nimport inquirerCheckbox from '@inquirer/checkbox'\nimport inquirerConfirm from '@inquirer/confirm'\nimport inquirerSelect, { Separator } from '@inquirer/select'\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { discoverApiApps, discoverUiApps, findMonorepoRoot } from 'src/dev/discovery'\nimport { commandEcho } from 'src/lib/command-echo'\nimport { INFRA_KIT_ENV_VAR } from 'src/lib/constants'\nimport { readTokenStore } from 'src/lib/env-tokens'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport type { DevPreset, ProxySource } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { deriveManualPlan, equivalentCommand } from './dev-wizard.js'\nimport type { DerivedPlan, ManualSelection, ProxyBackend, RouteCap, WizardApp, WizardModel } from './dev-wizard.js'\nimport { validatePresetProxy } from './presets.js'\nimport type { DiscoveredParts, PresetProxyContext } from './presets.js'\n\n/** A wizard prompt choice \u2014 all values are strings, so the seam needs no generics. */\nexport interface WizardChoice {\n name: string\n value: string\n description?: string\n checked?: boolean\n disabled?: boolean | string\n}\n\n/**\n * Injectable prompt seam (a string-valued subset of `@inquirer/*`). The default implementation\n * ({@link defaultPrompts}) delegates to the real prompts, rendering to stderr so the dev-server's\n * stdout stays clean. Tests pass a scripted object.\n */\nexport interface WizardPrompts {\n select: (cfg: { message: string; choices: (WizardChoice | Separator)[]; default?: string }) => Promise<string>\n checkbox: (cfg: { message: string; choices: WizardChoice[] }) => Promise<string[]>\n confirm: (cfg: { message: string; default?: boolean }) => Promise<boolean>\n}\n\n/**\n * Shared `@inquirer/*` context. Rendered to stderr (mirrors the bare-`infra-kit` command palette).\n *\n * `clearPromptOnDone` erases each answered prompt instead of leaving a `\u2714 <question> <answer>` line\n * behind, so the wizard collapses to nothing once it finishes and the dev-server's ready header lands\n * at the top of a clean screen. The choices are not lost: {@link echoManual} / {@link runPresetBranch}\n * print the equivalent flag command, which is the durable record of what was picked.\n */\nconst promptContext = { output: process.stderr, clearPromptOnDone: true }\n\n/**\n * Real `@inquirer/*` prompts, rendered to stderr and erased once answered.\n *\n * Every one goes through {@link withEscape}, which binds Esc to cancellation. The wrap is here rather\n * than around the {@link WizardPrompts} seam so the scripted prompts the tests inject stay untouched:\n * the seam is the test boundary, `defaultPrompts` is the only implementation that talks to a terminal.\n *\n * Esc rejects with an `AbortPromptError`, which `entry/cli.ts` catches as a cancellation \u2192 exit 0. The\n * wizard therefore needs no cancel branch of its own: a cancelled prompt never returns here at all, so\n * no server is started.\n */\nexport const defaultPrompts: WizardPrompts = {\n select: (cfg) => {\n return withEscape((context) => {\n return inquirerSelect({ message: cfg.message, choices: cfg.choices, default: cfg.default }, context)\n }, promptContext)\n },\n checkbox: (cfg) => {\n return withEscape((context) => {\n return inquirerCheckbox({ message: cfg.message, choices: cfg.choices }, context)\n }, promptContext)\n },\n confirm: (cfg) => {\n return withEscape((context) => {\n return inquirerConfirm({ message: cfg.message, default: cfg.default }, context)\n }, promptContext)\n },\n}\n\n/** What the wizard hands back to the entry point (merged into `DevServerOptions`), or null on cancel. */\nexport interface WizardResult {\n /** Named preset (preset branch) \u2014 passed through as `options.preset`. */\n preset?: string\n /** In-memory preset (manual branch, non-cmux) \u2014 passed through as `options.presetDef`. */\n presetDef?: DevPreset\n /**\n * App-name include list for the cmux path only: which discovered API apps get a pane. Paired with\n * `presetDef`, which tells each pane the exact parts to run. An app selected UI-only gets no pane\n * (cmux panes are opened per API app). Unset for the non-cmux manual path.\n */\n include?: string[]\n watch: boolean\n cmux: boolean\n}\n\n/** Group one frontend's `dev.proxy.routes` into {@link ProxyBackend}s keyed by backend package. */\nconst groupBackends = (\n routes: Record<string, { packageName: string; from: readonly string[]; default?: 'local' | 'cloud' }>,\n ownerByPkg: Map<string, string>,\n): ProxyBackend[] => {\n const byPkg = new Map<string, ProxyBackend>()\n\n for (const [route, def] of Object.entries(routes)) {\n const cap: RouteCap = {\n path: route,\n localCapable: def.from.includes('local'),\n cloudCapable: def.from.includes('cloud'),\n default: def.default,\n }\n const existing = byPkg.get(def.packageName)\n\n if (existing) {\n existing.routes.push(cap)\n existing.localCapable = existing.localCapable || cap.localCapable\n existing.cloudCapable = existing.cloudCapable || cap.cloudCapable\n } else {\n byPkg.set(def.packageName, {\n packageName: def.packageName,\n routes: [cap],\n localCapable: cap.localCapable,\n cloudCapable: cap.cloudCapable,\n ownerApp: ownerByPkg.get(def.packageName),\n })\n }\n }\n\n return [...byPkg.values()]\n}\n\n/**\n * Load one frontend's proxy routes and group them into backends. A config that throws \u2014 schema-invalid\n * or an import-time error \u2014 degrades THAT app to zero backends with a named warning instead of rejecting.\n * Without this, a single broken `apps/<x>/ui/infra-kit.config.ts` fails the whole `Promise.all` in\n * {@link gatherWizardModel} and takes the entire wizard down, so `infra-kit dev` becomes unusable for every\n * other app in the monorepo. Mirrors the audit path's per-app guard ({@link file://../commands/audit/preset-proxy-check.ts}).\n */\nexport const loadBackends = async (\n uiDir: string,\n name: string,\n ownerByPkg: Map<string, string>,\n): Promise<ProxyBackend[]> => {\n try {\n const routes = (await loadDev(uiDir))?.proxy?.routes\n\n return routes ? groupBackends(routes, ownerByPkg) : []\n } catch (error) {\n logger.warn(\n `\u26A0\uFE0F Skipping ${name}: its dev config failed to load \u2014 ${error instanceof Error ? error.message : String(error)}`,\n )\n\n return []\n }\n}\n\n/** Discover apps + configs and assemble the {@link WizardModel} (backends resolved per frontend). */\nexport const gatherWizardModel = async (root: string): Promise<WizardModel> => {\n const apiApps = discoverApiApps(root)\n const uiApps = discoverUiApps(root)\n const config = await getInfraKitConfig()\n\n const ownerByPkg = new Map(\n apiApps.map((a) => {\n return [a.packageName, a.name] as const\n }),\n )\n const apiPkgByName = new Map(\n apiApps.map((a) => {\n return [a.name, a.packageName] as const\n }),\n )\n const uiNames = new Set(\n uiApps.map((a) => {\n return a.name\n }),\n )\n const apiNames = new Set(\n apiApps.map((a) => {\n return a.name\n }),\n )\n const allNames = [...new Set([...apiNames, ...uiNames])].sort()\n\n const apps: WizardApp[] = await Promise.all(\n allNames.map(async (name): Promise<WizardApp> => {\n const hasUi = uiNames.has(name)\n\n return {\n name,\n hasApi: apiNames.has(name),\n hasUi,\n apiPackage: apiPkgByName.get(name),\n backends: hasUi ? await loadBackends(path.join(root, 'apps', name, 'ui'), name, ownerByPkg) : [],\n }\n }),\n )\n\n // The cloud-env choices are the envs we hold a token for \u2014 the same authority as `env-load`, because\n // it is the same question. This picker writes INFRA_KIT_ENV, which `@slip-stream-kit/config/vite`\n // reads to build the cloud backend's URL, and whose only other writer is `env-load` (which cannot run\n // without a Doppler token). Sourcing it from the workflow options instead would put `prod` in the list\n // for everyone \u2014 including a developer holding no prod credential \u2014 and point a local UI at\n // production. No token, no entry.\n const store = await readTokenStore()\n\n return {\n apps,\n presets: Object.keys(config.devServersPresets ?? {}),\n environments: Object.keys(store?.envs ?? {}).sort(),\n }\n}\n\n/**\n * Build the checkbox choices: one `<app>/ui` per frontend, plus `<app>/api` ONLY for api-only apps\n * (an api with no ui). A full-stack `<app>/api` is deliberately NOT offered \u2014 a full-stack backend is\n * launched by choosing `local` for one of its frontend's routes (asked per-route afterwards), so the\n * checkbox stays a pick of frontends + standalone backends.\n *\n * Nothing starts checked: the manual branch is opt-in, so a run only ever launches what was explicitly\n * ticked. Pre-checking every part would make the fast path (accept the defaults) boot the whole monorepo\n * \u2014 the exact opposite of why someone reached for \"Manual\" over a preset.\n */\nconst buildPartChoices = (model: WizardModel): WizardChoice[] => {\n const choices: WizardChoice[] = []\n\n for (const app of model.apps) {\n if (app.hasUi) {\n const paths = app.backends.flatMap((b) => {\n return b.routes.map((r) => {\n return r.path\n })\n })\n const description = paths.length > 0 ? `frontend \u2014 proxies ${[...paths].sort().join(', ')}` : 'frontend'\n\n choices.push({ name: `${app.name}/ui`, value: `${app.name}/ui`, description })\n }\n if (app.hasApi && !app.hasUi) {\n choices.push({ name: `${app.name}/api`, value: `${app.name}/api`, description: 'backend' })\n }\n }\n\n return choices\n}\n\n/** Build the audit context from the gathered model (no re-reading of configs). */\nconst buildAuditContext = (model: WizardModel): PresetProxyContext => {\n const discovered: DiscoveredParts = {\n api: model.apps\n .filter((a) => {\n return a.hasApi\n })\n .map((a) => {\n return a.name\n }),\n ui: model.apps\n .filter((a) => {\n return a.hasUi\n })\n .map((a) => {\n return a.name\n }),\n }\n const apiPkgByApp: Record<string, string> = {}\n const routeToPkg = new Map<string, string>()\n\n for (const app of model.apps) {\n // Map EVERY discovered api app to its own api package \u2014 including api-only apps a frontend proxies\n // to cross-app \u2014 so `launchedPkgs` in validatePresetProxy is faithful (mirrors preset-proxy-check.ts).\n // Deriving this from proxy backends alone would miss api-only owners and false-positive the audit.\n if (app.apiPackage != null) apiPkgByApp[app.name] = app.apiPackage\n for (const b of app.backends) {\n for (const route of b.routes) {\n routeToPkg.set(`${app.name} ${route.path}`, b.packageName)\n }\n }\n }\n\n return {\n discovered,\n apiPkgByApp,\n routePkg: (app, route) => {\n return routeToPkg.get(`${app} ${route}`)\n },\n }\n}\n\n/**\n * Run the assembled plan through the SAME proxy-locality rule the root audit uses. Returns issue\n * messages (empty when clean). Catches a `local` override whose backend won't launch \u2014 the wizard's\n * derivation launches owners, so a hit means the backend has no discoverable owning app.\n */\nexport const auditManualPlan = (presetDef: DevPreset, model: WizardModel): string[] => {\n return validatePresetProxy({ __wizard__: presetDef }, buildAuditContext(model)).map((i) => {\n return i.message\n })\n}\n\n/**\n * Opt back into the cmux question: set to exactly `'1'`. The prompt is temporarily off \u2014 the manual\n * branch always runs in-process \u2014 but the derivation below is kept whole for when it returns. `--cmux`\n * on the command line is a separate path and stays live either way.\n */\nexport const WIZARD_CMUX_VAR = 'INFRA_KIT_DEV_WIZARD_CMUX'\n\nconst asksCmux = (): boolean => {\n return process.env[WIZARD_CMUX_VAR] === '1'\n}\n\n/**\n * Ask, per selected frontend, an EXPLICIT local/cloud choice for every TWO-OPTION route (its `from`\n * lists both). Single-option routes are auto-picked in the pure mapping, so they are never prompted.\n * The answers are keyed `${app}/ui ${routePath}` to match {@link ManualSelection.sources}; the select's\n * default seeds from the route's declared `default` when it has one.\n */\nconst promptRouteSources = async (\n prompts: WizardPrompts,\n model: WizardModel,\n uiKeys: string[],\n): Promise<Record<string, ProxySource>> => {\n const apps = new Map(\n model.apps.map((a) => {\n return [a.name, a] as const\n }),\n )\n const sources: Record<string, ProxySource> = {}\n\n for (const key of uiKeys) {\n const app = apps.get(key.split('/')[0]!)\n\n for (const backend of app?.backends ?? []) {\n for (const route of backend.routes) {\n if (!route.localCapable || !route.cloudCapable) continue\n\n const answer = await prompts.select({\n message: `\uD83D\uDD00 ${key} ${route.path} \u2192 local or cloud?`,\n choices: [\n { name: 'local (this machine)', value: 'local' },\n { name: 'cloud', value: 'cloud' },\n ],\n default: route.default ?? 'local',\n })\n\n sources[`${key} ${route.path}`] = answer as ProxySource\n }\n }\n }\n\n return sources\n}\n\n/** Look up a frontend route's capability in the model (for the recap's \"only option\" annotation). */\nconst findRouteCap = (model: WizardModel, app: string, routePath: string): RouteCap | undefined => {\n return model.apps\n .find((a) => {\n return a.name === app\n })\n ?.backends.flatMap((b) => {\n return b.routes\n })\n .find((r) => {\n return r.path === routePath\n })\n}\n\n/**\n * Print a one-line-per-route recap of what each frontend route resolved to, so the chosen sources are\n * visible before launch. A single-option route is annotated `(only option)` \u2014 it was auto-picked, not\n * asked. This is in addition to {@link echoManual}'s pasteable `--target` command.\n */\nconst recapSources = (plan: DerivedPlan, model: WizardModel): void => {\n const lines: string[] = []\n\n for (const [key, cfg] of Object.entries(plan.presetDef.apps ?? {})) {\n if (!key.endsWith('/ui') || !cfg.proxy) continue\n\n const app = key.split('/')[0]!\n\n for (const [routePath, source] of Object.entries(cfg.proxy)) {\n const cap = findRouteCap(model, app, routePath)\n const suffix = cap && cap.localCapable && cap.cloudCapable ? '' : ' (only option)'\n\n lines.push(` ${key} ${routePath} \u2192 ${source}${suffix}`)\n }\n }\n\n if (lines.length === 0) return\n logger.info('Resolved routes:')\n for (const line of [...lines].sort()) {\n logger.info(line)\n }\n}\n\n/** The manual-branch flow: frontends + per-route source + env + watch + cmux \u2192 audited plan \u2192 recap \u2192 echo. */\nconst runManualBranch = async (prompts: WizardPrompts, model: WizardModel): Promise<WizardResult | null> => {\n if (model.apps.length === 0) {\n logger.warn('No apps discovered to run.')\n\n return null\n }\n\n const selectedTargets = await prompts.checkbox({ message: '\uD83D\uDCE6 Which packages?', choices: buildPartChoices(model) })\n\n if (selectedTargets.length === 0) {\n logger.warn('No packages selected.')\n\n return null\n }\n\n const uiKeys = selectedTargets.filter((t) => {\n return t.endsWith('/ui')\n })\n const sources = await promptRouteSources(prompts, model, uiKeys)\n\n const watch = await prompts.confirm({ message: '\uD83D\uDC40 Rebuild & restart on save (watch)?', default: false })\n const cmux = asksCmux()\n ? await prompts.confirm({ message: '\uD83E\uDDE9 Run each app in its own cmux pane?', default: false })\n : false\n\n const selection: ManualSelection = { targets: selectedTargets, sources, watch, cmux }\n const plan = deriveManualPlan(selection, model)\n\n if (plan.anyCloudRoute) {\n // A cloud route needs an environment to point at, and the only environments we can offer are those we\n // hold a token for. With none loaded, the `select` below would be handed zero choices and `@inquirer/select`\n // throws `No selectable choices` \u2014 a raw stack on a realistic first-run path (fresh clone, no `env-load`).\n // Back out cleanly with guidance instead, and BEFORE mutating `process.env`, so a refused run leaks nothing.\n if (model.environments.length === 0) {\n logger.warn('\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded.')\n logger.warn(' Run `infra-kit env-load` to add one, then re-run the wizard.')\n\n return null\n }\n\n selection.env = await prompts.select({\n message: '\u2601\uFE0F Point cloud routes at which environment?',\n choices: model.environments.map((e) => {\n return { name: e, value: e }\n }),\n })\n process.env[INFRA_KIT_ENV_VAR] = selection.env\n }\n\n const issues = auditManualPlan(plan.presetDef, model)\n\n if (issues.length > 0) {\n logger.warn('\u26A0\uFE0F Proxy audit found issues with this selection:')\n for (const issue of issues) {\n logger.warn(` \u2022 ${issue}`)\n }\n\n return null\n }\n\n recapSources(plan, model)\n echoManual(plan, selection)\n\n // cmux opens one pane per selected API app. `include` picks WHICH apps get a pane; `presetDef` tells\n // each pane exactly which of its parts to run. Without the latter a pane runs `--app=<name>`, which\n // expands to every part the app has \u2014 silently starting a UI the user just unticked.\n const apiApps = plan.targetKeys\n .filter((k) => {\n return k.endsWith('/api')\n })\n .map((k) => {\n return k.split('/')[0]!\n })\n\n // An empty include would collapse to `null` in `normalizeAppInclude` and make cmux run EVERY api app,\n // so a cmux run with no selected backends (e.g. an all-frontend selection) falls back to in-process.\n if (cmux && apiApps.length > 0) {\n return { include: apiApps, presetDef: plan.presetDef, watch, cmux: true }\n }\n\n if (cmux) {\n logger.info('\u2139\uFE0F cmux needs at least one local backend (panes are backend-only) \u2014 running in-process instead.')\n }\n\n return { presetDef: plan.presetDef, watch, cmux: false }\n}\n\n/** Print the equivalent (`--target=\u2026`) flag command, plus a save-as-preset ergonomics hint. */\nconst echoManual = (plan: DerivedPlan, selection: ManualSelection): void => {\n commandEcho.setInteractive()\n\n const eq = equivalentCommand(plan, selection)\n\n commandEcho.addOption(eq.flags, true)\n commandEcho.print()\n\n // The `--target=\u2026` line reproduces the selection exactly; the preset is pure convenience \u2014 a short,\n // memorable name instead of retyping the target keys.\n logger.info('\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.')\n}\n\n/** The preset-branch flow: run a named preset, asking only whether to watch (presets can't encode it). */\nconst runPresetBranch = async (prompts: WizardPrompts, preset: string): Promise<WizardResult> => {\n const watch = await prompts.confirm({ message: '\uD83D\uDC40 Rebuild & restart on save (watch)?', default: false })\n\n commandEcho.setInteractive()\n commandEcho.addOption(preset, true)\n if (watch) commandEcho.addOption('--watch', true)\n commandEcho.print()\n\n return { preset, watch, cmux: false }\n}\n\n/** Sentinel value for the \"Manual (custom)\" step-0 choice (a preset name can never be empty). */\nexport const MANUAL_CHOICE = ' manual'\n\n/**\n * Drive the wizard's branch flow over an ALREADY-gathered model (no disk/config access). Split from\n * {@link runDevWizard} so the flow is unit-testable with scripted prompts + a fixture model.\n */\nexport const runWizardFlow = async (prompts: WizardPrompts, model: WizardModel): Promise<WizardResult | null> => {\n if (model.presets.length === 0) {\n return runManualBranch(prompts, model)\n }\n\n const choice = await prompts.select({\n message: '\uD83D\uDE80 Start from a preset, or configure manually?',\n choices: [\n ...model.presets.map((p) => {\n return { name: p, value: p }\n }),\n new Separator(' '),\n { name: 'Manual (custom)\u2026', value: MANUAL_CHOICE },\n ],\n })\n\n return choice === MANUAL_CHOICE ? runManualBranch(prompts, model) : runPresetBranch(prompts, choice)\n}\n\n/**\n * Gather the model from disk/config, then drive the wizard flow, returning the resolved run options (or\n * null on cancel / empty selection). The entry point calls this on a bare TTY `infra-kit dev`.\n */\nexport const runDevWizard = async (\n prompts: WizardPrompts = defaultPrompts,\n root: string = findMonorepoRoot(process.cwd()),\n): Promise<WizardResult | null> => {\n return runWizardFlow(prompts, await gatherWizardModel(root))\n}\n", "/**\n * Pure core of the interactive `infra-kit dev` wizard (the no-args, TTY path).\n *\n * The wizard is FRONTEND-CENTRIC: you pick which frontends to run, and for each frontend you choose,\n * every proxy route that has TWO real options (its `from` lists both `local` and `cloud`) is decided\n * EXPLICITLY \u2014 local (its backend is launched \u2192 the route resolves local) or cloud (the route proxies\n * to the `<env>` cloud target). Single-option routes are auto-picked. Because a backend runs local OR\n * cloud as a whole, routes that share one backend package RECONCILE: if any of them resolved local, the\n * backend runs local and all its local-capable routes follow. This module turns those answers into an\n * in-memory {@link DevPreset} the runner consumes verbatim (part-level targets the app-name-only `--app`\n * include cannot express) \u2014 and is side-effect-free so the mapping is fully unit-testable. The impure\n * I/O (discovery, inquirer prompts, audit, launch) lives in {@link file://./dev-wizard-run.ts}.\n */\nimport type { DevPreset, ProxySource } from 'src/lib/infra-kit-config'\n\n/**\n * One proxy route's per-route capability, carried through grouping so the wizard can decide whether it\n * even needs to ask about the route (only a `local`+`cloud` route is a real choice).\n */\nexport interface RouteCap {\n /** Route path (e.g. `/api`). */\n path: string\n /** `from` includes `local` \u2014 the route can resolve to a locally-launched backend. */\n localCapable: boolean\n /** `from` includes `cloud` \u2014 the route can resolve to the cloud target. */\n cloudCapable: boolean\n /** The route's declared `default` source when it has one (present iff `from` lists >1 source) \u2014 seeds the prompt's default. */\n default?: ProxySource\n}\n\n/**\n * One backend a frontend's proxy routes can be pointed at, grouped by the backend package. A frontend\n * that maps `/api` and `/media` to the same package yields ONE {@link ProxyBackend} with both routes \u2014\n * launching the package flips every one of its `local`-capable routes together (the reconcile in\n * {@link deriveManualPlan}).\n */\nexport interface ProxyBackend {\n /** Backend package name (a route's `packageName`). */\n packageName: string\n /** The routes that resolve to this package, each with its own local/cloud capability. */\n routes: RouteCap[]\n /** True when at least one of `routes` lists `local` in its `from` capabilities \u2014 i.e. it is launchable-local. */\n localCapable: boolean\n /** True when at least one of `routes` lists `cloud` \u2014 i.e. it can stay on the cloud target. */\n cloudCapable: boolean\n /** App folder whose `api` package is {@link packageName}, or undefined when no discovered app owns it (a `local` choice then has nothing to launch \u2014 the audit flags it). */\n ownerApp?: string\n}\n\n/** A discovered app as the wizard sees it: which parts exist + which backends its frontend proxies to. */\nexport interface WizardApp {\n /** App folder name (e.g. `client`). */\n name: string\n /** Has `apps/<app>/api` (a launchable backend). */\n hasApi: boolean\n /** Has `apps/<app>/ui` (a launchable frontend). */\n hasUi: boolean\n /**\n * This app's OWN `api` package name (from `apps/<app>/api`), or undefined when it has no api. Carried\n * so the audit can build a faithful `app \u2192 apiPackage` map for EVERY discovered api app \u2014 including\n * api-only apps a frontend proxies to cross-app \u2014 mirroring the root audit (`preset-proxy-check.ts`).\n */\n apiPackage?: string\n /** Backends this app's frontend proxies to (empty for api-only apps or a frontend with no `dev.proxy`). */\n backends: ProxyBackend[]\n}\n\n/** Everything the wizard needs, gathered impurely by {@link file://./dev-wizard-run.ts}. */\nexport interface WizardModel {\n /** All discovered apps (api and/or ui), sorted by name. */\n apps: WizardApp[]\n /** `devServersPresets` names (drives the preset-or-manual step-0). */\n presets: string[]\n /** Configured `environments` (the cloud-env `select` options). */\n environments: string[]\n}\n\n/** The manual-branch answers collected from the prompts, fed to {@link deriveManualPlan}. */\nexport interface ManualSelection {\n /**\n * The target keys the user ticked directly: every selected `<app>/ui` frontend, plus any api-only\n * `<app>/api` backend (apps with an api but no ui). A full-stack backend is NOT ticked here \u2014 it is\n * launched by choosing `local` for one of its frontend's routes (recorded in {@link sources}).\n */\n targets: string[]\n /**\n * Explicit per-route choice for every TWO-OPTION route, keyed `${app}/ui ${routePath}` (e.g.\n * `client/ui /api`). Single-option routes are absent (auto-picked). Missing two-option answers fall\n * back to the route's cloud/local capability in {@link deriveManualPlan}.\n */\n sources: Record<string, ProxySource>\n /** Chosen cloud env for cloud routes (undefined when nothing resolves cloud). */\n env?: string\n /** Rebuild + restart on save. */\n watch: boolean\n /** One cmux pane per app. */\n cmux: boolean\n}\n\n/** The resolved run plan derived from a {@link ManualSelection}. */\nexport interface DerivedPlan {\n /** In-memory preset handed to the runner (`options.presetDef`). */\n presetDef: DevPreset\n /** At least one route resolves to cloud \u2192 an env must be chosen (pre-flight gate). */\n anyCloudRoute: boolean\n /** Resolved `<app>/<part>` target keys, sorted \u2014 for the echo + audit display. */\n targetKeys: string[]\n}\n\n/** App folder name from an `<app>/<part>` target key. */\nconst appOf = (key: string): string => {\n return key.split('/')[0]!\n}\n\n/** Index a model's apps by folder name for O(1) lookup. */\nconst byName = (model: WizardModel): Map<string, WizardApp> => {\n return new Map(\n model.apps.map((a) => {\n return [a.name, a]\n }),\n )\n}\n\n/** Is this route a real choice (both local and cloud reachable)? */\nconst isTwoOption = (route: RouteCap): boolean => {\n return route.localCapable && route.cloudCapable\n}\n\n/**\n * The source a single route resolves to BEFORE per-backend reconciliation:\n * - two-option: the user's recorded answer, else 'cloud' when cloud-capable else 'local';\n * - single local-only: always 'local';\n * - single cloud-only: always 'cloud'.\n */\nconst rawSource = (uiKey: string, route: RouteCap, sources: Record<string, ProxySource>): ProxySource => {\n if (isTwoOption(route)) {\n return sources[`${uiKey} ${route.path}`] ?? (route.cloudCapable ? 'cloud' : 'local')\n }\n\n return route.localCapable ? 'local' : 'cloud'\n}\n\n/**\n * Pass 1: which backend packages resolve local (any of their routes did), plus each package's owner app.\n * A package's local verdict is shared across every frontend that proxies to it \u2014 that is the reconcile.\n */\nconst collectLocalPackages = (\n uiKeys: string[],\n apps: Map<string, WizardApp>,\n sources: Record<string, ProxySource>,\n): { localPkgs: Set<string>; ownerByPkg: Map<string, string | undefined> } => {\n const localPkgs = new Set<string>()\n const ownerByPkg = new Map<string, string | undefined>()\n\n for (const key of uiKeys) {\n const app = apps.get(appOf(key))\n\n for (const backend of app?.backends ?? []) {\n ownerByPkg.set(backend.packageName, backend.ownerApp)\n for (const route of backend.routes) {\n if (rawSource(key, route, sources) === 'local') localPkgs.add(backend.packageName)\n }\n }\n }\n\n return { localPkgs, ownerByPkg }\n}\n\n/**\n * Pass 2 for ONE frontend: its per-route overrides after the per-package verdict, and whether any route\n * went cloud. A local-capable route on a local package is `local` (reconciled up); everything else `cloud`.\n */\nconst frontendOverrides = (\n app: WizardApp | undefined,\n localPkgs: ReadonlySet<string>,\n): { overrides: Record<string, ProxySource>; anyCloud: boolean } => {\n const overrides: Record<string, ProxySource> = {}\n let anyCloud = false\n\n for (const backend of app?.backends ?? []) {\n const backendLocal = localPkgs.has(backend.packageName)\n\n for (const route of backend.routes) {\n const source: ProxySource = route.localCapable && backendLocal ? 'local' : 'cloud'\n\n overrides[route.path] = source\n if (source === 'cloud') anyCloud = true\n }\n }\n\n return { overrides, anyCloud }\n}\n\n/**\n * Turn the manual {@link ManualSelection} into an in-memory {@link DevPreset}. The frontend checkbox picks\n * which UIs (and standalone api-only backends) to run; the per-route answers in {@link ManualSelection.sources}\n * decide each two-option route. Resolution is two passes so same-backend routes stay coherent:\n *\n * 1. Resolve every route of every selected frontend to its raw source; a package is LOCAL iff any of its\n * routes resolved local.\n * 2. Re-resolve each route against that per-package verdict: a local-capable route on a local package is\n * `local` (reconciled up even if it was individually answered cloud); a cloud-only route stays `cloud`.\n *\n * Launched backends are the ticked api-only parts \u222A every package that resolved local (added as\n * `${ownerApp}/api` when the owner is discoverable \u2014 a local override on an owner-less package is still\n * emitted, and the audit flags it).\n *\n * @example\n * // client frontend, its /api answered local \u2192 launches client/api + client/ui, /api resolves local:\n * deriveManualPlan(\n * { targets: ['client/ui'], sources: { 'client/ui /api': 'local' }, watch: false, cmux: false },\n * { apps: [{ name: 'client', hasApi: true, hasUi: true,\n * backends: [{ packageName: 'client-api', cloudCapable: true, localCapable: true,\n * routes: [{ path: '/api', localCapable: true, cloudCapable: true }],\n * ownerApp: 'client' }] }],\n * presets: [], environments: ['dev'] },\n * ).targetKeys // => ['client/api', 'client/ui']\n */\nexport const deriveManualPlan = (selection: ManualSelection, model: WizardModel): DerivedPlan => {\n const apps = byName(model)\n const uiKeys = selection.targets.filter((t) => {\n return t.endsWith('/ui')\n })\n const apiOnlyKeys = selection.targets.filter((t) => {\n return t.endsWith('/api')\n })\n\n // Pass 1: a package is local iff any of its routes (across every selected frontend) resolved local.\n const { localPkgs, ownerByPkg } = collectLocalPackages(uiKeys, apps, selection.sources)\n\n // Pass 2: re-resolve each route against the per-package verdict + build per-frontend overrides.\n const presetApps: Record<string, { proxy?: Record<string, ProxySource> }> = {}\n let anyCloud = false\n\n for (const key of uiKeys) {\n const { overrides, anyCloud: cloud } = frontendOverrides(apps.get(appOf(key)), localPkgs)\n\n if (cloud) anyCloud = true\n presetApps[key] = Object.keys(overrides).length > 0 ? { proxy: overrides } : {}\n }\n\n // Launch: the ticked api-only backends, plus every package that resolved local (via its owner app).\n for (const key of apiOnlyKeys) {\n presetApps[key] ??= {}\n }\n for (const pkg of localPkgs) {\n const owner = ownerByPkg.get(pkg)\n\n if (owner != null) presetApps[`${owner}/api`] ??= {}\n }\n\n return {\n presetDef: { apps: presetApps, cmux: selection.cmux },\n anyCloudRoute: anyCloud,\n targetKeys: Object.keys(presetApps).sort(),\n }\n}\n\n/** The equivalent non-interactive command for a derived plan. */\nexport interface EquivalentCommand {\n /** The `--target=<app>/<part>,\u2026`-form flag string (no leading `infra-kit dev`). */\n flags: string\n}\n\n/**\n * Build the equivalent `infra-kit dev --target=\u2026 [--watch] [--cmux]` flag string for a derived plan.\n * Always exact: `--target` names packages at `<app>/<part>` granularity \u2014 the same grammar the plan's\n * `targetKeys` already use \u2014 so every wizard selection, whole-app or part-level, round-trips into a\n * pasteable command. (`--app` is deliberately NOT used here: its app-name granularity over-launches a\n * part-level pick \u2014 `--app=client` starts `client/api` even when only `client/ui` was ticked.)\n */\nexport const equivalentCommand = (plan: DerivedPlan, selection: ManualSelection): EquivalentCommand => {\n const parts = [`--target=${plan.targetKeys.join(',')}`]\n\n if (selection.watch) parts.push('--watch')\n if (selection.cmux) parts.push('--cmux')\n\n return { flags: parts.join(' ') }\n}\n"],
5
+ "mappings": "qMASA,OAAOA,MAAsB,qBAC7B,OAAOC,MAAqB,oBAC5B,OAAOC,GAAkB,aAAAC,MAAiB,mBAC1C,OAAS,WAAAC,MAAe,mCACxB,OAAOC,MAAU,YACjB,OAAOC,MAAa,eCg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,IAAMoD,EAAS,MAAMlC,EAAQ,OAAO,CAClC,QAAS,wDACT,QAAS,CACP,GAAGlB,EAAM,QAAQ,IAAKqD,IACb,CAAE,KAAMA,EAAG,MAAOA,CAAE,EAC5B,EACD,IAAIC,EAAU,GAAG,EACjB,CAAE,KAAM,wBAAoB,MAAOJ,CAAc,CACnD,CACF,CAAC,EAED,OAAOE,IAAWF,EAAgBlB,EAAgBd,EAASlB,CAAK,EAAIgD,GAAgB9B,EAASkC,CAAM,CACrG,EAMaG,GAAe,MAC1BrC,EAAyB1D,EACzBsB,EAAe0E,EAAiBjG,EAAQ,IAAI,CAAC,IAEtC4F,GAAcjC,EAAS,MAAMrC,EAAkBC,CAAI,CAAC",
6
+ "names": ["inquirerCheckbox", "inquirerConfirm", "inquirerSelect", "Separator", "loadDev", "path", "process", "appOf", "key", "byName", "model", "a", "isTwoOption", "route", "rawSource", "uiKey", "sources", "collectLocalPackages", "uiKeys", "apps", "localPkgs", "ownerByPkg", "app", "backend", "frontendOverrides", "overrides", "anyCloud", "backendLocal", "source", "deriveManualPlan", "selection", "t", "apiOnlyKeys", "presetApps", "cloud", "pkg", "owner", "equivalentCommand", "plan", "parts", "promptContext", "process", "defaultPrompts", "cfg", "withEscape", "context", "inquirerSelect", "inquirerCheckbox", "inquirerConfirm", "groupBackends", "routes", "ownerByPkg", "byPkg", "route", "def", "cap", "existing", "loadBackends", "uiDir", "name", "loadDev", "error", "logger", "gatherWizardModel", "root", "apiApps", "discoverApiApps", "uiApps", "discoverUiApps", "config", "getInfraKitConfig", "a", "apiPkgByName", "uiNames", "apiNames", "allNames", "apps", "hasUi", "path", "store", "readTokenStore", "buildPartChoices", "model", "choices", "app", "paths", "b", "r", "description", "buildAuditContext", "discovered", "apiPkgByApp", "routeToPkg", "auditManualPlan", "presetDef", "validatePresetProxy", "i", "WIZARD_CMUX_VAR", "asksCmux", "promptRouteSources", "prompts", "uiKeys", "sources", "key", "backend", "answer", "findRouteCap", "routePath", "recapSources", "plan", "lines", "source", "suffix", "line", "runManualBranch", "selectedTargets", "t", "watch", "cmux", "selection", "deriveManualPlan", "e", "INFRA_KIT_ENV_VAR", "issues", "issue", "echoManual", "k", "commandEcho", "eq", "equivalentCommand", "runPresetBranch", "preset", "MANUAL_CHOICE", "runWizardFlow", "choice", "p", "Separator", "runDevWizard", "findMonorepoRoot"]
7
+ }
package/dist/mcp.js CHANGED
@@ -1,2 +1,2 @@
1
- import{_ as u,ba as f,p as d}from"./chunk-K46DOODL.js";import"./chunk-S45AAYXO.js";import"./chunk-OS5Z2WME.js";import"./chunk-A7FAXZGI.js";import{i as m,j as l}from"./chunk-GZNE5CBQ.js";import{s as c,t as p,u as s}from"./chunk-IVWPZEMC.js";import"./chunk-CHETBZ6M.js";import{StdioServerTransport as w}from"@modelcontextprotocol/sdk/server/stdio.js";import T from"node:process";import o from"node:process";var v=r=>{o.on("SIGINT",()=>{r.info({msg:"Received SIGINT. Shutting down..."}),o.exit(0)}),o.on("SIGTERM",()=>{r.info({msg:"Received SIGTERM. Shutting down..."}),o.exit(0)}),o.on("uncaughtException",e=>{r.fatal({err:e,msg:"Uncaught Exception"}),r.error(`Uncaught Exception! Check ${c}. Shutting down...`),r.flush(),o.exit(1)}),o.on("unhandledRejection",(e,n)=>{r.fatal({reason:e,promise:n,msg:"Unhandled Rejection"}),r.error(`Unhandled Rejection! Check ${c}. Shutting down...`),r.flush(),o.exit(1)})};import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";var h=async r=>{};var x=async r=>{};var a=({toolName:r,handler:e})=>async n=>{s.info({msg:`Tool execution started: ${r}`,params:n});try{await d(),m.reset();let i=await e({...n,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${r}`}),i}catch(i){throw s.error({err:i,params:n,msg:`Tool execution failed: ${r}`}),i}};var S=async r=>{for(let e of u())r.registerTool(e.name,{description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema},a({toolName:e.name,handler:e.handler}))};async function g(){l.enabled=!0;let r=new y({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await h(r),await x(r),await S(r),r}f();var t=p(),M=async()=>{let r;try{r=await g(),t.info("MCP Server instance created")}catch(e){t.error({err:e,msg:"Failed to create MCP server"}),t.error("Fatal error during server creation."),T.exit(1)}try{let e=new w;await r.connect(e),t.info({msg:"Server connected to transport. Ready."})}catch(e){t.error({err:e,msg:"Failed to initialize server"}),t.error("Fatal error during server transport init."),T.exit(1)}};v(t);M();
1
+ import{_ as u,ba as f,p as d}from"./chunk-IURGCRSN.js";import"./chunk-XTRPE4SX.js";import"./chunk-N6ML3SBF.js";import"./chunk-LKKKDB6V.js";import{i as m,j as l}from"./chunk-7DL27USH.js";import{t as c,u as p,v as s}from"./chunk-PZU6BLQR.js";import"./chunk-CHETBZ6M.js";import"./chunk-X46DP23W.js";import{StdioServerTransport as w}from"@modelcontextprotocol/sdk/server/stdio.js";import T from"node:process";import o from"node:process";var v=r=>{o.on("SIGINT",()=>{r.info({msg:"Received SIGINT. Shutting down..."}),o.exit(0)}),o.on("SIGTERM",()=>{r.info({msg:"Received SIGTERM. Shutting down..."}),o.exit(0)}),o.on("uncaughtException",e=>{r.fatal({err:e,msg:"Uncaught Exception"}),r.error(`Uncaught Exception! Check ${c}. Shutting down...`),r.flush(),o.exit(1)}),o.on("unhandledRejection",(e,n)=>{r.fatal({reason:e,promise:n,msg:"Unhandled Rejection"}),r.error(`Unhandled Rejection! Check ${c}. Shutting down...`),r.flush(),o.exit(1)})};import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";var h=async r=>{};var x=async r=>{};var a=({toolName:r,handler:e})=>async n=>{s.info({msg:`Tool execution started: ${r}`,params:n});try{await d(),m.reset();let i=await e({...n,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${r}`}),i}catch(i){throw s.error({err:i,params:n,msg:`Tool execution failed: ${r}`}),i}};var S=async r=>{for(let e of u())r.registerTool(e.name,{description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema},a({toolName:e.name,handler:e.handler}))};async function g(){l.enabled=!0;let r=new y({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await h(r),await x(r),await S(r),r}f();var t=p(),M=async()=>{let r;try{r=await g(),t.info("MCP Server instance created")}catch(e){t.error({err:e,msg:"Failed to create MCP server"}),t.error("Fatal error during server creation."),T.exit(1)}try{let e=new w;await r.connect(e),t.info({msg:"Server connected to transport. Ready."})}catch(e){t.error({err:e,msg:"Failed to initialize server"}),t.error("Fatal error during server transport init."),T.exit(1)}};v(t);M();
2
2
  //# sourceMappingURL=mcp.js.map
package/dist/mcp.js.map CHANGED
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/entry/mcp.ts", "../src/lib/error-handlers/index.ts", "../src/mcp/server.ts", "../src/mcp/prompts/index.ts", "../src/mcp/resources/index.ts", "../src/lib/tool-handler/tool-handler.ts", "../src/mcp/tools/index.ts"],
4
4
  "sourcesContent": ["import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport process from 'node:process'\n\nimport { setupErrorHandlers } from 'src/lib/error-handlers'\nimport { initLoggerMcp } from 'src/lib/logger'\nimport { suppressTypelessPackageJsonWarning } from 'src/lib/node-warnings'\n\nimport { createMcpServer } from '../mcp/server'\n\n// The MCP tools run the same commands as the CLI, so they hit the same consumer `.ts` configs.\n// This keeps the client's log pane clean; it cannot affect protocol framing either way, since\n// the stdio transport frames JSON-RPC on stdout and `emitWarning` only ever writes to stderr.\nsuppressTypelessPackageJsonWarning()\n\nconst logger = initLoggerMcp()\n\nconst startServer = async () => {\n let server\n\n try {\n server = await createMcpServer()\n\n logger.info('MCP Server instance created')\n } catch (error) {\n logger.error({ err: error, msg: 'Failed to create MCP server' })\n logger.error(`Fatal error during server creation.`)\n\n process.exit(1)\n }\n\n try {\n const transport = new StdioServerTransport()\n\n await server.connect(transport)\n\n logger.info({ msg: 'Server connected to transport. Ready.' })\n } catch (error) {\n logger.error({ err: error, msg: 'Failed to initialize server' })\n logger.error(`Fatal error during server transport init.`)\n\n process.exit(1)\n }\n}\n\n// Setup error handlers\nsetupErrorHandlers(logger)\n\n// Start the server\nstartServer()\n", "import process from 'node:process'\nimport type { Logger } from 'pino'\n\nimport { LOG_FILE_PATH } from '../logger/index'\n\n/**\n * Setup error handlers for the application\n * @param logger - The logger instance\n *\n * ONLY FOR SERVER!\n */\nexport const setupErrorHandlers = (logger: Logger) => {\n process.on('SIGINT', () => {\n logger.info({ msg: 'Received SIGINT. Shutting down...' })\n process.exit(0)\n })\n\n process.on('SIGTERM', () => {\n logger.info({ msg: 'Received SIGTERM. Shutting down...' })\n process.exit(0)\n })\n\n process.on('uncaughtException', (error) => {\n logger.fatal({ err: error, msg: 'Uncaught Exception' })\n logger.error(`Uncaught Exception! Check ${LOG_FILE_PATH}. Shutting down...`)\n logger.flush()\n process.exit(1)\n })\n\n process.on('unhandledRejection', (reason, promise) => {\n logger.fatal({ reason, promise, msg: 'Unhandled Rejection' })\n logger.error(`Unhandled Rejection! Check ${LOG_FILE_PATH}. Shutting down...`)\n logger.flush()\n process.exit(1)\n })\n}\n", "import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nimport { mcpMode } from 'src/lib/mcp-mode'\n\nimport { initializePrompts } from './prompts'\nimport { initializeResources } from './resources'\nimport { initializeTools } from './tools'\n\nexport async function createMcpServer() {\n // Marks `process.stdin` as the JSON-RPC transport for every prompt guard in the\n // process. Set HERE rather than in `entry/mcp.ts` (the sole caller) because that\n // module starts a server at import time and so can never be unit-tested \u2014 a test\n // there could only stub the flag, which proves nothing about it ever being set.\n // This runs before `server.connect`, so no tool handler can outrun it.\n mcpMode.enabled = true\n\n const server = new McpServer(\n {\n name: 'infra-kit',\n version: '1.0.0',\n },\n {\n capabilities: {\n resources: {},\n tools: {},\n prompts: {},\n },\n },\n )\n\n await initializePrompts(server)\n await initializeResources(server)\n await initializeTools(server)\n\n return server\n}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nexport const initializePrompts = async (_server: McpServer) => {}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nexport const initializeResources = async (_server: McpServer) => {}\n", "import { commandEcho } from 'src/lib/command-echo'\nimport { ensureUserProjectConfig } from 'src/lib/config-bootstrap'\nimport { logger } from 'src/lib/logger'\nimport type { ToolsExecutionResult } from 'src/types'\n\ninterface ToolHandlerArgs {\n toolName: string\n handler: (params: any) => Promise<ToolsExecutionResult>\n}\n\nexport const createToolHandler = ({\n toolName,\n handler,\n}: ToolHandlerArgs): ((params: unknown) => Promise<ToolsExecutionResult>) => {\n return async (params: unknown) => {\n logger.info({ msg: `Tool execution started: ${toolName}`, params })\n try {\n // MCP entry-boundary seed. This wrapper is the sole chokepoint for every exposed tool\n // (`src/mcp/tools/index.ts` holds the only `registerTool` call), and the `mcp` command itself is\n // in program.ts's SEED_EXCLUDED \u2014 so an MCP server seeds lazily, on its FIRST tool invocation,\n // and a server that never receives one never writes to $HOME. The once-per-process guard inside\n // ensureUserProjectConfig makes calls 2..N free on this long-lived process.\n //\n // Deliberately INSIDE the try, not before it: defense-in-depth. ensureUserProjectConfig is\n // contractually never-throw, but if that contract ever broke, an unhandled rejection here would\n // take down the long-lived server. Inside the try it degrades to an ordinary tool error.\n await ensureUserProjectConfig()\n\n // The command handlers record their resolved flags into the `commandEcho` singleton. On the CLI,\n // Commander's `preAction` clears it before every command; this long-lived server never runs that\n // hook, so without a reset here one tool call's flags would leak into the next one's snapshot and\n // the options array would grow for the life of the process.\n commandEcho.reset()\n\n const payload = await handler({ ...(params as object), confirmedCommand: true })\n\n logger.info({ msg: `Tool execution successful: ${toolName}` })\n\n return payload\n } catch (error) {\n logger.error({\n err: error,\n params,\n msg: `Tool execution failed: ${toolName}`,\n })\n\n throw error\n }\n }\n}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nimport { getExposedMcpTools } from 'src/lib/command-catalog'\nimport { createToolHandler } from 'src/lib/tool-handler'\n\nexport const initializeTools = async (server: McpServer) => {\n // The registered tool set is derived from the single command catalog, filtered\n // by its explicit `mcpExposed` allowlist. doctor / vendor-sync / vendor-manifest\n // are intentionally excluded there and must never be registered here.\n for (const tool of getExposedMcpTools()) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n },\n createToolHandler({ toolName: tool.name, handler: tool.handler }),\n )\n }\n}\n"],
5
- "mappings": "4QAAA,OAAS,wBAAAA,MAA4B,4CACrC,OAAOC,MAAa,eCDpB,OAAOC,MAAa,eAWb,IAAMC,EAAsBC,GAAmB,CACpDC,EAAQ,GAAG,SAAU,IAAM,CACzBD,EAAO,KAAK,CAAE,IAAK,mCAAoC,CAAC,EACxDC,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDA,EAAQ,GAAG,UAAW,IAAM,CAC1BD,EAAO,KAAK,CAAE,IAAK,oCAAqC,CAAC,EACzDC,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDA,EAAQ,GAAG,oBAAsBC,GAAU,CACzCF,EAAO,MAAM,CAAE,IAAKE,EAAO,IAAK,oBAAqB,CAAC,EACtDF,EAAO,MAAM,6BAA6BG,CAAa,oBAAoB,EAC3EH,EAAO,MAAM,EACbC,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDA,EAAQ,GAAG,qBAAsB,CAACG,EAAQC,IAAY,CACpDL,EAAO,MAAM,CAAE,OAAAI,EAAQ,QAAAC,EAAS,IAAK,qBAAsB,CAAC,EAC5DL,EAAO,MAAM,8BAA8BG,CAAa,oBAAoB,EAC5EH,EAAO,MAAM,EACbC,EAAQ,KAAK,CAAC,CAChB,CAAC,CACH,ECnCA,OAAS,aAAAK,MAAiB,0CCEnB,IAAMC,EAAoB,MAAOC,GAAuB,CAAC,ECAzD,IAAMC,EAAsB,MAAOC,GAAuB,CAAC,ECQ3D,IAAMC,EAAoB,CAAC,CAChC,SAAAC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,CAEA,GAAI,CACF,IAAMC,EAAY,IAAIC,EAEtB,MAAML,EAAO,QAAQI,CAAS,EAE9BP,EAAO,KAAK,CAAE,IAAK,uCAAwC,CAAC,CAC9D,OAASK,EAAO,CACdL,EAAO,MAAM,CAAE,IAAKK,EAAO,IAAK,6BAA8B,CAAC,EAC/DL,EAAO,MAAM,2CAA2C,EAExDM,EAAQ,KAAK,CAAC,CAChB,CACF,EAGAG,EAAmBT,CAAM,EAGzBE,EAAY",
6
6
  "names": ["StdioServerTransport", "process", "process", "setupErrorHandlers", "logger", "process", "error", "LOG_FILE_PATH", "reason", "promise", "McpServer", "initializePrompts", "_server", "initializeResources", "_server", "createToolHandler", "toolName", "handler", "params", "logger", "ensureUserProjectConfig", "commandEcho", "payload", "error", "initializeTools", "server", "tool", "getExposedMcpTools", "createToolHandler", "createMcpServer", "mcpMode", "server", "McpServer", "initializePrompts", "initializeResources", "initializeTools", "suppressTypelessPackageJsonWarning", "logger", "initLoggerMcp", "startServer", "server", "createMcpServer", "error", "process", "transport", "StdioServerTransport", "setupErrorHandlers"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{h as i}from"./chunk-UO3FYLPX.js";import{a as t}from"./chunk-OS5Z2WME.js";import"./chunk-A7FAXZGI.js";import"./chunk-CHETBZ6M.js";import a from"node:fs";import o from"node:process";import{fileURLToPath as s}from"node:url";var m=r=>{let n=r.indexOf("--parent-pid");if(n===-1)return;let e=Number(r[n+1]);return Number.isInteger(e)&&e>0?e:void 0},p=()=>a.realpathSync(s(new URL("./cli.js",import.meta.url))),d=async()=>{await i(t.version,{selfRealPath:p(),parentPid:m(o.argv)})};d().catch(()=>{o.exitCode=0});
1
+ import{h as i}from"./chunk-KAWDTA5H.js";import{a as t}from"./chunk-N6ML3SBF.js";import"./chunk-LKKKDB6V.js";import"./chunk-CHETBZ6M.js";import a from"node:fs";import o from"node:process";import{fileURLToPath as s}from"node:url";var m=r=>{let n=r.indexOf("--parent-pid");if(n===-1)return;let e=Number(r[n+1]);return Number.isInteger(e)&&e>0?e:void 0},p=()=>a.realpathSync(s(new URL("./cli.js",import.meta.url))),d=async()=>{await i(t.version,{selfRealPath:p(),parentPid:m(o.argv)})};d().catch(()=>{o.exitCode=0});
2
2
  //# sourceMappingURL=update-check.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "infra-kit",
3
3
  "type": "module",
4
- "version": "0.3.5",
4
+ "version": "0.3.7",
5
5
  "files": [
6
6
  "dist"
7
7
  ],
@@ -1,2 +0,0 @@
1
- import{b as Z}from"./chunk-TPVXMJ7N.js";import{render as Ie}from"ink";import ce from"node:process";import{Box as J,Text as R,useApp as he,useInput as we,useWindowSize as xe}from"ink";import{useEffect as ee,useState as F}from"react";import{useMemo as de,useState as V}from"react";var D=(e,t)=>{let[r,m]=V(""),[n,a]=V(0),o=de(()=>{let d=r.trim().toLowerCase();return d?e.filter(p=>t(p).toLowerCase().includes(d)):e},[e,r,t]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(d,p)=>{let S=o.length;return p.upArrow?(S>0&&a((u-1+S)%S),!0):p.downArrow?(S>0&&a((u+1)%S),!0):p.backspace||p.delete?(m(r.slice(0,-1)),a(0),!0):d&&!p.ctrl&&!p.meta?(m(r+d),a(0),!0):!1},clearQuery:()=>r?(m(""),a(0),!0):!1}};var pe=()=>{},_=(e,t=0)=>e<5?{mode:"tiny",chromeRows:0,groups:!1}:e<10?{mode:"compact",chromeRows:4+t,groups:!1}:{mode:"full",chromeRows:6+t,groups:!0},fe=(e,t,r,m)=>{let n=0,a;for(let o=t;o<r;o+=1){let u=e[o];if(!u)break;let w=m(u),T=w!==void 0&&w!==a;n+=1+(T?1:0)+(T&&o>t?1:0),a=w}return n},j=(e,t,r,m)=>{let n=t;for(;n<e.length&&fe(e,t,n+1,m)<=r;)n+=1;return n},$=(e,t,r,m,n)=>{let a=n?.groupOf??pe,o=Math.max(0,m-(n?.chromeRows??6)),u=Math.min(t,r);for(;r>=j(e,u,o,a)&&u<r;)u+=1;let w=j(e,u,o,a);return{visible:e.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,e.length-w)}};import{jsx as I,jsxs as G}from"react/jsx-runtime";var te=e=>{let{items:t,onSubmit:r,onCancel:m,required:n=!0,allowSelectAll:a=!0}=e,o=Te,u=t.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=he(),{rows:T}=xe(),{filtered:d,activeIndex:p,query:S,handleNavigation:v,clearQuery:M}=D(t,ge),[B,O]=F(()=>new Set),[E,h]=F(!1),[C,f]=F(0),[l,b]=F(!1);ee(()=>{l&&w()},[l,w]);let q=_(T,1),y=$(d,C,p,T,{chromeRows:q.chromeRows});ee(()=>{y.start!==C&&f(y.start)},[y.start,C]);let k=s=>{O(x=>{let g=new Set(x);return g.has(s)?g.delete(s):g.add(s),g})},H=()=>{O(s=>t.every(g=>s.has(g.value))?new Set:new Set(t.map(g=>g.value)))},i=()=>{m(),b(!0)},c=()=>{if(n&&B.size===0){h(!0);return}r([...B]),b(!0)};return we((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&H();return}if(s===" "){let g=d[p];g&&k(g.value);return}if(x.return){c();return}v(s,x)}}),l?null:q.mode==="tiny"?I(R,{dimColor:!0,wrap:"truncate",children:o.tiny}):G(J,{flexDirection:"column",children:[q.mode==="full"?I(R,{dimColor:!0,wrap:"truncate",children:o.hint}):null,G(J,{children:[I(R,{color:"cyan",children:o.prompt}),I(R,{wrap:"truncate-start",children:S})]}),G(J,{flexDirection:"column",marginTop:q.mode==="full"?1:0,children:[d.length===0?I(R,{dimColor:!0,wrap:"truncate",children:o.empty}):null,y.hiddenBefore>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenBefore} above`}):null,y.visible.map((s,x)=>{let g=y.start+x===p,me=B.has(s.value);return G(R,{color:g?"green":void 0,wrap:"truncate",children:[g?"\u203A ":" ",me?"[x] ":"[ ] ",s.label.padEnd(u)," ",I(R,{dimColor:!0,children:s.description??""})]},s.value)}),y.hiddenAfter>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenAfter} below`}):null]}),E?I(R,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function ge(e){return`${e.label} ${e.description??""}`}var Te={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as U,Text as W,useApp as be,useInput as Se,useWindowSize as Ce}from"ink";import{useEffect as re,useState as ne}from"react";import{jsx as L,jsxs as z}from"react/jsx-runtime";var oe=e=>{let{items:t,onSelect:r,onCancel:m}=e,n=ve,a=t.reduce((f,l)=>Math.max(f,l.label.length),0),{exit:o}=be(),{rows:u}=Ce(),{filtered:w,activeIndex:T,query:d,handleNavigation:p,clearQuery:S}=D(t,Pe),[v,M]=ne(0),[B,O]=ne(!1);re(()=>{B&&o()},[B,o]);let E=_(u),h=$(w,v,T,u,{chromeRows:E.chromeRows});re(()=>{h.start!==v&&M(h.start)},[h.start,v]);let C=()=>{m(),O(!0)};return Se((f,l)=>{if(!B){if(l.ctrl&&f==="c"){C();return}if(l.escape){S()||C();return}if(l.return){let b=w[T];b&&(r(b.value),O(!0));return}p(f,l)}}),B?null:E.mode==="tiny"?L(W,{dimColor:!0,wrap:"truncate",children:n.tiny}):z(U,{flexDirection:"column",children:[E.mode==="full"?L(W,{dimColor:!0,wrap:"truncate",children:n.hint}):null,z(U,{children:[L(W,{color:"cyan",children:n.prompt}),L(W,{wrap:"truncate-start",children:d})]}),z(U,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(W,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((f,l)=>{let b=h.start+l===T;return z(W,{color:ye(f.type,b),wrap:"truncate",children:[b?"\u203A ":" ",f.label.padEnd(a)," ",L(W,{dimColor:!0,children:f.description??""})]},f.value)}),h.hiddenAfter>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function ye(e,t){return e==="hotfix"?"red":t?"green":void 0}function Pe(e){return`${e.label} ${e.description??""}`}var ve={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as P,useApp as Be,useInput as Oe,useWindowSize as Re}from"ink";import{useEffect as ie,useMemo as Ae,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var se=e=>{let{items:t,onSelect:r,onCancel:m,onSuspend:n}=e,a={hint:Ee(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:u,suspendTerminal:w}=Be(),{rows:T}=Re(),[d,p]=K(""),[S,v]=K(0),[M,B]=K(0),[O,E]=K(!1);ie(()=>{O&&u()},[O,u]);let h=Ae(()=>{let i=d.trim().toLowerCase();return i?t.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):t},[t,d]),C=Math.min(S,Math.max(0,h.length-1)),f=_(T),l=$(h,M,C,T,{chromeRows:f.chromeRows,groupOf:f.groups?i=>i.group:void 0});ie(()=>{l.start!==M&&B(l.start)},[l.start,M]);let b=()=>{m(),E(!0)},q=()=>{n&&w(n).catch(()=>{})},y=i=>i==="c"||i==="d"?(b(),!0):i==="z"?(q(),!0):!1,k=i=>{let c=h.length;c>0&&v((C+i+c)%c)};if(Oe((i,c)=>{if(!O&&!(c.ctrl&&y(i))){if(c.escape&&d){p(""),v(0);return}if(c.escape){b();return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){k(-1);return}if(c.downArrow){k(1);return}if(c.backspace||c.delete){p(d.slice(0,-1)),v(0);return}i&&!c.ctrl&&!c.meta&&(p(d+i),v(0))}}),O)return null;if(f.mode==="tiny")return A(P,{dimColor:!0,wrap:"truncate",children:a.tiny});let H="";return N(Q,{flexDirection:"column",children:[f.mode==="full"?A(P,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(P,{color:"cyan",children:a.prompt}),A(P,{wrap:"truncate-start",children:d})]}),N(Q,{flexDirection:"column",marginTop:f.mode==="full"?1:0,children:[h.length===0?A(P,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=f.groups&&i.group!==H;return H=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(P,{children:" "}):null,x?A(P,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(P,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(P,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},le={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear/quit \xB7 Ctrl-D quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear/quit \xB7 Ctrl-D quit"},Ee=e=>e?le.suspend:le.plain;import ae from"node:process";var ue=(e={})=>{let t=e.platform??ae.platform,r=e.kill??((m,n)=>{ae.kill(m,n)});if(t!=="win32")try{r(0,"SIGSTOP")}catch{}};import{jsx as X}from"react/jsx-runtime";var Y=async e=>{let t=Z(),{waitUntilExit:r}=Ie(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await r()}catch{}finally{ce.stdin.ref()}},st=async e=>{let t=null;return await Y(X(se,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null},onSuspend:ce.platform==="win32"?void 0:()=>{ue()}})),t},at=async e=>{let t=null;return await Y(X(oe,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null}})),t},ut=async(e,t)=>{let r=null;return await Y(X(te,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:m=>{r=m},onCancel:()=>{r=null}})),r};export{ut as runBranchMultiPicker,at as runBranchPicker,st as runCommandPalette};
2
- //# sourceMappingURL=boot-EEEVHAMO.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/tui/boot.tsx", "../src/tui/screens/branch-multi-picker.tsx", "../src/tui/hooks/use-list-filter.ts", "../src/tui/screens/palette-window.ts", "../src/tui/screens/branch-picker.tsx", "../src/tui/screens/command-palette.tsx", "../src/tui/suspend.ts"],
4
- "sourcesContent": ["import { render } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\n\nimport { safeStderr } from './safe-stderr'\nimport { BranchMultiPicker } from './screens/branch-multi-picker'\nimport { BranchPicker } from './screens/branch-picker'\nimport { CommandPalette } from './screens/command-palette'\nimport { suspendForeground } from './suspend'\nimport type { PaletteItem } from './types'\n\n/**\n * Entry point for the Ink TUI. This module (and everything under `src/tui/`) is\n * the ONLY place allowed to import `ink`/`react`; it is reached exclusively via a\n * dynamic `await import('src/tui/boot')` from the TTY branch of entry/cli.ts, so\n * React never loads on the MCP / `--json` / non-TTY paths. Build splitting keeps\n * it in a separate lazy chunk (see scripts/build.js).\n */\n\n/**\n * Render an Ink element to stderr and resolve once it tears down. Frames are\n * written to stderr so stdout stays clean for the command that runs afterwards\n * (mirrors the previous Inquirer menu).\n *\n * Ink `unref()`s process.stdin when it tears down raw mode on exit. That ref is\n * process-wide and never restored, so the next consumer of stdin \u2014 the Inquirer\n * prompt the selected command opens (e.g. the worktrees-remove checkbox), or a\n * SECOND Ink render in the same process (the bare-menu palette \u2192 picker hop) \u2014\n * reads from an unref'd handle that no longer keeps the event loop alive. Once\n * the command's git/gh subprocesses settle, the loop drains mid-prompt, Node\n * flags entry/cli.ts's top-level await as unsettled, and the process exits with\n * code 13 (the prompt dies on arrival). Re-ref stdin on BOTH the resolve and the\n * reject path so it holds the loop while the next prompt is reading; an idle\n * ref'd stdin does not block exit, so non-interactive follow-up commands still\n * terminate normally. Every render must go through here so the re-ref is never\n * skipped.\n */\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const stdout = safeStderr()\n const { waitUntilExit } = render(element, {\n stdout,\n // Ink's default is `exitOnCtrlC: true`, which intercepts the 0x03 byte in its own App and calls\n // `handleExit()` BEFORE it ever reaches `useInput`. That makes every screen's own ctrl+c branch\n // dead code, and \u2014 worse \u2014 it tears down on the CURRENT frame, so `log.done()` freezes the drawn\n // command list into the scrollback instead of erasing it (Esc, which goes through the screens'\n // own quit path, erases correctly; Ctrl-C left a corpse). Every screen rendered here already\n // handles ctrl+c itself, so hand them the key.\n exitOnCtrlC: false,\n // Ink's default is `!isInCi && stdout.isTTY`. We drop the isInCi term: a developer with CI\n // exported in their shell would otherwise get a NON-interactive Ink on a real terminal, and Ink\n // skips ALL terminal management in that mode \u2014 `beginSuspend` returns before it can drop raw mode\n // or erase the frame, and `endSuspend` never redraws. Ctrl-Z would hand the shell a raw-mode tty\n // with a stranded frame and a hidden cursor, and `fg` would come back to nothing. Whether we own\n // the terminal is a question about the tty, and only about the tty.\n interactive: Boolean(stdout.isTTY),\n })\n\n try {\n await waitUntilExit()\n } catch {\n // Swallow a teardown rejection: the caller reports cancellation via its own\n // captured sentinel (which stays at its initial value), not via a throw.\n } finally {\n process.stdin.ref()\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels. A Ctrl-Z suspends the job and resolves nothing \u2014 the same\n * palette redraws, filter and all, when the user brings it back with `fg`.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n // This module is the platform authority: `undefined` tells the palette that suspending is\n // impossible here, so it neither binds Ctrl-Z nor advertises it in the footer. (`suspendForeground`\n // guards win32 again on its own \u2014 the palette itself must stay free of `process`.)\n onSuspend={\n process.platform === 'win32'\n ? undefined\n : () => {\n suspendForeground()\n }\n }\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n *\n * The list is WINDOWED to the terminal height for the same safety reason as the\n * palette and the single picker: an overflowing Ink frame corrupts the cursor and\n * welds later output onto the transcript. See `palette-window.ts`.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = BRANCH_MULTI_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n // The extra chrome row is this screen's `select at least one` hint: counted unconditionally, because\n // it appears on a keystroke and a budget that shrinks mid-frame is a budget that overflows.\n const layout = listLayout(rows, 1)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: the typed filter first, the picker only once\n // there is no filter left to clear. It never touches `selected` \u2014 a filter keystroke is\n // not a selection, so clearing one must not discard the other. Stage 2 discards it, as before.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const isChecked = selected.has(item.value)\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width. Ink reads the wrap style off the\n // OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n {showRequiredHint ? (\n <Text dimColor wrap=\"truncate\">\n {T.requiredHint}\n </Text>\n ) : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_MULTI_PICKER_TEXT = {\n hint: 'filter \u00B7 \u2191\u2193 move \u00B7 Space toggle \u00B7 Ctrl-A all \u00B7 Enter submit \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick branches',\n requiredHint: 'select at least one',\n more: '\u2026',\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n /**\n * Stage 1 of the Esc ladder: clears a non-empty query (back to the first row) and\n * returns true. Returns false when the query is already empty \u2014 the boolean IS the\n * ladder, and a false tells the caller there is nothing left to cancel but the screen.\n *\n * Deliberately NOT folded into `handleNavigation`: the two pickers want different\n * stage-2 actions, so the escape branch belongs to each screen, not to the shared handler.\n */\n clearQuery: () => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n const clearQuery = (): boolean => {\n if (!query) {\n return false\n }\n\n setQuery('')\n setIndex(0)\n\n return true\n }\n\n return { filtered, activeIndex, query, handleNavigation, clearQuery }\n}\n", "/**\n * Pure viewport arithmetic shared by every Ink list screen (the command palette and both branch\n * pickers): which slice of the (already filtered) list fits the terminal, and how much chrome the\n * screen may spend around it.\n *\n * This is a SAFETY guard, not a readability one. Ink's cleanup walks the cursor upward one line at a\n * time (`ESC[2K ESC[1A` per row) and `ESC[1A` SATURATES AT ROW 0. So the moment a frame is taller than\n * the viewport, the terminal scrolls while Ink draws, the upward walk erases the wrong rows, and the\n * cursor is left parked ABOVE live content \u2014 after which every later write (the session's status\n * footer, the next palette frame) is deposited on top of the transcript. That is the \"welded rows\" bug:\n * `\u276F ` printed over the head of `ERROR: \u2026`, leaving `ROR: \u2026` behind.\n *\n * The invariant this module exists to enforce, for every (columns, rows):\n *\n * rendered frame height < terminal rows\n *\n * Hold that, and Ink never takes its overflow path: `clearTerminal` never fires, `eraseLines` never\n * saturates, the cursor stays below the transcript, and a fresh (cold) Ink instance \u2014 which erases\n * NOTHING before its first frame \u2014 simply appends below the transcript like any other CLI. No new\n * escape bytes required.\n *\n * Two things make the row count knowable at all:\n * - Every list row is rendered `wrap=\"truncate\"`, so one item is always exactly one row. Without that\n * a long description wraps to two rows and this arithmetic silently under-counts (Ink wraps text\n * itself and measures the WRAPPED height, so it, not us, would be right).\n * - Chrome is counted unconditionally, even when a given row is not drawn (see `CHROME_ROWS`). Over-\n * counting shrinks the list; under-counting overflows. Only one of those is a bug.\n *\n * `src/tui/safe-stderr.ts` (the `ESC[3J` byte filter) remains the last-resort backstop for the case\n * this cannot cover \u2014 a SIGWINCH that invalidates a frame's height retroactively.\n */\nimport type { PaletteItem } from '../types'\n\n/**\n * Reads an item's group label. Omitted by the branch pickers, whose lists have no headers at all.\n * (Passed as an accessor rather than constrained with a `{ group?: string }` marker interface: a type\n * whose properties are ALL optional is \"weak\", and TypeScript refuses to match a `BranchPickerItem`\n * against it \u2014 inference silently falls back to the constraint and every field access breaks.)\n */\nexport type GroupOf<T> = (item: T) => string | undefined\n\n/** The slice to render, plus how many rows fell off each end (for the `\u2026 n more` affordances). */\nexport interface ListWindow<T> {\n visible: T[]\n /** Index the window starts at \u2014 the component stores it so the list does not jump between frames. */\n start: number\n hiddenBefore: number\n hiddenAfter: number\n}\n\n/** Back-compat alias: the command palette's window is a window of `PaletteItem`s. */\nexport type PaletteWindow = ListWindow<PaletteItem>\n\n/**\n * Rows a screen spends on everything that is not a list row, counted UNCONDITIONALLY (a `\u2026 n above`\n * that is not drawn today may be drawn on the next keystroke, and re-deriving the budget mid-frame is\n * how you get an off-by-one that only bites on a full list):\n * hint, `\u276F` prompt, the list's `marginTop`, `\u2026 n above`, `\u2026 n below`, and one row of headroom.\n *\n * The headroom row is what makes the frame strictly SHORTER than the viewport: Ink treats a frame\n * exactly as tall as the terminal as fullscreen and clears the screen.\n */\nexport const CHROME_ROWS = 6\n\n/** Compact chrome: the hint and the list's `marginTop` are dropped. Prompt + affordances + headroom. */\nexport const COMPACT_CHROME_ROWS = 4\n\n/** Below this many rows a screen drops its hint, its `marginTop`, and its group headers. */\nexport const COMPACT_BELOW_ROWS = 10\n\n/** Below this many rows no usable list fits at all; the screen renders a single-line notice instead. */\nexport const TINY_BELOW_ROWS = 5\n\n/** How a screen must lay itself out to keep its frame shorter than `rows`. */\nexport type ListLayoutMode = 'full' | 'compact' | 'tiny'\n\nexport interface ListLayout {\n mode: ListLayoutMode\n /** Rows reserved for chrome. Pass to `paletteWindow` as `chromeRows`. */\n chromeRows: number\n /** Whether group headers may be drawn (they cost a row each, so a compact frame drops them). */\n groups: boolean\n}\n\n/** A list with no group headers: every item costs exactly one row. */\nconst NO_GROUPS = (): undefined => {\n return undefined\n}\n\n/**\n * The layout a screen must use at this terminal height. `extraChromeRows` is for chrome a screen has\n * that the others do not \u2014 the multi-picker's `select at least one` hint is the only one today.\n *\n * A `tiny` frame is one truncated line, which is strictly shorter than any terminal of 2+ rows. (At\n * `rows === 1` nothing can be shorter than the viewport; Ink will clear. That is a degenerate terminal,\n * and `safe-stderr` keeps even that harmless.)\n *\n * @example\n * listLayout(24) // => { mode: 'full', chromeRows: 6, groups: true }\n * listLayout(8) // => { mode: 'compact', chromeRows: 4, groups: false }\n * listLayout(8, 1) // => { mode: 'compact', chromeRows: 5, groups: false } (multi-picker)\n * listLayout(4) // => { mode: 'tiny', chromeRows: 0, groups: false }\n */\nexport const listLayout = (rows: number, extraChromeRows = 0): ListLayout => {\n if (rows < TINY_BELOW_ROWS) {\n return { mode: 'tiny', chromeRows: 0, groups: false }\n }\n\n if (rows < COMPACT_BELOW_ROWS) {\n return { mode: 'compact', chromeRows: COMPACT_CHROME_ROWS + extraChromeRows, groups: false }\n }\n\n return { mode: 'full', chromeRows: CHROME_ROWS + extraChromeRows, groups: true }\n}\n\n/**\n * How many rows rendering `items[start..end)` costs: one per item (guaranteed by `wrap=\"truncate\"`),\n * plus, when `groups` is on, one for each group header and one for the blank line between groups (the\n * first rendered group gets a header but no blank \u2014 it mirrors the `showGroup && position > 0` rule in\n * the components). A list whose items carry no `group` never spends a header row.\n */\nconst heightOf = <T>(items: T[], start: number, end: number, groupOf: GroupOf<T>): number => {\n let height = 0\n let previousGroup: string | undefined\n\n for (let index = start; index < end; index += 1) {\n const item = items[index]\n\n if (!item) break\n\n const group = groupOf(item)\n const startsGroup = group !== undefined && group !== previousGroup\n\n height += 1 + (startsGroup ? 1 : 0) + (startsGroup && index > start ? 1 : 0)\n previousGroup = group\n }\n\n return height\n}\n\n/** The last index (exclusive) that still fits `budget` rows when rendering from `start`. */\nconst endThatFits = <T>(items: T[], start: number, budget: number, groupOf: GroupOf<T>): number => {\n let end = start\n\n while (end < items.length && heightOf(items, start, end + 1, groupOf) <= budget) {\n end += 1\n }\n\n return end\n}\n\n/**\n * The window of items to render: the largest slice starting at or after `start` that fits the terminal\n * while still containing `activeIndex`. Scrolls by the minimum needed \u2014 the caller keeps `start` in\n * state, so the list only moves when the cursor would otherwise leave the window.\n *\n * An empty `visible` is a legitimate result on a terminal too short to hold even one row. It is NOT\n * clamped up to one item: forcing a row that does not fit is exactly how the frame overflows and the\n * cursor corruption starts. A screen that gets nothing back renders its `tiny` notice instead \u2014 see\n * `listLayout`.\n *\n * @example\n * const window = paletteWindow(items, 0, 12, 24)\n * window.visible.length // => however many commands fit 18 rows\n * window.hiddenAfter // => the rest, surfaced as '\u2026 n below'\n */\nexport const paletteWindow = <T>(\n items: T[],\n start: number,\n activeIndex: number,\n rows: number,\n opts?: { chromeRows?: number; groupOf?: GroupOf<T> },\n): ListWindow<T> => {\n const groupOf = opts?.groupOf ?? NO_GROUPS\n const budget = Math.max(0, rows - (opts?.chromeRows ?? CHROME_ROWS))\n\n // Scroll up only if the cursor moved above the window; otherwise scroll down just far enough.\n let first = Math.min(start, activeIndex)\n\n while (activeIndex >= endThatFits(items, first, budget, groupOf) && first < activeIndex) {\n first += 1\n }\n\n const end = endThatFits(items, first, budget, groupOf)\n\n return {\n visible: items.slice(first, end),\n start: first,\n hiddenBefore: first,\n hiddenAfter: Math.max(0, items.length - end),\n }\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n *\n * Like the palette, the list is WINDOWED to the terminal height. That is a safety\n * requirement, not a nicety: a repo with ~20 open releases produced a frame taller\n * than an 80x24 window, and an overflowing Ink frame corrupts the cursor and welds\n * the next frame onto the command's own output. See `palette-window.ts`.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = BRANCH_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const layout = listLayout(rows)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: a typed filter first, the picker only once\n // there is no filter left to clear. `clearQuery` returning false IS that ladder.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width (a long branch name would\n // otherwise wrap and make the frame taller than this component believes). Ink reads the wrap\n // style off the OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_PICKER_TEXT = {\n hint: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter select \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick a branch',\n more: '\u2026',\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /**\n * Stop the foreground job (Ctrl-Z). ABSENT means suspend is impossible on this platform \u2014 the\n * palette stays pure presentation and never inspects `process`; boot.tsx is the platform authority.\n */\n onSuspend?: () => void\n}\n\n/**\n * Fuzzy-ish command picker rendered with Ink. Pure presentation: it receives a\n * flat list of commands (already grouped/ordered by the catalog) and returns the\n * selected name. It never executes anything \u2014 the caller runs the command via\n * the existing Commander path.\n *\n * NOTE: this component sits at exactly the sonarjs cognitive-complexity ceiling (15). Any `if` or\n * `?:` added to its BODY breaks `pnpm run qa` \u2014 which is why the hint is picked by the module-scope\n * `hintFor` below and the control keys by `handleCtrlKey`, rather than inline.\n */\nexport const CommandPalette = (props: CommandPaletteProps) => {\n const { items, onSelect, onCancel, onSuspend } = props\n\n const T = {\n hint: hintFor(Boolean(onSuspend)),\n prompt: '\u276F ',\n empty: 'No matching commands',\n tiny: 'terminal too short \u2014 resize to pick a command',\n more: '\u2026',\n }\n const nameWidth = 24\n\n const { exit, suspendTerminal } = useApp()\n const { rows } = useWindowSize()\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n // First command in the visible window. Kept in state so the list scrolls by the minimum needed\n // instead of jumping every time the cursor moves.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame (Ink's `log.done()` would otherwise\n // freeze the last drawn frame \u2014 the command list \u2014 into the scrollback).\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return `${item.name} ${item.description}`.toLowerCase().includes(q)\n })\n }, [items, query])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n // The slice that fits this terminal, and how much chrome we may spend around it. A frame taller than\n // the viewport corrupts the cursor (see palette-window.ts) \u2014 every row here is budgeted, and every\n // row below is `wrap=\"truncate\"` so one command is always exactly one row.\n const layout = listLayout(rows)\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, {\n chromeRows: layout.chromeRows,\n // A compact frame drops group headers, so they must not be budgeted for either.\n groupOf: layout.groups\n ? (item) => {\n return item.group\n }\n : undefined,\n })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n // Back out with nothing picked (Ctrl-C, or Esc on an empty filter).\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Hand the terminal back to the user's shell until they `fg`.\n //\n // Ink does all the terminal work for us, in the right order and synchronously: `beginSuspend`\n // settles pending frames, erases the list, restores the cursor and drops raw mode BEFORE our\n // callback runs, and on resume `endSuspend` re-arms raw mode and force-redraws THIS SAME LIVE\n // COMPONENT \u2014 so the typed filter survives the suspend. That is why we must NOT set `submitted`\n // here: unmounting would throw the query away and give us a blank palette on return.\n //\n // The `.catch` is the PRIMARY guard, not a backstop \u2014 never simplify it to `void`. Two 0x1a bytes\n // in one read chunk (a double-tap) are both already queued in Ink's input loop, and `pauseInput`\n // only detaches the stdin listener, so the second one still fires \u2014 into a `beginSuspend` that is\n // already suspended, which throws. Harmless (it throws before flipping its own state, and the first\n // suspension still unwinds), but the rejection must be caught: `void` would make it an unhandled\n // rejection that kills the process mid terminal-restore.\n const suspend = () => {\n if (!onSuspend) {\n return\n }\n\n suspendTerminal(onSuspend).catch(() => {\n // See above: a double Ctrl-Z is a no-op, not a crash.\n })\n }\n\n /**\n * Ctrl-C / Ctrl-Z, hoisted OUT of the `useInput` body. Mandatory, not tidiness: that handler sits at\n * cognitive complexity 14, and an inline `if (key.ctrl && input === 'z' && onSuspend)` costs +2 \u2014\n * 16, over the sonarjs ceiling of 15, and `pnpm run qa` goes red.\n *\n * The palette's Ctrl-Z is a BYTE (0x1a), not a signal: Ink holds stdin in raw mode, which clears\n * termios ISIG, so the tty never generates SIGTSTP here at all. We therefore stop the process GROUP\n * ourselves (kill(0), see ../suspend.ts). The session shell's SIGTSTP handler does the opposite \u2014\n * it self-stops with raise('SIGSTOP') (lib/session/run-session.ts) \u2014 and that is CORRECT there,\n * because while a child command holds the foreground the tty is cooked and has already TSTP'd the\n * whole group, leaving only us to follow. DO NOT UNIFY THE TWO.\n */\n const handleCtrlKey = (input: string): boolean => {\n if (input === 'c') {\n quit()\n\n return true\n }\n\n // Ctrl-D is the REPL/shell convention for \"end of input\", and it is UNCONDITIONAL: unlike Esc it\n // is not part of the filter ladder, so it quits with a filter typed as readily as without one.\n // It exists because Esc-on-an-empty-filter ending the session is the one binding a shell user does\n // not expect, and this gives them the key their fingers already reach for without changing Esc.\n if (input === 'd') {\n quit()\n\n return true\n }\n\n if (input === 'z') {\n suspend()\n\n return true\n }\n\n return false\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C quits, Ctrl-Z suspends (see handleCtrlKey). Esc clears a non-empty filter first, and\n // only quits on an empty filter \u2014 the standard REPL/palette split, so the session shell keeps\n // running while the user narrows.\n if (key.ctrl && handleCtrlKey(input)) {\n return\n }\n\n if (key.escape && query) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.escape) {\n quit()\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one command row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START on the input: overflow must eat the head of the filter, never the character\n being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const showGroup = layout.groups && item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the first row of the window). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\" wrap=\"truncate\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n {/* `wrap=\"truncate\"` is load-bearing, not cosmetic: it is what makes \"one command = one\n row\" true at any width, which is what keeps the frame shorter than the viewport. Ink\n reads the wrap style off the OUTER <Text> only \u2014 it squashes the nested <Text> into\n this one's string \u2014 so it must live here. */}\n <Text color={isActive ? 'green' : undefined} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Footer copy. Kept out of the component's `T` because picking between the two is a conditional.\n *\n * Exported so the hint-width guard can measure these strings: they render under `wrap=\"truncate\"`,\n * so a hint of \u226580 columns silently loses its TAIL \u2014 and the tail is where the newest keybinding\n * always lands. `Esc clear/quit` (not `Esc cancel`) is the honest description: Esc pops the filter\n * first and only ends the session once there is nothing left to clear.\n */\nexport const HINTS = {\n suspend: 'filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear/quit \u00B7 Ctrl-D quit \u00B7 Ctrl-Z suspend',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear/quit \u00B7 Ctrl-D quit',\n}\n\n/**\n * The footer hint, which advertises Ctrl-Z only where suspending is possible.\n *\n * Module scope for two reasons, both load-bearing. It cannot live in the component: a `?:` in\n * `CommandPalette`'s body pushes it from 15 to 16, over the sonarjs cognitive-complexity ceiling. And\n * it cannot sit above the component either: `@wl/component-file-order` pins this file to\n * imports \u2192 props interface \u2192 component with nothing in between. Below is the only legal home.\n *\n * Both strings are SHORTER than the hint they replace, on purpose \u2014 the footer renders with\n * `wrap=\"truncate\"`, so anything longer silently loses its tail on a narrow terminal, and the tail is\n * exactly where a newly-added key would land.\n *\n * @example\n * hintFor(true).includes('Ctrl-Z') // => true\n */\nconst hintFor = (canSuspend: boolean): string => {\n return canSuspend ? HINTS.suspend : HINTS.plain\n}\n", "import process from 'node:process'\n\n/**\n * Ctrl-Z at the palette, from the process side. React-free on purpose: the palette is pure\n * presentation and must not reach for `node:process`, and this half is worth unit-testing with plain\n * vitest (inject `kill`, assert the signal) rather than through an Ink frame.\n *\n * It lives under `src/tui/` rather than `src/lib/session/` because `boot.tsx` is its only caller and\n * the whole `src/tui/**` tree is the lazily-imported Ink chunk \u2014 the session layer never imports it,\n * and parking it there would drag it into the eager CLI chunk for nothing.\n */\n\n/** Seams for the stop. Production passes nothing; tests inject fakes and assert the signal. */\nexport interface SuspendDeps {\n platform?: NodeJS.Platform\n kill?: (pid: number, signal: NodeJS.Signals) => void\n}\n\n/**\n * Stop the foreground PROCESS GROUP so the user's shell reclaims the tty and prints a prompt.\n * Returns when the job is resumed (`fg` \u2192 SIGCONT): the kill halts JS synchronously, and execution\n * continues at the next statement \u2014 so there is no SIGCONT handler and nothing to re-arm.\n *\n * **pid 0 is the whole process group, and that is load-bearing.** Under `pnpm exec infra-kit`, pnpm's\n * node wrapper shares our pgid and the interactive shell only ever waits on PNPM \u2014 we are a\n * grandchild it never reaps. Stopping only ourselves would leave pnpm blocked in `waitpid`, so the\n * job never reads as stopped, the shell never reclaims the tty, and the terminal wedges with no\n * prompt and no way back. Stopping the group suspends the job as a unit, exactly as the tty's own\n * Ctrl-Z would; on direct-bin invocation it degenerates to a self-stop, so this is one code path.\n *\n * Only ever called from inside Ink's `suspendTerminal`, which has already erased the frame, restored\n * the cursor and dropped raw mode by the time we get here.\n *\n * `bg` is NOT supported: on resume Ink re-arms raw mode, and a `tcsetattr` from a background process\n * group raises SIGTTOU, which stops the job again. Same as vim. Use `fg`.\n *\n * @example\n * const stopped: number[] = []\n * suspendForeground({ platform: 'darwin', kill: (pid) => stopped.push(pid) })\n * stopped // => [0] (the process group, not process.pid)\n */\nexport const suspendForeground = (deps: SuspendDeps = {}): void => {\n const platform = deps.platform ?? process.platform\n const kill =\n deps.kill ??\n ((pid: number, signal: NodeJS.Signals) => {\n process.kill(pid, signal)\n })\n\n // SIGSTOP does not exist on Windows: `process.kill` there goes to uv_kill, which fails with ENOSYS\n // and THROWS. That throw would surface inside an Ink input handler \u2192 the ErrorBoundary \u2192\n // `handleExit(error)` \u2192 the session shell would silently QUIT. And Windows really does reach this\n // code: `sessionGateEnabled` (lib/session/run-session.ts) gates on TTYs only, with no platform\n // check, so Windows Terminal enters the palette like any other. Belt to boot.tsx's braces.\n if (platform === 'win32') {\n return\n }\n\n // No cursor/newline work here, deliberately: Ink's `beginSuspend` has already erased its frame and\n // left the cursor at column 0, so the shell's \"suspended\" line lands on a clean row. Writing a\n // newline first only opens a gratuitous blank gap above it (verified on a real pty).\n try {\n kill(0, 'SIGSTOP')\n } catch {\n // A stop we could not perform must degrade to a no-op, never to a crash: we are called mid\n // terminal-restore, and throwing here would take the session down with the tty half-handed-back.\n }\n}\n"],
5
- "mappings": "wCAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,OAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,GAAQ,YAAAC,GAAU,iBAAAC,OAAqB,MAC3D,OAAS,aAAAC,GAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,YAAAC,MAAgB,QA+B3B,IAAMC,EAAgB,CAAIC,EAAYC,IAA+C,CAC1F,GAAM,CAACC,EAAOC,CAAQ,EAAIL,EAAS,EAAE,EAC/B,CAACM,EAAOC,CAAQ,EAAIP,EAAS,CAAC,EAE9BQ,EAAWT,GAAQ,IAAM,CAC7B,IAAMU,EAAIL,EAAM,KAAK,EAAE,YAAY,EAEnC,OAAKK,EAIEP,EAAM,OAAQQ,GACZP,EAAOO,CAAI,EAAE,YAAY,EAAE,SAASD,CAAC,CAC7C,EALQP,CAMX,EAAG,CAACA,EAAOE,EAAOD,CAAM,CAAC,EAEnBQ,EAAc,KAAK,IAAIL,EAAO,KAAK,IAAI,EAAGE,EAAS,OAAS,CAAC,CAAC,EAmDpE,MAAO,CAAE,SAAAA,EAAU,YAAAG,EAAa,MAAAP,EAAO,iBAjDd,CAACQ,EAAeC,IAAsB,CAC7D,IAAMC,EAAIN,EAAS,OAEnB,OAAIK,EAAI,SAEFC,EAAI,GACNP,GAAUI,EAAc,EAAIG,GAAKA,CAAC,EAG7B,IAGLD,EAAI,WACFC,EAAI,GACNP,G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Aa,EAAQA,EAAO,KAC9B,CAAC,EAED,GAAI,CACF,MAAME,EAAc,CACtB,MAAQ,CAGR,QAAE,CACAE,GAAQ,MAAM,IAAI,CACpB,CACF,EAOaC,GAAoB,MAAOC,GAAiD,CACvF,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACW,GAAA,CACC,MAAOF,EACP,SAAWG,GAAS,CAClBF,EAAWE,CACb,EACA,SAAU,IAAM,CACdF,EAAW,IACb,EAIA,UACEH,GAAQ,WAAa,QACjB,OACA,IAAM,CACJM,GAAkB,CACpB,EAER,CACF,EAEOH,CACT,EAMaI,GAAkB,MAAOL,GAAsD,CAC1F,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACe,GAAA,CACC,MAAON,EACP,SAAWO,GAAU,CACnBN,EAAWM,CACb,EACA,SAAU,IAAM,CACdN,EAAW,IACb,EACF,CACF,EAEOA,CACT,EAQaO,GAAuB,MAClCR,EACAS,IAC6B,CAC7B,IAAIR,EAA4B,KAEhC,aAAMT,EACJD,EAACmB,GAAA,CACC,MAAOV,EACP,SAAUS,GAAM,SAChB,eAAgBA,GAAM,eACtB,SAAWE,GAAW,CACpBV,EAAWU,CACb,EACA,SAAU,IAAM,CACdV,EAAW,IACb,EACF,CACF,EAEOA,CACT",
6
- "names": ["render", "process", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "useMemo", "useState", "useListFilter", "items", "toText", "query", "setQuery", "index", "setIndex", "filtered", "q", "item", "activeIndex", "input", "key", "n", "NO_GROUPS", "listLayout", "rows", "extraChromeRows", "heightOf", "items", "start", "end", "groupOf", "height", "previousGroup", "index", "item", "group", "startsGroup", "endThatFits", "budget", "paletteWindow", "activeIndex", "opts", "first", "jsx", "jsxs", "BranchMultiPicker", "props", "items", "onSubmit", "onCancel", "required", "allowSelectAll", "T", "BRANCH_MULTI_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "toggleValue", "value", "prev", "next", "toggleSelectAll", "cancel", "submit", "useInput", "input", "key", "active", "Text", "Box", "position", "isActive", "isChecked", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "jsx", "jsxs", "BranchPicker", "props", "items", "onSelect", "onCancel", "T", "BRANCH_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "windowStart", "setWindowStart", "useState", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "cancel", "useInput", "input", "key", "selected", "Text", "Box", "position", "isActive", "labelColor", "type", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useMemo", "useState", "jsx", "jsxs", "CommandPalette", "props", "items", "onSelect", "onCancel", "onSuspend", "T", "hintFor", "nameWidth", "exit", "suspendTerminal", "useApp", "rows", "useWindowSize", "query", "setQuery", "useState", "index", "setIndex", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "filtered", "useMemo", "q", "item", "activeIndex", "layout", "listLayout", "view", "paletteWindow", "quit", "suspend", "handleCtrlKey", "input", "step", "delta", "n", "useInput", "key", "selected", "Text", "lastGroup", "Box", "position", "isActive", "showGroup", "HINTS", "canSuspend", "process", "suspendForeground", "deps", "platform", "kill", "pid", "signal", "jsx", "renderToStderr", "element", "stdout", "safeStderr", "waitUntilExit", "render", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "suspendForeground", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
7
- }
@@ -1,7 +0,0 @@
1
- import{O as E,u as m}from"./chunk-IVWPZEMC.js";import{q as w}from"./chunk-CHETBZ6M.js";import f from"node:fs/promises";import c from"node:path";import{z as s}from"zod";var i=class extends Error{env;constructor(e,o=null){super(e),this.name="EnvAuthError",this.env=o}},J=t=>t instanceof i;import b from"node:fs/promises";import $ from"node:os";var C=async t=>{try{return await b.access(t),!0}catch{return!1}},l=t=>{let e=$.homedir();return t.startsWith(e)?`~${t.slice(e.length)}`:t};var I="tokens.json",p=1,k=384,y=448,M=s.object({version:s.literal(p).default(p),envs:s.record(s.string().min(1),s.string().min(1))}).strict(),d=async()=>{let t=await E();return c.join(c.dirname(t.userProject),I)},u=async()=>{let t=await d(),e;try{e=await f.readFile(t,"utf-8")}catch{return null}let o;try{o=JSON.parse(e)}catch(n){throw new i(`Invalid JSON in the token store at ${l(t)}: ${n.message}
2
- Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let r=M.safeParse(o);if(!r.success)throw new i(`Invalid token store at ${l(t)}: ${s.prettifyError(r.error)}
3
- Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return r.data},g=async t=>{let e=await d(),o=c.dirname(e),r=c.dirname(o),n=c.dirname(r);for(let a of[n,r,o])await f.mkdir(a,{recursive:!0,mode:y}),await f.chmod(a,y);w(e,`${JSON.stringify(t,null,2)}
4
- `,k),await f.chmod(e,k)},N=async(t,e)=>{let o=await u();await g({version:p,envs:{...o?.envs,[t]:e}})},_=async t=>{let e=await u();if(!e||!(t in e.envs))return;let o={...e.envs};delete o[t],await g({version:p,envs:o})};var j=()=>{let t="",e=[],o=!1;return{start(r){t=r,e=[],o=!1},setInteractive(){o=!0},addOption(r,n){e.push({flag:r,value:n})},formatOptions(){return e.map(r=>typeof r.value=="boolean"?r.value?r.flag:"":Array.isArray(r.value)?`${r.flag} "${r.value.join(", ")}"`:`${r.flag} "${r.value}"`).filter(Boolean).join(" ")},snapshot(){return e.length===0?null:{formattedOptions:this.formatOptions()}},print(){!o||e.length===0||!t||m.info(`\u{1F4DF} Equivalent command:
5
- pnpm exec infra-kit ${t} ${this.formatOptions()}
6
- `)},reset(){t="",e=[],o=!1}}},h=j();import T from"node:process";var S={enabled:!1},v=()=>S.enabled;var D=27,O=async(t,e)=>{let o=new AbortController,r={...e,signal:o.signal};if(v()||!T.stdin.isTTY)return t(r);let n=T.stdin,a=x=>{x.length===1&&x[0]===D&&o.abort()},P=t(r);n.on("data",a);try{return await P}finally{n.removeListener("data",a)}};import A from"@inquirer/confirm";import F from"node:process";var R=async(t,e)=>{let o=t?!0:await O(r=>A({message:e},r));t||h.setInteractive(),o||(m.info("Operation cancelled. Exiting..."),F.exit(0))};export{i as a,J as b,C as c,l as d,d as e,u as f,N as g,_ as h,h as i,S as j,v as k,O as l,R as m};
7
- //# sourceMappingURL=chunk-GZNE5CBQ.js.map
@@ -1,4 +0,0 @@
1
- import L from"node:process";import C from"pino";import re from"pino-pretty";var _="/tmp/mcp-infra-kit.log",K=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],bt=()=>{let e=L.argv.includes("--debug")?"debug":"info",t=C({level:e,redact:K},C.destination({dest:_}));return t.info(`Logger initialized with level: ${e}. Logging to: ${_}`),t},ne=()=>{let e=L.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),C({level:e,redact:K},re({destination:2,ignore:t.join(","),colorize:!0}))},Ct=ne();import*as p from"node:fs";import*as a from"node:path";function oe(e){let t=e;for(let r=0;r<10;r++){let n=a.join(t,"pnpm-workspace.yaml");if(p.existsSync(n))return t;t=a.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function M(e,t){let r=a.join(e,"package.json");if(!p.existsSync(r))return t;try{let n=JSON.parse(p.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:t}catch{return t}}function It(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let n=p.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=a.join(t,o,"api"),c=a.join(i,"serverless.yml");p.existsSync(c)&&r.push({name:o,packageName:M(i,o),path:i})}return r}var se=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],ie=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function ae(e){for(let t of se){let r=a.join(e,t);if(p.existsSync(r))try{let n=p.readFileSync(r,"utf-8");return ie.some(o=>n.includes(o))}catch{return!1}}return!1}function ce(e){let t=a.join(e,"package.json");if(!p.existsSync(t))return!1;try{let r=JSON.parse(p.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function Et(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))return r;let n=p.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=a.join(t,o,"ui");p.existsSync(i)&&ce(i)&&r.push({name:o,packageName:M(i,o),path:i,managedPort:ae(i)})}return r}function jt(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function Dt(e){let t=oe(e),r=a.relative(a.join(t,"apps"),e),n=r.split(a.sep)[0];if(r===""||r.startsWith("..")||a.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return n}var pe=new Set(["api","ui"]),O=e=>{let t=a.join(e,"dist");return p.existsSync(t)&&p.statSync(t).isDirectory()?t:void 0},S=e=>p.existsSync(e)?p.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function At(e){let t=[];for(let n of S(a.join(e,"packages"))){let o=O(a.join(e,"packages",n));o!==void 0&&t.push(o)}let r=a.join(e,"apps");for(let n of S(r))for(let o of S(a.join(r,n))){if(pe.has(o))continue;let i=a.join(r,n,o);if(!p.existsSync(a.join(i,"package.json")))continue;let c=O(i);c!==void 0&&t.push(c)}return t}function $t(e){return e.map(t=>a.join(t.path,"dist")).filter(t=>p.existsSync(t))}function Nt(e,t,r){let n=a.normalize(e),o=r.find(c=>n.startsWith(a.normalize(c)));return o?{kind:"package",packageDir:o}:{kind:"app",app:t.find(c=>n.startsWith(a.normalize(c)))}}var le={"*/api":{},"*/ui":{}},B=e=>{let t=e.split("/"),[r,n]=t;return t.length!==2||!r?`devServersPresets: invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${e}" (expected "api" or "ui")`:null},ue=e=>{let t=B(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},_t=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let o of Object.keys(n.apps??{})){let i=B(o);i&&t.push({preset:r,key:o,message:`preset "${r}": ${i}`})}return t},fe=(e,t)=>t==="api"?e.api:e.ui,ge=e=>[...new Set([...e.api,...e.ui])].sort(),F=(e,t)=>`${e}/${t}`,de=e=>e?0:1,me=(e,t)=>t.watchDeps===void 0?e??{watchDeps:!0,rank:t.rank,explicitValue:!1}:!e||!e.explicitValue?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:t.rank>e.rank?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:e,he=(e,t,r)=>{let{app:n,part:o,watchDeps:i,isGlob:c}=r;if(!fe(t,o).includes(n)){c||e.unmatched.push(F(n,o));return}let l=F(n,o),u=me(e.targets.get(l),{watchDeps:i,rank:de(c)});e.targets.set(l,{app:n,part:o,...u})},ve=(e,t)=>{let r=Object.entries(e.apps??le),n={targets:new Map,proxy:{},unmatched:[]};for(let[c,l]of r){let{appGlob:u,part:h}=ue(c),P=u==="*",R=P?ge(t):[u];for(let b of R)he(n,t,{app:b,part:h,watchDeps:l.watchDeps,isGlob:P}),l.proxy&&(n.proxy[b]={...n.proxy[b]??{},...l.proxy})}let o=[...n.targets.values()].map(({app:c,part:l,watchDeps:u})=>({app:c,part:l,watchDeps:u})),i=[...new Set(o.filter(c=>c.part==="api").map(c=>c.app))];return{targets:o,cmux:e.cmux??!1,proxy:n.proxy,localApps:i,unmatched:n.unmatched}},Lt=e=>{if(e.preset!=null)return e.preset;if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(n=>t.has(n))?"*":[...t].sort().join(" + ")},ye=(e,t)=>Object.keys(e).find(r=>e[r]===t),xe=({preset:e,app:t,route:r,launchedPkgs:n,ctx:o})=>{let i=o.routePkg(t,r);if(i===void 0)return{preset:e,app:t,route:r,kind:"unknown-route",message:`preset "${e}": proxy override "${r}" on "${t}" names a route not declared in ${t}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(i))return null;let c=ye(o.apiPkgByApp,i),l=c?`add "${c}/api" to the preset`:`launch the api whose package is "${i}"`;return{preset:e,app:t,route:r,pkg:i,kind:"backend-not-launched",message:`preset "${e}": proxy override "${r}" \u2192 "local" requires backend "${i}" to run locally, but the preset does not launch it \u2014 ${l}, or set "${r}" to "cloud"`}},Kt=(e,t)=>{let r=[];for(let[n,o]of Object.entries(e)){let i=ve(o,t.discovered),c=new Set(i.localApps.map(l=>t.apiPkgByApp[l]).filter(l=>l!==void 0));for(let[l,u]of Object.entries(i.proxy))for(let[h,P]of Object.entries(u)){if(P!=="local")continue;let R=xe({preset:n,app:l,route:h,launchedPkgs:c,ctx:t});R&&r.push(R)}}return r};import N from"node:fs/promises";import Y from"node:os";import x from"node:path";import Me from"node:process";import{z as s}from"zod";import d from"node:path";import{$ as f}from"zx";var ke=/^v?(\d+)\.(\d+)\.(\d+)$/,Pe=/^(\d+)\.(\d+)\.(\d+)$/,Re=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,w="release/",I="release/v",G="refs/heads/",we="next";var z=new Set(["dev","main","next","hotfix","regular","release"]),g=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},v=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},W=e=>e.startsWith(G)?e.slice(G.length):e,U=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),E=e=>{if(e.length===0)throw new g('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new g(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!Re.test(e))throw new g(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(z.has(e))throw new g(`Release name "${e}" is reserved. Reserved names: ${[...z].join(", ")}.`)},j=e=>{let t=W(e.trim());if(!t.startsWith(w))return null;if(t.startsWith(I)){let n=t.slice(I.length),o=Pe.exec(n);if(o)return U(Number(o[1]),Number(o[2]),Number(o[3]))}let r=t.slice(w.length);try{E(r)}catch{return null}return{kind:"name",name:r,raw:r}},be=e=>{let t=e.trim();if(W(t).startsWith(w)){let o=j(t);if(!o)throw new v(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return o}let n=ke.exec(t);if(n)return U(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===we)throw new v('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{E(t)}catch(o){let i=o instanceof Error?o.message:String(o);throw new v(`Cannot parse "${e}" as a release ref: ${i}`)}return{kind:"name",name:t,raw:t}},Ce=e=>e.kind==="version"?`${I}${e.raw}`:`${w}${e.name}`,Se=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ie=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Ee=e=>e.kind==="version"?`v${e.raw}`:e.name,je=e=>e.raw,D=e=>e==null?!1:j(e)!==null,V=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},De=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let n=V(r?.a),o=V(r?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<t.name?-1:e.name>t.name?1:0};var Ae=async e=>{let r=(await f`git worktree list`).stdout.split(`
2
- `).filter(Boolean),n={release:$e,feature:Ne};return r.map(n[e]).filter(o=>o!==null)},H=e=>{let t=e.trimEnd();if(!t.endsWith("]"))return null;let r=t.lastIndexOf("[");if(r===-1)return null;let n=t.slice(r+1,-1);return n.length>0?n:null},$e=e=>{let t=H(e);return D(t)?t:null},Ne=e=>{let t=H(e);return t?.startsWith("feature/")?t:null},y=async()=>(await f`git rev-parse --show-toplevel`).stdout.trim(),A=async e=>{let t=e??await y(),r=(await f({cwd:t})`git rev-parse --git-common-dir`).stdout.trim(),n=d.resolve(t,r);return n.includes(`${d.sep}.git${d.sep}modules${d.sep}`)?t:d.dirname(n)},X=async()=>(await f`git rev-parse --abbrev-ref HEAD`).stdout.trim(),Te=async()=>(await f`git status --porcelain`).stdout.trim().length===0,_e=async()=>{let e=await y(),[t,r]=await Promise.all([f({cwd:e})`git rev-parse --absolute-git-dir`,f({cwd:e})`git rev-parse --git-common-dir`]),n=t.stdout.trim(),o=d.resolve(e,r.stdout.trim());return n!==o},Le=async()=>{let e=await y();return d.basename(e)},Ke=async e=>{(await f`git branch --list ${e}`).stdout.trim().length!==0&&await X()!==e&&await f`git branch -D ${e}`},Oe=async e=>{(await f`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await f`git push origin --delete ${e}`};var q="infra-kit.json",Q=".infra-kit",Fe="infra-kit.json",Be="projects",Ge=s.object({provider:s.literal("doppler"),config:s.object({name:s.string().min(1)})}),ze=s.discriminatedUnion("provider",[Ge]),Ve=s.object({workspaceConfigPath:s.string().min(1)}),We=s.object({provider:s.literal("cursor"),config:Ve}),Ue=s.object({}),He=s.object({provider:s.literal("zed"),config:Ue}),J=s.discriminatedUnion("provider",[We,He]),Xe=s.union([J,s.array(J).min(1)]),qe=s.object({provider:s.literal("jira"),config:s.object({baseUrl:s.string().url(),projectId:s.number().int().positive()})}),Je=s.discriminatedUnion("provider",[qe]),Ye=["two-columns","three-pane"],Qe=s.object({layout:s.enum(Ye).optional()}),Ze=s.object({openInGithubDesktop:s.boolean().optional(),openInCmux:s.boolean().optional(),cmux:Qe.optional()}),et=s.object({port:s.number().int().positive().optional(),prefixUrl:s.string().min(1).optional()}).strict(),tt=s.record(s.string().min(1),et),rt=s.enum(["local","cloud"]),nt=s.object({watchDeps:s.boolean().optional(),proxy:s.record(s.string().min(1),rt).optional()}).strict(),ot=s.object({apps:s.record(s.string().min(1),nt).optional(),cmux:s.boolean().optional()}).strict(),st=s.record(s.string().min(1),ot),it=s.object({port:s.number().int().positive().optional()}).strict(),at=s.object({trigger:s.enum(["shell-startup","cli-invocation"]),config:s.string().min(1)}).strict(),T=s.object({envManagement:ze,ide:Xe.optional(),taskManager:Je.optional(),worktrees:Ze.optional(),envAutoLoad:at.optional(),dev:tt.optional(),devServersPresets:st.optional(),devProxy:it.optional()}).strict(),ct=443,Z=T.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let n of e.ide){if(r.has(n.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(n.provider)}}),ee=T.partial(),pt=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},lt="two-columns",ut=e=>e.worktrees?.cmux?.layout??lt,m=null,k=null,ft=()=>`${Me.cwd()} ${Y.homedir()}`,te=async()=>{let e=ft();if(k&&k.key===e)return k.value;let t=await y(),r=await A(t),n=x.basename(r),o=x.join(Y.homedir(),Q),i={main:x.join(t,q),userGlobal:x.join(o,Fe),userProject:x.join(o,Be,n,q),projectName:n};return k={key:e,value:i},i},gt=async()=>{let e=await te(),t;try{t=await N.stat(e.main)}catch{m=null;let u=e.main.replace(/\.json$/,".yml");throw await $(u)?new Error(`infra-kit.json not found at ${e.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(`infra-kit.json not found at ${e.main}`)}let[r,n]=await Promise.all([$(e.userGlobal),$(e.userProject)]),o={main:Number(t.mtimeMs),userGlobal:r?Number(r.mtimeMs):null,userProject:n?Number(n.mtimeMs):null};if(m&&vt(m.mtimes,o))return m.value;let i=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],c={};for(let u of i){let h=await yt(u);h!==null&&(c={...c,...h})}let l=Z.safeParse(c);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${s.prettifyError(l.error)}`);return m={mtimes:o,value:l.data},l.data},dt=()=>{m=null},mt=()=>{m=null,k=null},$=async e=>{try{return await N.stat(e)}catch{return null}},ht=async e=>{try{return await N.readFile(e,"utf-8")}catch{return null}},vt=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},yt=async e=>{let t=await ht(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${o.message}`)}if(xt(r)&&"envTokens"in r)throw new Error(kt(e));let n=ee.safeParse(r);if(!n.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${s.prettifyError(n.error)}`);return n.data},xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kt=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
3
- `);export{g as a,E as b,j as c,be as d,Ce as e,Se as f,Ie as g,Ee as h,je as i,D as j,De as k,Ae as l,y as m,Te as n,_e as o,Le as p,Ke as q,Oe as r,_ as s,bt as t,Ct as u,oe as v,It as w,Et as x,jt as y,Dt as z,At as A,$t as B,Nt as C,B as D,_t as E,ve as F,Lt as G,Kt as H,Q as I,ct as J,Z as K,ee as L,pt as M,ut as N,te as O,gt as P,dt as Q,mt as R};
4
- //# sourceMappingURL=chunk-IVWPZEMC.js.map