infra-kit 0.3.8 → 0.3.11
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-OA6HGGO6.js +2 -0
- package/dist/boot-OA6HGGO6.js.map +7 -0
- package/dist/{chunk-KAWDTA5H.js → chunk-2QJAIOPI.js} +2 -2
- package/dist/chunk-JXLXSX7Q.js +2 -0
- package/dist/chunk-JXLXSX7Q.js.map +7 -0
- package/dist/chunk-KPQTJQ42.js +2 -0
- package/dist/chunk-KPQTJQ42.js.map +7 -0
- package/dist/chunk-M46KGMQ6.js +4 -0
- package/dist/chunk-M46KGMQ6.js.map +7 -0
- package/dist/chunk-PZ2AWWGK.js +7 -0
- package/dist/{chunk-7DL27USH.js.map → chunk-PZ2AWWGK.js.map} +4 -4
- package/dist/chunk-VNHAMXNA.js +218 -0
- package/dist/chunk-VNHAMXNA.js.map +7 -0
- package/dist/cli.js +9 -9
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +32 -28
- package/dist/dev-server.js.map +3 -3
- package/dist/{dev-wizard-run-KIOSJM4D.js → dev-wizard-run-S5HEFLYE.js} +2 -2
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/package.json +3 -1
- package/readme.md +106 -1
- package/dist/boot-HP5ORQEX.js +0 -2
- package/dist/boot-HP5ORQEX.js.map +0 -7
- package/dist/chunk-3LPUAYWA.js +0 -2
- package/dist/chunk-3LPUAYWA.js.map +0 -7
- package/dist/chunk-7DL27USH.js +0 -7
- package/dist/chunk-PZU6BLQR.js +0 -4
- package/dist/chunk-PZU6BLQR.js.map +0 -7
- package/dist/chunk-RDRJX6TT.js +0 -232
- package/dist/chunk-RDRJX6TT.js.map +0 -7
- package/dist/chunk-XTRPE4SX.js +0 -2
- package/dist/chunk-XTRPE4SX.js.map +0 -7
- /package/dist/{chunk-KAWDTA5H.js.map → chunk-2QJAIOPI.js.map} +0 -0
- /package/dist/{dev-wizard-run-KIOSJM4D.js.map → dev-wizard-run-S5HEFLYE.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as j}from"./chunk-TPVXMJ7N.js";import{c as V}from"./chunk-X46DP23W.js";import{render as We}from"ink";import Y from"node:process";import{Box as J,Text as R,useApp as we,useInput as xe,useWindowSize as ge}from"ink";import{useEffect as re,useState as G}from"react";import{useMemo as pe,useState as ee}from"react";var F=(e,t)=>{let[r,m]=ee(""),[n,a]=ee(0),o=pe(()=>{let f=r.trim().toLowerCase();return f?e.filter(d=>t(d).toLowerCase().includes(f)):e},[e,r,t]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(f,d)=>{let b=o.length;return d.upArrow?(b>0&&a((u-1+b)%b),!0):d.downArrow?(b>0&&a((u+1)%b),!0):d.backspace||d.delete?(m(r.slice(0,-1)),a(0),!0):f&&!d.ctrl&&!d.meta?(m(r+f),a(0),!0):!1},clearQuery:()=>r?(m(""),a(0),!0):!1}};var fe=()=>{},q=(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},he=(e,t,r,m)=>{let n=0,a;for(let o=t;o<r;o+=1){let u=e[o];if(!u)break;let w=m(u),T=w!==void 0&&w!==a;n+=1+(T?1:0)+(T&&o>t?1:0),a=w}return n},te=(e,t,r,m)=>{let n=t;for(;n<e.length&&he(e,t,n+1,m)<=r;)n+=1;return n},$=(e,t,r,m,n)=>{let a=n?.groupOf??fe,o=Math.max(0,m-(n?.chromeRows??6)),u=Math.min(t,r);for(;r>=te(e,u,o,a)&&u<r;)u+=1;let w=te(e,u,o,a);return{visible:e.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,e.length-w)}};import{jsx as I,jsxs as D}from"react/jsx-runtime";var ne=e=>{let{items:t,onSubmit:r,onCancel:m,required:n=!0,allowSelectAll:a=!0}=e,o=be,u=t.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=we(),{rows:T}=ge(),{filtered:f,activeIndex:d,query:b,handleNavigation:v,clearQuery:M}=F(t,Te),[B,O]=G(()=>new Set),[E,h]=G(!1),[C,p]=G(0),[l,S]=G(!1);re(()=>{l&&w()},[l,w]);let _=q(T,1),y=$(f,C,d,T,{chromeRows:_.chromeRows});re(()=>{y.start!==C&&p(y.start)},[y.start,C]);let k=s=>{O(x=>{let g=new Set(x);return g.has(s)?g.delete(s):g.add(s),g})},H=()=>{O(s=>t.every(g=>s.has(g.value))?new Set:new Set(t.map(g=>g.value)))},i=()=>{m(),S(!0)},c=()=>{if(n&&B.size===0){h(!0);return}r([...B]),S(!0)};return xe((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&H();return}if(s===" "){let g=f[d];g&&k(g.value);return}if(x.return){c();return}v(s,x)}}),l?null:_.mode==="tiny"?I(R,{dimColor:!0,wrap:"truncate",children:o.tiny}):D(J,{flexDirection:"column",children:[_.mode==="full"?I(R,{dimColor:!0,wrap:"truncate",children:o.hint}):null,D(J,{children:[I(R,{color:"cyan",children:o.prompt}),I(R,{wrap:"truncate-start",children:b})]}),D(J,{flexDirection:"column",marginTop:_.mode==="full"?1:0,children:[f.length===0?I(R,{dimColor:!0,wrap:"truncate",children:o.empty}):null,y.hiddenBefore>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenBefore} above`}):null,y.visible.map((s,x)=>{let g=y.start+x===d,de=B.has(s.value);return D(R,{color:g?"green":void 0,wrap:"truncate",children:[g?"\u203A ":" ",de?"[x] ":"[ ] ",s.label.padEnd(u)," ",I(R,{dimColor:!0,children:s.description??""})]},s.value)}),y.hiddenAfter>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenAfter} below`}):null]}),E?I(R,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function Te(e){return`${e.label} ${e.description??""}`}var be={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as U,Text as W,useApp as Ce,useInput as Se,useWindowSize as ye}from"ink";import{useEffect as oe,useState as ie}from"react";import{jsx as L,jsxs as z}from"react/jsx-runtime";var le=e=>{let{items:t,onSelect:r,onCancel:m}=e,n=Be,a=t.reduce((p,l)=>Math.max(p,l.label.length),0),{exit:o}=Ce(),{rows:u}=ye(),{filtered:w,activeIndex:T,query:f,handleNavigation:d,clearQuery:b}=F(t,ve),[v,M]=ie(0),[B,O]=ie(!1);oe(()=>{B&&o()},[B,o]);let E=q(u),h=$(w,v,T,u,{chromeRows:E.chromeRows});oe(()=>{h.start!==v&&M(h.start)},[h.start,v]);let C=()=>{m(),O(!0)};return Se((p,l)=>{if(!B){if(l.ctrl&&p==="c"){C();return}if(l.escape){b()||C();return}if(l.return){let S=w[T];S&&(r(S.value),O(!0));return}d(p,l)}}),B?null:E.mode==="tiny"?L(W,{dimColor:!0,wrap:"truncate",children:n.tiny}):z(U,{flexDirection:"column",children:[E.mode==="full"?L(W,{dimColor:!0,wrap:"truncate",children:n.hint}):null,z(U,{children:[L(W,{color:"cyan",children:n.prompt}),L(W,{wrap:"truncate-start",children:f})]}),z(U,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(W,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((p,l)=>{let S=h.start+l===T;return z(W,{color:Pe(p.type,S),wrap:"truncate",children:[S?"\u203A ":" ",p.label.padEnd(a)," ",L(W,{dimColor:!0,children:p.description??""})]},p.value)}),h.hiddenAfter>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function Pe(e,t){return e==="hotfix"?"red":t?"green":void 0}function ve(e){return`${e.label} ${e.description??""}`}var Be={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as P,useApp as Oe,useInput as Re,useWindowSize as Ae}from"ink";import{useEffect as se,useMemo as Ee,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var ue=e=>{let{items:t,onSelect:r,onCancel:m,onSuspend:n}=e,a={hint:Ie(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:u,suspendTerminal:w}=Oe(),{rows:T}=Ae(),[f,d]=K(""),[b,v]=K(0),[M,B]=K(0),[O,E]=K(!1);se(()=>{O&&u()},[O,u]);let h=Ee(()=>{let i=f.trim().toLowerCase();return i?t.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):t},[t,f]),C=Math.min(b,Math.max(0,h.length-1)),p=q(T),l=$(h,M,C,T,{chromeRows:p.chromeRows,groupOf:p.groups?i=>i.group:void 0});se(()=>{l.start!==M&&B(l.start)},[l.start,M]);let S=()=>{m(),E(!0)},_=()=>{n&&w(n).catch(()=>{})},y=i=>i==="c"||i==="d"?(S(),!0):i==="z"?(_(),!0):!1,k=i=>{let c=h.length;c>0&&v((C+i+c)%c)};if(Re((i,c)=>{if(!O&&!(c.ctrl&&y(i))){if(c.escape){d(""),v(0);return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){k(-1);return}if(c.downArrow){k(1);return}if(c.backspace||c.delete){d(f.slice(0,-1)),v(0);return}i&&!c.ctrl&&!c.meta&&(d(f+i),v(0))}}),O)return null;if(p.mode==="tiny")return A(P,{dimColor:!0,wrap:"truncate",children:a.tiny});let H="";return N(Q,{flexDirection:"column",children:[p.mode==="full"?A(P,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(P,{color:"cyan",children:a.prompt}),A(P,{wrap:"truncate-start",children:f})]}),N(Q,{flexDirection:"column",marginTop:p.mode==="full"?1:0,children:[h.length===0?A(P,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=p.groups&&i.group!==H;return H=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(P,{children:" "}):null,x?A(P,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(P,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(P,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},ae={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-C quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-C quit"},Ie=e=>e?ae.suspend:ae.plain;import ce from"node:process";var me=(e={})=>{let t=e.platform??ce.platform,r=e.kill??((m,n)=>{ce.kill(m,n)});if(t!=="win32")try{r(0,"SIGSTOP")}catch{}};import{jsx as Z}from"react/jsx-runtime";var X=async e=>{let t=j(),{waitUntilExit:r}=We(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await r()}catch{}finally{V()>0?Y.stdin.ref():Y.stdin.pause()}},ut=async e=>{let t=null;return await X(Z(ue,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null},onSuspend:Y.platform==="win32"?void 0:()=>{me()}})),t},ct=async e=>{let t=null;return await X(Z(le,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null}})),t},mt=async(e,t)=>{let r=null;return await X(Z(ne,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:m=>{r=m},onCancel:()=>{r=null}})),r};export{mt as runBranchMultiPicker,ct as runBranchPicker,ut as runCommandPalette};
|
|
2
|
+
//# sourceMappingURL=boot-OA6HGGO6.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 { stdinReaderCount } from 'src/lib/prompts/stdin-ref'\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 * STDIN \u2014 Ink is self-balancing: it `ref()`s when it arms raw mode and `unref()`s when it\n * drops it on teardown (ink/build/components/App.js:225 / :137). A later Ink render refs\n * itself again on mount, and an `@inquirer/*` prompt \u2014 which refs nothing on its own \u2014 now\n * gets its ref from `withEscape` (lib/prompts/stdin-ref). So the common paths need nothing\n * from us here.\n *\n * The one thing Ink's `unref()` cannot know about is a reader that is ALREADY live: an Ink\n * screen rendered inside a `withEscape` callback would, on teardown, unref the handle the\n * outer prompt is still reading from and kill it with exit 13. Hence the re-assert below,\n * conditional on the counter. It is a net for a boundary nothing structurally enforces \u2014\n * see lib/prompts/stdin-ref \u2014 not the mechanism that keeps prompts alive.\n *\n * It replaces an UNCONDITIONAL `process.stdin.ref()`, whose stated premise \u2014 \"an idle\n * ref'd stdin does not block exit\" \u2014 is simply false: a ref'd tty ReadStream holds the\n * event loop open whether or not anything is listening to it. That re-ref bought the next\n * prompt its handle and cost the session shell its exit, so every quit key in the palette\n * tore the frame down correctly and then hung forever.\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 if (stdinReaderCount() > 0) {\n process.stdin.ref()\n } else {\n // STOP READING, not just \"stop holding the loop open\". `unref()` answers \"may node exit?\", not\n // \"is anyone still consuming this fd?\" \u2014 and Ink's teardown only drops its `readable` listener\n // and unrefs (App.js:136-137). The session shell then spawns the next command with\n // `stdio: 'inherit'`, so parent and child hold the SAME tty and each keystroke goes to exactly\n // one of them. Left unpaused, the parent wins often enough to eat the user's Esc; the child then\n // never cancels, `waitForExit` never resolves, and `childOwnsSigint` (lib/session/run-session)\n // swallows every Ctrl-C that follows. That is the \"Esc worked, then nothing does\" wedge.\n //\n // WHY `pause()` REACHES libuv AT ALL \u2014 it looks inert, and on a generic stream it is. The chain:\n // 1. `Readable.prototype.pause()` (node internal/streams/readable.js) emits `'pause'` ONLY IF\n // `readableFlowing !== false`.\n // 2. `process.stdin` \u2014 and ONLY `process.stdin`, ONLY on the main thread \u2014 carries a `'pause'`\n // listener installed by node's bootstrap (internal/bootstrap/switches/is_main_thread.js:263).\n // 3. That listener defers to `onpause` (:267), which calls `stdin._handle.readStop()` (:273).\n // `net.Socket.prototype.pause` never calls `readStop` itself (it does so only under `kBuffer`,\n // which is unset here), so a harness built on a CONSTRUCTED `tty.ReadStream`, or run in a worker\n // thread, measures a stream with ZERO `'pause'` listeners and correctly reports no effect. That\n // is a false negative about a different object, not evidence against this line.\n //\n // THE PRECONDITION, AND WHY THIS CALL SITE MEETS IT \u2014 Ink reads via a `readable` listener\n // (App.js:206, removed at :126), where `readableFlowing === false`, which would fail step 1 and\n // make this a silent no-op. It does not, because `removeListener('readable')` schedules\n // `updateReadableListening` on the NEXTTICK queue (clearing flowing to `null`), while this\n // `finally` runs in the PROMISE MICROTASK behind `await waitUntilExit()` above \u2014 and node drains\n // nextTick before microtasks. Ink resolves no earlier than it detaches (App.js:126 <- unmount\n // ink.js:300 <- resolveExitPromise ink.js:580). Measured on a pty: synchronous call => 0 `'pause'`\n // events, 0 readStops; behind the await => 1 and 1, flowing `null`, 3/3.\n //\n // SO: KEEP THIS BEHIND THE `await`. Making it synchronous silently disarms it with every test\n // still green \u2014 which is what src/tui/__tests__/stdin-pause-semantics.test.ts exists to catch.\n // Deferring it by a tick is NOT a hardening: `readStop` already lands after the `spawn` in\n // run-session.ts (pause -> spawn -> readStop) and deferring only widens that window. Verified\n // against ink 7.1.0; if Ink ever resolves before detaching, this reverts to a no-op.\n process.stdin.pause()\n }\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels. A Ctrl-Z suspends the job and resolves nothing \u2014 the same\n * palette redraws, filter and all, when the user brings it back with `fg`.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n // This module is the platform authority: `undefined` tells the palette that suspending is\n // impossible here, so it neither binds Ctrl-Z nor advertises it in the footer. (`suspendForeground`\n // guards win32 again on its own \u2014 the palette itself must stay free of `process`.)\n onSuspend={\n process.platform === 'win32'\n ? undefined\n : () => {\n suspendForeground()\n }\n }\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n *\n * The list is WINDOWED to the terminal height for the same safety reason as the\n * palette and the single picker: an overflowing Ink frame corrupts the cursor and\n * welds later output onto the transcript. See `palette-window.ts`.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = BRANCH_MULTI_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n // The extra chrome row is this screen's `select at least one` hint: counted unconditionally, because\n // it appears on a keystroke and a budget that shrinks mid-frame is a budget that overflows.\n const layout = listLayout(rows, 1)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: the typed filter first, the picker only once\n // there is no filter left to clear. It never touches `selected` \u2014 a filter keystroke is\n // not a selection, so clearing one must not discard the other. Stage 2 discards it, as before.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const isChecked = selected.has(item.value)\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width. Ink reads the wrap style off the\n // OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n {showRequiredHint ? (\n <Text dimColor wrap=\"truncate\">\n {T.requiredHint}\n </Text>\n ) : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_MULTI_PICKER_TEXT = {\n hint: 'filter \u00B7 \u2191\u2193 move \u00B7 Space toggle \u00B7 Ctrl-A all \u00B7 Enter submit \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick branches',\n requiredHint: 'select at least one',\n more: '\u2026',\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n /**\n * Stage 1 of the Esc ladder: clears a non-empty query (back to the first row) and\n * returns true. Returns false when the query is already empty \u2014 the boolean IS the\n * ladder, and a false tells the caller there is nothing left to cancel but the screen.\n *\n * Deliberately NOT folded into `handleNavigation`: the two pickers want different\n * stage-2 actions, so the escape branch belongs to each screen, not to the shared handler.\n */\n clearQuery: () => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n const clearQuery = (): boolean => {\n if (!query) {\n return false\n }\n\n setQuery('')\n setIndex(0)\n\n return true\n }\n\n return { filtered, activeIndex, query, handleNavigation, clearQuery }\n}\n", "/**\n * Pure viewport arithmetic shared by every Ink list screen (the command palette and both branch\n * pickers): which slice of the (already filtered) list fits the terminal, and how much chrome the\n * screen may spend around it.\n *\n * This is a SAFETY guard, not a readability one. Ink's cleanup walks the cursor upward one line at a\n * time (`ESC[2K ESC[1A` per row) and `ESC[1A` SATURATES AT ROW 0. So the moment a frame is taller than\n * the viewport, the terminal scrolls while Ink draws, the upward walk erases the wrong rows, and the\n * cursor is left parked ABOVE live content \u2014 after which every later write (the session's status\n * footer, the next palette frame) is deposited on top of the transcript. That is the \"welded rows\" bug:\n * `\u276F ` printed over the head of `ERROR: \u2026`, leaving `ROR: \u2026` behind.\n *\n * The invariant this module exists to enforce, for every (columns, rows):\n *\n * rendered frame height < terminal rows\n *\n * Hold that, and Ink never takes its overflow path: `clearTerminal` never fires, `eraseLines` never\n * saturates, the cursor stays below the transcript, and a fresh (cold) Ink instance \u2014 which erases\n * NOTHING before its first frame \u2014 simply appends below the transcript like any other CLI. No new\n * escape bytes required.\n *\n * Two things make the row count knowable at all:\n * - Every list row is rendered `wrap=\"truncate\"`, so one item is always exactly one row. Without that\n * a long description wraps to two rows and this arithmetic silently under-counts (Ink wraps text\n * itself and measures the WRAPPED height, so it, not us, would be right).\n * - Chrome is counted unconditionally, even when a given row is not drawn (see `CHROME_ROWS`). Over-\n * counting shrinks the list; under-counting overflows. Only one of those is a bug.\n *\n * `src/tui/safe-stderr.ts` (the `ESC[3J` byte filter) remains the last-resort backstop for the case\n * this cannot cover \u2014 a SIGWINCH that invalidates a frame's height retroactively.\n */\nimport type { PaletteItem } from '../types'\n\n/**\n * Reads an item's group label. Omitted by the branch pickers, whose lists have no headers at all.\n * (Passed as an accessor rather than constrained with a `{ group?: string }` marker interface: a type\n * whose properties are ALL optional is \"weak\", and TypeScript refuses to match a `BranchPickerItem`\n * against it \u2014 inference silently falls back to the constraint and every field access breaks.)\n */\nexport type GroupOf<T> = (item: T) => string | undefined\n\n/** The slice to render, plus how many rows fell off each end (for the `\u2026 n more` affordances). */\nexport interface ListWindow<T> {\n visible: T[]\n /** Index the window starts at \u2014 the component stores it so the list does not jump between frames. */\n start: number\n hiddenBefore: number\n hiddenAfter: number\n}\n\n/** Back-compat alias: the command palette's window is a window of `PaletteItem`s. */\nexport type PaletteWindow = ListWindow<PaletteItem>\n\n/**\n * Rows a screen spends on everything that is not a list row, counted UNCONDITIONALLY (a `\u2026 n above`\n * that is not drawn today may be drawn on the next keystroke, and re-deriving the budget mid-frame is\n * how you get an off-by-one that only bites on a full list):\n * hint, `\u276F` prompt, the list's `marginTop`, `\u2026 n above`, `\u2026 n below`, and one row of headroom.\n *\n * The headroom row is what makes the frame strictly SHORTER than the viewport: Ink treats a frame\n * exactly as tall as the terminal as fullscreen and clears the screen.\n */\nexport const CHROME_ROWS = 6\n\n/** Compact chrome: the hint and the list's `marginTop` are dropped. Prompt + affordances + headroom. */\nexport const COMPACT_CHROME_ROWS = 4\n\n/** Below this many rows a screen drops its hint, its `marginTop`, and its group headers. */\nexport const COMPACT_BELOW_ROWS = 10\n\n/** Below this many rows no usable list fits at all; the screen renders a single-line notice instead. */\nexport const TINY_BELOW_ROWS = 5\n\n/** How a screen must lay itself out to keep its frame shorter than `rows`. */\nexport type ListLayoutMode = 'full' | 'compact' | 'tiny'\n\nexport interface ListLayout {\n mode: ListLayoutMode\n /** Rows reserved for chrome. Pass to `paletteWindow` as `chromeRows`. */\n chromeRows: number\n /** Whether group headers may be drawn (they cost a row each, so a compact frame drops them). */\n groups: boolean\n}\n\n/** A list with no group headers: every item costs exactly one row. */\nconst NO_GROUPS = (): undefined => {\n return undefined\n}\n\n/**\n * The layout a screen must use at this terminal height. `extraChromeRows` is for chrome a screen has\n * that the others do not \u2014 the multi-picker's `select at least one` hint is the only one today.\n *\n * A `tiny` frame is one truncated line, which is strictly shorter than any terminal of 2+ rows. (At\n * `rows === 1` nothing can be shorter than the viewport; Ink will clear. That is a degenerate terminal,\n * and `safe-stderr` keeps even that harmless.)\n *\n * @example\n * listLayout(24) // => { mode: 'full', chromeRows: 6, groups: true }\n * listLayout(8) // => { mode: 'compact', chromeRows: 4, groups: false }\n * listLayout(8, 1) // => { mode: 'compact', chromeRows: 5, groups: false } (multi-picker)\n * listLayout(4) // => { mode: 'tiny', chromeRows: 0, groups: false }\n */\nexport const listLayout = (rows: number, extraChromeRows = 0): ListLayout => {\n if (rows < TINY_BELOW_ROWS) {\n return { mode: 'tiny', chromeRows: 0, groups: false }\n }\n\n if (rows < COMPACT_BELOW_ROWS) {\n return { mode: 'compact', chromeRows: COMPACT_CHROME_ROWS + extraChromeRows, groups: false }\n }\n\n return { mode: 'full', chromeRows: CHROME_ROWS + extraChromeRows, groups: true }\n}\n\n/**\n * How many rows rendering `items[start..end)` costs: one per item (guaranteed by `wrap=\"truncate\"`),\n * plus, when `groups` is on, one for each group header and one for the blank line between groups (the\n * first rendered group gets a header but no blank \u2014 it mirrors the `showGroup && position > 0` rule in\n * the components). A list whose items carry no `group` never spends a header row.\n */\nconst heightOf = <T>(items: T[], start: number, end: number, groupOf: GroupOf<T>): number => {\n let height = 0\n let previousGroup: string | undefined\n\n for (let index = start; index < end; index += 1) {\n const item = items[index]\n\n if (!item) break\n\n const group = groupOf(item)\n const startsGroup = group !== undefined && group !== previousGroup\n\n height += 1 + (startsGroup ? 1 : 0) + (startsGroup && index > start ? 1 : 0)\n previousGroup = group\n }\n\n return height\n}\n\n/** The last index (exclusive) that still fits `budget` rows when rendering from `start`. */\nconst endThatFits = <T>(items: T[], start: number, budget: number, groupOf: GroupOf<T>): number => {\n let end = start\n\n while (end < items.length && heightOf(items, start, end + 1, groupOf) <= budget) {\n end += 1\n }\n\n return end\n}\n\n/**\n * The window of items to render: the largest slice starting at or after `start` that fits the terminal\n * while still containing `activeIndex`. Scrolls by the minimum needed \u2014 the caller keeps `start` in\n * state, so the list only moves when the cursor would otherwise leave the window.\n *\n * An empty `visible` is a legitimate result on a terminal too short to hold even one row. It is NOT\n * clamped up to one item: forcing a row that does not fit is exactly how the frame overflows and the\n * cursor corruption starts. A screen that gets nothing back renders its `tiny` notice instead \u2014 see\n * `listLayout`.\n *\n * @example\n * const window = paletteWindow(items, 0, 12, 24)\n * window.visible.length // => however many commands fit 18 rows\n * window.hiddenAfter // => the rest, surfaced as '\u2026 n below'\n */\nexport const paletteWindow = <T>(\n items: T[],\n start: number,\n activeIndex: number,\n rows: number,\n opts?: { chromeRows?: number; groupOf?: GroupOf<T> },\n): ListWindow<T> => {\n const groupOf = opts?.groupOf ?? NO_GROUPS\n const budget = Math.max(0, rows - (opts?.chromeRows ?? CHROME_ROWS))\n\n // Scroll up only if the cursor moved above the window; otherwise scroll down just far enough.\n let first = Math.min(start, activeIndex)\n\n while (activeIndex >= endThatFits(items, first, budget, groupOf) && first < activeIndex) {\n first += 1\n }\n\n const end = endThatFits(items, first, budget, groupOf)\n\n return {\n visible: items.slice(first, end),\n start: first,\n hiddenBefore: first,\n hiddenAfter: Math.max(0, items.length - end),\n }\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n *\n * Like the palette, the list is WINDOWED to the terminal height. That is a safety\n * requirement, not a nicety: a repo with ~20 open releases produced a frame taller\n * than an 80x24 window, and an overflowing Ink frame corrupts the cursor and welds\n * the next frame onto the command's own output. See `palette-window.ts`.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = BRANCH_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const layout = listLayout(rows)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: a typed filter first, the picker only once\n // there is no filter left to clear. `clearQuery` returning false IS that ladder.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width (a long branch name would\n // otherwise wrap and make the frame taller than this component believes). Ink reads the wrap\n // style off the OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_PICKER_TEXT = {\n hint: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter select \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick a branch',\n more: '\u2026',\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Ctrl-C / Ctrl-D); the app then exits. Esc never reaches this. */\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 / Ctrl-D). Esc is NOT a caller: it pops the filter only.\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Hand the terminal back to the user's shell until they `fg`.\n //\n // Ink does all the terminal work for us, in the right order and synchronously: `beginSuspend`\n // settles pending frames, erases the list, restores the cursor and drops raw mode BEFORE our\n // callback runs, and on resume `endSuspend` re-arms raw mode and force-redraws THIS SAME LIVE\n // COMPONENT \u2014 so the typed filter survives the suspend. That is why we must NOT set `submitted`\n // here: unmounting would throw the query away and give us a blank palette on return.\n //\n // The `.catch` is the PRIMARY guard, not a backstop \u2014 never simplify it to `void`. Two 0x1a bytes\n // in one read chunk (a double-tap) are both already queued in Ink's input loop, and `pauseInput`\n // only detaches the stdin listener, so the second one still fires \u2014 into a `beginSuspend` that is\n // already suspended, which throws. Harmless (it throws before flipping its own state, and the first\n // suspension still unwinds), but the rejection must be caught: `void` would make it an unhandled\n // rejection that kills the process mid terminal-restore.\n const suspend = () => {\n if (!onSuspend) {\n return\n }\n\n suspendTerminal(onSuspend).catch(() => {\n // See above: a double Ctrl-Z is a no-op, not a crash.\n })\n }\n\n /**\n * Ctrl-C / Ctrl-Z, hoisted OUT of the `useInput` body. Mandatory, not tidiness: that handler sits at\n * cognitive complexity 14, and an inline `if (key.ctrl && input === 'z' && onSuspend)` costs +2 \u2014\n * 16, over the sonarjs ceiling of 15, and `pnpm run qa` goes red.\n *\n * The palette's Ctrl-Z is a BYTE (0x1a), not a signal: Ink holds stdin in raw mode, which clears\n * termios ISIG, so the tty never generates SIGTSTP here at all. We therefore stop the process GROUP\n * ourselves (kill(0), see ../suspend.ts). The session shell's SIGTSTP handler does the opposite \u2014\n * it self-stops with raise('SIGSTOP') (lib/session/run-session.ts) \u2014 and that is CORRECT there,\n * because while a child command holds the foreground the tty is cooked and has already TSTP'd the\n * whole group, leaving only us to follow. DO NOT UNIFY THE TWO.\n */\n const handleCtrlKey = (input: string): boolean => {\n if (input === 'c') {\n quit()\n\n return true\n }\n\n // Ctrl-D is the REPL/shell convention for \"end of input\", and it quits exactly like Ctrl-C above.\n // UNCONDITIONAL, unlike anything Esc does: it ends the session with a filter typed as readily as\n // without one. It is no longer the key the footer names \u2014 Ctrl-C is, because that is the one a\n // hand reaches for to abandon a picker \u2014 but a shell user's fingers know this one, so it stays.\n if (input === 'd') {\n quit()\n\n return true\n }\n\n if (input === 'z') {\n suspend()\n\n return true\n }\n\n return false\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C quits, Ctrl-Z suspends (see handleCtrlKey). Esc pops one level and this palette has\n // exactly one \u2014 the filter \u2014 so an empty filter makes it a no-op, NOT a quit. Popping the root\n // would leave nowhere to land: the session shell has no screen behind the palette, so an Esc that\n // quit would be a quit wearing a back-out's clothes. Quitting is Ctrl-C / Ctrl-D, and only those.\n // No emptiness check: clearing an already-empty query is a React no-op.\n if (key.ctrl && handleCtrlKey(input)) {\n return\n }\n\n if (key.escape) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one command row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START on the input: overflow must eat the head of the filter, never the character\n being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const showGroup = layout.groups && item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the first row of the window). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\" wrap=\"truncate\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n {/* `wrap=\"truncate\"` is load-bearing, not cosmetic: it is what makes \"one command = one\n row\" true at any width, which is what keeps the frame shorter than the viewport. Ink\n reads the wrap style off the OUTER <Text> only \u2014 it squashes the nested <Text> into\n this one's string \u2014 so it must live here. */}\n <Text color={isActive ? 'green' : undefined} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Footer copy. Kept out of the component's `T` because picking between the two is a conditional.\n *\n * Exported so the hint-width guard can measure these strings: they render under `wrap=\"truncate\"`,\n * so a hint of \u226580 columns silently loses its TAIL \u2014 and the tail is where the newest keybinding\n * always lands. `Esc clear` is the whole truth, not an abbreviation of one: Esc pops the filter and\n * never quits, so the `quit` beside it is the only advertised way out.\n *\n * That advertised key is Ctrl-C, though Ctrl-D quits identically (see `handleCtrlKey`). Naming only\n * one is a width decision, and Ctrl-C wins it: it is what a hand reaches for to abandon a picker, and\n * it went UNADVERTISED here for as long as the palette existed.\n *\n * The slack this leaves is NOT spendable: restoring `type to filter` to the suspend variant would\n * measure 79 against the guard's `toBeLessThan(80)`, i.e. one column from silently truncating again.\n */\nexport const HINTS = {\n suspend: 'filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear \u00B7 Ctrl-C quit \u00B7 Ctrl-Z suspend',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear \u00B7 Ctrl-C quit',\n}\n\n/**\n * The footer hint, which advertises Ctrl-Z only where suspending is possible.\n *\n * Module scope for two reasons, both load-bearing. It cannot live in the component: a `?:` in\n * `CommandPalette`'s body pushes it from 15 to 16, over the sonarjs cognitive-complexity ceiling. And\n * it cannot sit above the component either: `@wl/component-file-order` pins this file to\n * imports \u2192 props interface \u2192 component with nothing in between. Below is the only legal home.\n *\n * Both strings are SHORTER than the hint they replace, on purpose \u2014 the footer renders with\n * `wrap=\"truncate\"`, so anything longer silently loses its tail on a narrow terminal, and the tail is\n * exactly where a newly-added key would land.\n *\n * @example\n * hintFor(true).includes('Ctrl-Z') // => true\n */\nconst hintFor = (canSuspend: boolean): string => {\n return canSuspend ? HINTS.suspend : HINTS.plain\n}\n", "import process from 'node:process'\n\n/**\n * Ctrl-Z at the palette, from the process side. React-free on purpose: the palette is pure\n * presentation and must not reach for `node:process`, and this half is worth unit-testing with plain\n * vitest (inject `kill`, assert the signal) rather than through an Ink frame.\n *\n * It lives under `src/tui/` rather than `src/lib/session/` because `boot.tsx` is its only caller and\n * the whole `src/tui/**` tree is the lazily-imported Ink chunk \u2014 the session layer never imports it,\n * and parking it there would drag it into the eager CLI chunk for nothing.\n */\n\n/** Seams for the stop. Production passes nothing; tests inject fakes and assert the signal. */\nexport interface SuspendDeps {\n platform?: NodeJS.Platform\n kill?: (pid: number, signal: NodeJS.Signals) => void\n}\n\n/**\n * Stop the foreground PROCESS GROUP so the user's shell reclaims the tty and prints a prompt.\n * Returns when the job is resumed (`fg` \u2192 SIGCONT): the kill halts JS synchronously, and execution\n * continues at the next statement \u2014 so there is no SIGCONT handler and nothing to re-arm.\n *\n * **pid 0 is the whole process group, and that is load-bearing.** Under `pnpm exec infra-kit`, pnpm's\n * node wrapper shares our pgid and the interactive shell only ever waits on PNPM \u2014 we are a\n * grandchild it never reaps. Stopping only ourselves would leave pnpm blocked in `waitpid`, so the\n * job never reads as stopped, the shell never reclaims the tty, and the terminal wedges with no\n * prompt and no way back. Stopping the group suspends the job as a unit, exactly as the tty's own\n * Ctrl-Z would; on direct-bin invocation it degenerates to a self-stop, so this is one code path.\n *\n * Only ever called from inside Ink's `suspendTerminal`, which has already erased the frame, restored\n * the cursor and dropped raw mode by the time we get here.\n *\n * `bg` is NOT supported: on resume Ink re-arms raw mode, and a `tcsetattr` from a background process\n * group raises SIGTTOU, which stops the job again. Same as vim. Use `fg`.\n *\n * @example\n * const stopped: number[] = []\n * suspendForeground({ platform: 'darwin', kill: (pid) => stopped.push(pid) })\n * stopped // => [0] (the process group, not process.pid)\n */\nexport const suspendForeground = (deps: SuspendDeps = {}): void => {\n const platform = deps.platform ?? process.platform\n const kill =\n deps.kill ??\n ((pid: number, signal: NodeJS.Signals) => {\n process.kill(pid, signal)\n })\n\n // SIGSTOP does not exist on Windows: `process.kill` there goes to uv_kill, which fails with ENOSYS\n // and THROWS. That throw would surface inside an Ink input handler \u2192 the ErrorBoundary \u2192\n // `handleExit(error)` \u2192 the session shell would silently QUIT. And Windows really does reach this\n // code: `sessionGateEnabled` (lib/session/run-session.ts) gates on TTYs only, with no platform\n // check, so Windows Terminal enters the palette like any other. Belt to boot.tsx's braces.\n if (platform === 'win32') {\n return\n }\n\n // No cursor/newline work here, deliberately: Ink's `beginSuspend` has already erased its frame and\n // left the cursor at column 0, so the shell's \"suspended\" line lands on a clean row. Writing a\n // newline first only opens a gratuitous blank gap above it (verified on a real pty).\n try {\n kill(0, 'SIGSTOP')\n } catch {\n // A stop we could not perform must degrade to a no-op, never to a crash: we are called mid\n // terminal-restore, and throwing here would take the session down with the tty half-handed-back.\n }\n}\n"],
|
|
5
|
+
"mappings": "gFAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,MAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,GAAQ,YAAAC,GAAU,iBAAAC,OAAqB,MAC3D,OAAS,aAAAC,GAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,Y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EAQaO,GAAuB,MAClCR,EACAS,IAC6B,CAC7B,IAAIR,EAA4B,KAEhC,aAAMV,EACJD,EAACoB,GAAA,CACC,MAAOV,EACP,SAAUS,GAAM,SAChB,eAAgBA,GAAM,eACtB,SAAWE,GAAW,CACpBV,EAAWU,CACb,EACA,SAAU,IAAM,CACdV,EAAW,IACb,EACF,CACF,EAEOA,CACT",
|
|
6
|
+
"names": ["render", "process", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "useMemo", "useState", "useListFilter", "items", "toText", "query", "setQuery", "index", "setIndex", "filtered", "q", "item", "activeIndex", "input", "key", "n", "NO_GROUPS", "listLayout", "rows", "extraChromeRows", "heightOf", "items", "start", "end", "groupOf", "height", "previousGroup", "index", "item", "group", "startsGroup", "endThatFits", "budget", "paletteWindow", "activeIndex", "opts", "first", "jsx", "jsxs", "BranchMultiPicker", "props", "items", "onSubmit", "onCancel", "required", "allowSelectAll", "T", "BRANCH_MULTI_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "toggleValue", "value", "prev", "next", "toggleSelectAll", "cancel", "submit", "useInput", "input", "key", "active", "Text", "Box", "position", "isActive", "isChecked", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "jsx", "jsxs", "BranchPicker", "props", "items", "onSelect", "onCancel", "T", "BRANCH_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "windowStart", "setWindowStart", "useState", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "cancel", "useInput", "input", "key", "selected", "Text", "Box", "position", "isActive", "labelColor", "type", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useMemo", "useState", "jsx", "jsxs", "CommandPalette", "props", "items", "onSelect", "onCancel", "onSuspend", "T", "hintFor", "nameWidth", "exit", "suspendTerminal", "useApp", "rows", "useWindowSize", "query", "setQuery", "useState", "index", "setIndex", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "filtered", "useMemo", "q", "item", "activeIndex", "layout", "listLayout", "view", "paletteWindow", "quit", "suspend", "handleCtrlKey", "input", "step", "delta", "n", "useInput", "key", "selected", "Text", "lastGroup", "Box", "position", "isActive", "showGroup", "HINTS", "canSuspend", "process", "suspendForeground", "deps", "platform", "kill", "pid", "signal", "jsx", "renderToStderr", "element", "stdout", "safeStderr", "waitUntilExit", "render", "stdinReaderCount", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "suspendForeground", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{b as P}from"./chunk-LKKKDB6V.js";import{m as f,q as E}from"./chunk-CHETBZ6M.js";import u from"node:path";var m="infra-kit",g=`${m}@latest`,S=(t,e,n)=>{let r=u.relative(n(u.resolve(t)),u.resolve(e));return r!==""&&!r.startsWith("..")&&!u.isAbsolute(r)},l=(t,e)=>u.resolve(t).split(u.sep).includes(e),z=(t,e)=>{let n=u.resolve(t).split(u.sep),r=n.indexOf("Cellar");return r!==-1&&n[r+1]===e},C=(t,e,n,r)=>{let o=t[e];return o!=null&&o!==""&&S(o,n,r)},H=[{manager:"volta",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"VOLTA_HOME",t,n)||l(t,".volta")||l(t,"volta"),updateCommand:["volta","install",m],canSelfSpawn:!0},{manager:"homebrew",test:({selfRealPath:t})=>z(t,m),updateCommand:["brew","upgrade",m],canSelfSpawn:!1},{manager:"pnpm",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"PNPM_HOME",t,n)||l(t,"pnpm")&&l(t,"global"),updateCommand:["pnpm","add","-g",g],canSelfSpawn:!0},{manager:"bun",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"BUN_INSTALL",t,n)||l(t,".bun"),updateCommand:["bun","add","-g",g],canSelfSpawn:!0},{manager:"yarn",test:({selfRealPath:t})=>l(t,".yarn")||l(t,"yarn")&&l(t,"global"),updateCommand:["yarn","global","add",g],canSelfSpawn:!0},{manager:"npm",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"npm_config_prefix",t,n),updateCommand:["npm","install","-g",g],canSelfSpawn:!0}],I=["npm","install","-g",g],b=t=>{let{selfRealPath:e,env:n,realpath:r,lazyNpmRoot:o}=t,s=H.find(({test:i})=>i({selfRealPath:e,env:n,realpath:r}));if(s)return{manager:s.manager,updateCommand:s.updateCommand,canSelfSpawn:s.canSelfSpawn};let a=o?.();return a!=null&&a!==""&&S(a,e,r)?{manager:"npm",updateCommand:I,canSelfSpawn:!0}:{manager:"unknown",updateCommand:I,canSelfSpawn:!1}},K=(t,e,n)=>l(t,"node_modules")&&S(e,t,n);import{realpathSync as G}from"node:fs";import $ from"node:path";var M=t=>{try{return G(t)}catch{return $.resolve(t)}};import{execFileSync as W}from"node:child_process";import B from"node:process";var Y=3e3,k=()=>{try{let e=W("npm",["root","-g"],{encoding:"utf-8",timeout:Y,stdio:["ignore","pipe","ignore"],shell:B.platform==="win32"}).trim();return e===""?void 0:e}catch{return}};import{spawnSync as de}from"node:child_process";import{homedir as fe}from"node:os";import v from"node:process";import d from"node:fs";import N from"node:path";import Q from"node:process";var X="update-check.lock",Z=1800*1e3,ee=()=>N.join(f(),X),te=(t,e)=>{try{e-d.statSync(t).mtimeMs>Z&&d.rmSync(t,{force:!0})}catch{}},A=(t={})=>{let e=t.nowMs??Date.now(),n=t.lockPath??ee();try{d.mkdirSync(N.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return d.openSync(n,"wx",384)}catch{return null}},o=r();if(o===null&&(te(n,e),o=r()),o===null)return null;try{d.writeFileSync(o,String(Q.pid))}catch{}return()=>{try{d.closeSync(o)}catch{}try{d.rmSync(n,{force:!0})}catch{}}};var ne="https://registry.npmjs.org",re=5e3,oe=t=>Object.entries(t).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],ae=t=>{let e=oe(t),n=e!=null&&e!==""?e:ne;for(;n.endsWith("/");)n=n.slice(0,-1);return n},R=async(t,e=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},re);try{let o=await e(`${ae(t)}/${m}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let a=(await o.json())?.version;return typeof a=="string"&&a!==""?a:null}catch{return null}finally{clearTimeout(r)}};var se=/^(\d+)\.(\d+)\.(\d+)$/,_=t=>{let[e=""]=t.trim().split("+"),[n="",...r]=e.split("-"),o=se.exec(n);if(!o)return null;let[s,a,i]=[o[1],o[2],o[3]].map(Number);return{release:[s,a,i],prerelease:r.length>0?r.join("-").split("."):[]}},L=/^\d+$/,le=(t,e)=>{let n=L.test(t),r=L.test(e);return n&&r?Number(t)-Number(e):n!==r?n?-1:1:t<e?-1:1},ie=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n+=1){let r=t[n],o=e[n];if(r===void 0)return-1;if(o===void 0)return 1;if(r!==o)return le(r,o)}return 0},U=(t,e)=>{let n=_(t),r=_(e);if(!n||!r)return!1;for(let a=0;a<3;a+=1){let i=n.release[a],h=r.release[a];if(i!==h)return i>h}let o=n.prerelease.length===0,s=r.prerelease.length===0;return o!==s?o:ie(n.prerelease,r.prerelease)>0};import T from"node:fs";import O from"node:path";var F="update-check.json",ce=1200*1e3,ue=()=>O.join(f(),F),pe=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),me=t=>{if(typeof t!="object"||t===null)return!1;let{lastCheckMs:e,latestVersion:n,updateCommand:r,outcome:o}=t;return typeof e=="number"&&Number.isFinite(e)&&(n===null||typeof n=="string")&&(r===null||pe(r))&&(o==null||typeof o=="string")},Ke=(t=e=>T.readFileSync(e,"utf8"))=>{try{let e=JSON.parse(t(ue()));return me(e)?e:null}catch{return null}},D=t=>{let e=f();T.mkdirSync(e,{recursive:!0}),E(O.join(e,F),JSON.stringify(t),384)},Ge=(t,e)=>{if(!t)return!0;let n=e-t.lastCheckMs;return n<0?!0:n>=ce};var ge=200,he=300*1e3,ye=t=>{try{return v.kill(t,0),!0}catch{return!1}},Ce=t=>new Promise(e=>{setTimeout(e,t)}),we=async(t,e)=>{let n=e.clock()+he;for(;e.clock()<n;){if(!e.isProcessAlive(t))return!0;await e.sleep(ge)}return!e.isProcessAlive(t)},rt=async(t,e)=>{let r=(e.acquireLock??A)();if(!r)return"already-running";try{return await Se(t,e)}finally{r()}},Se=async(t,e)=>{let n=e.env??v.env,r=e.nowMs??Date.now(),o=e.fetchLatest??R,s=e.writeCache??D,a=e.isProcessAlive??ye,i=e.sleep??Ce,h=e.clock??Date.now,V=e.lazyNpmRoot??k,j=e.spawnSync??de,c=await o(n),p=(x,q)=>(s({lastCheckMs:r,...q,outcome:x}),x);if(c===null)return p("fetch-failed",{latestVersion:null,updateCommand:null});if(!U(c,t))return p("up-to-date",{latestVersion:c,updateCommand:null});let{canSelfSpawn:J,updateCommand:y}=b({selfRealPath:e.selfRealPath,env:n,realpath:M,lazyNpmRoot:V});if(!J)return p("cannot-self-spawn",{latestVersion:c,updateCommand:y});if(e.parentPid==null)return p("parent-unknown",{latestVersion:c,updateCommand:null});if(s({lastCheckMs:r,latestVersion:c,updateCommand:null,outcome:"installing"}),!await we(e.parentPid,{isProcessAlive:a,sleep:i,clock:h}))return p("parent-still-running",{latestVersion:c,updateCommand:null});let w=j(y[0],y.slice(1),{stdio:"ignore",shell:v.platform==="win32",cwd:fe(),env:P(n),windowsHide:!0});return w.error||w.signal||w.status!==0?p("install-failed",{latestVersion:c,updateCommand:y}):p("installed",{latestVersion:null,updateCommand:null})};export{b as a,K as b,k as c,M as d,U as e,Ke as f,Ge as g,rt as h};
|
|
2
|
+
//# sourceMappingURL=chunk-2QJAIOPI.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as _}from"./chunk-LKKKDB6V.js";import{L,T as A,V as O,g as S,m as R,z as c}from"./chunk-M46KGMQ6.js";import B from"node:process";import{$ as w}from"zx";var M=async()=>{try{return await w`cmux --version`.quiet(),!0}catch{return!1}},j=async r=>{let{cwd:e,title:t,layout:o}=r,s=JSON.stringify(o),n=(await w({env:{...B.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${t} --cwd ${e} --focus false --layout ${s}`).stdout;return U(n)},F=async r=>{try{await w`cmux close-workspace --workspace ${r}`.quiet()}catch(e){c.debug({error:e,ref:r},"cmux: skipped closing dev workspace")}},U=r=>{let e=r.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in new-workspace output");return e[0]};import{$ as J}from"zx";import{realpath as q}from"node:fs/promises";import{$ as I}from"zx";var y=async r=>{try{return await q(r)}catch{return r}},P=async()=>{try{let[r,e]=await Promise.all([I`cmux workspace list --json`.quiet(),I`cmux workspace-group list --json`.quiet()]),t=JSON.parse(r.stdout).workspaces??[],o=JSON.parse(e.stdout).groups??[],s=new Set(o.map(n=>n.anchor_workspace_ref).filter(n=>typeof n=="string")),a=new Map;for(let n of t)!n.current_directory||s.has(n.ref)||a.set(await y(n.current_directory),n.ref);return a}catch(r){return c.debug({error:r},"cmux: skipped listing workspaces by cwd"),new Map}};var G=async r=>{try{let t=(await P()).get(await y(r));if(!t)return;await J`cmux workspace close ${t}`.quiet()}catch(e){c.debug({error:e,cwd:r},"cmux: skipped closing workspace by cwd")}};import{$ as k}from"zx";var N=async r=>{try{let e=(await k`cmux workspace-group list --json`.quiet()).stdout;return(JSON.parse(e).groups??[]).find(s=>s.name===r)?.ref??null}catch(e){return c.debug({error:e,name:r},"cmux: skipped group lookup"),null}},H=async(r,e)=>{try{let o=(await k`cmux workspace-group create --name ${r} --from ${e.join(",")}`).stdout.match(/workspace_group:\d+/)?.[0]??await N(r);return o&&await k`cmux workspace-group pin ${o}`.quiet(),o??null}catch(t){return c.warn({error:t,name:r},"\u26A0\uFE0F cmux: failed to create workspace group"),null}};import{$ as m}from"zx";var z=async r=>{let{cwd:e,title:t,group:o}=r,s=A(await O()),a=o?(await m`cmux workspace create --cwd ${e} --group ${o} --group-placement end`).stdout:(await m`cmux workspace create --cwd ${e}`).stdout,n=Q(a),p=(await m`cmux list-pane-surfaces --workspace ${n}`).stdout,u=K(p);return await m`cmux new-split right --workspace ${n} --surface ${u}`,s==="three-pane"&&await m`cmux new-split down --workspace ${n} --surface ${u}`,t&&await m`cmux workspace rename --workspace ${n} --title ${t}`,n},K=r=>{let e=r.match(/surface:\d+/);if(!e)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return e[0]},Q=r=>{let e=r.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in workspace create output");return e[0]};var V=r=>{let{branch:e}=r,t=S(e);return t?R(t):e};var X=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),T=r=>r instanceof Error&&X.has(r.name),ne=r=>{if(T(r))return!0;let e=r?.cause;return T(e)};import{loadDev as Y}from"@slip-stream-kit/config/internal";import Z from"node:path";var rr=(r,e)=>{let t=new Set;for(let o of Object.values(r))for(let s of Object.keys(L(o,e).proxy))t.add(s);return[...t]},er=async(r,e)=>{let t={},o=[];return await Promise.all(e.map(async s=>{try{let n=(await Y(Z.join(r,"apps",s,"ui")))?.proxy?.routes;if(!n)return;t[s]=Object.fromEntries(Object.entries(n).map(([p,u])=>[p,u.packageName]))}catch(a){o.push({app:s,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(s,a)=>t[s]?.[a],loadErrors:o}},pe=async(r,e,t,o)=>{let{routePkg:s,loadErrors:a}=await er(r,rr(e,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(n=>[n.name,n.packageName])),routePkg:s},loadErrors:a}};import{execFile as tr}from"node:child_process";import{createHash as or}from"node:crypto";import{existsSync as W,readFileSync as d}from"node:fs";import sr from"node:http";import nr from"node:https";import ar from"node:net";import{homedir as ir}from"node:os";import{dirname as h,join as l}from"node:path";import f from"node:process";import cr from"node:tls";import{fileURLToPath as ur}from"node:url";import{promisify as pr}from"node:util";var mr=pr(tr),lr=r=>{let e=JSON.parse(d(r,"utf-8")),t=typeof e.bin=="string"?e.bin:e.bin?.portless;return t==null||t===""?null:t},fr=()=>{try{let r=h(ur(import.meta.url));for(;;){let e=l(r,"node_modules","portless","package.json");if(W(e)){let o=lr(e);return o==null?null:l(h(e),o)}let t=h(r);if(t===r)return null;r=t}}catch{return null}},b,D=()=>(b===void 0&&(b=fr()),b),gr=/^[\w@%+=:,./-]+$/,dr="'\\''",xr=r=>gr.test(r)?r:`'${r.replaceAll("'",dr)}'`,ve=(r,e)=>{let t=[e.execPath??f.execPath,e.bin,...r];return(e.sudo===!0?"sudo ":"")+t.map(xr).join(" ")},yr=1500,C=1500,wr="x-portless",E="127.0.0.1",Pr="localhost",kr="/Library/LaunchDaemons/sh.portless.proxy.plist",hr="/etc/systemd/system/portless.service",br=(r=W)=>{try{return f.platform==="darwin"?r(kr)?"yes":"no":f.platform==="linux"?r(hr)?"yes":"no":"unknown"}catch{return"unknown"}},Cr=r=>new Promise(e=>{let t=ar.connect({host:E,port:r}),o=s=>{t.destroy(),e(s)};t.setTimeout(C),t.once("connect",()=>{o(!0)}),t.once("timeout",()=>{o(!1)}),t.once("error",()=>{o(!1)})}),Er=(r,e)=>new Promise(t=>{let s=(e?nr.request:sr.request)({host:E,port:r,method:"HEAD",path:"/",timeout:C,...e?{rejectUnauthorized:!1,servername:Pr}:{}},a=>{a.resume(),t(a.headers[wr]==="1")});s.on("error",()=>{t(!1)}),s.on("timeout",()=>{s.destroy(),t(!1)}),s.end()}),vr=async(r,{timeoutMs:e})=>{let t=D();if(t==null)throw new Error("portless is not installed (not resolvable from node_modules)");await mr(f.execPath,[t,...r],{signal:AbortSignal.timeout(e),encoding:"utf-8",env:_(f.env)})},v=()=>f.env.PORTLESS_STATE_DIR??l(ir(),".portless"),Sr="ca.pem",Rr="ca.trusted",$=()=>l(v(),Sr),Se=()=>{try{let r=d(l(v(),Rr),"utf-8").trim();return r===""?!1:or("sha256").update(d($())).digest("hex")===r.toLowerCase()}catch{return!1}},Re=(r,e)=>new Promise(t=>{let o;try{o=d($())}catch{t({ok:!1,code:"ENOENT"});return}let s=cr.connect({host:E,port:r,servername:e,ca:[o],rejectUnauthorized:!0},()=>{let a=s.authorizationError,n=s.authorized;s.destroy(),t(n?{ok:!0}:{ok:!1,code:a?.code??a?.message??"UNKNOWN"})});s.setTimeout(C),s.once("timeout",()=>{s.destroy(),t({ok:!1,code:"ETIMEDOUT"})}),s.once("error",a=>{s.destroy(),t({ok:!1,code:a.code??"UNKNOWN"})})}),Le=()=>{try{let r=JSON.parse(d(l(v(),"routes.json"),"utf-8"));return Array.isArray(r)?r.flatMap(e=>{let{hostname:t,port:o}=e??{};return typeof t!="string"||t===""||typeof o!="number"?[]:[{name:t,port:o}]}):[]}catch{return[]}},Ae=(r={})=>{let e=r.bin===void 0?D():r.bin,t=r.run??vr,o=r.isListening??Cr,s=r.isProxyServing??Er,a=r.isServiceInstalled??br,n=r.timeoutMs??yr,p=null,u=async i=>{try{return await t(i,{timeoutMs:n}),!0}catch{return!1}},x=async()=>(p??=await u(["--version"]),p);return{binPath:()=>e,isAvailable:x,isProxyServing:async(i,g)=>!await x()||!await o(i)?!1:s(i,g),probeProxy:async(i,g)=>await o(i)?await s(i,g)?"serving":"not-portless":"daemon-down",isServiceInstalled:a,registerAlias:async(i,g)=>await x()?u(["alias",i,String(g)]):!1,removeAlias:async i=>{await x()&&await u(["alias","--remove",i])}}};export{pe as a,fr as b,ve as c,Cr as d,Er as e,$ as f,Se as g,Re as h,Le as i,Ae as j,y as k,P as l,G as m,N as n,H as o,M as p,j as q,F as r,z as s,V as t,ne as u};
|
|
2
|
+
//# sourceMappingURL=chunk-JXLXSX7Q.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/integrations/cmux/open-dev-workspace.ts", "../src/integrations/cmux/close-workspace-by-cwd.ts", "../src/integrations/cmux/list-workspaces-by-cwd.ts", "../src/integrations/cmux/cmux-groups.ts", "../src/integrations/cmux/open-workspace-with-layout.ts", "../src/integrations/cmux/workspace-title.ts", "../src/lib/errors/is-prompt-cancellation.ts", "../src/dev/preset-proxy-context.ts", "../src/dev/proxy/portless-driver.ts"],
|
|
4
|
+
"sourcesContent": ["import process from 'node:process'\nimport { $ } from 'zx'\n\nimport type { CmuxLayoutNode } from 'src/dev/cmux-layout'\nimport { logger } from 'src/lib/logger'\n\n/** Args for {@link openCmuxDevWorkspace}: the workspace root, title, and pane layout tree. */\ninterface OpenCmuxDevWorkspaceArgs {\n cwd: string\n title: string\n layout: CmuxLayoutNode\n}\n\n/**\n * True iff the `cmux` CLI is invokable (i.e. `cmux --version` resolves). Used to\n * gate `--cmux` mode and fall back to single-process dev when cmux is absent.\n */\nexport const isCmuxAvailable = async (): Promise<boolean> => {\n try {\n await $`cmux --version`.quiet()\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Open ONE cmux workspace rooted at `cwd`, laid out per `layout` (one pane per\n * command). Runs in a `CMUX_QUIET=1` scoped env to suppress cmux's one-time compat\n * notice, then parses and returns the `workspace:<id>` ref from stdout.\n */\nexport const openCmuxDevWorkspace = async (args: OpenCmuxDevWorkspaceArgs): Promise<string> => {\n const { cwd, title, layout } = args\n const layoutJson = JSON.stringify(layout)\n\n const $cmux = $({ env: { ...process.env, CMUX_QUIET: '1' } })\n const output = (await $cmux`cmux new-workspace --name ${title} --cwd ${cwd} --focus false --layout ${layoutJson}`)\n .stdout\n\n return parseWorkspaceRef(output)\n}\n\n/**\n * Best-effort close of the cmux workspace `ref`, tearing down the workspace and\n * every pane process. Silently no-ops (debug-logged) if cmux isn't running or the\n * close fails, mirroring {@link file://./close-workspace-by-cwd.ts}.\n */\nexport const closeCmuxDevWorkspace = async (ref: string): Promise<void> => {\n try {\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, ref }, 'cmux: skipped closing dev workspace')\n }\n}\n\n/**\n * Extract the `workspace:<id>` ref from `cmux new-workspace` output (e.g.\n * `OK workspace:5`). Throws a clear error when no ref is present.\n *\n * @example\n * parseWorkspaceRef('OK workspace:5\\n') // => 'workspace:5'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in new-workspace output')\n }\n\n return match[0]\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { listCmuxWorkspacesByCwd, realpathForCmuxCwd } from './list-workspaces-by-cwd'\n\n/**\n * Best-effort close of the cmux workspace rooted at `cwd`. Resolves the workspace\n * ref via {@link listCmuxWorkspacesByCwd} (which excludes group anchors, so this\n * can never close a group header) and closes it. Silently no-ops if cmux isn't\n * running, no workspace matches the cwd, or the close fails.\n *\n * Called BEFORE `git worktree remove`, so `cwd` still exists and normalizes the\n * same way as cmux's reported `current_directory`.\n */\nexport const closeCmuxWorkspaceByCwd = async (cwd: string): Promise<void> => {\n try {\n const byCwd = await listCmuxWorkspacesByCwd()\n\n const ref = byCwd.get(await realpathForCmuxCwd(cwd))\n\n if (!ref) {\n return\n }\n\n await $`cmux workspace close ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, cwd }, 'cmux: skipped closing workspace by cwd')\n }\n}\n", "import { realpath } from 'node:fs/promises'\nimport { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxWorkspaceListEntry {\n ref: string\n current_directory: string | null\n}\n\ninterface CmuxGroupListEntry {\n anchor_workspace_ref: string | null\n}\n\n/**\n * Resolve `path` through the filesystem, falling back to the input when it can't\n * be resolved (e.g. the directory was already removed). Both the cmux-reported\n * cwd and the caller's target cwd are normalized the same way so a macOS\n * `/var`\u2192`/private/var` style symlink can't make two equal paths compare unequal\n * (the realpath-asymmetry footgun this repo has been burned by before).\n */\nconst safeRealpath = async (path: string): Promise<string> => {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n\n/**\n * Build a `realpath(cwd) \u2192 workspace ref` map of every currently-open cmux\n * workspace, keyed on its working directory. This is the dedup/close identity for\n * infra-kit's worktree workspaces \u2014 unique per worktree, and (unlike the title)\n * stable after the repo-name title prefix was dropped (two repos can share a\n * branch name like `fix-post-script-ci-cd`, but never a worktree path).\n *\n * Two entries are deliberately excluded:\n * - workspaces with no `current_directory` (e.g. `infra-kit dev` panes) \u2014 they\n * carry no worktree identity;\n * - group ANCHOR workspaces \u2014 cmux reports the anchor's cwd as the main-repo\n * root, so it collides with the real main-checkout workspace. Keying an\n * anchor into the map would shadow the main workspace (breaking dedup) and,\n * worse, let close-by-cwd close the group header. Anchors are dropped up front\n * via `workspace-group list`'s `anchor_workspace_ref`.\n *\n * Returns an empty map if cmux isn't running or the output can't be parsed \u2014\n * callers treat \"empty\" as \"unknown, proceed as if nothing is open\".\n */\nexport const listCmuxWorkspacesByCwd = async (): Promise<Map<string, string>> => {\n try {\n const [workspacesOutput, groupsOutput] = await Promise.all([\n $`cmux workspace list --json`.quiet(),\n $`cmux workspace-group list --json`.quiet(),\n ])\n\n const workspaces = (JSON.parse(workspacesOutput.stdout).workspaces ?? []) as CmuxWorkspaceListEntry[]\n const groups = (JSON.parse(groupsOutput.stdout).groups ?? []) as CmuxGroupListEntry[]\n\n const anchorRefs = new Set(\n groups\n .map((group) => {\n return group.anchor_workspace_ref\n })\n .filter((ref): ref is string => {\n return typeof ref === 'string'\n }),\n )\n\n const byCwd = new Map<string, string>()\n\n for (const workspace of workspaces) {\n if (!workspace.current_directory || anchorRefs.has(workspace.ref)) {\n continue\n }\n\n byCwd.set(await safeRealpath(workspace.current_directory), workspace.ref)\n }\n\n return byCwd\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspaces by cwd')\n\n return new Map()\n }\n}\n\n/** Exported for callers that need the same normalization when looking up a target cwd. */\nexport { safeRealpath as realpathForCmuxCwd }\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxGroupListEntry {\n ref: string\n name: string\n}\n\n/**\n * Return the `workspace_group:N` ref of the sidebar group titled exactly `name`,\n * or `null` if no such group exists (or cmux is unreachable). Group names are the\n * repo name (basename of the main-repo root), so worktree workspaces for one repo\n * all resolve to the same group regardless of which worktree the command runs in.\n */\nexport const findCmuxGroupRefByName = async (name: string): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group list --json`.quiet()).stdout\n\n const groups = (JSON.parse(output).groups ?? []) as CmuxGroupListEntry[]\n\n const match = groups.find((group) => {\n return group.name === name\n })\n\n return match?.ref ?? null\n } catch (error) {\n logger.debug({ error, name }, 'cmux: skipped group lookup')\n\n return null\n }\n}\n\n/**\n * Create a pinned sidebar group named `name` seeded with EXACTLY `fromRefs`, and\n * return its ref (or `null` on failure).\n *\n * `--from` is load-bearing: `cmux workspace-group create` defaults `--from` to the\n * currently-selected/caller workspace, so omitting it silently captures an\n * unrelated workspace (and, under the `--all` fan-out, steals a sibling repo's\n * freshly-created workspace). Passing the seed refs explicitly makes creation\n * deterministic and capture-free \u2014 no snapshot/self-heal needed. The group also\n * gets a synthetic anchor workspace (its header row), matching how the user's\n * groups are already shaped.\n */\nexport const createCmuxGroupFrom = async (name: string, fromRefs: string[]): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group create --name ${name} --from ${fromRefs.join(',')}`).stdout\n\n const ref = output.match(/workspace_group:\\d+/)?.[0] ?? (await findCmuxGroupRefByName(name))\n\n if (ref) {\n await $`cmux workspace-group pin ${ref}`.quiet()\n }\n\n return ref ?? null\n } catch (error) {\n logger.warn({ error, name }, '\u26A0\uFE0F cmux: failed to create workspace group')\n\n return null\n }\n}\n", "import { $ } from 'zx'\n\nimport { getInfraKitConfig, resolveCmuxLayout } from 'src/lib/infra-kit-config'\n\ninterface OpenCmuxWorkspaceArgs {\n cwd: string\n title?: string\n /**\n * When set, the workspace is created directly inside this sidebar group\n * (`workspace_group:N` ref) via `--group`, appended at the end so existing\n * members aren't reordered. Omit to create an ungrouped workspace (e.g. the\n * first worktree of a repo, which then seeds a new group).\n */\n group?: string\n}\n\n/**\n * Opens a new cmux workspace rooted at `cwd`, with panes arranged per the\n * configured `worktrees.cmux.layout` (resolved via {@link resolveCmuxLayout},\n * default `two-columns`):\n * two-columns \u2014 left | right, both full-height (two panes)\n * three-pane \u2014 left-top / left-bottom | full-height right (three panes)\n * All panes inherit `cwd` from the workspace. Returns the created\n * `workspace:N` ref so callers can seed a group from it.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<string> => {\n const { cwd, title, group } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = group\n ? (await $`cmux workspace create --cwd ${cwd} --group ${group} --group-placement end`).stdout\n : (await $`cmux workspace create --cwd ${cwd}`).stdout\n\n const workspaceRef = parseWorkspaceRef(newWorkspaceOutput)\n\n const surfacesOutput = (await $`cmux list-pane-surfaces --workspace ${workspaceRef}`).stdout\n\n const leftTopRef = parseFirstSurfaceRef(surfacesOutput)\n\n // Both layouts share the vertical split into left | right columns; only the\n // legacy three-pane layout additionally splits the left column top/bottom.\n await $`cmux new-split right --workspace ${workspaceRef} --surface ${leftTopRef}`\n\n if (layout === 'three-pane') {\n await $`cmux new-split down --workspace ${workspaceRef} --surface ${leftTopRef}`\n }\n\n if (title) {\n await $`cmux workspace rename --workspace ${workspaceRef} --title ${title}`\n }\n\n return workspaceRef\n}\n\n/**\n * Extracts the first `surface:<id>` reference from the output of\n * `cmux list-pane-surfaces`. Used to locate the initial (primary) pane\n * surface so subsequent splits can be anchored relative to it.\n *\n * @example\n * const output = 'surface:12 (active)\\nsurface:13\\n'\n * parseFirstSurfaceRef(output) // => 'surface:12'\n */\nconst parseFirstSurfaceRef = (output: string): string => {\n const match = output.match(/surface:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate initial surface in list-pane-surfaces output')\n }\n\n return match[0]\n}\n\n/**\n * Extracts the `workspace:<id>` reference from the output of\n * `cmux workspace create`. The returned ref is used to target the newly\n * created workspace in follow-up `cmux` commands (splits, rename, etc.).\n *\n * @example\n * const output = 'created workspace:7\\n'\n * parseWorkspaceRef(output) // => 'workspace:7'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in workspace create output')\n }\n\n return match[0]\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildCmuxWorkspaceTitleArgs {\n branch: string\n}\n\n/**\n * Builds the cmux workspace title for a worktree. The title is now just the\n * branch's display label \u2014 the repo name is NOT prefixed, because every worktree\n * workspace lives inside a per-repo sidebar GROUP whose header already carries the\n * repo name (e.g. group `hulyo-monorepo` \u2192 workspaces titled `1.48.0`,\n * `checkout-redesign`, `dev`). Release branches render via their release-id label\n * (`release/v1.48.0` \u2192 `1.48.0`, `release/checkout-redesign` \u2192 `checkout-redesign`);\n * non-release branches fall back to the raw branch string.\n *\n * Note: the title is NO LONGER a dedup/close key \u2014 that role moved to the\n * workspace cwd (see {@link listCmuxWorkspacesByCwd}), because dropping the repo\n * prefix makes titles collide across repos (both hulyo and travelist can have a\n * `fix-post-script-ci-cd` branch).\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { branch } = args\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\n}\n", "/**\n * Names of the error classes thrown when an interactive prompt ends without a\n * value. From `@inquirer/core`: `ExitPromptError` (Ctrl-C \u2014 and ONLY Ctrl-C:\n * inquirer binds no escape key, so it raises this from readline's SIGINT) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`, which is how\n * Esc arrives \u2014 see lib/prompts/escapable-context). From our own Ink pickers:\n * `PromptCancelledError` (see ./prompt-cancelled-error), which is registered here\n * rather than impersonating an inquirer class name. All are intentional\n * cancellations, not failures.\n */\nconst CANCELLATION_ERROR_NAMES = new Set(['ExitPromptError', 'AbortPromptError', 'PromptCancelledError'])\n\nconst hasCancellationName = (value: unknown): boolean => {\n return value instanceof Error && CANCELLATION_ERROR_NAMES.has(value.name)\n}\n\n/**\n * True when `error` represents a user (or signal) cancellation of an interactive\n * prompt \u2014 Ctrl-C anywhere, or Esc, which reaches an `@inquirer` prompt as an\n * abort and an Ink picker as a `PromptCancelledError`. Matched by `name` rather\n * than `instanceof` so it stays correct\n * even when pnpm dedupes more than one copy of `@inquirer/core` into the tree\n * (an `instanceof` check fails across realms/duplicate classes).\n *\n * Also unwraps one level of `cause`, so a cancellation re-wrapped in an\n * {@link ./operation-error.OperationError} is still recognised at the top-level\n * error boundary.\n *\n * @example\n * try {\n * await checkbox({ message: 'Select release branches', choices })\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // clean back-out, not an error\n * throw err\n * }\n */\nexport const isPromptCancellation = (error: unknown): boolean => {\n if (hasCancellationName(error)) return true\n\n const cause = (error as { cause?: unknown } | null | undefined)?.cause\n\n return hasCancellationName(cause)\n}\n", "/**\n * Assembles the impure {@link PresetProxyContext} `validatePresetProxy` needs, so the STATIC\n * proxy-locality rule in `presets.ts` never has to touch the filesystem or `loadDev` itself.\n *\n * Shared by two callers that must never disagree about what \"satisfiable\" means:\n * - `infra-kit audit` (`commands/audit/preset-proxy-check.ts`) \u2014 checks every preset.\n * - `infra-kit dev <preset>` (`dev-server.ts`) \u2014 checks only the one preset about to run, BEFORE\n * any server spawns.\n */\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\n\nimport { resolvePreset } from 'src/dev/presets'\nimport type { DiscoveredParts, PresetProxyContext } from 'src/dev/presets'\nimport type { DevPresets } from 'src/lib/infra-kit-config'\n\n/** A frontend config that a preset references but that failed to load (bad/invalid config). */\nexport interface LoadError {\n app: string\n message: string\n}\n\ninterface RoutePkgLookup {\n routePkg: PresetProxyContext['routePkg']\n loadErrors: LoadError[]\n}\n\n/**\n * The set of frontend app folders any preset's proxy override actually references \u2014\n * the only configs the caller needs to load. Scoping to these keeps an unrelated\n * broken frontend config from failing (or crashing) a check it was never relevant to.\n */\nconst collectReferencedApps = (presets: DevPresets, discovered: DiscoveredParts): string[] => {\n const apps = new Set<string>()\n\n for (const preset of Object.values(presets)) {\n for (const app of Object.keys(resolvePreset(preset, discovered).proxy)) {\n apps.add(app)\n }\n }\n\n return [...apps]\n}\n\n/**\n * Load each referenced frontend's `dev.proxy.routes` into a sync `(app, route) \u2192 pkg`\n * lookup. A config that throws (schema-invalid, import error) is captured as a\n * {@link LoadError} instead of rejecting, so one bad config yields an actionable\n * result rather than crashing the whole check.\n */\nconst buildRoutePkgLookup = async (root: string, apps: string[]): Promise<RoutePkgLookup> => {\n const routesByApp: Record<string, Record<string, string>> = {}\n const loadErrors: LoadError[] = []\n\n await Promise.all(\n apps.map(async (app) => {\n try {\n const dev = await loadDev(path.join(root, 'apps', app, 'ui'))\n const routes = dev?.proxy?.routes\n\n if (!routes) return\n\n routesByApp[app] = Object.fromEntries(\n Object.entries(routes).map(([route, route_]) => {\n return [route, route_.packageName]\n }),\n )\n } catch (error) {\n loadErrors.push({ app, message: error instanceof Error ? error.message : String(error) })\n }\n }),\n )\n\n return {\n routePkg: (app, route) => {\n return routesByApp[app]?.[route]\n },\n loadErrors,\n }\n}\n\n/** Result of {@link buildPresetProxyContext}: the assembled context, plus any config that failed to load. */\nexport interface PresetProxyContextResult {\n ctx: PresetProxyContext\n loadErrors: LoadError[]\n}\n\n/**\n * Build the {@link PresetProxyContext} `validatePresetProxy` needs for `presets`: a sync\n * `(app, route) \u2192 pkg` lookup from each referenced frontend's `infra-kit.config.ts`\n * (the SAME file, through the same `loadDev`, that the vite helper resolves at runtime), plus\n * the api package name for every discovered api app.\n *\n * @example\n * const { ctx, loadErrors } = await buildPresetProxyContext('/repo', presets, discovered, apiApps)\n * const issues = validatePresetProxy(presets, ctx)\n */\nexport const buildPresetProxyContext = async (\n root: string,\n presets: DevPresets,\n discovered: DiscoveredParts,\n apiApps: { name: string; packageName: string }[],\n): Promise<PresetProxyContextResult> => {\n const { routePkg, loadErrors } = await buildRoutePkgLookup(root, collectReferencedApps(presets, discovered))\n\n return {\n ctx: {\n discovered,\n apiPkgByApp: Object.fromEntries(\n apiApps.map((a) => {\n return [a.name, a.packageName]\n }),\n ),\n routePkg,\n },\n loadErrors,\n }\n}\n", "/**\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, a cmux runner, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set (a space, a paren \u2014 both of\n * which appear in real install paths like `/Applications/My Editor.app`) gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nconst shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless service\n * install` hands the user a command that dies with `sudo: portless: command not found`. `sudo` makes it\n * strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve `portless`\n * loses it the moment the command is elevated.\n *\n * We therefore print what the driver itself runs (see {@link defaultRun}): the current interpreter, by\n * absolute path, invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the\n * command works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * This is not merely cosmetic. portless's `service install` writes **the interpreter and script path it was\n * invoked with** straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n * `process.argv[1]`), so the command printed here is the command that gets installed as a **root system\n * daemon**. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as root.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + words.map(shellQuote).join(' ')\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_PLIST_PATH = '/Library/LaunchDaemons/sh.portless.proxy.plist'\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was **unsound**: portless's\n * `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n * process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n * stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n * old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n * were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Validating the chain here would collapse two different\n * failures \u2014 a daemon that is down, and a CA that was never trusted \u2014 into one indistinguishable error,\n * with two different fixes (a root `service install` vs the sudo-free `trust`). Trust is a separate,\n * explicitly-validating probe (doctor's CA check).\n */\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * *invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n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epC,GAClCuC,EAAiBH,EAAK,gBAAkB7B,GACxCiC,EAAqBJ,EAAK,oBAAsBtC,GAChDgB,EAAYsB,EAAK,WAAa7C,GAChCkD,EAA+B,KAG7BC,EAAS,MAAOvD,GAAqC,CACzD,GAAI,CACF,aAAMkD,EAAIlD,EAAM,CAAE,UAAA2B,CAAU,CAAC,EAEtB,EACT,MAAQ,CACN,MAAO,EACT,CACF,EAEM6B,EAAc,UAClBF,IAAiB,MAAMC,EAAO,CAAC,WAAW,CAAC,EAEpCD,GAkCT,MAAO,CACL,QAAS,IACA1B,EAET,YAAA4B,EACA,eApCc,MAAO1C,EAAcO,IAC/B,CAAE,MAAMmC,EAAY,GAEpB,CAAE,MAAML,EAAYrC,CAAI,EAAW,GAEhCsC,EAAetC,EAAMO,CAAG,EAgC/B,WAvBiB,MAAOP,EAAcO,IAChC,MAAM8B,EAAYrC,CAAI,EAEpB,MAAMsC,EAAetC,EAAMO,CAAG,EAAK,UAAY,eAFhB,cAuBvC,mBAAAgC,EACA,cAnBoB,MAAOI,EAAc3C,IACnC,MAAM0C,EAAY,EAEjBD,EAAO,CAAC,QAASE,EAAM,OAAO3C,CAAI,CAAC,CAAC,EAFR,GAmBnC,YAdkB,MAAO2C,GAAgC,CACnD,MAAMD,EAAY,GACxB,MAAMD,EAAO,CAAC,QAAS,WAAYE,CAAI,CAAC,CAC1C,CAYA,CACF",
|
|
6
|
+
"names": ["process", "$", "isCmuxAvailable", "$", "openCmuxDevWorkspace", "args", "cwd", "title", "layout", "layoutJson", "output", "process", "parseWorkspaceRef", "closeCmuxDevWorkspace", "ref", "error", "logger", "match", "$", "realpath", "$", "safeRealpath", "path", "realpath", "listCmuxWorkspacesByCwd", "workspacesOutput", "groupsOutput", "$", "workspaces", "groups", "anchorRefs", "group", "ref", "byCwd", "workspace", "error", "logger", "closeCmuxWorkspaceByCwd", "cwd", "ref", "listCmuxWorkspacesByCwd", "safeRealpath", "$", "error", "logger", "$", "findCmuxGroupRefByName", "name", "output", "$", "group", "error", "logger", "createCmuxGroupFrom", "fromRefs", "ref", "$", "openCmuxWorkspaceWithLayout", "args", "cwd", "title", "group", "layout", "resolveCmuxLayout", "getInfraKitConfig", "newWorkspaceOutput", "$", "workspaceRef", "parseWorkspaceRef", "surfacesOutput", "leftTopRef", "parseFirstSurfaceRef", "output", "match", "buildCmuxWorkspaceTitle", "args", "branch", "id", "parseBranchName", "displayLabel", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "loadDev", "path", "collectReferencedApps", "presets", "discovered", "apps", "preset", "app", "resolvePreset", "buildRoutePkgLookup", "root", "routesByApp", "loadErrors", "routes", "loadDev", "path", "route", "route_", "error", "buildPresetProxyContext", "apiApps", "routePkg", "a", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "formatPortlessCommand", "args", "options", "words", "process", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var i={name:"infra-kit",type:"module",version:"0.3.11",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:pty":"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts",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/input":"^5.1.2","@inquirer/password":"^5.0.2","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0","@slip-stream-kit/config":"^0.3.3",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-KPQTJQ42.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.11\",\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:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts\",\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/input\": \"^5.1.2\",\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.3\",\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,SACX,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,SAAU,sJACV,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,kBAAmB,SACnB,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,4 @@
|
|
|
1
|
+
import M from"node:process";import j from"pino";import pe from"pino-pretty";var O="/tmp/mcp-infra-kit.log",F=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],It=()=>{let e=M.argv.includes("--debug")?"debug":"info",t=j({level:e,redact:F},j.destination({dest:O}));return t.info(`Logger initialized with level: ${e}. Logging to: ${O}`),t},le=()=>{let e=M.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),j({level:e,redact:F},pe({destination:2,ignore:t.join(","),colorize:!0}))},Dt=le();import*as p from"node:fs";import*as a from"node:path";function ue(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 G(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 $t(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:G(i,o),path:i})}return r}var B=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],fe=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function de(e){for(let t of B){let r=a.join(e,t);if(p.existsSync(r))try{let n=p.readFileSync(r,"utf-8");return fe.some(o=>n.includes(o))}catch{return!1}}return!1}function Tt(e){for(let t of B){let r=a.join(e,t);if(p.existsSync(r))try{return p.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function ge(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 Nt(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)&&ge(i)&&r.push({name:o,packageName:G(i,o),path:i,managedPort:de(i)})}return r}function _t(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function Lt(e){let t=ue(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 me=new Set(["api","ui"]),W=e=>{let t=a.join(e,"dist");return p.existsSync(t)&&p.statSync(t).isDirectory()?t:void 0},I=e=>p.existsSync(e)?p.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function Kt(e){let t=[];for(let n of I(a.join(e,"packages"))){let o=W(a.join(e,"packages",n));o!==void 0&&t.push(o)}let r=a.join(e,"apps");for(let n of I(r))for(let o of I(a.join(r,n))){if(me.has(o))continue;let i=a.join(r,n,o);if(!p.existsSync(a.join(i,"package.json")))continue;let c=W(i);c!==void 0&&t.push(c)}return t}function Ot(e){return e.map(t=>a.join(t.path,"dist")).filter(t=>p.existsSync(t))}function Mt(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 he={"*/api":{},"*/ui":{}},V=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},ve=e=>{let t=V(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},Wt=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let o of Object.keys(n.apps??{})){let i=V(o);i&&t.push({preset:r,key:o,message:`preset "${r}": ${i}`})}return t},ye=(e,t)=>t==="api"?e.api:e.ui,ke=e=>[...new Set([...e.api,...e.ui])].sort(),z=(e,t)=>`${e}/${t}`,xe=e=>e?0:1,be=(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,we=(e,t,r)=>{let{app:n,part:o,watchDeps:i,isGlob:c}=r;if(!ye(t,o).includes(n)){c||e.unmatched.push(z(n,o));return}let l=z(n,o),u=be(e.targets.get(l),{watchDeps:i,rank:xe(c)});e.targets.set(l,{app:n,part:o,...u})},Pe=(e,t)=>{let r=Object.entries(e.apps??he),n={targets:new Map,proxy:{},unmatched:[]};for(let[c,l]of r){let{appGlob:u,part:g}=ve(c),m=u==="*",P=m?ke(t):[u];for(let C of P)we(n,t,{app:C,part:g,watchDeps:l.watchDeps,isGlob:m}),l.proxy&&(n.proxy[C]={...n.proxy[C]??{},...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}},Gt=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(" + ")},Re=(e,t)=>Object.keys(e).find(r=>e[r]===t),Ee=({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=Re(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"`}},Bt=(e,t)=>{let r=[];for(let[n,o]of Object.entries(e)){let i=Pe(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[g,m]of Object.entries(u)){if(m!=="local")continue;let P=Ee({preset:n,app:l,route:g,launchedPkgs:c,ctx:t});P&&r.push(P)}}return r};import L from"node:fs/promises";import ne from"node:os";import b from"node:path";import Ve from"node:process";import{z as s}from"zod";import y from"node:path";import Q from"node:process";import{$ as f}from"zx";var E=e=>{if(e===null||typeof e!="object")return;let t=e.stderr;return typeof t=="string"&&t.length>0?t:void 0},Se=(e,t)=>{let r=t.stderrExcerpt??E(e),n=[`failed to ${t.operation}`];return r&&n.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&n.push(`try: ${t.remediation}`),n.join(" \u2014 ")},R=class extends Error{operation;remediation;constructor(t,r){super(Se(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation}};var U={enabled:!1},k=()=>U.enabled;var Ce=/^v?(\d+)\.(\d+)\.(\d+)$/,je=/^(\d+)\.(\d+)\.(\d+)$/,Ie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,S="release/",D="release/v",X="refs/heads/",De="next";var H=new Set(["dev","main","next","hotfix","regular","release"]),h=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},v=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},J=e=>e.startsWith(X)?e.slice(X.length):e,Y=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),A=e=>{if(e.length===0)throw new h('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new h(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!Ie.test(e))throw new h(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(H.has(e))throw new h(`Release name "${e}" is reserved. Reserved names: ${[...H].join(", ")}.`)},$=e=>{let t=J(e.trim());if(!t.startsWith(S))return null;if(t.startsWith(D)){let n=t.slice(D.length),o=je.exec(n);if(o)return Y(Number(o[1]),Number(o[2]),Number(o[3]))}let r=t.slice(S.length);try{A(r)}catch{return null}return{kind:"name",name:r,raw:r}},Ae=e=>{let t=e.trim();if(J(t).startsWith(S)){let o=$(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=Ce.exec(t);if(n)return Y(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===De)throw new v('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{A(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}},$e=e=>e.kind==="version"?`${D}${e.raw}`:`${S}${e.name}`,Te=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ne=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,_e=e=>e.kind==="version"?`v${e.raw}`:e.name,Le=e=>e.raw,T=e=>e==null?!1:$(e)!==null,q=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},Ke=(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=q(r?.a),o=q(r?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<t.name?-1:e.name>t.name?1:0};var Z=async e=>{let t=await f({cwd:e})`git worktree list --porcelain`,r=[],n=null;for(let o of t.stdout.split(`
|
|
2
|
+
`)){if(o.startsWith("worktree ")){n&&r.push(n),n={path:o.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o.startsWith("branch ")?n.branch=o.slice(7).replace(/^refs\/heads\//,""):o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="locked"||o.startsWith("locked ")?n.locked=!0:(o==="prunable"||o.startsWith("prunable "))&&(n.prunable=!0))}return n&&r.push(n),r},Oe=async e=>{let t=await Z(Q.cwd()),r=n=>e==="release"?T(n):n.startsWith("feature/");return t.map(n=>n.branch).filter(n=>n!==null&&r(n))},Me=e=>{let t=E(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},Fe=({hasStderr:e})=>{if(k())return"the infra-kit MCP server resolves its project from the working directory it was launched in; the operator must relaunch the server with its working directory set to an infra-kit project repo";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},x=async()=>{try{return(await f({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=Me(e)??E(e);throw new R(e,{operation:`resolve the project root from ${Q.cwd()}`,stderrExcerpt:t,remediation:Fe({hasStderr:t!==void 0})})}},N=async e=>{let t=e??await x(),r=(await f({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=y.resolve(t,r);return n.includes(`${y.sep}.git${y.sep}modules${y.sep}`)?t:y.dirname(n)},ee=async()=>(await f`git rev-parse --abbrev-ref HEAD`).stdout.trim(),We=async()=>(await f`git status --porcelain`).stdout.trim().length===0,Ge=async()=>{let e=await x(),[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=y.resolve(e,r.stdout.trim());return n!==o};var Be=async e=>{(await f`git branch --list ${e}`).stdout.trim().length!==0&&await ee()!==e&&await f`git branch -D ${e}`},ze=async e=>{(await f`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await f`git push origin --delete ${e}`};var te="infra-kit.json",oe=".infra-kit",Ue="infra-kit.json",Xe="projects",He=s.object({provider:s.literal("doppler"),config:s.object({name:s.string().min(1)})}),qe=s.discriminatedUnion("provider",[He]),Je=s.object({workspaceConfigPath:s.string().min(1)}),Ye=s.object({provider:s.literal("cursor"),config:Je}),Qe=s.object({}),Ze=s.object({provider:s.literal("zed"),config:Qe}),re=s.discriminatedUnion("provider",[Ye,Ze]),et=s.union([re,s.array(re).min(1)]),tt=s.object({provider:s.literal("jira"),config:s.object({baseUrl:s.string().url(),projectId:s.number().int().positive()})}),rt=s.discriminatedUnion("provider",[tt]),nt=["two-columns","three-pane"],ot=s.object({layout:s.enum(nt).optional()}),st=s.object({openInGithubDesktop:s.boolean().optional(),openInCmux:s.boolean().optional(),cmux:ot.optional()}),it=s.object({port:s.number().int().positive().optional(),prefixUrl:s.string().min(1).optional()}).strict(),at=s.record(s.string().min(1),it),ct=s.enum(["local","cloud"]),pt=s.object({watchDeps:s.boolean().optional(),proxy:s.record(s.string().min(1),ct).optional()}).strict(),lt=s.object({apps:s.record(s.string().min(1),pt).optional(),cmux:s.boolean().optional()}).strict(),ut=s.record(s.string().min(1),lt),ft=s.object({port:s.number().int().positive().optional()}).strict(),dt=s.object({trigger:s.enum(["shell-startup","cli-invocation"]),config:s.string().min(1)}).strict(),K=s.object({envManagement:qe,ide:et.optional(),taskManager:rt.optional(),worktrees:st.optional(),envAutoLoad:dt.optional(),dev:at.optional(),devServersPresets:ut.optional(),devProxy:ft.optional()}).strict(),gt=443,se=K.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)}}),ie=K.partial(),mt=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},ht="two-columns",vt=e=>e.worktrees?.cmux?.layout??ht,d=null,w=null,ae=()=>`${Ve.cwd()} ${ne.homedir()}`,ce=async()=>{let e=ae();if(w&&w.key===e)return w.value;let t=await x(),r=await N(t),n=b.basename(r),o=b.join(ne.homedir(),oe),i={main:b.join(t,te),userGlobal:b.join(o,Ue),userProject:b.join(o,Xe,n,te),projectName:n};return w={key:e,value:i},i},yt=async()=>{let e=ae(),t=await ce(),r;try{r=await L.stat(t.main)}catch{d=null;let g=t.main.replace(/\.json$/,".yml");throw await _(g)?new Error(`infra-kit.json not found at ${t.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(k()?`infra-kit.json not found at ${t.main} \u2014 the directory the infra-kit MCP server was launched in is not an infra-kit project. The operator must relaunch the server with its working directory set to an infra-kit project repo.`:`infra-kit.json not found at ${t.main} \u2014 this git repo is not an infra-kit project. Run \`infra-kit init\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`)}let[n,o]=await Promise.all([_(t.userGlobal),_(t.userProject)]),i={main:Number(r.mtimeMs),userGlobal:n?Number(n.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(d&&d.key===e&&wt(d.mtimes,i))return d.value;let c=[{label:"infra-kit.json",path:t.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:t.userGlobal,required:!1},{label:`~/.infra-kit/projects/${t.projectName}/infra-kit.json`,path:t.userProject,required:!1}],l={};for(let g of c){let m=await Pt(g);m!==null&&(l={...l,...m})}let u=se.safeParse(l);if(!u.success)throw new Error(`Invalid merged infra-kit config: ${s.prettifyError(u.error)}`);return d={key:e,mtimes:i,value:u.data},u.data},kt=()=>{d=null},xt=()=>{d=null,w=null},_=async e=>{try{return await L.stat(e)}catch{return null}},bt=async e=>{try{return await L.readFile(e,"utf-8")}catch{return null}},wt=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},Pt=async e=>{let t=await bt(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(Rt(r)&&"envTokens"in r)throw new Error(Et(e));let n=ie.safeParse(r);if(!n.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${s.prettifyError(n.error)}`);return n.data},Rt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Et=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{E as a,R as b,U as c,k as d,h as e,A as f,$ as g,Ae as h,$e as i,Te as j,Ne as k,_e as l,Le as m,T as n,Ke as o,Z as p,Oe as q,x as r,N as s,We as t,Ge as u,Be as v,ze as w,O as x,It as y,Dt as z,ue as A,$t as B,Tt as C,Nt as D,_t as E,Lt as F,Kt as G,Ot as H,Mt as I,V as J,Wt as K,Pe as L,Gt as M,Bt as N,oe as O,gt as P,se as Q,ie as R,mt as S,vt as T,ce as U,yt as V,kt as W,xt as X};
|
|
4
|
+
//# sourceMappingURL=chunk-M46KGMQ6.js.map
|