infra-kit 0.1.134 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/boot-YQAPYAKT.js +2 -0
- package/dist/boot-YQAPYAKT.js.map +7 -0
- package/dist/chunk-A7FAXZGI.js +2 -0
- package/dist/chunk-A7FAXZGI.js.map +7 -0
- package/dist/chunk-AVLZBOOA.js +4 -0
- package/dist/chunk-AVLZBOOA.js.map +7 -0
- package/dist/chunk-JPTSUMWI.js +2 -0
- package/dist/chunk-JPTSUMWI.js.map +7 -0
- package/dist/chunk-KAKTWDWJ.js +7 -0
- package/dist/chunk-KAKTWDWJ.js.map +7 -0
- package/dist/chunk-TI33V5G2.js +6 -0
- package/dist/chunk-TI33V5G2.js.map +7 -0
- package/dist/chunk-TL7LO2FF.js +231 -0
- package/dist/chunk-TL7LO2FF.js.map +7 -0
- package/dist/{chunk-FAR2L74S.js → chunk-TPVXMJ7N.js} +1 -1
- package/dist/chunk-UO3FYLPX.js +2 -0
- package/dist/chunk-UO3FYLPX.js.map +7 -0
- package/dist/{chunk-27PDA2PN.js → chunk-V4XK2YEH.js} +2 -2
- package/dist/cli.js +10 -7
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +21 -20
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-2ISRQPGA.js +2 -0
- package/dist/dev-wizard-run-2ISRQPGA.js.map +7 -0
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +3 -3
- package/dist/persistent-ink-dev-ui-KOI44ZVT.js +2 -0
- package/dist/persistent-ink-dev-ui-KOI44ZVT.js.map +7 -0
- package/dist/safe-stderr-HXDR2DNJ.js +2 -0
- package/dist/update-check.js +1 -1
- package/package.json +4 -15
- package/dist/boot-YCABHUPP.js +0 -2
- package/dist/boot-YCABHUPP.js.map +0 -7
- package/dist/chunk-2YHPK2VY.js +0 -221
- package/dist/chunk-2YHPK2VY.js.map +0 -7
- package/dist/chunk-3F7XYJWY.js +0 -3
- package/dist/chunk-3F7XYJWY.js.map +0 -7
- package/dist/chunk-3OMHS5RE.js +0 -2
- package/dist/chunk-3OMHS5RE.js.map +0 -7
- package/dist/chunk-6FU2TRU5.js +0 -2
- package/dist/chunk-6FU2TRU5.js.map +0 -7
- package/dist/chunk-DOG3OPNW.js +0 -2
- package/dist/chunk-DOG3OPNW.js.map +0 -7
- package/dist/chunk-JD5T4VCB.js +0 -6
- package/dist/chunk-JD5T4VCB.js.map +0 -7
- package/dist/chunk-LTKR3F4N.js +0 -2
- package/dist/chunk-LTKR3F4N.js.map +0 -7
- package/dist/chunk-TFHVQOVF.js +0 -4
- package/dist/chunk-TFHVQOVF.js.map +0 -7
- package/dist/chunk-TUVUKM4K.js +0 -2
- package/dist/chunk-TUVUKM4K.js.map +0 -7
- package/dist/chunk-Z6KTUVIC.js +0 -2
- package/dist/chunk-Z6KTUVIC.js.map +0 -7
- package/dist/dev-wizard-run-HGQO6FZV.js +0 -2
- package/dist/dev-wizard-run-HGQO6FZV.js.map +0 -7
- package/dist/entry/index.d.ts +0 -4
- package/dist/entry/vite.d.ts +0 -2
- package/dist/index.js +0 -2
- package/dist/lib/package-config/package-config-schema.d.ts +0 -35
- package/dist/lib/package-config/package-config.d.ts +0 -99
- package/dist/lib/release-slug/release-slug.d.ts +0 -43
- package/dist/lib/vendor/config-schema.d.ts +0 -58
- package/dist/lib/vite/vite.d.ts +0 -168
- package/dist/persistent-ink-dev-ui-FUJQDFNY.js +0 -8
- package/dist/persistent-ink-dev-ui-FUJQDFNY.js.map +0 -7
- package/dist/vite.js +0 -2
- package/dist/vite.js.map +0 -7
- /package/dist/{chunk-FAR2L74S.js.map → chunk-TPVXMJ7N.js.map} +0 -0
- /package/dist/{chunk-27PDA2PN.js.map → chunk-V4XK2YEH.js.map} +0 -0
- /package/dist/{index.js.map → safe-stderr-HXDR2DNJ.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as Z}from"./chunk-TPVXMJ7N.js";import{render as Oe}from"ink";import ce from"node:process";import{Box as J,Text as v,useApp as pe,useInput as fe,useWindowSize as he}from"ink";import{useEffect as j,useState as F}from"react";import{useMemo as ue,useState as V}from"react";var k=(e,t)=>{let[o,d]=V(""),[i,a]=V(0),l=ue(()=>{let p=o.trim().toLowerCase();return p?e.filter(c=>t(c).toLowerCase().includes(p)):e},[e,o,t]),s=Math.min(i,Math.max(0,l.length-1));return{filtered:l,activeIndex:s,query:o,handleNavigation:(p,c)=>{let w=l.length;return c.upArrow?(w>0&&a((s-1+w)%w),!0):c.downArrow?(w>0&&a((s+1)%w),!0):c.backspace||c.delete?(d(o.slice(0,-1)),a(0),!0):p&&!c.ctrl&&!c.meta?(d(o+p),a(0),!0):!1}}};var me=()=>{},M=(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},de=(e,t,o,d)=>{let i=0,a;for(let l=t;l<o;l+=1){let s=e[l];if(!s)break;let h=d(s),p=h!==void 0&&h!==a;i+=1+(p?1:0)+(p&&l>t?1:0),a=h}return i},X=(e,t,o,d)=>{let i=t;for(;i<e.length&&de(e,t,i+1,d)<=o;)i+=1;return i},E=(e,t,o,d,i)=>{let a=i?.groupOf??me,l=Math.max(0,d-(i?.chromeRows??6)),s=Math.min(t,o);for(;o>=X(e,s,l,a)&&s<o;)s+=1;let h=X(e,s,l,a);return{visible:e.slice(s,h),start:s,hiddenBefore:s,hiddenAfter:Math.max(0,e.length-h)}};import{jsx as B,jsxs as G}from"react/jsx-runtime";var ee=e=>{let{items:t,onSubmit:o,onCancel:d,required:i=!0,allowSelectAll:a=!0}=e,l={hint:"Select branches \u2014 type to filter, \u2191\u2193 to move, Space to toggle, Ctrl-A all, Enter to submit, Esc to cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"},s=t.reduce((r,n)=>Math.max(r,n.label.length),0),{exit:h}=pe(),{rows:p}=he(),{filtered:c,activeIndex:w,query:A,handleNavigation:R}=k(t,we),[b,L]=F(()=>new Set),[S,g]=F(!1),[m,x]=F(0),[f,T]=F(!1);j(()=>{f&&h()},[f,h]);let I=M(p,1),y=E(c,m,w,p,{chromeRows:I.chromeRows});j(()=>{y.start!==m&&x(y.start)},[y.start,m]);let K=r=>{L(n=>{let u=new Set(n);return u.has(r)?u.delete(r):u.add(r),u})},q=()=>{L(r=>t.every(u=>r.has(u.value))?new Set:new Set(t.map(u=>u.value)))},_=()=>{if(i&&b.size===0){g(!0);return}o([...b]),T(!0)};return fe((r,n)=>{if(!f){if(n.escape||n.ctrl&&r==="c"){d(),T(!0);return}if(n.ctrl&&r==="a"){a&&q();return}if(r===" "){let u=c[w];u&&K(u.value);return}if(n.return){_();return}R(r,n)}}),f?null:I.mode==="tiny"?B(v,{dimColor:!0,wrap:"truncate",children:l.tiny}):G(J,{flexDirection:"column",children:[I.mode==="full"?B(v,{dimColor:!0,wrap:"truncate",children:l.hint}):null,G(J,{children:[B(v,{color:"cyan",children:l.prompt}),B(v,{wrap:"truncate-start",children:A})]}),G(J,{flexDirection:"column",marginTop:I.mode==="full"?1:0,children:[c.length===0?B(v,{dimColor:!0,wrap:"truncate",children:l.empty}):null,y.hiddenBefore>0?B(v,{dimColor:!0,wrap:"truncate",children:`${l.more} ${y.hiddenBefore} above`}):null,y.visible.map((r,n)=>{let u=y.start+n===w,N=b.has(r.value);return G(v,{color:u?"green":void 0,wrap:"truncate",children:[u?"\u203A ":" ",N?"[x] ":"[ ] ",r.label.padEnd(s)," ",B(v,{dimColor:!0,children:r.description??""})]},r.value)}),y.hiddenAfter>0?B(v,{dimColor:!0,wrap:"truncate",children:`${l.more} ${y.hiddenAfter} below`}):null]}),S?B(v,{dimColor:!0,wrap:"truncate",children:l.requiredHint}):null]})};function we(e){return`${e.label} ${e.description??""}`}import{Box as Y,Text as O,useApp as xe,useInput as ge,useWindowSize as be}from"ink";import{useEffect as te,useState as re}from"react";import{jsx as W,jsxs as H}from"react/jsx-runtime";var ne=e=>{let{items:t,onSelect:o,onCancel:d}=e,i={hint:"Select a branch \u2014 type to filter, \u2191\u2193 to move, Enter to select, Esc to cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"},a=t.reduce((m,x)=>Math.max(m,x.label.length),0),{exit:l}=xe(),{rows:s}=be(),{filtered:h,activeIndex:p,query:c,handleNavigation:w}=k(t,Se),[A,R]=re(0),[b,L]=re(!1);te(()=>{b&&l()},[b,l]);let S=M(s),g=E(h,A,p,s,{chromeRows:S.chromeRows});return te(()=>{g.start!==A&&R(g.start)},[g.start,A]),ge((m,x)=>{if(!b){if(x.escape||x.ctrl&&m==="c"){d(),L(!0);return}if(x.return){let f=h[p];f&&(o(f.value),L(!0));return}w(m,x)}}),b?null:S.mode==="tiny"?W(O,{dimColor:!0,wrap:"truncate",children:i.tiny}):H(Y,{flexDirection:"column",children:[S.mode==="full"?W(O,{dimColor:!0,wrap:"truncate",children:i.hint}):null,H(Y,{children:[W(O,{color:"cyan",children:i.prompt}),W(O,{wrap:"truncate-start",children:c})]}),H(Y,{flexDirection:"column",marginTop:S.mode==="full"?1:0,children:[h.length===0?W(O,{dimColor:!0,wrap:"truncate",children:i.empty}):null,g.hiddenBefore>0?W(O,{dimColor:!0,wrap:"truncate",children:`${i.more} ${g.hiddenBefore} above`}):null,g.visible.map((m,x)=>{let f=g.start+x===p;return H(O,{color:Te(m.type,f),wrap:"truncate",children:[f?"\u203A ":" ",m.label.padEnd(a)," ",W(O,{dimColor:!0,children:m.description??""})]},m.value)}),g.hiddenAfter>0?W(O,{dimColor:!0,wrap:"truncate",children:`${i.more} ${g.hiddenAfter} below`}):null]})]})};function Te(e,t){return e==="hotfix"?"red":t?"green":void 0}function Se(e){return`${e.label} ${e.description??""}`}import{Box as D,Text as C,useApp as ye,useInput as Ce,useWindowSize as ve}from"ink";import{useEffect as oe,useMemo as Pe,useState as z}from"react";import{jsx as P,jsxs as $}from"react/jsx-runtime";var le=e=>{let{items:t,onSelect:o,onCancel:d,onSuspend:i}=e,a={hint:Be(!!i),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},l=24,{exit:s,suspendTerminal:h}=ye(),{rows:p}=ve(),[c,w]=z(""),[A,R]=z(0),[b,L]=z(0),[S,g]=z(!1);oe(()=>{S&&s()},[S,s]);let m=Pe(()=>{let r=c.trim().toLowerCase();return r?t.filter(n=>`${n.name} ${n.description}`.toLowerCase().includes(r)):t},[t,c]),x=Math.min(A,Math.max(0,m.length-1)),f=M(p),T=E(m,b,x,p,{chromeRows:f.chromeRows,groupOf:f.groups?r=>r.group:void 0});oe(()=>{T.start!==b&&L(T.start)},[T.start,b]);let I=()=>{d(),g(!0)},y=()=>{i&&h(i).catch(()=>{})},K=r=>r==="c"?(I(),!0):r==="z"?(y(),!0):!1,q=r=>{let n=m.length;n>0&&R((x+r+n)%n)};if(Ce((r,n)=>{if(!S&&!(n.ctrl&&K(r))){if(n.escape&&c){w(""),R(0);return}if(n.escape){I();return}if(n.return){let u=m[x];u&&(o(u.name),g(!0));return}if(n.upArrow){q(-1);return}if(n.downArrow){q(1);return}if(n.backspace||n.delete){w(c.slice(0,-1)),R(0);return}r&&!n.ctrl&&!n.meta&&(w(c+r),R(0))}}),S)return null;if(f.mode==="tiny")return P(C,{dimColor:!0,wrap:"truncate",children:a.tiny});let _="";return $(D,{flexDirection:"column",children:[f.mode==="full"?P(C,{dimColor:!0,wrap:"truncate",children:a.hint}):null,$(D,{children:[P(C,{color:"cyan",children:a.prompt}),P(C,{wrap:"truncate-start",children:c})]}),$(D,{flexDirection:"column",marginTop:f.mode==="full"?1:0,children:[m.length===0?P(C,{dimColor:!0,wrap:"truncate",children:a.empty}):null,T.hiddenBefore>0?P(C,{dimColor:!0,wrap:"truncate",children:`${a.more} ${T.hiddenBefore} above`}):null,T.visible.map((r,n)=>{let u=T.start+n===x,N=f.groups&&r.group!==_;return _=r.group,$(D,{flexDirection:"column",children:[N&&n>0?P(C,{children:" "}):null,N?P(C,{color:"yellow",wrap:"truncate",children:`\u2014 ${r.group} \u2014`}):null,$(C,{color:u?"green":void 0,wrap:"truncate",children:[u?"\u203A ":" ",r.name.padEnd(l)," ",P(C,{dimColor:!0,children:r.description})]})]},r.name)}),T.hiddenAfter>0?P(C,{dimColor:!0,wrap:"truncate",children:`${a.more} ${T.hiddenAfter} below`}):null]})]})},ie={suspend:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Ctrl-Z suspend \xB7 Esc cancel",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc cancel"},Be=e=>e?ie.suspend:ie.plain;import se from"node:process";var ae=(e={})=>{let t=e.platform??se.platform,o=e.kill??((d,i)=>{se.kill(d,i)});if(t!=="win32")try{o(0,"SIGSTOP")}catch{}};import{jsx as U}from"react/jsx-runtime";var Q=async e=>{let t=Z(),{waitUntilExit:o}=Oe(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await o()}catch{}finally{ce.stdin.ref()}},nt=async e=>{let t=null;return await Q(U(le,{items:e,onSelect:o=>{t=o},onCancel:()=>{t=null},onSuspend:ce.platform==="win32"?void 0:()=>{ae()}})),t},ot=async e=>{let t=null;return await Q(U(ne,{items:e,onSelect:o=>{t=o},onCancel:()=>{t=null}})),t},it=async(e,t)=>{let o=null;return await Q(U(ee,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:d=>{o=d},onCancel:()=>{o=null}})),o};export{it as runBranchMultiPicker,ot as runBranchPicker,nt as runCommandPalette};
|
|
2
|
+
//# sourceMappingURL=boot-YQAPYAKT.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
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 = {\n hint: 'Select branches \u2014 type to filter, \u2191\u2193 to move, Space to toggle, Ctrl-A all, Enter to submit, Esc to 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 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 } = 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 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.escape || (key.ctrl && input === 'c')) {\n onCancel()\n setSubmitted(true)\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", "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\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 return { filtered, activeIndex, query, handleNavigation }\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 = {\n hint: 'Select a branch \u2014 type to filter, \u2191\u2193 to move, Enter to select, Esc to 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 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 } = 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 useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.escape || (key.ctrl && input === 'c')) {\n onCancel()\n setSubmitted(true)\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", "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 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/** Footer copy. Kept out of the component's `T` because picking between the two is a conditional. */\nconst HINTS = {\n suspend: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Ctrl-Z suspend \u00B7 Esc cancel',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc cancel',\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,EAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,YAAAC,MAAgB,QAsB3B,IAAMC,EAAgB,CAAIC,EAAYC,IAA+C,CAC1F,GAAM,CAACC,EAAOC,CAAQ,EAAIL,EAAS,EAAE,EAC/B,CAACM,EAAOC,CAAQ,EAAIP,EAAS,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FC,EAAK,EAAG,SAAS,CACnB,MAAQ,CAGR,CACF,ENWI,cAAAG,MAAA,oBAvCJ,IAAMC,EAAiB,MAAOC,GAAyC,CACrE,IAAMC,EAASC,EAAW,EACpB,CAAE,cAAAC,CAAc,EAAIC,GAAOJ,EAAS,CACxC,OAAAC,EAOA,YAAa,GAOb,YAAa,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", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "toggleValue", "value", "prev", "next", "toggleSelectAll", "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", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "useListFilter", "filterText", "windowStart", "setWindowStart", "useState", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "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", "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
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var r=t=>Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("npm_")&&e!=="PNPM_SCRIPT_SRC_DIR")),o=/^npm_config_(?:prefix|registry)$/i,a=t=>{let e=r(t);for(let[n,s]of Object.entries(t))o.test(n)&&(e[n]=s);return e};export{r as a,a as b};
|
|
2
|
+
//# sourceMappingURL=chunk-A7FAXZGI.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/pm-env/pm-env.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install.\n *\n * Any child we launch through `node <bin>` (the portless driver, self-update, the mcp launcher) inherits\n * our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm dlx` and refuse\n * to work. portless is the motivating case; its guard (cli.js `main()`) is:\n *\n * isNpx = npm_command === 'exec' && !npm_lifecycle_event\n * isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n * if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) \u2192 abort\n *\n * `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n * transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is live.\n * `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event \u2192 `isNpx` \u2192 every\n * portless call exits 1 \u2192 `isAvailable()` is false \u2192 `ensureProxy` aborts the whole dev boot with\n * \"portless is not installed\", on a machine where it plainly is.\n *\n * `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n * `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n * `npm_*` removes that suppressor and *creates* an abort for the script-style invocation that\n * previously worked. Both markers go, or neither is safe.\n *\n * The result makes the child look exactly like a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config kept.\n *\n * {@link withoutPackageManagerEnv} is deliberately a blunt `npm_*` prefix filter, and it is the right tool\n * for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it also drops the two\n * variables that tell the package manager *where* and *from where* to install:\n *\n * - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and we\n * detect a global install rooted at prefix P, then run the install with P erased \u2014 so it lands in the\n * DEFAULT prefix instead. That is either a permanent EACCES, or a second global copy that is not the\n * one on PATH. Nothing notices: the install exits 0, we report `installed`, the version on PATH never\n * moves, and the whole cycle repeats every 24h forever. `export npm_config_prefix=~/.npm-global` is\n * npm's own documented EACCES workaround, so this is a mainstream layout, not an exotic one.\n * - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it here\n * means we decide against a corporate mirror and then install from somewhere else.\n *\n * Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`, `npm_lifecycle_event`, and\n * `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm *config*, and all of which remain stripped.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
|
|
5
|
+
"mappings": "AAwBO,IAAMA,EAA4BC,GAChC,OAAO,YACZ,OAAO,QAAQA,CAAG,EAAE,OAAO,CAAC,CAACC,CAAG,IACvB,CAACA,EAAI,WAAW,MAAM,GAAKA,IAAQ,qBAC3C,CACH,EASIC,EAAyB,oCAyBlBC,EAA4BH,GAA8C,CACrF,IAAMI,EAAYL,EAAyBC,CAAG,EAE9C,OAAW,CAACC,EAAKI,CAAK,IAAK,OAAO,QAAQL,CAAG,EACvCE,EAAuB,KAAKD,CAAG,IAAGG,EAAUH,CAAG,EAAII,GAGzD,OAAOD,CACT",
|
|
6
|
+
"names": ["withoutPackageManagerEnv", "env", "key", "NPM_CONFIG_TO_PRESERVE", "packageManagerInstallEnv", "sanitised", "value"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
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,X as n,Te as o,_e as p,Le as q,Ke as r,Oe as s,_ as t,bt as u,Ct as v,oe as w,It as x,Et as y,jt as z,Dt as A,At as B,$t as C,Nt as D,B as E,_t as F,ve as G,Lt as H,Kt as I,Q as J,ct as K,Z as L,ee as M,pt as N,ut as O,te as P,gt as Q,dt as R,mt as S};
|
|
4
|
+
//# sourceMappingURL=chunk-AVLZBOOA.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/logger/index.ts", "../src/dev/discovery.ts", "../src/dev/presets.ts", "../src/lib/infra-kit-config/infra-kit-config.ts", "../src/lib/git-utils/git-utils.ts", "../src/lib/release-id/release-id.ts"],
|
|
4
|
+
"sourcesContent": ["import process from 'node:process'\nimport pino from 'pino'\nimport pretty from 'pino-pretty'\n\n// eslint-disable-next-line sonarjs/publicly-writable-directories\nexport const LOG_FILE_PATH = '/tmp/mcp-infra-kit.log'\n\n/**\n * Key paths pino censors before anything reaches a destination. The load-bearing case is the MCP\n * tool-handler, which logs every tool's `params` object \u2014 twice (at entry, and again in its catch) \u2014\n * into a WORLD-READABLE `/tmp/mcp-infra-kit.log`. A token-carrying key in that object would be\n * written to a file every user on the box can read.\n *\n * The wildcard forms cover the nesting we actually produce: `{ params: { \u2026 } }` and `{ err: { \u2026 } }`\n * are both one level deep, so `*.token` catches `params.token` without enumerating every wrapper.\n *\n * LIMIT \u2014 read this before trusting it: pino's `redact` is KEY-PATH based. It cannot see a token that\n * was INTERPOLATED into a message string (`logger.info(\\`token ${t}\\`)`) \u2014 that string is opaque to\n * it and would be written verbatim. So this is a backstop, not the rule. The RULE is that a token\n * never enters a message string; everything user-facing renders it through `redactToken` first.\n */\nconst REDACT_PATHS = [\n 'token',\n '*.token',\n 'serviceToken',\n '*.serviceToken',\n 'DOPPLER_TOKEN',\n '*.DOPPLER_TOKEN',\n 'INFRA_KIT_ENV_TOKEN',\n '*.INFRA_KIT_ENV_TOKEN',\n]\n\nexport const initLoggerMcp = () => {\n const logLevel = process.argv.includes('--debug') ? 'debug' : 'info'\n\n const logger = pino({ level: logLevel, redact: REDACT_PATHS }, pino.destination({ dest: LOG_FILE_PATH }))\n\n logger.info(`Logger initialized with level: ${logLevel}. Logging to: ${LOG_FILE_PATH}`)\n\n return logger\n}\n\nexport const initLoggerCLI = () => {\n const logLevel = process.argv.includes('--debug') ? 'debug' : 'info'\n\n const ignoreFields = ['time', 'pid', 'hostname']\n\n if (logLevel === 'debug') {\n ignoreFields.push('level')\n }\n\n const logger = pino(\n { level: logLevel, redact: REDACT_PATHS },\n pretty({\n destination: 2,\n ignore: ignoreFields.join(','),\n colorize: true,\n }),\n )\n\n return logger\n}\n\n// Singleton logger instance for CLI usage\nexport const logger = initLoggerCLI()\n", "/**\n * Filesystem discovery helpers for the dev-server.\n *\n * These functions read the filesystem (walking for the monorepo root, scanning\n * `apps/` and `packages/`) but never `chdir` and never resolve ports / prefixes \u2014\n * that stays with the pure {@link file://./ports.ts} layer. The starting directory\n * is passed in so discovery is testable against a fixture root.\n */\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n/** Bare metadata for a discovered API app (no resolved port / prefix). */\nexport interface DiscoveredApiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** Package name from package.json (e.g. sls-trvl-client), or the folder name as fallback. */\n packageName: string\n path: string\n}\n\n/** Walk up from `startDir` (max 10 levels) to the dir containing `pnpm-workspace.yaml`. */\nexport function findMonorepoRoot(startDir: string): string {\n let currentDir = startDir\n\n for (let i = 0; i < 10; i++) {\n const workspaceFile = path.join(currentDir, 'pnpm-workspace.yaml')\n\n if (fs.existsSync(workspaceFile)) {\n return currentDir\n }\n currentDir = path.dirname(currentDir)\n }\n\n throw new Error('Could not find monorepo root (pnpm-workspace.yaml)')\n}\n\n/** Read the `name` field from `<apiPath>/package.json`, falling back to `appName`. */\nexport function getPackageName(apiPath: string, appName: string): string {\n const pkgPath = path.join(apiPath, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return appName\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { name?: string }\n\n return typeof pkg.name === 'string' ? pkg.name : appName\n } catch {\n return appName\n }\n}\n\n/** Discover every `apps/<app>` that has an `api/serverless.yml` (bare metadata only). */\nexport function discoverApiApps(root: string): DiscoveredApiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredApiApp[] = []\n\n if (!fs.existsSync(appsDir)) {\n throw new Error(`Apps directory not found: ${appsDir}`)\n }\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const apiPath = path.join(appsDir, appName, 'api')\n const serverlessPath = path.join(apiPath, 'serverless.yml')\n\n if (fs.existsSync(serverlessPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(apiPath, appName),\n path: apiPath,\n })\n }\n }\n\n return apps\n}\n\n/** Bare metadata for a discovered UI app (a frontend with its own framework `dev` script). */\nexport interface DiscoveredUiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** package.json `name` \u2014 used as the exact `turbo run dev --filter` target. */\n packageName: string\n /** Absolute path to `apps/<app>/ui`. */\n path: string\n /**\n * True when this UI's vite config wires `infra-kit/vite`'s `infraKitDev()` helper \u2014 the ONLY thing\n * that makes it honor the runner-assigned `INFRA_KIT_UI_PORTS` port (which it binds with `strictPort`).\n *\n * The runner treats frameworks opaquely, so it cannot assume a pre-assigned port is the port the child\n * will bind. Without this signal it would print a confident, wrong URL for any UI that picks its own\n * port (vike, astro, a hand-rolled vite config). Unwired \u2192 the runner claims no port and the UI keeps\n * its honest \"vite prints its URL below\" reference line.\n */\n managedPort: boolean\n}\n\n/** Vite config filenames checked for the helper import, in vite's own resolution order. */\nconst VITE_CONFIG_FILES = [\n 'vite.config.ts',\n 'vite.config.mts',\n 'vite.config.cts',\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.cjs',\n]\n\n/**\n * Every module specifier that binds a UI to infra-kit's dev wiring \u2014 whether through the raw\n * `infraKitDev` helper or through the `@slip-stream-kit/vite` plugin that wraps it.\n *\n * A LIST, not a single literal, because the wiring moved packages twice: it used to ship from the\n * `infra-kit` CLI itself, then from `@slip-stream-kit/config` (the split that let the CLI become a\n * global install \u2014 a local `node_modules/.bin/infra-kit` would otherwise shadow the global bin, see\n * that package's readme), and the plugin form now ships from `@slip-stream-kit/vite`. Consumers migrate\n * one repo at a time, so all three specifiers are live.\n *\n * This is what makes `managedPort` true, so a MISSING entry is not cosmetic: the runner would stop\n * claiming the port for every UI on that specifier, and with it the hero URL.\n *\n * Note this is a SUBSTRING match, which is why the config package could not be called `@infra-kit/vite`:\n * that name *contains* `infra-kit/vite`, so the legacy entry would have matched it by accident and\n * hidden the very coupling the split makes explicit. Neither `@slip-stream-kit/config/vite` nor\n * `@slip-stream-kit/vite` contains any other entry, so no entry here shadows another.\n *\n * Drop the legacy entry once every consumer repo is migrated.\n */\nexport const INFRA_KIT_VITE_SPECIFIERS = [\n '@slip-stream-kit/vite',\n '@slip-stream-kit/config/vite',\n 'infra-kit/vite',\n] as const\n\n/**\n * True when `<dir>`'s vite config references the `infraKitDev` helper module. A text match, not a\n * module load: the config is TypeScript the runner must not execute, and importing it would run the\n * consumer's own side effects. False negatives (a config that re-exports the helper from a shared\n * preset) cost only the reference line, never a wrong URL \u2014 the safe direction to be wrong in.\n */\nexport function usesInfraKitVite(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n const source = fs.readFileSync(configPath, 'utf-8')\n\n return INFRA_KIT_VITE_SPECIFIERS.some((specifier) => {\n return source.includes(specifier)\n })\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/** True when `<dir>/package.json` declares a non-empty `scripts.dev`. */\nfunction hasDevScript(dir: string): boolean {\n const pkgPath = path.join(dir, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return false\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { scripts?: Record<string, string> }\n\n return typeof pkg.scripts?.dev === 'string' && pkg.scripts.dev.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Discover every `apps/<app>/ui` whose package.json declares a `dev` script \u2014 the frontends\n * `infra-kit dev --ui` runs (via one delegated `turbo run dev`). Lenient: no `apps/` dir \u2192 `[]`\n * (UIs are optional), unlike {@link discoverApiApps} which requires it.\n */\nexport function discoverUiApps(root: string): DiscoveredUiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredUiApp[] = []\n\n if (!fs.existsSync(appsDir)) return apps\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const uiPath = path.join(appsDir, appName, 'ui')\n\n if (fs.existsSync(uiPath) && hasDevScript(uiPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(uiPath, appName),\n path: uiPath,\n managedPort: usesInfraKitVite(uiPath),\n })\n }\n }\n\n return apps\n}\n\n/** Normalize the `--app` include list: drop empties, and collapse an empty list to `null`. */\nexport function normalizeAppInclude(include?: string[] | null): string[] | null {\n const filtered = include?.filter(Boolean) ?? []\n\n return filtered.length > 0 ? filtered : null\n}\n\n/**\n * Infer the current app's folder name from `startDir`, so a per-app script can\n * run `infra-kit dev --self` without hardcoding its own app name. Walks up to the\n * monorepo root (via {@link findMonorepoRoot}), then takes the first path segment\n * of `startDir` relative to `<root>/apps` \u2014 e.g. `apps/config-handler/api` and\n * `apps/config-handler` both resolve to `config-handler`. Throws when `startDir`\n * isn't inside `<root>/apps/<app>/...` (repo root, or an unrelated path).\n *\n * @example\n * resolveSelfAppName('/repo/apps/config-handler/api') // => 'config-handler'\n */\nexport function resolveSelfAppName(startDir: string): string {\n const root = findMonorepoRoot(startDir)\n const relative = path.relative(path.join(root, 'apps'), startDir)\n const firstSegment = relative.split(path.sep)[0]\n const isOutsideApps = relative === '' || relative.startsWith('..') || path.isAbsolute(relative)\n\n if (isOutsideApps || !firstSegment) {\n throw new Error(\n `--self: not inside an apps/<app> directory (cwd: ${startDir}). Run from an app folder or use --app=<name>.`,\n )\n }\n\n return firstSegment\n}\n\n/** App-part directory names that are apps in their own right, never shared packages. See {@link getPackageDistDirs}. */\nconst APP_PART_DIRS = new Set(['api', 'ui'])\n\n/** `<dir>/dist` when it exists and is a directory, else `undefined`. */\nconst existingDistDir = (dir: string): string | undefined => {\n const distDir = path.join(dir, 'dist')\n\n return fs.existsSync(distDir) && fs.statSync(distDir).isDirectory() ? distDir : undefined\n}\n\n/** Immediate subdirectory names of `dir`, or `[]` when `dir` does not exist. */\nconst subdirNames = (dir: string): string[] => {\n if (!fs.existsSync(dir)) return []\n\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((d) => {\n return d.isDirectory()\n })\n .map((d) => {\n return d.name\n })\n}\n\n/**\n * Existing dist directories of every SHARED workspace package \u2014 the compiled outputs `turbo watch`\n * rewrites. Watched (alongside app dist) because editing a shared lib rewrites only the lib's `dist`,\n * never the dependent app's, so a package-dist change is the only signal that a lib was rebuilt.\n *\n * Two homes, because the pnpm workspace globs cover `packages/<pkg>` as well as `apps/<app>/<part>`:\n * - `packages/<pkg>/dist` \u2014 the obvious one.\n * - `apps/<app>/<part>/dist` where `<part>` is neither `api` nor `ui` and the dir is a real workspace\n * member (it has a `package.json`). A shared library may legally live beside the app that owns it \u2014\n * hulyo's `@pkg/ai-mcp` is `apps/ai/mcp`, and two backends depend on it. Scanning only `packages`\n * left such a package watched by nobody: turbo rebuilt its dist, the runner never saw the change, and\n * every dependent backend kept serving stale code.\n *\n * `api`/`ui` parts are excluded deliberately: an api's dist is already covered by {@link getAppDistDirs},\n * and treating a frontend's dist as a shared package would bounce every backend on a UI rebuild.\n */\nexport function getPackageDistDirs(root: string): string[] {\n const dirs: string[] = []\n\n for (const name of subdirNames(path.join(root, 'packages'))) {\n const distDir = existingDistDir(path.join(root, 'packages', name))\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n\n const appsDir = path.join(root, 'apps')\n\n for (const app of subdirNames(appsDir)) {\n for (const part of subdirNames(path.join(appsDir, app))) {\n if (APP_PART_DIRS.has(part)) continue\n\n const partDir = path.join(appsDir, app, part)\n\n // A workspace member, not a stray build artifact directory.\n if (!fs.existsSync(path.join(partDir, 'package.json'))) continue\n\n const distDir = existingDistDir(partDir)\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n }\n\n return dirs\n}\n\n/** Existing `<app.path>/dist` directories for the given apps (order preserved). */\nexport function getAppDistDirs(apps: Array<{ path: string }>): string[] {\n return apps\n .map((app) => {\n return path.join(app.path, 'dist')\n })\n .filter((dir) => {\n return fs.existsSync(dir)\n })\n}\n\n/** How a watched dist change should be routed. */\nexport interface ChangeClassification {\n kind: 'app' | 'package'\n /** For app changes: the matched app dist dir (undefined when nothing matched). */\n app?: string\n /** For package changes: the matched `packages/<pkg>/dist` dir (the change identity used to scope restarts). */\n packageDir?: string\n}\n\n/**\n * Route a changed compiled-output path: a `packages/<pkg>/dist` change is a shared-package\n * rebuild \u2014 the matched package dist dir is returned so the caller can restart only the apps\n * whose dependency closure includes it. An `<app>/dist` change restarts only that app (the\n * matched app dist dir is returned; `undefined` when the path matches neither). Package matches\n * take precedence.\n */\nexport function classifyDistChange(\n changedPath: string,\n appDistDirs: string[],\n packageDistDirs: string[],\n): ChangeClassification {\n const normalized = path.normalize(changedPath)\n\n const matchedPackageDir = packageDistDirs.find((dir) => {\n return normalized.startsWith(path.normalize(dir))\n })\n\n if (matchedPackageDir) {\n return { kind: 'package', packageDir: matchedPackageDir }\n }\n\n const matchedDir = appDistDirs.find((dir) => {\n return normalized.startsWith(path.normalize(dir))\n })\n\n return { kind: 'app', app: matchedDir }\n}\n", "/**\n * Pure resolution of a named dev preset into a concrete run plan.\n *\n * A preset (declared under `devServersPresets` in the per-project infra-kit.json) names\n * launch targets (`client/api`, `client/ui`, with `*` allowed in the app position), optional\n * per-target `watchDeps` (api + ui), per-route proxy-source overrides, and a `cmux` layout\n * flag. This module turns that declarative shape into a flat {@link ResolvedPreset}\n * the runner consumes. Side-effect free: the discovered app parts are passed in\n * (never read from disk here), so resolution is fully unit-testable.\n *\n * Every target key names exactly one workspace package \u2014 the app folder plus the part\n * (`apps/<app>/api` or `apps/<app>/ui`). A bare `<app>` is not a package and is rejected.\n */\nimport type { DevPreset, DevPresets, ProxySource } from 'src/lib/infra-kit-config'\n\n/** The two launchable halves of an `apps/<app>` folder. */\nexport type AppPart = 'api' | 'ui'\n\n/** One concrete thing to launch: a single part of a single app. */\nexport interface ResolvedTarget {\n /** App folder name (e.g. `client`). */\n app: string\n /** Which half of the app to launch. */\n part: AppPart\n /**\n * Participate in dependency-closure watching (uniform for api + ui): react to a change in\n * this target's own workspace-dependency closure. Default `true` (opt-in participation).\n * Resolution is specificity-ordered: an explicit value on a more-specific key (a concrete\n * app, or an explicit `/part`) wins over a `*` glob; at equal specificity an explicit\n * `false` wins over `true` (order-independent opt-out). See {@link resolveWatch}.\n */\n watchDeps: boolean\n}\n\n/** Which apps have an `api` / `ui` part on disk \u2014 the resolver's view of discovery. */\nexport interface DiscoveredParts {\n /** App names that have `apps/<app>/api`. */\n api: string[]\n /** App names that have `apps/<app>/ui`. */\n ui: string[]\n}\n\n/** A fully-resolved preset: the flat run plan derived from its declarative shape. */\nexport interface ResolvedPreset {\n /** Every (app, part) to launch, de-duplicated. */\n targets: ResolvedTarget[]\n /** Run each target in its own cmux pane. */\n cmux: boolean\n /** app \u2192 (route path \u2192 source) overrides, threaded to the proxy resolver. */\n proxy: Record<string, Record<string, ProxySource>>\n /** Apps whose `api` part is launched \u2014 their backends are local (derived). */\n localApps: string[]\n /** Concretely-named `<app>/<part>` targets that matched no discovered app/part (for a warning). */\n unmatched: string[]\n}\n\n/** The target keys resolution falls back to when a preset omits `apps`: every discovered package. */\nconst ALL_TARGETS_KEYS: NonNullable<DevPreset['apps']> = { '*/api': {}, '*/ui': {} }\n\n/** A preset target key that does not name an `<app>/<part>` package. */\nexport interface PresetKeyIssue {\n /** Preset name the bad key is under. */\n preset: string\n /** The offending key, verbatim. */\n key: string\n /** Human-readable, actionable explanation (already prefixed with the preset name). */\n message: string\n}\n\ninterface ParsedKey {\n /** App name or `*` (all discovered apps). */\n appGlob: string\n /** The single part the key selects. */\n part: AppPart\n}\n\n/**\n * Explain why `key` is not a valid target, or null when it parses. Keys name one workspace\n * package, so the `/api`|`/ui` part is mandatory \u2014 a bare `client` names a folder, not a package.\n */\nexport const explainTargetKey = (key: string): string | null => {\n const segments = key.split('/')\n const [appGlob, part] = segments\n\n if (segments.length !== 2 || !appGlob) {\n return `devServersPresets: invalid target \"${key}\" (expected \"<app>/api\" or \"<app>/ui\")`\n }\n\n if (part !== 'api' && part !== 'ui') {\n return `devServersPresets: invalid target part \"${part}\" in \"${key}\" (expected \"api\" or \"ui\")`\n }\n\n return null\n}\n\n/**\n * Parse a preset target key into an app glob + its part. Throws when the key is not an\n * `<app>/<part>` package identity (see {@link explainTargetKey}).\n *\n * A `*` app glob is legal (`*` plus a part), and expands to every discovered app.\n *\n * @example\n * parseTargetKey('client/api') // => { appGlob: 'client', part: 'api' }\n */\nexport const parseTargetKey = (key: string): ParsedKey => {\n const error = explainTargetKey(key)\n\n if (error) {\n throw new Error(error)\n }\n\n const [appGlob, part] = key.split('/') as [string, AppPart]\n\n return { appGlob, part }\n}\n\n/** Every `preset \u2192 invalid target key` in the map, with the reason (empty when all keys parse). */\nexport const validatePresetKeys = (presets: DevPresets): PresetKeyIssue[] => {\n const issues: PresetKeyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n for (const key of Object.keys(def.apps ?? {})) {\n const error = explainTargetKey(key)\n\n if (error) {\n issues.push({ preset, key, message: `preset \"${preset}\": ${error}` })\n }\n }\n }\n\n return issues\n}\n\n/** App names that have `part` on disk, per the discovery result. */\nconst appsWithPart = (discovered: DiscoveredParts, part: AppPart): string[] => {\n return part === 'api' ? discovered.api : discovered.ui\n}\n\n/** Every discovered app name (union of api + ui halves), sorted for deterministic output. */\nconst allApps = (discovered: DiscoveredParts): string[] => {\n return [...new Set([...discovered.api, ...discovered.ui])].sort()\n}\n\n/** Stable `app/part` identity key for de-duplicating targets across preset keys. */\nconst targetId = (app: string, part: AppPart): string => {\n return `${app}/${part}`\n}\n\n/** A resolved target plus the provenance the merge needs to order later keys by specificity. */\ninterface ResolvedTargetInternal extends ResolvedTarget {\n /** Specificity rank of the key that set `watchDeps` (see {@link keyRank}) \u2014 a higher rank wins. */\n rank: number\n /** Whether `watchDeps` came from an explicit preset value (vs the participate-default). */\n explicitValue: boolean\n}\n\ninterface ResolveState {\n targets: Map<string, ResolvedTargetInternal>\n proxy: Record<string, Record<string, ProxySource>>\n unmatched: string[]\n}\n\n/**\n * Specificity rank of a preset key, higher = more specific. Every key names a part, so the\n * only axis left is the app: a concrete `client/api` (1) beats a `*` glob key (0).\n */\nconst keyRank = (isGlob: boolean): number => {\n return isGlob ? 0 : 1\n}\n\n/**\n * Merge a preset key's `watchDeps` into any prior resolution for the same target. A key that\n * omits `watchDeps` never clobbers a prior explicit value (and, absent any explicit value,\n * seeds the participate-default `true`). A more-specific key ({@link keyRank}) wins in either\n * direction, so a `*` glob cannot override a concrete `client/api` and vice-versa. Two explicit\n * keys can never tie: each target is named by at most one key per rank (one glob, one concrete),\n * so the merge is order-independent.\n */\nconst resolveWatch = (\n prior: ResolvedTargetInternal | undefined,\n next: { watchDeps: boolean | undefined; rank: number },\n): { watchDeps: boolean; rank: number; explicitValue: boolean } => {\n // This key configured nothing \u2192 keep the prior resolution, or seed the participate-default.\n if (next.watchDeps === undefined) {\n return prior ?? { watchDeps: true, rank: next.rank, explicitValue: false }\n }\n\n // No prior explicit value (fresh, or only a default) \u2192 this explicit value takes it.\n if (!prior || !prior.explicitValue) {\n return { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true }\n }\n\n // Two explicit values: the more-specific key wins, in either direction.\n return next.rank > prior.rank ? { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true } : prior\n}\n\n/**\n * Fold one (app, part) into the accumulator: record a target when the part exists,\n * merge `watchDeps` with any prior target of the same identity by specificity\n * ({@link resolveWatch}), and flag a named-but-missing package as unmatched\n * (glob-expanded misses are silent).\n */\nconst addTarget = (\n state: ResolveState,\n discovered: DiscoveredParts,\n spec: { app: string; part: AppPart; watchDeps: boolean | undefined; isGlob: boolean },\n): void => {\n const { app, part, watchDeps, isGlob } = spec\n\n if (!appsWithPart(discovered, part).includes(app)) {\n // A glob expands over discovery, so its misses are expected; a concretely-named\n // `<app>/<part>` that can't be found is a mistake worth surfacing.\n if (!isGlob) {\n state.unmatched.push(targetId(app, part))\n }\n\n return\n }\n\n const id = targetId(app, part)\n const merged = resolveWatch(state.targets.get(id), { watchDeps, rank: keyRank(isGlob) })\n\n state.targets.set(id, { app, part, ...merged })\n}\n\n/**\n * Resolve a preset against the discovered app parts. Expands `*` app globs,\n * de-duplicates targets, derives the local-backend set from the launched `api`\n * targets, and collects per-app proxy overrides. Unknown app/route names are\n * tolerated (a missing named target lands in `unmatched`, not an exception) so a\n * stale preset degrades gracefully \u2014 but a key that is not an `<app>/<part>`\n * package identity throws, since it can't be resolved at all.\n *\n * @example\n * resolvePreset(\n * { apps: { 'client/ui': {}, 'client/api': { watchDeps: false } } },\n * { api: ['client'], ui: ['client'] },\n * )\n * // => {\n * // targets: [{ app: 'client', part: 'ui', watchDeps: true }, // default participate\n * // { app: 'client', part: 'api', watchDeps: false }], // explicit opt-out\n * // cmux: false, proxy: {}, localApps: ['client'], unmatched: [],\n * // }\n */\nexport const resolvePreset = (preset: DevPreset, discovered: DiscoveredParts): ResolvedPreset => {\n const entries = Object.entries(preset.apps ?? ALL_TARGETS_KEYS)\n const state: ResolveState = { targets: new Map(), proxy: {}, unmatched: [] }\n\n for (const [key, cfg] of entries) {\n const { appGlob, part } = parseTargetKey(key)\n const isGlob = appGlob === '*'\n const apps = isGlob ? allApps(discovered) : [appGlob]\n\n for (const app of apps) {\n addTarget(state, discovered, { app, part, watchDeps: cfg.watchDeps, isGlob })\n\n if (cfg.proxy) {\n state.proxy[app] = { ...(state.proxy[app] ?? {}), ...cfg.proxy }\n }\n }\n }\n\n const targets: ResolvedTarget[] = [...state.targets.values()].map(({ app, part, watchDeps }) => {\n return { app, part, watchDeps }\n })\n const localApps = [\n ...new Set(\n targets\n .filter((t) => {\n return t.part === 'api'\n })\n .map((t) => {\n return t.app\n }),\n ),\n ]\n\n return { targets, cmux: preset.cmux ?? false, proxy: state.proxy, localApps, unmatched: state.unmatched }\n}\n\n/** What the run launched, as passed to {@link deriveTargetLabel}. */\nexport interface TargetLabelInput {\n /** Named preset (`infra-kit dev <preset>`) \u2014 its name is the label when present. */\n preset?: string\n /** The `<app>/<part>` package keys actually being launched, after preset resolution and `--app`. */\n running: string[]\n /** Every `<app>/<part>` package key discovered in the monorepo. */\n discovered: string[]\n}\n\n/**\n * The header's target label. A named preset labels itself; otherwise the label is the set of\n * `<app>/<part>` packages actually launching, collapsing to `*` when that set is everything\n * discovered. Never a bare app name: `client` is not a target anywhere in this system (see\n * {@link parseTargetKey}) and would hide which half of the app is running \u2014 the whole point of\n * the wizard's part-level selection.\n *\n * @example\n * deriveTargetLabel({ running: ['client/ui', 'client/api'], discovered: ['client/api', 'client/ui', 'seo/ui'] })\n * // => 'client/api + client/ui'\n * deriveTargetLabel({ running: ['client/api'], discovered: ['client/api'] }) // => '*'\n * deriveTargetLabel({ preset: 'full', running: ['client/api'], discovered: ['client/api', 'seo/ui'] }) // => 'full'\n */\nexport const deriveTargetLabel = (input: TargetLabelInput): string => {\n if (input.preset != null) {\n return input.preset\n }\n if (input.running.length === 0) {\n return 'nothing'\n }\n\n const running = new Set(input.running)\n const isEverything = input.discovered.every((key) => {\n return running.has(key)\n })\n\n return isEverything ? '*' : [...running].sort().join(' + ')\n}\n\n/** A devServersPresets proxy-locality violation surfaced by the audit. */\nexport interface PresetProxyIssue {\n /** Preset name the violation is in. */\n preset: string\n /** Frontend app folder the override is under (e.g. `client`). */\n app: string\n /** Route path forced to a source (e.g. `/api`). */\n route: string\n /** Backend pkg the route maps to; undefined when the route is not declared in the frontend config. */\n pkg?: string\n /** `unknown-route` = route absent from the frontend config; `backend-not-launched` = local target not launched. */\n kind: 'unknown-route' | 'backend-not-launched'\n /** Human-readable, actionable explanation. */\n message: string\n}\n\n/**\n * Cross-file lookups the proxy validator needs, kept injectable so the rule stays\n * filesystem-free (and unit-testable). The impure side (audit) builds these from\n * discovery + each frontend's loaded `infra-kit.config.ts`.\n */\nexport interface PresetProxyContext {\n /** Discovered app parts, for resolving each preset's launch set. */\n discovered: DiscoveredParts\n /** App folder name \u2192 its `apps/<app>/api` package name. */\n apiPkgByApp: Record<string, string>\n /** (frontend app folder, route path) \u2192 backend pkg from that frontend's config; undefined when the route is absent. */\n routePkg: (app: string, route: string) => string | undefined\n}\n\ninterface CheckLocalRouteArgs {\n preset: string\n app: string\n route: string\n launchedPkgs: ReadonlySet<string>\n ctx: PresetProxyContext\n}\n\n/** App folder whose `api` package is `pkg` (for the remediation hint), or undefined. */\nconst ownerApp = (apiPkgByApp: Record<string, string>, pkg: string): string | undefined => {\n return Object.keys(apiPkgByApp).find((app) => {\n return apiPkgByApp[app] === pkg\n })\n}\n\n/**\n * Validate one `route \u2192 'local'` override: the route must be declared in the\n * frontend config, and the backend pkg it maps to must be in the preset's launched\n * set. Returns the issue, or null when the override is satisfiable.\n */\nconst checkLocalRoute = ({ preset, app, route, launchedPkgs, ctx }: CheckLocalRouteArgs): PresetProxyIssue | null => {\n const pkg = ctx.routePkg(app, route)\n\n if (pkg === undefined) {\n return {\n preset,\n app,\n route,\n kind: 'unknown-route',\n message: `preset \"${preset}\": proxy override \"${route}\" on \"${app}\" names a route not declared in ${app}'s infra-kit.config.ts dev.proxy.routes`,\n }\n }\n\n if (launchedPkgs.has(pkg)) {\n return null\n }\n\n const owner = ownerApp(ctx.apiPkgByApp, pkg)\n const hint = owner ? `add \"${owner}/api\" to the preset` : `launch the api whose package is \"${pkg}\"`\n\n return {\n preset,\n app,\n route,\n pkg,\n kind: 'backend-not-launched',\n message: `preset \"${preset}\": proxy override \"${route}\" \u2192 \"local\" requires backend \"${pkg}\" to run locally, but the preset does not launch it \u2014 ${hint}, or set \"${route}\" to \"cloud\"`,\n }\n}\n\n/**\n * Audit every preset's per-route proxy overrides: a route pinned to `local` is only\n * valid when the backend package it resolves to (per the frontend's\n * `infra-kit.config.ts`) is actually launched by that same preset. Catches the\n * `{ \"client/ui\": { \"proxy\": { \"/api\": \"local\" } } }` case where no local backend\n * is running to serve `/api`. `cloud` overrides are always satisfiable and skipped.\n *\n * @example\n * validatePresetProxy(\n * { 'client-remote': { apps: { 'client/ui': { proxy: { '/api': 'local' } } } } },\n * { discovered: { api: ['client'], ui: ['client'] }, apiPkgByApp: { client: 'backend-api' },\n * routePkg: () => 'backend-api' },\n * )\n * // => [{ preset: 'client-remote', app: 'client', route: '/api', pkg: 'backend-api',\n * // kind: 'backend-not-launched', message: '\u2026' }]\n */\nexport const validatePresetProxy = (presets: DevPresets, ctx: PresetProxyContext): PresetProxyIssue[] => {\n const issues: PresetProxyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n const resolved = resolvePreset(def, ctx.discovered)\n const launchedPkgs = new Set(\n resolved.localApps\n .map((app) => {\n return ctx.apiPkgByApp[app]\n })\n .filter((pkg): pkg is string => {\n return pkg !== undefined\n }),\n )\n\n for (const [app, routes] of Object.entries(resolved.proxy)) {\n for (const [route, source] of Object.entries(routes)) {\n if (source !== 'local') {\n continue\n }\n\n const issue = checkLocalRoute({ preset, app, route, launchedPkgs, ctx })\n\n if (issue) {\n issues.push(issue)\n }\n }\n }\n }\n\n return issues\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport { getMainRepoRoot, getProjectRoot } from 'src/lib/git-utils'\n\nconst INFRA_KIT_CONFIG_FILE = 'infra-kit.json'\n\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, and the factory\n * registry (`vendor.json`). Single source of truth for `.infra-kit`, reused\n * by the vendor factory-config loader (no import cycle \u2014 this module imports no\n * `lib/vendor` code).\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\nconst USER_GLOBAL_CONFIG_FILE = 'infra-kit.json'\nconst USER_PROJECTS_DIR = 'projects'\n\n// envManagement\nconst dopplerEnvManagementSchema = z.object({\n provider: z.literal('doppler'),\n config: z.object({\n name: z.string().min(1),\n }),\n})\n\nconst envManagementSchema = z.discriminatedUnion('provider', [dopplerEnvManagementSchema])\n\n// ide\n// There is one attach style: each worktree is added to the configured editor's\n// workspace and opened (no per-window mode). Cursor needs a `.code-workspace`\n// path to reconcile its `folders` array against.\nconst cursorIdeConfigSchema = z.object({\n workspaceConfigPath: z.string().min(1),\n})\n\nconst cursorIdeSchema = z.object({\n provider: z.literal('cursor'),\n config: cursorIdeConfigSchema,\n})\n\n// Zed has no portable workspace file (no `.code-workspace`) and no folder-remove\n// CLI: a multi-worktree workspace is realized by a single `zed <root> <wt...>`\n// invocation. So `config` carries no settings \u2014 there's no path to point at.\nconst zedIdeConfigSchema = z.object({})\n\nconst zedIdeSchema = z.object({\n provider: z.literal('zed'),\n config: zedIdeConfigSchema,\n})\n\nconst ideSchema = z.discriminatedUnion('provider', [cursorIdeSchema, zedIdeSchema])\n\n// `ide` accepts a single provider (back-compat) OR an array to drive multiple\n// editors at once (e.g. Cursor + Zed). Normalized to an array everywhere via\n// `resolveConfiguredIdes`. Uniqueness-by-provider is enforced at parse time by a\n// `.superRefine` on the full config schema (see below) \u2014 not here, so the message\n// survives `z.union` error aggregation.\nconst idesSchema = z.union([ideSchema, z.array(ideSchema).min(1)])\n\n// taskManager\nconst jiraTaskManagerSchema = z.object({\n provider: z.literal('jira'),\n config: z.object({\n baseUrl: z.string().url(),\n projectId: z.number().int().positive(),\n }),\n})\n\nconst taskManagerSchema = z.discriminatedUnion('provider', [jiraTaskManagerSchema])\n\n// cmux pane layout for opened worktree workspaces. Named presets keep the config\n// typo-proof (an enum, not a free string) and let the opener switch on a single\n// value; extend the enum + the opener's switch to add a layout.\n// two-columns \u2014 left | right, both full-height (default)\n// three-pane \u2014 left split top/bottom + full-height right (legacy layout)\nconst cmuxLayouts = ['two-columns', 'three-pane'] as const\n\nconst cmuxConfigSchema = z.object({\n layout: z.enum(cmuxLayouts).optional(),\n})\n\n// worktrees prompt defaults\nconst worktreesConfigSchema = z.object({\n openInGithubDesktop: z.boolean().optional(),\n openInCmux: z.boolean().optional(),\n cmux: cmuxConfigSchema.optional(),\n})\n\n// dev-server per-app overrides. Maps an app folder name (e.g. `client`) to its\n// local dev port and/or URL prefix. Both keys optional. An app absent from the\n// map falls back to env (`{APP}_PORT` / `PORT`) then the built-in defaults, so\n// the map is intentionally NOT validated against the discovered apps here \u2014 an\n// unknown app name is simply ignored at resolve time (lib/dev), never a parse\n// error that would brick every command.\nconst devAppConfigSchema = z\n .object({\n port: z.number().int().positive().optional(),\n prefixUrl: z.string().min(1).optional(),\n })\n .strict()\n\nconst devConfigSchema = z.record(z.string().min(1), devAppConfigSchema)\n\n// devServersPresets: named local-dev sessions, declared in the per-project infra-kit.json\n// (team presets committed; personal ones layered via the user-project override).\n// Each preset names launch targets (apps/<app>/{api,ui}), optional per-backend\n// `watchDeps`, per-route proxy-source overrides, and a `cmux` layout flag; it is\n// consumed by `infra-kit dev <preset>` and resolved by src/dev/presets. Each target key\n// names exactly one workspace package (`<app>/api` or `<app>/ui`) \u2014 a bare `<app>` is a\n// folder, not a package, and is rejected. The SHAPE is strict (typos in a preset surface\n// as parse errors), but unknown app/route NAMES are intentionally NOT validated here \u2014\n// they resolve at run time against the discovered apps, so a stale preset never bricks\n// every command.\nconst proxySourceSchema = z.enum(['local', 'cloud'])\n\nconst devPresetAppSchema = z\n .object({\n // api targets only: watch the backend's dist + shared-package subdeps and restart on change.\n watchDeps: z.boolean().optional(),\n // route path (e.g. `/api`) \u2192 source, overriding that route's config.ts default for this session.\n proxy: z.record(z.string().min(1), proxySourceSchema).optional(),\n })\n .strict()\n\nconst devPresetSchema = z\n .object({\n // Launch-target key \u2014 one package: `client/ui`, `client/api`, `*/api`. Omit `apps` = all.\n apps: z.record(z.string().min(1), devPresetAppSchema).optional(),\n // Run each launched target in its own cmux pane (one workspace, N panes).\n cmux: z.boolean().optional(),\n })\n .strict()\n\nconst devPresetsSchema = z.record(z.string().min(1), devPresetSchema)\n\n// DEPRECATED (accepted and ignored). Layer-B local-dev proxy (portless).\n//\n// The proxy port is no longer negotiable: every dev URL is `https://<release>.<packageName>.localhost`\n// with NO port, and the only port that can serve a port-free HTTPS URL is 443. A configurable port would\n// put the port straight back into the URL \u2014 the exact thing this design removes.\n//\n// The key is still PARSED so it does not brick anything: `infraKitConfigObject` is `.strict()` and\n// `getInfraKitConfig` THROWS on an unknown key, so simply deleting it would hard-fail EVERY infra-kit\n// command (not just `dev`) on any machine whose config still carries it \u2014 arriving unannounced, because\n// the CLI self-updates. It is read by nothing and silently ignored. Remove one release from now.\nconst devProxyConfigSchema = z\n .object({\n port: z.number().int().positive().optional(),\n })\n .strict()\n\n// env auto-load: opt-in convenience that primes Doppler env when you work inside\n// this project / a worktree. Absent => disabled. `trigger` selects the moment\n// (pick one):\n// shell-startup \u2014 when a new shell opens inside the project\n// cli-invocation \u2014 before each `infra-kit` command (primes SUBSEQUENT commands)\n// `config` names which environment to load. It is intentionally NOT validated\n// against `environments` here: an invalid name must DISABLE the feature at\n// resolve time (lib/env-autoload), never throw inside the merged-config parse and\n// brick every command.\nconst envAutoLoadSchema = z\n .object({\n trigger: z.enum(['shell-startup', 'cli-invocation']),\n config: z.string().min(1),\n })\n .strict()\n\n// Base object shape, kept separate so `.partial()` (which only works on a plain\n// ZodObject, not the `.superRefine`-wrapped full schema) can derive the override\n// schema from it.\n//\n// `.strict()` for the same reason every leaf schema below is: this is the one config file humans\n// hand-edit, and a non-strict top level silently swallows the typo that matters most. `devServersPreset`\n// (missing `s`) or `dev-proxy` would parse clean and turn the feature off with no message. The `dev` and\n// `devServersPresets` values stay open `z.record`s \u2014 app and preset NAMES are user-chosen \u2014 so strictness\n// applies to the key set, not the contents.\n// GONE: `environments`. It answered three questions at once and was therefore wrong for two of them.\n// Where can I deploy? \u2192 each workflow's own `workflow_dispatch` `environment.options`, which GitHub\n// validates server-side (`lib/workflow-envs`). What can I authenticate to? \u2192 the token store\n// (`lib/env-tokens`). Being a third, hand-maintained copy of both, it drifted from both: hulyo declared\n// 6 envs while every hulyo workflow declared 8, and the client-side check turned that drift into a\n// REFUSAL to deploy to `stage` and `prod`.\n//\n// Deleted outright rather than accepted-and-ignored: the key is removed from every repo in the same\n// change, so nothing that is checked out on a current branch still carries it. Because this schema is\n// `.strict()`, a config that DOES still carry it (an old release branch, an unmigrated worktree) is\n// refused with `Unrecognized key: \"environments\"` \u2014 delete the key there too.\nexport const infraKitConfigObject = z\n .object({\n envManagement: envManagementSchema,\n ide: idesSchema.optional(),\n taskManager: taskManagerSchema.optional(),\n worktrees: worktreesConfigSchema.optional(),\n envAutoLoad: envAutoLoadSchema.optional(),\n dev: devConfigSchema.optional(),\n devServersPresets: devPresetsSchema.optional(),\n devProxy: devProxyConfigSchema.optional(),\n })\n .strict()\n\n/**\n * The portless proxy's listen port. `443` \u2014 the implicit HTTPS port \u2014 because that is the ONLY port that\n * can serve a port-free `https://<release>.<packageName>.localhost` URL, which is the whole point.\n *\n * It is privileged, so the daemon must already be running: `infra-kit dev` PROBES it and never elevates\n * (portless binds `:443` by re-execing through `sudo` with an inherited stdio, which a detached child can\n * never answer). One-time, out-of-band: a root `portless service install`, which `dev` and `doctor` print\n * for the user as an absolute-path command (portless is not on `PATH`; see `formatPortlessCommand`). There\n * is deliberately no unprivileged fallback \u2014 a fallback puts the port back in the URL.\n *\n * Not a constant of convenience: it is the single value that decides the scheme, and TLS on 443 is\n * portless's own default (our previous `--no-tls` was the deviation).\n */\nexport const DEFAULT_DEV_PROXY_PORT = 443\n\n// Full schema = base object + a parse-time uniqueness check on the `ide` array.\n// This runs inside the *merged* `safeParse` in getInfraKitConfig, so it's the\n// gate for the final config. (The override layers use the `.partial()` form\n// below, which drops this object-level refinement \u2014 acceptable, the merged\n// parse is authoritative.)\nexport const infraKitConfigSchema = infraKitConfigObject.superRefine((cfg, ctx) => {\n if (!Array.isArray(cfg.ide)) return\n\n const seen = new Set<string>()\n\n for (const entry of cfg.ide) {\n if (seen.has(entry.provider)) {\n ctx.addIssue({\n code: 'custom',\n message: 'each IDE provider may appear at most once',\n path: ['ide'],\n })\n\n return\n }\n\n seen.add(entry.provider)\n }\n})\n\nexport const infraKitOverrideConfigSchema = infraKitConfigObject.partial()\n\nexport type InfraKitConfig = z.infer<typeof infraKitConfigSchema>\n\n/** Resolved env auto-load config (`{ trigger, config }`), or `undefined` when off. */\nexport type EnvAutoLoadConfig = z.infer<typeof envAutoLoadSchema>\n\n/** Per-app dev-server overrides (`{ port?, prefixUrl? }`). */\nexport type DevAppConfig = z.infer<typeof devAppConfigSchema>\n\n/** The full `dev` section: a map of app folder name to its {@link DevAppConfig}. */\nexport type DevConfig = z.infer<typeof devConfigSchema>\n\n/** A proxy route's resolved source in a preset override (`'local' | 'cloud'`). */\nexport type ProxySource = z.infer<typeof proxySourceSchema>\n\n/** A single dev preset (`{ apps?, cmux? }`) from the `devServersPresets` map. */\nexport type DevPreset = z.infer<typeof devPresetSchema>\n\n/** The `devServersPresets` map: preset name \u2192 {@link DevPreset}. */\nexport type DevPresets = z.infer<typeof devPresetsSchema>\n\n/** A single resolved IDE entry (`{ provider, config }`). */\nexport type ConfiguredIde = z.infer<typeof ideSchema>\n\n/**\n * Normalize the `ide` config (single object, array, or unset) into a flat list.\n * Validation-free: assumes already-parsed input (uniqueness is enforced by the\n * schema). The one source of truth for \"which editors are configured.\"\n *\n * @example\n * resolveConfiguredIdes({ ide: { provider: 'cursor', config: {...} } }) // => [cursor]\n * resolveConfiguredIdes({ ide: [cursor, zed] }) // => [cursor, zed]\n * resolveConfiguredIdes({}) // => []\n */\nexport const resolveConfiguredIdes = (config: InfraKitConfig): ConfiguredIde[] => {\n const ide = config.ide\n\n if (!ide) return []\n\n return Array.isArray(ide) ? ide : [ide]\n}\n\n/** A cmux pane layout preset (see {@link cmuxLayouts}). */\nexport type CmuxLayout = (typeof cmuxLayouts)[number]\n\n/** The layout applied when `worktrees.cmux.layout` is left unset. */\nexport const DEFAULT_CMUX_LAYOUT: CmuxLayout = 'two-columns'\n\n/**\n * Resolve the cmux pane layout for opened worktree workspaces, falling back to\n * {@link DEFAULT_CMUX_LAYOUT} when unconfigured. The one source of truth for\n * \"which layout should the cmux opener build.\"\n *\n * @example\n * resolveCmuxLayout({ worktrees: { cmux: { layout: 'three-pane' } } }) // => 'three-pane'\n * resolveCmuxLayout({}) // => 'two-columns'\n */\nexport const resolveCmuxLayout = (config: InfraKitConfig): CmuxLayout => {\n return config.worktrees?.cmux?.layout ?? DEFAULT_CMUX_LAYOUT\n}\n\nexport interface InfraKitConfigPaths {\n /** Committed project config (required). */\n main: string\n /** User-scope global overrides applied to every project. */\n userGlobal: string\n /** User-scope per-project overrides \u2014 `<userProjectsDir>/<projectName>/infra-kit.json`. */\n userProject: string\n /** Repo basename (`path.basename(projectRoot)`) used to namespace the user-project file. */\n projectName: string\n}\n\ninterface CacheEntry {\n mtimes: Record<keyof Omit<InfraKitConfigPaths, 'projectName'>, number | null>\n value: InfraKitConfig\n}\n\nlet cached: CacheEntry | null = null\n\ninterface PathsCacheEntry {\n key: string\n value: InfraKitConfigPaths\n}\n\n/**\n * Memo slot for {@link getInfraKitConfigPaths}. SINGLE-ENTRY, not a `Map`: the resolver's only\n * inputs are `process.cwd()` and `os.homedir()`, and production never mutates either (there is zero\n * `process.chdir` outside tests), so one key covers the whole process lifetime. A `Map` would buy\n * nothing there and could hand a chdir'ing test file a stale sibling entry; a single slot that\n * recomputes on key mismatch is strictly safer and identically fast.\n */\nlet cachedPaths: PathsCacheEntry | null = null\n\n/**\n * Cache key for {@link cachedPaths}. `homedir` is load-bearing, not decoration: the resolver reads\n * it directly, and a dozen test files swap it for a fresh `mkdtemp` home WITHOUT chdir'ing \u2014 a\n * cwd-only key would hand test B test A's already-deleted temp home.\n *\n * @example\n * pathsCacheKey() // => '/Users/arthur/projects/api /Users/arthur'\n */\nconst pathsCacheKey = (): string => {\n return `${process.cwd()} ${os.homedir()}`\n}\n\n/**\n * Resolve every file path that participates in the config merge chain. Always\n * returns paths even for files that don't yet exist, so callers can use them\n * for \"where would my override go?\" prompts.\n *\n * Memoized on `cwd + homedir` (see {@link cachedPaths}) because the two `git rev-parse` spawns below\n * run BEFORE the mtime cache in `getInfraKitConfig`, so without this every call paid for both. The\n * memo is populated on success only \u2014 `getProjectRoot` rejects outside a git repo and callers depend\n * on that rejection, so a cached rejection would be a stateful negative path. Cleared by\n * {@link resetInfraKitConfigCache}.\n *\n * Safe to memoize: this is a pure path resolver (inputs = cwd + homedir; it returns paths, never\n * file contents), so filesystem mutation cannot invalidate it.\n *\n * @example\n * const paths = await getInfraKitConfigPaths()\n * // {\n * // main: '/Users/arthur/projects/api/infra-kit.json',\n * // userGlobal: '/Users/arthur/.infra-kit/infra-kit.json',\n * // userProject: '/Users/arthur/.infra-kit/projects/api/infra-kit.json',\n * // projectName: 'api',\n * // }\n */\nexport const getInfraKitConfigPaths = async (): Promise<InfraKitConfigPaths> => {\n const key = pathsCacheKey()\n\n if (cachedPaths && cachedPaths.key === key) {\n return cachedPaths.value\n }\n\n const projectRoot = await getProjectRoot()\n // Namespace the per-project override on the MAIN repo root, not `projectRoot`.\n // Inside a linked worktree `projectRoot` is the worktree's own path, so its\n // basename is the worktree's leaf dir (e.g. `feature-x`), which would key the\n // override to a different, per-worktree file. `getMainRepoRoot` resolves the\n // shared git common dir so every worktree of a repo converges on one key. The\n // second `git rev-parse` this costs is fine \u2014 the merged config is mtime-cached.\n const mainRepoRoot = await getMainRepoRoot(projectRoot)\n const projectName = path.basename(mainRepoRoot)\n const userConfigDir = path.join(os.homedir(), USER_CONFIG_DIR_NAME)\n\n const value: InfraKitConfigPaths = {\n main: path.join(projectRoot, INFRA_KIT_CONFIG_FILE),\n userGlobal: path.join(userConfigDir, USER_GLOBAL_CONFIG_FILE),\n userProject: path.join(userConfigDir, USER_PROJECTS_DIR, projectName, INFRA_KIT_CONFIG_FILE),\n projectName,\n }\n\n // Populate only after both git calls RESOLVED \u2014 never cache a rejection.\n cachedPaths = { key, value }\n\n return value\n}\n\n/**\n * Read and validate `infra-kit.json`, with optional override layers shallow-merged\n * on top in this order (later wins):\n * 1. project `infra-kit.json` \u2014 committed source of truth\n * 2. `~/.infra-kit/infra-kit.json` \u2014 user-global defaults\n * 3. `~/.infra-kit/projects/<repo-name>/infra-kit.json` \u2014 user-scope per-project overrides\n *\n * Top-level keys (entire capability sections like `ide`, `envManagement`)\n * replace wholesale. Results are cached per file mtimes so the long-running\n * MCP server picks up edits without a restart.\n *\n * @example\n * // infra-kit.json: { \"environments\": [\"dev\"], \"envManagement\": { \"provider\": \"doppler\", \"config\": { \"name\": \"p\" } } }\n * // ~/.infra-kit/infra-kit.json: { \"ide\": { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"./ws.code-workspace\" } } }\n * const cfg = await getInfraKitConfig()\n * // => { environments: ['dev'], envManagement: {...}, ide: { provider: 'cursor', config: { workspaceConfigPath: './ws.code-workspace' } } }\n */\nexport const getInfraKitConfig = async (): Promise<InfraKitConfig> => {\n const paths = await getInfraKitConfigPaths()\n\n let mainStat: Awaited<ReturnType<typeof fs.stat>>\n\n try {\n mainStat = await fs.stat(paths.main)\n } catch {\n cached = null\n\n // Bridge the YAML\u2192JSON cutover: if a legacy infra-kit.yml is sitting where\n // the JSON config should be, point the user at the one-shot migration.\n const legacyYmlPath = paths.main.replace(/\\.json$/, '.yml')\n\n if (await statIfExists(legacyYmlPath)) {\n throw new Error(\n `infra-kit.json not found at ${paths.main}. A legacy infra-kit.yml exists \u2014 run \\`infra-kit init\\` to convert it.`,\n )\n }\n\n throw new Error(`infra-kit.json not found at ${paths.main}`)\n }\n\n const [userGlobalStat, userProjectStat] = await Promise.all([\n statIfExists(paths.userGlobal),\n statIfExists(paths.userProject),\n ])\n\n const mtimes = {\n main: Number(mainStat.mtimeMs),\n userGlobal: userGlobalStat ? Number(userGlobalStat.mtimeMs) : null,\n userProject: userProjectStat ? Number(userProjectStat.mtimeMs) : null,\n }\n\n if (cached && shallowEqual(cached.mtimes, mtimes)) {\n return cached.value\n }\n\n const layers: ConfigLayer[] = [\n { label: 'infra-kit.json', path: paths.main, required: true },\n { label: '~/.infra-kit/infra-kit.json', path: paths.userGlobal, required: false },\n {\n label: `~/.infra-kit/projects/${paths.projectName}/infra-kit.json`,\n path: paths.userProject,\n required: false,\n },\n ]\n\n let merged: Record<string, unknown> = {}\n\n for (const layer of layers) {\n const data = await loadLayer(layer)\n\n if (data === null) continue\n\n merged = { ...merged, ...data }\n }\n\n const finalResult = infraKitConfigSchema.safeParse(merged)\n\n if (!finalResult.success) {\n throw new Error(`Invalid merged infra-kit config: ${z.prettifyError(finalResult.error)}`)\n }\n\n cached = { mtimes, value: finalResult.data }\n\n return finalResult.data\n}\n\n/**\n * Drop ONLY the merged-config cache ({@link cached}), keeping the path memo ({@link cachedPaths})\n * intact. For writers of a merge layer \u2014 the config bootstrap, which creates the layer-3\n * `~/.infra-kit/projects/<repo>/infra-kit.json`.\n *\n * WHY this exists separately from {@link resetInfraKitConfigCache}: writing the layer-3 file changes\n * the MERGE RESULT (a stale merged config would miss the new layer) but it cannot change the\n * RESOLVED PATHS \u2014 those are a pure function of `cwd + homedir`, and creating a file mutates\n * neither. Blowing away the path memo there would just make the very run that creates the file\n * re-spawn both `git rev-parse` processes for nothing: 4 spawns instead of 2.\n *\n * @example\n * await fs.writeFile(paths.userProject, '{}\\n', 'utf-8')\n * resetMergedConfigCache()\n * await getInfraKitConfig() // sees the new layer-3 layer\n * await getInfraKitConfigPaths() // still served from the memo \u2014 zero extra git spawns\n */\nexport const resetMergedConfigCache = (): void => {\n cached = null\n}\n\n/**\n * For tests \u2014 drops BOTH in-memory caches: the mtime-fingerprinted merged config and the\n * `cwd + homedir`-keyed path memo ({@link cachedPaths}). The next read re-spawns `git rev-parse`\n * and re-hits disk. Production writers want the narrower {@link resetMergedConfigCache}.\n *\n * @example\n * resetInfraKitConfigCache()\n * await getInfraKitConfig() // re-resolves paths and re-reads files even if mtimes look unchanged\n */\nexport const resetInfraKitConfigCache = (): void => {\n cached = null\n cachedPaths = null\n}\n\n/**\n * `fs.stat` that returns `null` instead of throwing on ENOENT. Used so the\n * resolver can probe optional files in the merge chain without try/catch noise.\n *\n * @example\n * const stat = await statIfExists('/does/not/exist') // => null\n */\nconst statIfExists = async (filePath: string): Promise<Awaited<ReturnType<typeof fs.stat>> | null> => {\n try {\n return await fs.stat(filePath)\n } catch {\n return null\n }\n}\n\n/**\n * `fs.readFile` that returns `null` instead of throwing on ENOENT.\n *\n * @example\n * const raw = await readIfExists('/missing.json') // => null\n * const raw = await readIfExists('/exists.json') // => '{ \"environments\": [\"dev\"] }\\n'\n */\nconst readIfExists = async (filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(filePath, 'utf-8')\n } catch {\n return null\n }\n}\n\n/**\n * Reference-equality comparison of every key in two flat records. Used to\n * cheaply detect whether the cached mtime fingerprint still matches.\n *\n * @example\n * shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true\n * shallowEqual({ a: 1 }, { a: 1, b: 2 }) // => false\n * shallowEqual({ a: 1 }, { a: 2 }) // => false\n */\nconst shallowEqual = <T extends Record<string, unknown>>(a: T, b: T): boolean => {\n const keys = Object.keys(a)\n\n if (keys.length !== Object.keys(b).length) return false\n\n return keys.every((k) => {\n return a[k] === b[k]\n })\n}\n\ninterface ConfigLayer {\n label: string\n path: string\n required: boolean\n}\n\n/**\n * Read a single layer of the merge chain: parse the JSON if the file exists\n * and validate it against the override schema. Returns `null` if an optional\n * layer is missing; throws if the layer is required, malformed, or invalid.\n * An empty/whitespace-only file is treated as `{}` (JSON.parse would throw).\n *\n * @example\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/missing.json', required: false })\n * // => null\n *\n * @example\n * // /home/me/.infra-kit/infra-kit.json: '{ \"ide\": { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"./ws.code-workspace\" } } }'\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/home/me/.infra-kit/infra-kit.json', required: false })\n * // => { ide: { provider: 'cursor', config: { workspaceConfigPath: './ws.code-workspace' } } }\n */\nconst loadLayer = async (layer: ConfigLayer): Promise<Record<string, unknown> | null> => {\n const raw = await readIfExists(layer.path)\n\n if (raw === null) {\n if (layer.required) {\n throw new Error(`${layer.label} not found at ${layer.path}`)\n }\n\n return null\n }\n\n let parsedRaw: unknown\n\n try {\n parsedRaw = raw.trim() === '' ? {} : JSON.parse(raw)\n } catch (err) {\n throw new Error(`Invalid JSON in ${layer.label} at ${layer.path}: ${(err as Error).message}`)\n }\n\n // `envTokens` is ALREADY rejected below \u2014 the override schema keeps `.strict()`, so it lands as a\n // generic `unrecognized_keys` issue. That generic message is wrong for this one key: the user has\n // pasted a live Doppler service token into a file that may be committed, backed up by their editor,\n // or opened by `config edit`. The first instruction has to be REVOKE, not \"fix your config\". Narrow\n // by construction \u2014 every other unknown key keeps the generic error.\n if (isRecord(parsedRaw) && 'envTokens' in parsedRaw) {\n throw new Error(buildEnvTokensRejectionMessage(layer))\n }\n\n const result = infraKitOverrideConfigSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new Error(`Invalid ${layer.label} at ${layer.path}: ${z.prettifyError(result.error)}`)\n }\n\n return result.data as Record<string, unknown>\n}\n\n/**\n * Narrow parsed JSON to a plain object so a key probe is safe (JSON's top level may be an array, a\n * string, or `null`).\n *\n * @example\n * isRecord({ envTokens: {} }) // => true\n * isRecord(['envTokens']) // => false\n * isRecord(null) // => false\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * The REVOKE-first refusal for a service token found in an `infra-kit.json`. Ordered by urgency: the\n * credential is already exposed, so revoking it beats editing the file. Tokens live in a SIBLING\n * `tokens.json` (0600) that this loader never reads \u2014 see `lib/env-tokens`.\n *\n * @example\n * buildEnvTokensRejectionMessage({ label: 'infra-kit.json', path: '/r/infra-kit.json', required: true })\n * // => 'Refusing to load infra-kit.json \u2014 `envTokens` is not a config key. \u2026'\n */\nconst buildEnvTokensRejectionMessage = (layer: ConfigLayer): string => {\n return [\n `Refusing to load ${layer.label} \u2014 \\`envTokens\\` is not a config key.`,\n 'A service token in a config file can be committed, backed up by your editor, or shared.',\n ' 1. REVOKE the token in Doppler now \u2014 treat it as compromised.',\n ` 2. Remove the \\`envTokens\\` key from ${layer.path}.`,\n ' 3. Re-add it privately: `infra-kit env-token-set <env>`',\n ' (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo).',\n ].join('\\n')\n}\n", "import path from 'node:path'\nimport { $ } from 'zx'\n\nimport { isReleaseBranch } from 'src/lib/release-id'\n\n/**\n * Get current git worktrees\n *\n * @returns [release/v1.18.22, release/v1.18.23, release/v1.18.24] or [feature/mobile-app, feature/explore-page, feature/login-page]\n */\nexport const getCurrentWorktrees = async (type: 'release' | 'feature'): Promise<string[]> => {\n const worktreesOutput = await $`git worktree list`\n\n const worktreeLines = worktreesOutput.stdout.split('\\n').filter(Boolean)\n\n const worktreePredicateMap = {\n release: releaseWorktreePredicate,\n feature: featureWorktreePredicate,\n }\n\n return worktreeLines.map(worktreePredicateMap[type]).filter((branch) => {\n return branch !== null\n })\n}\n\n/**\n * Extract the branch name from a `git worktree list` output line.\n *\n * `git worktree list` formats each line as:\n * <path> <hash> [<branch>]\n *\n * Reads the branch from the trailing `[branch]` token so it works for the\n * main checkout too (whose path does not encode the branch name).\n */\nconst parseWorktreeBranch = (line: string): string | null => {\n const trimmed = line.trimEnd()\n\n if (!trimmed.endsWith(']')) return null\n\n const open = trimmed.lastIndexOf('[')\n\n if (open === -1) return null\n\n const branch = trimmed.slice(open + 1, -1)\n\n return branch.length > 0 ? branch : null\n}\n\n/**\n * Extract a release branch name from a `git worktree list` output line.\n *\n * Returns `null` for lines that are not release worktrees.\n *\n * @example\n * releaseWorktreePredicate('/path/to/release/v1.18.22 abc1234 [release/v1.18.22]')\n * // => 'release/v1.18.22'\n *\n * @example\n * releaseWorktreePredicate('/path/to/feature/login abc1234 [feature/login]')\n * // => null\n */\nconst releaseWorktreePredicate = (line: string): string | null => {\n const branch = parseWorktreeBranch(line)\n\n return isReleaseBranch(branch) ? branch : null\n}\n\n/**\n * Extract a feature branch name from a `git worktree list` output line.\n *\n * Returns `null` for lines that are not feature worktrees.\n *\n * @example\n * featureWorktreePredicate('/path/to/feature/login-page abc1234 [feature/login-page]')\n * // => 'feature/login-page'\n *\n * @example\n * featureWorktreePredicate('/path/to/release/v1.18.22 abc1234 [release/v1.18.22]')\n * // => null\n */\nconst featureWorktreePredicate = (line: string): string | null => {\n const branch = parseWorktreeBranch(line)\n\n return branch?.startsWith('feature/') ? branch : null\n}\n\n/**\n * Get the current project root directory\n */\nexport const getProjectRoot = async (): Promise<string> => {\n const result = await $`git rev-parse --show-toplevel`\n\n return result.stdout.trim()\n}\n\n/**\n * Absolute path to the MAIN repository root \u2014 invariant across the main checkout\n * and all of its linked worktrees. A linked worktree's `--show-toplevel` is the\n * worktree's own path, but its `--git-common-dir` still points at the shared\n * `<main>/.git`, so the parent of the resolved common dir is always the main repo.\n * This is the stable identity to key per-repo state on (unlike `getProjectRoot`,\n * whose basename is the worktree's leaf directory inside a worktree).\n *\n * Submodules are the one exception: their common dir is\n * `<super>/.git/modules/<name>`, whose parent (`.../.git/modules`) is not a repo\n * root \u2014 there is no meaningful \"main repo\" to converge on \u2014 so we fall back to\n * the caller-supplied toplevel unchanged. Callers must pass a git toplevel as\n * `cwd` (e.g. the result of {@link getProjectRoot}); the fallback assumes it.\n *\n * @example\n * // main checkout: common dir '.git' \u2192 resolve \u2192 '<main>/.git' \u2192 dirname \u2192 '<main>'\n * await getMainRepoRoot('/Users/me/projects/hulyo') // => '/Users/me/projects/hulyo'\n * // linked worktree: common dir '<main>/.git' \u2192 dirname \u2192 '<main>'\n * await getMainRepoRoot('/Users/me/projects/hulyo-worktrees/feature/x') // => '/Users/me/projects/hulyo'\n */\nexport const getMainRepoRoot = async (cwd?: string): Promise<string> => {\n const root = cwd ?? (await getProjectRoot())\n const commonDir = (await $({ cwd: root })`git rev-parse --git-common-dir`).stdout.trim()\n const resolved = path.resolve(root, commonDir)\n\n // Submodule: common dir sits under `<super>/.git/modules/<name>` \u2014 no stable\n // main-repo root to key on, so keep the caller's own toplevel.\n if (resolved.includes(`${path.sep}.git${path.sep}modules${path.sep}`)) return root\n\n return path.dirname(resolved)\n}\n\n/**\n * Get the current git branch name (e.g. `dev`, `main`, `release/v1.2.3`).\n */\nexport const getCurrentBranch = async (): Promise<string> => {\n const result = await $`git rev-parse --abbrev-ref HEAD`\n\n return result.stdout.trim()\n}\n\n/**\n * Whether the working tree has no staged, unstaged, or untracked changes.\n */\nexport const isWorkingTreeClean = async (): Promise<boolean> => {\n const result = await $`git status --porcelain`\n\n return result.stdout.trim().length === 0\n}\n\n/**\n * Whether the current checkout is a linked git worktree rather than the main\n * repository checkout.\n *\n * A linked worktree's git dir lives under `<main>/.git/worktrees/<name>`, so it\n * differs from the shared common dir; in the main checkout the two resolve to\n * the same path. Both are anchored to the toplevel so `--git-common-dir` (which\n * git may report relative to cwd) resolves consistently.\n */\nexport const isInsideLinkedWorktree = async (): Promise<boolean> => {\n const cwd = await getProjectRoot()\n\n const [gitDirResult, commonDirResult] = await Promise.all([\n $({ cwd })`git rev-parse --absolute-git-dir`,\n $({ cwd })`git rev-parse --git-common-dir`,\n ])\n\n const gitDir = gitDirResult.stdout.trim()\n const commonDir = path.resolve(cwd, commonDirResult.stdout.trim())\n\n return gitDir !== commonDir\n}\n\n/**\n * Get the current repository name (basename of the project root)\n */\nexport const getRepoName = async (): Promise<string> => {\n const projectRoot = await getProjectRoot()\n\n return path.basename(projectRoot)\n}\n\n/**\n * Delete a local branch if it exists and is not the current checkout.\n *\n * Idempotent: a no-op when the branch is absent (`git branch --list` prints\n * nothing). Uses force `-D` because a delivered release branch was\n * squash-merged \u2014 its tip is unreachable from the base, so `-d` would refuse\n * with \"not fully merged\". The delete itself still rejects if the branch is\n * checked out in another worktree; callers decide how to handle that.\n */\nexport const deleteLocalBranch = async (branch: string): Promise<void> => {\n const listed = await $`git branch --list ${branch}`\n\n if (listed.stdout.trim().length === 0) return\n\n if ((await getCurrentBranch()) === branch) return\n\n await $`git branch -D ${branch}`\n}\n\n/**\n * Delete a branch on the `origin` remote if it exists.\n *\n * Idempotent: a no-op when the branch is absent on the remote. Existence is\n * probed with `git ls-remote --heads` (empty stdout = absent) rather than\n * `--exit-code`, so a genuine network/auth failure rejects and propagates to\n * the caller instead of being silently misread as \"branch absent\".\n */\nexport const deleteRemoteBranch = async (branch: string): Promise<void> => {\n const refs = await $`git ls-remote --heads origin ${branch}`\n\n if (refs.stdout.trim().length === 0) return\n\n await $`git push origin --delete ${branch}`\n}\n", "/**\n * A release identity is either a semantic version or a free-form kebab-case\n * name. `raw` is the canonical token for the id: the no-`v` semver string for\n * versions (e.g. `1.2.3`) and the name itself for named releases.\n */\nexport type ReleaseId =\n | { kind: 'version'; semver: { major: number; minor: number; patch: number }; raw: string }\n | { kind: 'name'; name: string; raw: string }\n\n/** Matches a bare or `v`-prefixed semver token, e.g. `1.2.3` or `v1.2.3`. */\nconst VERSION_RE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/** Matches the semver core after the `v` in a `release/v\u2026` branch. */\nconst BRANCH_SEMVER_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/** Kebab-case: lowercase alphanumeric segments joined by single hyphens. */\nconst KEBAB_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\nconst RELEASE_BRANCH_PREFIX = 'release/'\nconst VERSION_BRANCH_PREFIX = 'release/v'\nconst REFS_HEADS_PREFIX = 'refs/heads/'\n\nconst NEXT_TOKEN = 'next'\nconst MAX_NAME_LENGTH = 50\n\n/**\n * Names that would collide with branch/release semantics or read as a special\n * token. Banned regardless of kebab-case validity.\n */\nconst RESERVED_NAMES: ReadonlySet<string> = new Set(['dev', 'main', 'next', 'hotfix', 'regular', 'release'])\n\n/** Thrown by {@link validateName} when a release name is not acceptable. */\nexport class InvalidReleaseNameError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidReleaseNameError'\n }\n}\n\n/** Thrown by {@link parseReleaseRef} when a release ref cannot be parsed. */\nexport class InvalidReleaseRefError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidReleaseRefError'\n }\n}\n\nconst stripRefsHeads = (input: string): string => {\n return input.startsWith(REFS_HEADS_PREFIX) ? input.slice(REFS_HEADS_PREFIX.length) : input\n}\n\nconst makeVersion = (major: number, minor: number, patch: number): ReleaseId => {\n return {\n kind: 'version',\n semver: { major, minor, patch },\n raw: `${major}.${minor}.${patch}`,\n }\n}\n\n/**\n * Validate a release name. Throws {@link InvalidReleaseNameError} with a\n * specific message unless the name is kebab-case, at most 50 characters, and\n * not a reserved word. Semver-looking tokens (e.g. `1.2.3`) are already\n * excluded by the kebab-case rule since they contain dots.\n */\nexport const validateName = (name: string): void => {\n if (name.length === 0) {\n throw new InvalidReleaseNameError('Release name is empty. Provide a kebab-case name like \"checkout-redesign\".')\n }\n\n if (name.length > MAX_NAME_LENGTH) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is ${name.length} characters; the maximum is ${MAX_NAME_LENGTH}.`,\n )\n }\n\n if (!KEBAB_RE.test(name)) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. \"checkout-redesign\".`,\n )\n }\n\n if (RESERVED_NAMES.has(name)) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is reserved. Reserved names: ${[...RESERVED_NAMES].join(', ')}.`,\n )\n }\n}\n\n/**\n * Lenient parse of a git branch name into a {@link ReleaseId}. Tolerates a\n * leading `refs/heads/`. Returns `null` for anything that is not a valid\n * `release/v<semver>` or `release/<name>` branch. Never throws.\n *\n * Precedence is version-first: `release/v<semver>` is a version, but if the\n * segment after `release/v` is not a valid semver (e.g. `release/vnext`), the\n * whole token after `release/` is treated as a candidate name instead.\n */\nexport const parseBranchName = (branch: string): ReleaseId | null => {\n const stripped = stripRefsHeads(branch.trim())\n\n if (!stripped.startsWith(RELEASE_BRANCH_PREFIX)) return null\n\n if (stripped.startsWith(VERSION_BRANCH_PREFIX)) {\n const semverPart = stripped.slice(VERSION_BRANCH_PREFIX.length)\n const match = BRANCH_SEMVER_RE.exec(semverPart)\n\n if (match) {\n return makeVersion(Number(match[1]), Number(match[2]), Number(match[3]))\n }\n }\n\n const namePart = stripped.slice(RELEASE_BRANCH_PREFIX.length)\n\n try {\n validateName(namePart)\n } catch {\n return null\n }\n\n return { kind: 'name', name: namePart, raw: namePart }\n}\n\n/**\n * Strict parse of a release ref into a {@link ReleaseId}. Throws\n * {@link InvalidReleaseRefError} on invalid input. Precedence (order matters):\n * 1. `release/\u2026` (or `refs/heads/release/\u2026`) \u2192 delegate to parseBranchName.\n * 2. semver token (`1.2.3` / `v1.2.3`) \u2192 version.\n * 3. `next` \u2192 throws; callers must resolve `next` to a concrete version\n * via computeNextVersion before calling this.\n * 4. otherwise \u2192 validateName, returning a named release.\n */\nexport const parseReleaseRef = (input: string): ReleaseId => {\n const trimmed = input.trim()\n const branchCandidate = stripRefsHeads(trimmed)\n\n if (branchCandidate.startsWith(RELEASE_BRANCH_PREFIX)) {\n const parsed = parseBranchName(trimmed)\n\n if (!parsed) {\n throw new InvalidReleaseRefError(\n `\"${input}\" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`,\n )\n }\n\n return parsed\n }\n\n const versionMatch = VERSION_RE.exec(trimmed)\n\n if (versionMatch) {\n return makeVersion(Number(versionMatch[1]), Number(versionMatch[2]), Number(versionMatch[3]))\n }\n\n if (trimmed.toLowerCase() === NEXT_TOKEN) {\n throw new InvalidReleaseRefError(\n 'The \"next\" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.',\n )\n }\n\n try {\n validateName(trimmed)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n\n throw new InvalidReleaseRefError(`Cannot parse \"${input}\" as a release ref: ${reason}`)\n }\n\n return { kind: 'name', name: trimmed, raw: trimmed }\n}\n\n/** Render the branch name for a release id: `release/v1.2.3` | `release/<name>`. */\nexport const formatBranchName = (id: ReleaseId): string => {\n if (id.kind === 'version') return `${VERSION_BRANCH_PREFIX}${id.raw}`\n\n return `${RELEASE_BRANCH_PREFIX}${id.name}`\n}\n\n/**\n * Render a PR title: `Release v1.2.3` / `Hotfix v1.2.3` for versions,\n * `Release <name>` / `Hotfix <name>` for names.\n */\nexport const formatPrTitle = (id: ReleaseId, type: 'regular' | 'hotfix'): string => {\n const prefix = type === 'hotfix' ? 'Hotfix' : 'Release'\n\n if (id.kind === 'version') return `${prefix} v${id.raw}`\n\n return `${prefix} ${id.name}`\n}\n\n/** Render a release-candidate PR title: `Release v1.2.3 (RC)` | `Release <name> (RC)`. */\nexport const formatRcTitle = (id: ReleaseId): string => {\n if (id.kind === 'version') return `Release v${id.raw} (RC)`\n\n return `Release ${id.name} (RC)`\n}\n\n/** Render the Jira fix-version name: `v1.2.3` | `<name>`. */\nexport const formatJiraName = (id: ReleaseId): string => {\n if (id.kind === 'version') return `v${id.raw}`\n\n return id.name\n}\n\n/** Render a short human display label: `1.2.3` | `<name>`. */\nexport const displayLabel = (id: ReleaseId): string => {\n return id.raw\n}\n\n/** True iff `branch` is a valid release branch under either scheme. */\nexport const isReleaseBranch = (branch: string | null | undefined): boolean => {\n if (branch === null || branch === undefined) return false\n\n return parseBranchName(branch) !== null\n}\n\nconst toTime = (value: string | Date | undefined): number | null => {\n if (value === undefined) return null\n\n const time = value instanceof Date ? value.getTime() : new Date(value).getTime()\n\n return Number.isNaN(time) ? null : time\n}\n\n/**\n * Comparator for {@link ReleaseId} values (locked ordering):\n * - All versions sort before all names.\n * - Versions: semver ascending (major, then minor, then patch; numeric).\n * - Names: by date ascending when both dates are provided, otherwise\n * lexicographic by name. The result is stable and deterministic.\n */\nexport const compareReleaseIds = (\n a: ReleaseId,\n b: ReleaseId,\n dates?: { a?: string | Date; b?: string | Date },\n): number => {\n if (a.kind === 'version' && b.kind === 'version') {\n if (a.semver.major !== b.semver.major) return a.semver.major - b.semver.major\n if (a.semver.minor !== b.semver.minor) return a.semver.minor - b.semver.minor\n\n return a.semver.patch - b.semver.patch\n }\n\n if (a.kind === 'version') return -1\n if (b.kind === 'version') return 1\n\n const timeA = toTime(dates?.a)\n const timeB = toTime(dates?.b)\n\n if (timeA !== null && timeB !== null && timeA !== timeB) {\n return timeA - timeB\n }\n\n if (a.name < b.name) return -1\n if (a.name > b.name) return 1\n\n return 0\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAOA,MAAa,eACpB,OAAOC,MAAU,OACjB,OAAOC,OAAY,cAGZ,IAAMC,EAAgB,yBAgBvBC,EAAe,CACnB,QACA,UACA,eACA,iBACA,gBACA,kBACA,sBACA,uBACF,EAEaC,GAAgB,IAAM,CACjC,IAAMC,EAAWN,EAAQ,KAAK,SAAS,SAAS,EAAI,QAAU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MAAM,IAAI,MAAMG,GAA+BhB,CAAK,CAAC,EAGvD,IAAMiB,EAASlD,GAA6B,UAAU8C,CAAS,EAE/D,GAAI,CAACI,EAAO,QACV,MAAM,IAAI,MAAM,WAAWjB,EAAM,KAAK,OAAOA,EAAM,IAAI,KAAK7D,EAAE,cAAc8E,EAAO,KAAK,CAAC,EAAE,EAG7F,OAAOA,EAAO,IAChB,EAWMF,GAAY5B,GACT,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,EAYtE6B,GAAkChB,GAC/B,CACL,oBAAoBA,EAAM,KAAK,6CAC/B,0FACA,uEACA,0CAA0CA,EAAM,IAAI,IACpD,4DACA,iGACF,EAAE,KAAK;AAAA,CAAI",
|
|
6
|
+
"names": ["process", "pino", "pretty", "LOG_FILE_PATH", "REDACT_PATHS", "initLoggerMcp", "logLevel", "logger", "initLoggerCLI", "ignoreFields", "fs", "path", "findMonorepoRoot", "startDir", "currentDir", "i", "workspaceFile", "getPackageName", "apiPath", "appName", "pkgPath", "pkg", "discoverApiApps", "root", "appsDir", "apps", "appDirs", "dirent", "serverlessPath", "VITE_CONFIG_FILES", "INFRA_KIT_VITE_SPECIFIERS", "usesInfraKitVite", "dir", "file", "configPath", "source", "specifier", "hasDevScript", "discoverUiApps", "uiPath", "normalizeAppInclude", "include", "filtered", "resolveSelfAppName", "relative", "firstSegment", "APP_PART_DIRS", "existingDistDir", "distDir", "subdirNames", "d", "getPackageDistDirs", "dirs", "name", "app", "part", "partDir", "getAppDistDirs", "classifyDistChange", "changedPath", "appDistDirs", "packageDistDirs", "normalized", "matchedPackageDir", "ALL_TARGETS_KEYS", "explainTargetKey", "key", "segments", "appGlob", "part", "parseTargetKey", "error", "validatePresetKeys", "presets", "issues", "preset", "def", "appsWithPart", "discovered", "allApps", "targetId", "app", "keyRank", "isGlob", "resolveWatch", "prior", "next", "addTarget", "state", "spec", "watchDeps", "id", "merged", "resolvePreset", "entries", "cfg", "apps", "targets", "localApps", "t", "deriveTargetLabel", "input", "running", "ownerApp", "apiPkgByApp", "pkg", "checkLocalRoute", "route", "launchedPkgs", "ctx", "owner", "hint", "validatePresetProxy", "resolved", "routes", "source", "issue", "fs", "os", "path", "process", "z", "path", "$", "VERSION_RE", "BRANCH_SEMVER_RE", "KEBAB_RE", "RELEASE_BRANCH_PREFIX", "VERSION_BRANCH_PREFIX", "REFS_HEADS_PREFIX", "NEXT_TOKEN", "RESERVED_NAMES", "InvalidReleaseNameError", "message", "InvalidReleaseRefError", "stripRefsHeads", "input", "REFS_HEADS_PREFIX", "makeVersion", "major", "minor", "patch", "validateName", "name", "KEBAB_RE", "parseBranchName", "branch", "stripped", "RELEASE_BRANCH_PREFIX", "VERSION_BRANCH_PREFIX", "semverPart", "match", "BRANCH_SEMVER_RE", "namePart", "parseReleaseRef", "trimmed", "parsed", "versionMatch", "VERSION_RE", "NEXT_TOKEN", "err", "reason", "formatBranchName", "id", "formatPrTitle", "type", "prefix", "formatRcTitle", "formatJiraName", "displayLabel", "isReleaseBranch", "toTime", "value", "time", "compareReleaseIds", "a", "b", "dates", "timeA", "timeB", "getCurrentWorktrees", "type", "worktreeLines", "$", "worktreePredicateMap", "releaseWorktreePredicate", "featureWorktreePredicate", "branch", "parseWorktreeBranch", "line", "trimmed", "open", "isReleaseBranch", "getProjectRoot", "getMainRepoRoot", "cwd", "root", "commonDir", "resolved", "path", "getCurrentBranch", "isWorkingTreeClean", "isInsideLinkedWorktree", "gitDirResult", "commonDirResult", "gitDir", "getRepoName", "projectRoot", "deleteLocalBranch", "deleteRemoteBranch", "INFRA_KIT_CONFIG_FILE", "USER_CONFIG_DIR_NAME", "USER_GLOBAL_CONFIG_FILE", "USER_PROJECTS_DIR", "dopplerEnvManagementSchema", "z", "envManagementSchema", "cursorIdeConfigSchema", "cursorIdeSchema", "zedIdeConfigSchema", "zedIdeSchema", "ideSchema", "idesSchema", "jiraTaskManagerSchema", "taskManagerSchema", "cmuxLayouts", "cmuxConfigSchema", "worktreesConfigSchema", "devAppConfigSchema", "devConfigSchema", "proxySourceSchema", "devPresetAppSchema", "devPresetSchema", "devPresetsSchema", "devProxyConfigSchema", "envAutoLoadSchema", "infraKitConfigObject", "DEFAULT_DEV_PROXY_PORT", "infraKitConfigSchema", "cfg", "ctx", "seen", "entry", "infraKitOverrideConfigSchema", "resolveConfiguredIdes", "config", "ide", "DEFAULT_CMUX_LAYOUT", "resolveCmuxLayout", "cached", "cachedPaths", "pathsCacheKey", "process", "os", "getInfraKitConfigPaths", "key", "projectRoot", "getProjectRoot", "mainRepoRoot", "getMainRepoRoot", "projectName", "path", "userConfigDir", "value", "getInfraKitConfig", "paths", "mainStat", "fs", "legacyYmlPath", "statIfExists", "userGlobalStat", "userProjectStat", "mtimes", "shallowEqual", "layers", "merged", "layer", "data", "loadLayer", "finalResult", "resetMergedConfigCache", "resetInfraKitConfigCache", "filePath", "readIfExists", "a", "b", "keys", "k", "raw", "parsedRaw", "err", "isRecord", "buildEnvTokensRejectionMessage", "result"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var i={name:"infra-kit",type:"module",version:"0.3.1",files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build",prepublishOnly:"pnpm run build","infra-kit-check":"pnpm exec infra-kit audit","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@aws-lambda-powertools/logger":"^2.33.1","@inquirer/checkbox":"^5.2.1","@inquirer/confirm":"^6.1.1","@inquirer/password":"^5.0.2","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0","@slip-stream-kit/config":"^0.3.0",chalk:"^5.6.2",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"5.10.0",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.2",react:"19.2.7",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/aws-lambda":"^8.10.162","@types/react":"19.2.17","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
|
|
2
|
+
//# sourceMappingURL=chunk-JPTSUMWI.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../package.json"],
|
|
4
|
+
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.3.1\",\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"inspector\": \"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug\",\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"prepublishOnly\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.33.1\",\n \"@inquirer/checkbox\": \"^5.2.1\",\n \"@inquirer/confirm\": \"^6.1.1\",\n \"@inquirer/password\": \"^5.0.2\",\n \"@inquirer/select\": \"^5.2.1\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"@slip-stream-kit/config\": \"^0.3.0\",\n \"chalk\": \"^5.6.2\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"5.10.0\",\n \"ink\": \"^7.1.0\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.2\",\n \"react\": \"19.2.7\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.162\",\n \"@types/react\": \"19.2.17\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.1\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,IAAAA,EAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,QACX,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,aACR,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,UAAa,iEACb,MAAS,sDACT,QAAW,iBACX,eAAkB,iBAClB,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,4EAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,qBAAsB,SACtB,mBAAoB,SACpB,4BAA6B,UAC7B,0BAA2B,SAC3B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,SACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,oBAAqB,YACrB,eAAgB,UAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF",
|
|
6
|
+
"names": ["package_default"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{P as v,v as c}from"./chunk-AVLZBOOA.js";import{q as k}from"./chunk-CHETBZ6M.js";import f from"node:fs/promises";import a from"node:path";import{z as i}from"zod";var n=class extends Error{env;constructor(r,e=null){super(r),this.name="EnvAuthError",this.env=e}},F=t=>t instanceof n;import w from"node:fs/promises";import y from"node:os";var O=async t=>{try{return await w.access(t),!0}catch{return!1}},m=t=>{let r=y.homedir();return t.startsWith(r)?`~${t.slice(r.length)}`:t};var S="tokens.json",l=1,x=384,E=448,T=i.object({version:i.literal(l).default(l),envs:i.record(i.string().min(1),i.string().min(1))}).strict(),p=async()=>{let t=await v();return a.join(a.dirname(t.userProject),S)},d=async()=>{let t=await p(),r;try{r=await f.readFile(t,"utf-8")}catch{return null}let e;try{e=JSON.parse(r)}catch(s){throw new n(`Invalid JSON in the token store at ${m(t)}: ${s.message}
|
|
2
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let o=T.safeParse(e);if(!o.success)throw new n(`Invalid token store at ${m(t)}: ${i.prettifyError(o.error)}
|
|
3
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return o.data},u=async t=>{let r=await p(),e=a.dirname(r),o=a.dirname(e),s=a.dirname(o);for(let h of[s,o,e])await f.mkdir(h,{recursive:!0,mode:E}),await f.chmod(h,E);k(r,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`,x),await f.chmod(r,x)},P=async(t,r)=>{let e=await d();await u({version:l,envs:{...e?.envs,[t]:r}})},$=async t=>{let r=await d();if(!r||!(t in r.envs))return;let e={...r.envs};delete e[t],await u({version:l,envs:e})};var I=()=>{let t="",r=[],e=!1;return{start(o){t=o,r=[],e=!1},setInteractive(){e=!0},addOption(o,s){r.push({flag:o,value:s})},formatOptions(){return r.map(o=>typeof o.value=="boolean"?o.value?o.flag:"":Array.isArray(o.value)?`${o.flag} "${o.value.join(", ")}"`:`${o.flag} "${o.value}"`).filter(Boolean).join(" ")},snapshot(){return r.length===0?null:{formattedOptions:this.formatOptions()}},print(){!e||r.length===0||!t||c.info(`\u{1F4DF} Equivalent command:
|
|
5
|
+
pnpm exec infra-kit ${t} ${this.formatOptions()}
|
|
6
|
+
`)},reset(){t="",r=[],e=!1}}},g=I();import j from"@inquirer/confirm";import N from"node:process";var _=async(t,r)=>{let e=t?!0:await j({message:r});t||g.setInteractive(),e||(c.info("Operation cancelled. Exiting..."),N.exit(0))};export{n as a,F as b,O as c,m as d,p as e,d as f,P as g,$ as h,g as i,_ as j};
|
|
7
|
+
//# sourceMappingURL=chunk-KAKTWDWJ.js.map
|