infra-kit 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/boot-EEEVHAMO.js +2 -0
  2. package/dist/boot-EEEVHAMO.js.map +7 -0
  3. package/dist/{chunk-NC2TIQ3M.js → chunk-7F5YKMWK.js} +2 -2
  4. package/dist/chunk-7F5YKMWK.js.map +7 -0
  5. package/dist/chunk-A7FAXZGI.js +2 -0
  6. package/dist/chunk-A7FAXZGI.js.map +7 -0
  7. package/dist/chunk-AJW5M44V.js +231 -0
  8. package/dist/chunk-AJW5M44V.js.map +7 -0
  9. package/dist/{chunk-E2NWNNC6.js → chunk-FTCM2766.js} +2 -2
  10. package/dist/{chunk-E2NWNNC6.js.map → chunk-FTCM2766.js.map} +1 -1
  11. package/dist/chunk-IPF7ILCB.js +7 -0
  12. package/dist/chunk-IPF7ILCB.js.map +7 -0
  13. package/dist/{chunk-KZP2SY37.js → chunk-KHEUED4B.js} +2 -2
  14. package/dist/chunk-KHEUED4B.js.map +7 -0
  15. package/dist/chunk-NLOLELZ5.js +6 -0
  16. package/dist/chunk-NLOLELZ5.js.map +7 -0
  17. package/dist/chunk-UO3FYLPX.js +2 -0
  18. package/dist/chunk-UO3FYLPX.js.map +7 -0
  19. package/dist/cli.js +10 -9
  20. package/dist/cli.js.map +3 -3
  21. package/dist/dev-server.js +39 -27
  22. package/dist/dev-server.js.map +4 -4
  23. package/dist/dev-wizard-run-5NOQIMR5.js +2 -0
  24. package/dist/dev-wizard-run-5NOQIMR5.js.map +7 -0
  25. package/dist/mcp.js +1 -1
  26. package/dist/mcp.js.map +3 -3
  27. package/dist/persistent-ink-dev-ui-TLUJJC2D.js +2 -0
  28. package/dist/persistent-ink-dev-ui-TLUJJC2D.js.map +7 -0
  29. package/dist/update-check.js +1 -1
  30. package/package.json +2 -2
  31. package/dist/boot-MTVHM4N7.js +0 -2
  32. package/dist/boot-MTVHM4N7.js.map +0 -7
  33. package/dist/chunk-4MRYIYJP.js +0 -4
  34. package/dist/chunk-4MRYIYJP.js.map +0 -7
  35. package/dist/chunk-6FU2TRU5.js +0 -2
  36. package/dist/chunk-6FU2TRU5.js.map +0 -7
  37. package/dist/chunk-E2SEBLGJ.js +0 -2
  38. package/dist/chunk-E2SEBLGJ.js.map +0 -7
  39. package/dist/chunk-KZP2SY37.js.map +0 -7
  40. package/dist/chunk-NC2TIQ3M.js.map +0 -7
  41. package/dist/chunk-RLZ5IB2E.js +0 -238
  42. package/dist/chunk-RLZ5IB2E.js.map +0 -7
  43. package/dist/chunk-TI33V5G2.js +0 -6
  44. package/dist/chunk-TI33V5G2.js.map +0 -7
  45. package/dist/dev-wizard-run-5HQOGE3R.js +0 -2
  46. package/dist/dev-wizard-run-5HQOGE3R.js.map +0 -7
  47. package/dist/persistent-ink-dev-ui-KOI44ZVT.js +0 -2
  48. package/dist/persistent-ink-dev-ui-KOI44ZVT.js.map +0 -7
@@ -0,0 +1,2 @@
1
+ import{b as Z}from"./chunk-TPVXMJ7N.js";import{render as Ie}from"ink";import ce from"node:process";import{Box as J,Text as R,useApp as he,useInput as we,useWindowSize as xe}from"ink";import{useEffect as ee,useState as F}from"react";import{useMemo as de,useState as V}from"react";var D=(e,t)=>{let[r,m]=V(""),[n,a]=V(0),o=de(()=>{let d=r.trim().toLowerCase();return d?e.filter(p=>t(p).toLowerCase().includes(d)):e},[e,r,t]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(d,p)=>{let S=o.length;return p.upArrow?(S>0&&a((u-1+S)%S),!0):p.downArrow?(S>0&&a((u+1)%S),!0):p.backspace||p.delete?(m(r.slice(0,-1)),a(0),!0):d&&!p.ctrl&&!p.meta?(m(r+d),a(0),!0):!1},clearQuery:()=>r?(m(""),a(0),!0):!1}};var pe=()=>{},_=(e,t=0)=>e<5?{mode:"tiny",chromeRows:0,groups:!1}:e<10?{mode:"compact",chromeRows:4+t,groups:!1}:{mode:"full",chromeRows:6+t,groups:!0},fe=(e,t,r,m)=>{let n=0,a;for(let o=t;o<r;o+=1){let u=e[o];if(!u)break;let w=m(u),T=w!==void 0&&w!==a;n+=1+(T?1:0)+(T&&o>t?1:0),a=w}return n},j=(e,t,r,m)=>{let n=t;for(;n<e.length&&fe(e,t,n+1,m)<=r;)n+=1;return n},$=(e,t,r,m,n)=>{let a=n?.groupOf??pe,o=Math.max(0,m-(n?.chromeRows??6)),u=Math.min(t,r);for(;r>=j(e,u,o,a)&&u<r;)u+=1;let w=j(e,u,o,a);return{visible:e.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,e.length-w)}};import{jsx as I,jsxs as G}from"react/jsx-runtime";var te=e=>{let{items:t,onSubmit:r,onCancel:m,required:n=!0,allowSelectAll:a=!0}=e,o=Te,u=t.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=he(),{rows:T}=xe(),{filtered:d,activeIndex:p,query:S,handleNavigation:v,clearQuery:M}=D(t,ge),[B,O]=F(()=>new Set),[E,h]=F(!1),[C,f]=F(0),[l,b]=F(!1);ee(()=>{l&&w()},[l,w]);let q=_(T,1),y=$(d,C,p,T,{chromeRows:q.chromeRows});ee(()=>{y.start!==C&&f(y.start)},[y.start,C]);let k=s=>{O(x=>{let g=new Set(x);return g.has(s)?g.delete(s):g.add(s),g})},H=()=>{O(s=>t.every(g=>s.has(g.value))?new Set:new Set(t.map(g=>g.value)))},i=()=>{m(),b(!0)},c=()=>{if(n&&B.size===0){h(!0);return}r([...B]),b(!0)};return we((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&H();return}if(s===" "){let g=d[p];g&&k(g.value);return}if(x.return){c();return}v(s,x)}}),l?null:q.mode==="tiny"?I(R,{dimColor:!0,wrap:"truncate",children:o.tiny}):G(J,{flexDirection:"column",children:[q.mode==="full"?I(R,{dimColor:!0,wrap:"truncate",children:o.hint}):null,G(J,{children:[I(R,{color:"cyan",children:o.prompt}),I(R,{wrap:"truncate-start",children:S})]}),G(J,{flexDirection:"column",marginTop:q.mode==="full"?1:0,children:[d.length===0?I(R,{dimColor:!0,wrap:"truncate",children:o.empty}):null,y.hiddenBefore>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenBefore} above`}):null,y.visible.map((s,x)=>{let g=y.start+x===p,me=B.has(s.value);return G(R,{color:g?"green":void 0,wrap:"truncate",children:[g?"\u203A ":" ",me?"[x] ":"[ ] ",s.label.padEnd(u)," ",I(R,{dimColor:!0,children:s.description??""})]},s.value)}),y.hiddenAfter>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenAfter} below`}):null]}),E?I(R,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function ge(e){return`${e.label} ${e.description??""}`}var Te={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as U,Text as W,useApp as be,useInput as Se,useWindowSize as Ce}from"ink";import{useEffect as re,useState as ne}from"react";import{jsx as L,jsxs as z}from"react/jsx-runtime";var oe=e=>{let{items:t,onSelect:r,onCancel:m}=e,n=ve,a=t.reduce((f,l)=>Math.max(f,l.label.length),0),{exit:o}=be(),{rows:u}=Ce(),{filtered:w,activeIndex:T,query:d,handleNavigation:p,clearQuery:S}=D(t,Pe),[v,M]=ne(0),[B,O]=ne(!1);re(()=>{B&&o()},[B,o]);let E=_(u),h=$(w,v,T,u,{chromeRows:E.chromeRows});re(()=>{h.start!==v&&M(h.start)},[h.start,v]);let C=()=>{m(),O(!0)};return Se((f,l)=>{if(!B){if(l.ctrl&&f==="c"){C();return}if(l.escape){S()||C();return}if(l.return){let b=w[T];b&&(r(b.value),O(!0));return}p(f,l)}}),B?null:E.mode==="tiny"?L(W,{dimColor:!0,wrap:"truncate",children:n.tiny}):z(U,{flexDirection:"column",children:[E.mode==="full"?L(W,{dimColor:!0,wrap:"truncate",children:n.hint}):null,z(U,{children:[L(W,{color:"cyan",children:n.prompt}),L(W,{wrap:"truncate-start",children:d})]}),z(U,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(W,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((f,l)=>{let b=h.start+l===T;return z(W,{color:ye(f.type,b),wrap:"truncate",children:[b?"\u203A ":" ",f.label.padEnd(a)," ",L(W,{dimColor:!0,children:f.description??""})]},f.value)}),h.hiddenAfter>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function ye(e,t){return e==="hotfix"?"red":t?"green":void 0}function Pe(e){return`${e.label} ${e.description??""}`}var ve={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as P,useApp as Be,useInput as Oe,useWindowSize as Re}from"ink";import{useEffect as ie,useMemo as Ae,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var se=e=>{let{items:t,onSelect:r,onCancel:m,onSuspend:n}=e,a={hint:Ee(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:u,suspendTerminal:w}=Be(),{rows:T}=Re(),[d,p]=K(""),[S,v]=K(0),[M,B]=K(0),[O,E]=K(!1);ie(()=>{O&&u()},[O,u]);let h=Ae(()=>{let i=d.trim().toLowerCase();return i?t.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):t},[t,d]),C=Math.min(S,Math.max(0,h.length-1)),f=_(T),l=$(h,M,C,T,{chromeRows:f.chromeRows,groupOf:f.groups?i=>i.group:void 0});ie(()=>{l.start!==M&&B(l.start)},[l.start,M]);let b=()=>{m(),E(!0)},q=()=>{n&&w(n).catch(()=>{})},y=i=>i==="c"||i==="d"?(b(),!0):i==="z"?(q(),!0):!1,k=i=>{let c=h.length;c>0&&v((C+i+c)%c)};if(Oe((i,c)=>{if(!O&&!(c.ctrl&&y(i))){if(c.escape&&d){p(""),v(0);return}if(c.escape){b();return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){k(-1);return}if(c.downArrow){k(1);return}if(c.backspace||c.delete){p(d.slice(0,-1)),v(0);return}i&&!c.ctrl&&!c.meta&&(p(d+i),v(0))}}),O)return null;if(f.mode==="tiny")return A(P,{dimColor:!0,wrap:"truncate",children:a.tiny});let H="";return N(Q,{flexDirection:"column",children:[f.mode==="full"?A(P,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(P,{color:"cyan",children:a.prompt}),A(P,{wrap:"truncate-start",children:d})]}),N(Q,{flexDirection:"column",marginTop:f.mode==="full"?1:0,children:[h.length===0?A(P,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=f.groups&&i.group!==H;return H=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(P,{children:" "}):null,x?A(P,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(P,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(P,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},le={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear/quit \xB7 Ctrl-D quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear/quit \xB7 Ctrl-D quit"},Ee=e=>e?le.suspend:le.plain;import ae from"node:process";var ue=(e={})=>{let t=e.platform??ae.platform,r=e.kill??((m,n)=>{ae.kill(m,n)});if(t!=="win32")try{r(0,"SIGSTOP")}catch{}};import{jsx as X}from"react/jsx-runtime";var Y=async e=>{let t=Z(),{waitUntilExit:r}=Ie(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await r()}catch{}finally{ce.stdin.ref()}},st=async e=>{let t=null;return await Y(X(se,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null},onSuspend:ce.platform==="win32"?void 0:()=>{ue()}})),t},at=async e=>{let t=null;return await Y(X(oe,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null}})),t},ut=async(e,t)=>{let r=null;return await Y(X(te,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:m=>{r=m},onCancel:()=>{r=null}})),r};export{ut as runBranchMultiPicker,at as runBranchPicker,st as runCommandPalette};
2
+ //# sourceMappingURL=boot-EEEVHAMO.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/tui/boot.tsx", "../src/tui/screens/branch-multi-picker.tsx", "../src/tui/hooks/use-list-filter.ts", "../src/tui/screens/palette-window.ts", "../src/tui/screens/branch-picker.tsx", "../src/tui/screens/command-palette.tsx", "../src/tui/suspend.ts"],
4
+ "sourcesContent": ["import { render } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\n\nimport { safeStderr } from './safe-stderr'\nimport { BranchMultiPicker } from './screens/branch-multi-picker'\nimport { BranchPicker } from './screens/branch-picker'\nimport { CommandPalette } from './screens/command-palette'\nimport { suspendForeground } from './suspend'\nimport type { PaletteItem } from './types'\n\n/**\n * Entry point for the Ink TUI. This module (and everything under `src/tui/`) is\n * the ONLY place allowed to import `ink`/`react`; it is reached exclusively via a\n * dynamic `await import('src/tui/boot')` from the TTY branch of entry/cli.ts, so\n * React never loads on the MCP / `--json` / non-TTY paths. Build splitting keeps\n * it in a separate lazy chunk (see scripts/build.js).\n */\n\n/**\n * Render an Ink element to stderr and resolve once it tears down. Frames are\n * written to stderr so stdout stays clean for the command that runs afterwards\n * (mirrors the previous Inquirer menu).\n *\n * Ink `unref()`s process.stdin when it tears down raw mode on exit. That ref is\n * process-wide and never restored, so the next consumer of stdin \u2014 the Inquirer\n * prompt the selected command opens (e.g. the worktrees-remove checkbox), or a\n * SECOND Ink render in the same process (the bare-menu palette \u2192 picker hop) \u2014\n * reads from an unref'd handle that no longer keeps the event loop alive. Once\n * the command's git/gh subprocesses settle, the loop drains mid-prompt, Node\n * flags entry/cli.ts's top-level await as unsettled, and the process exits with\n * code 13 (the prompt dies on arrival). Re-ref stdin on BOTH the resolve and the\n * reject path so it holds the loop while the next prompt is reading; an idle\n * ref'd stdin does not block exit, so non-interactive follow-up commands still\n * terminate normally. Every render must go through here so the re-ref is never\n * skipped.\n */\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const stdout = safeStderr()\n const { waitUntilExit } = render(element, {\n stdout,\n // Ink's default is `exitOnCtrlC: true`, which intercepts the 0x03 byte in its own App and calls\n // `handleExit()` BEFORE it ever reaches `useInput`. That makes every screen's own ctrl+c branch\n // dead code, and \u2014 worse \u2014 it tears down on the CURRENT frame, so `log.done()` freezes the drawn\n // command list into the scrollback instead of erasing it (Esc, which goes through the screens'\n // own quit path, erases correctly; Ctrl-C left a corpse). Every screen rendered here already\n // handles ctrl+c itself, so hand them the key.\n exitOnCtrlC: false,\n // Ink's default is `!isInCi && stdout.isTTY`. We drop the isInCi term: a developer with CI\n // exported in their shell would otherwise get a NON-interactive Ink on a real terminal, and Ink\n // skips ALL terminal management in that mode \u2014 `beginSuspend` returns before it can drop raw mode\n // or erase the frame, and `endSuspend` never redraws. Ctrl-Z would hand the shell a raw-mode tty\n // with a stranded frame and a hidden cursor, and `fg` would come back to nothing. Whether we own\n // the terminal is a question about the tty, and only about the tty.\n interactive: Boolean(stdout.isTTY),\n })\n\n try {\n await waitUntilExit()\n } catch {\n // Swallow a teardown rejection: the caller reports cancellation via its own\n // captured sentinel (which stays at its initial value), not via a throw.\n } finally {\n process.stdin.ref()\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels. A Ctrl-Z suspends the job and resolves nothing \u2014 the same\n * palette redraws, filter and all, when the user brings it back with `fg`.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n // This module is the platform authority: `undefined` tells the palette that suspending is\n // impossible here, so it neither binds Ctrl-Z nor advertises it in the footer. (`suspendForeground`\n // guards win32 again on its own \u2014 the palette itself must stay free of `process`.)\n onSuspend={\n process.platform === 'win32'\n ? undefined\n : () => {\n suspendForeground()\n }\n }\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n *\n * The list is WINDOWED to the terminal height for the same safety reason as the\n * palette and the single picker: an overflowing Ink frame corrupts the cursor and\n * welds later output onto the transcript. See `palette-window.ts`.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = BRANCH_MULTI_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n // The extra chrome row is this screen's `select at least one` hint: counted unconditionally, because\n // it appears on a keystroke and a budget that shrinks mid-frame is a budget that overflows.\n const layout = listLayout(rows, 1)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: the typed filter first, the picker only once\n // there is no filter left to clear. It never touches `selected` \u2014 a filter keystroke is\n // not a selection, so clearing one must not discard the other. Stage 2 discards it, as before.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const isChecked = selected.has(item.value)\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width. Ink reads the wrap style off the\n // OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n {showRequiredHint ? (\n <Text dimColor wrap=\"truncate\">\n {T.requiredHint}\n </Text>\n ) : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_MULTI_PICKER_TEXT = {\n hint: 'filter \u00B7 \u2191\u2193 move \u00B7 Space toggle \u00B7 Ctrl-A all \u00B7 Enter submit \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick branches',\n requiredHint: 'select at least one',\n more: '\u2026',\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n /**\n * Stage 1 of the Esc ladder: clears a non-empty query (back to the first row) and\n * returns true. Returns false when the query is already empty \u2014 the boolean IS the\n * ladder, and a false tells the caller there is nothing left to cancel but the screen.\n *\n * Deliberately NOT folded into `handleNavigation`: the two pickers want different\n * stage-2 actions, so the escape branch belongs to each screen, not to the shared handler.\n */\n clearQuery: () => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n const clearQuery = (): boolean => {\n if (!query) {\n return false\n }\n\n setQuery('')\n setIndex(0)\n\n return true\n }\n\n return { filtered, activeIndex, query, handleNavigation, clearQuery }\n}\n", "/**\n * Pure viewport arithmetic shared by every Ink list screen (the command palette and both branch\n * pickers): which slice of the (already filtered) list fits the terminal, and how much chrome the\n * screen may spend around it.\n *\n * This is a SAFETY guard, not a readability one. Ink's cleanup walks the cursor upward one line at a\n * time (`ESC[2K ESC[1A` per row) and `ESC[1A` SATURATES AT ROW 0. So the moment a frame is taller than\n * the viewport, the terminal scrolls while Ink draws, the upward walk erases the wrong rows, and the\n * cursor is left parked ABOVE live content \u2014 after which every later write (the session's status\n * footer, the next palette frame) is deposited on top of the transcript. That is the \"welded rows\" bug:\n * `\u276F ` printed over the head of `ERROR: \u2026`, leaving `ROR: \u2026` behind.\n *\n * The invariant this module exists to enforce, for every (columns, rows):\n *\n * rendered frame height < terminal rows\n *\n * Hold that, and Ink never takes its overflow path: `clearTerminal` never fires, `eraseLines` never\n * saturates, the cursor stays below the transcript, and a fresh (cold) Ink instance \u2014 which erases\n * NOTHING before its first frame \u2014 simply appends below the transcript like any other CLI. No new\n * escape bytes required.\n *\n * Two things make the row count knowable at all:\n * - Every list row is rendered `wrap=\"truncate\"`, so one item is always exactly one row. Without that\n * a long description wraps to two rows and this arithmetic silently under-counts (Ink wraps text\n * itself and measures the WRAPPED height, so it, not us, would be right).\n * - Chrome is counted unconditionally, even when a given row is not drawn (see `CHROME_ROWS`). Over-\n * counting shrinks the list; under-counting overflows. Only one of those is a bug.\n *\n * `src/tui/safe-stderr.ts` (the `ESC[3J` byte filter) remains the last-resort backstop for the case\n * this cannot cover \u2014 a SIGWINCH that invalidates a frame's height retroactively.\n */\nimport type { PaletteItem } from '../types'\n\n/**\n * Reads an item's group label. Omitted by the branch pickers, whose lists have no headers at all.\n * (Passed as an accessor rather than constrained with a `{ group?: string }` marker interface: a type\n * whose properties are ALL optional is \"weak\", and TypeScript refuses to match a `BranchPickerItem`\n * against it \u2014 inference silently falls back to the constraint and every field access breaks.)\n */\nexport type GroupOf<T> = (item: T) => string | undefined\n\n/** The slice to render, plus how many rows fell off each end (for the `\u2026 n more` affordances). */\nexport interface ListWindow<T> {\n visible: T[]\n /** Index the window starts at \u2014 the component stores it so the list does not jump between frames. */\n start: number\n hiddenBefore: number\n hiddenAfter: number\n}\n\n/** Back-compat alias: the command palette's window is a window of `PaletteItem`s. */\nexport type PaletteWindow = ListWindow<PaletteItem>\n\n/**\n * Rows a screen spends on everything that is not a list row, counted UNCONDITIONALLY (a `\u2026 n above`\n * that is not drawn today may be drawn on the next keystroke, and re-deriving the budget mid-frame is\n * how you get an off-by-one that only bites on a full list):\n * hint, `\u276F` prompt, the list's `marginTop`, `\u2026 n above`, `\u2026 n below`, and one row of headroom.\n *\n * The headroom row is what makes the frame strictly SHORTER than the viewport: Ink treats a frame\n * exactly as tall as the terminal as fullscreen and clears the screen.\n */\nexport const CHROME_ROWS = 6\n\n/** Compact chrome: the hint and the list's `marginTop` are dropped. Prompt + affordances + headroom. */\nexport const COMPACT_CHROME_ROWS = 4\n\n/** Below this many rows a screen drops its hint, its `marginTop`, and its group headers. */\nexport const COMPACT_BELOW_ROWS = 10\n\n/** Below this many rows no usable list fits at all; the screen renders a single-line notice instead. */\nexport const TINY_BELOW_ROWS = 5\n\n/** How a screen must lay itself out to keep its frame shorter than `rows`. */\nexport type ListLayoutMode = 'full' | 'compact' | 'tiny'\n\nexport interface ListLayout {\n mode: ListLayoutMode\n /** Rows reserved for chrome. Pass to `paletteWindow` as `chromeRows`. */\n chromeRows: number\n /** Whether group headers may be drawn (they cost a row each, so a compact frame drops them). */\n groups: boolean\n}\n\n/** A list with no group headers: every item costs exactly one row. */\nconst NO_GROUPS = (): undefined => {\n return undefined\n}\n\n/**\n * The layout a screen must use at this terminal height. `extraChromeRows` is for chrome a screen has\n * that the others do not \u2014 the multi-picker's `select at least one` hint is the only one today.\n *\n * A `tiny` frame is one truncated line, which is strictly shorter than any terminal of 2+ rows. (At\n * `rows === 1` nothing can be shorter than the viewport; Ink will clear. That is a degenerate terminal,\n * and `safe-stderr` keeps even that harmless.)\n *\n * @example\n * listLayout(24) // => { mode: 'full', chromeRows: 6, groups: true }\n * listLayout(8) // => { mode: 'compact', chromeRows: 4, groups: false }\n * listLayout(8, 1) // => { mode: 'compact', chromeRows: 5, groups: false } (multi-picker)\n * listLayout(4) // => { mode: 'tiny', chromeRows: 0, groups: false }\n */\nexport const listLayout = (rows: number, extraChromeRows = 0): ListLayout => {\n if (rows < TINY_BELOW_ROWS) {\n return { mode: 'tiny', chromeRows: 0, groups: false }\n }\n\n if (rows < COMPACT_BELOW_ROWS) {\n return { mode: 'compact', chromeRows: COMPACT_CHROME_ROWS + extraChromeRows, groups: false }\n }\n\n return { mode: 'full', chromeRows: CHROME_ROWS + extraChromeRows, groups: true }\n}\n\n/**\n * How many rows rendering `items[start..end)` costs: one per item (guaranteed by `wrap=\"truncate\"`),\n * plus, when `groups` is on, one for each group header and one for the blank line between groups (the\n * first rendered group gets a header but no blank \u2014 it mirrors the `showGroup && position > 0` rule in\n * the components). A list whose items carry no `group` never spends a header row.\n */\nconst heightOf = <T>(items: T[], start: number, end: number, groupOf: GroupOf<T>): number => {\n let height = 0\n let previousGroup: string | undefined\n\n for (let index = start; index < end; index += 1) {\n const item = items[index]\n\n if (!item) break\n\n const group = groupOf(item)\n const startsGroup = group !== undefined && group !== previousGroup\n\n height += 1 + (startsGroup ? 1 : 0) + (startsGroup && index > start ? 1 : 0)\n previousGroup = group\n }\n\n return height\n}\n\n/** The last index (exclusive) that still fits `budget` rows when rendering from `start`. */\nconst endThatFits = <T>(items: T[], start: number, budget: number, groupOf: GroupOf<T>): number => {\n let end = start\n\n while (end < items.length && heightOf(items, start, end + 1, groupOf) <= budget) {\n end += 1\n }\n\n return end\n}\n\n/**\n * The window of items to render: the largest slice starting at or after `start` that fits the terminal\n * while still containing `activeIndex`. Scrolls by the minimum needed \u2014 the caller keeps `start` in\n * state, so the list only moves when the cursor would otherwise leave the window.\n *\n * An empty `visible` is a legitimate result on a terminal too short to hold even one row. It is NOT\n * clamped up to one item: forcing a row that does not fit is exactly how the frame overflows and the\n * cursor corruption starts. A screen that gets nothing back renders its `tiny` notice instead \u2014 see\n * `listLayout`.\n *\n * @example\n * const window = paletteWindow(items, 0, 12, 24)\n * window.visible.length // => however many commands fit 18 rows\n * window.hiddenAfter // => the rest, surfaced as '\u2026 n below'\n */\nexport const paletteWindow = <T>(\n items: T[],\n start: number,\n activeIndex: number,\n rows: number,\n opts?: { chromeRows?: number; groupOf?: GroupOf<T> },\n): ListWindow<T> => {\n const groupOf = opts?.groupOf ?? NO_GROUPS\n const budget = Math.max(0, rows - (opts?.chromeRows ?? CHROME_ROWS))\n\n // Scroll up only if the cursor moved above the window; otherwise scroll down just far enough.\n let first = Math.min(start, activeIndex)\n\n while (activeIndex >= endThatFits(items, first, budget, groupOf) && first < activeIndex) {\n first += 1\n }\n\n const end = endThatFits(items, first, budget, groupOf)\n\n return {\n visible: items.slice(first, end),\n start: first,\n hiddenBefore: first,\n hiddenAfter: Math.max(0, items.length - end),\n }\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n *\n * Like the palette, the list is WINDOWED to the terminal height. That is a safety\n * requirement, not a nicety: a repo with ~20 open releases produced a frame taller\n * than an 80x24 window, and an overflowing Ink frame corrupts the cursor and welds\n * the next frame onto the command's own output. See `palette-window.ts`.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = BRANCH_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const layout = listLayout(rows)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: a typed filter first, the picker only once\n // there is no filter left to clear. `clearQuery` returning false IS that ladder.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width (a long branch name would\n // otherwise wrap and make the frame taller than this component believes). Ink reads the wrap\n // style off the OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_PICKER_TEXT = {\n hint: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter select \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick a branch',\n more: '\u2026',\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /**\n * Stop the foreground job (Ctrl-Z). ABSENT means suspend is impossible on this platform \u2014 the\n * palette stays pure presentation and never inspects `process`; boot.tsx is the platform authority.\n */\n onSuspend?: () => void\n}\n\n/**\n * Fuzzy-ish command picker rendered with Ink. Pure presentation: it receives a\n * flat list of commands (already grouped/ordered by the catalog) and returns the\n * selected name. It never executes anything \u2014 the caller runs the command via\n * the existing Commander path.\n *\n * NOTE: this component sits at exactly the sonarjs cognitive-complexity ceiling (15). Any `if` or\n * `?:` added to its BODY breaks `pnpm run qa` \u2014 which is why the hint is picked by the module-scope\n * `hintFor` below and the control keys by `handleCtrlKey`, rather than inline.\n */\nexport const CommandPalette = (props: CommandPaletteProps) => {\n const { items, onSelect, onCancel, onSuspend } = props\n\n const T = {\n hint: hintFor(Boolean(onSuspend)),\n prompt: '\u276F ',\n empty: 'No matching commands',\n tiny: 'terminal too short \u2014 resize to pick a command',\n more: '\u2026',\n }\n const nameWidth = 24\n\n const { exit, suspendTerminal } = useApp()\n const { rows } = useWindowSize()\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n // First command in the visible window. Kept in state so the list scrolls by the minimum needed\n // instead of jumping every time the cursor moves.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame (Ink's `log.done()` would otherwise\n // freeze the last drawn frame \u2014 the command list \u2014 into the scrollback).\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return `${item.name} ${item.description}`.toLowerCase().includes(q)\n })\n }, [items, query])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n // The slice that fits this terminal, and how much chrome we may spend around it. A frame taller than\n // the viewport corrupts the cursor (see palette-window.ts) \u2014 every row here is budgeted, and every\n // row below is `wrap=\"truncate\"` so one command is always exactly one row.\n const layout = listLayout(rows)\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, {\n chromeRows: layout.chromeRows,\n // A compact frame drops group headers, so they must not be budgeted for either.\n groupOf: layout.groups\n ? (item) => {\n return item.group\n }\n : undefined,\n })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n // Back out with nothing picked (Ctrl-C, or Esc on an empty filter).\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Hand the terminal back to the user's shell until they `fg`.\n //\n // Ink does all the terminal work for us, in the right order and synchronously: `beginSuspend`\n // settles pending frames, erases the list, restores the cursor and drops raw mode BEFORE our\n // callback runs, and on resume `endSuspend` re-arms raw mode and force-redraws THIS SAME LIVE\n // COMPONENT \u2014 so the typed filter survives the suspend. That is why we must NOT set `submitted`\n // here: unmounting would throw the query away and give us a blank palette on return.\n //\n // The `.catch` is the PRIMARY guard, not a backstop \u2014 never simplify it to `void`. Two 0x1a bytes\n // in one read chunk (a double-tap) are both already queued in Ink's input loop, and `pauseInput`\n // only detaches the stdin listener, so the second one still fires \u2014 into a `beginSuspend` that is\n // already suspended, which throws. Harmless (it throws before flipping its own state, and the first\n // suspension still unwinds), but the rejection must be caught: `void` would make it an unhandled\n // rejection that kills the process mid terminal-restore.\n const suspend = () => {\n if (!onSuspend) {\n return\n }\n\n suspendTerminal(onSuspend).catch(() => {\n // See above: a double Ctrl-Z is a no-op, not a crash.\n })\n }\n\n /**\n * Ctrl-C / Ctrl-Z, hoisted OUT of the `useInput` body. Mandatory, not tidiness: that handler sits at\n * cognitive complexity 14, and an inline `if (key.ctrl && input === 'z' && onSuspend)` costs +2 \u2014\n * 16, over the sonarjs ceiling of 15, and `pnpm run qa` goes red.\n *\n * The palette's Ctrl-Z is a BYTE (0x1a), not a signal: Ink holds stdin in raw mode, which clears\n * termios ISIG, so the tty never generates SIGTSTP here at all. We therefore stop the process GROUP\n * ourselves (kill(0), see ../suspend.ts). The session shell's SIGTSTP handler does the opposite \u2014\n * it self-stops with raise('SIGSTOP') (lib/session/run-session.ts) \u2014 and that is CORRECT there,\n * because while a child command holds the foreground the tty is cooked and has already TSTP'd the\n * whole group, leaving only us to follow. DO NOT UNIFY THE TWO.\n */\n const handleCtrlKey = (input: string): boolean => {\n if (input === 'c') {\n quit()\n\n return true\n }\n\n // Ctrl-D is the REPL/shell convention for \"end of input\", and it is UNCONDITIONAL: unlike Esc it\n // is not part of the filter ladder, so it quits with a filter typed as readily as without one.\n // It exists because Esc-on-an-empty-filter ending the session is the one binding a shell user does\n // not expect, and this gives them the key their fingers already reach for without changing Esc.\n if (input === 'd') {\n quit()\n\n return true\n }\n\n if (input === 'z') {\n suspend()\n\n return true\n }\n\n return false\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C quits, Ctrl-Z suspends (see handleCtrlKey). Esc clears a non-empty filter first, and\n // only quits on an empty filter \u2014 the standard REPL/palette split, so the session shell keeps\n // running while the user narrows.\n if (key.ctrl && handleCtrlKey(input)) {\n return\n }\n\n if (key.escape && query) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.escape) {\n quit()\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one command row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START on the input: overflow must eat the head of the filter, never the character\n being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const showGroup = layout.groups && item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the first row of the window). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\" wrap=\"truncate\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n {/* `wrap=\"truncate\"` is load-bearing, not cosmetic: it is what makes \"one command = one\n row\" true at any width, which is what keeps the frame shorter than the viewport. Ink\n reads the wrap style off the OUTER <Text> only \u2014 it squashes the nested <Text> into\n this one's string \u2014 so it must live here. */}\n <Text color={isActive ? 'green' : undefined} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Footer copy. Kept out of the component's `T` because picking between the two is a conditional.\n *\n * Exported so the hint-width guard can measure these strings: they render under `wrap=\"truncate\"`,\n * so a hint of \u226580 columns silently loses its TAIL \u2014 and the tail is where the newest keybinding\n * always lands. `Esc clear/quit` (not `Esc cancel`) is the honest description: Esc pops the filter\n * first and only ends the session once there is nothing left to clear.\n */\nexport const HINTS = {\n suspend: 'filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear/quit \u00B7 Ctrl-D quit \u00B7 Ctrl-Z suspend',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear/quit \u00B7 Ctrl-D quit',\n}\n\n/**\n * The footer hint, which advertises Ctrl-Z only where suspending is possible.\n *\n * Module scope for two reasons, both load-bearing. It cannot live in the component: a `?:` in\n * `CommandPalette`'s body pushes it from 15 to 16, over the sonarjs cognitive-complexity ceiling. And\n * it cannot sit above the component either: `@wl/component-file-order` pins this file to\n * imports \u2192 props interface \u2192 component with nothing in between. Below is the only legal home.\n *\n * Both strings are SHORTER than the hint they replace, on purpose \u2014 the footer renders with\n * `wrap=\"truncate\"`, so anything longer silently loses its tail on a narrow terminal, and the tail is\n * exactly where a newly-added key would land.\n *\n * @example\n * hintFor(true).includes('Ctrl-Z') // => true\n */\nconst hintFor = (canSuspend: boolean): string => {\n return canSuspend ? HINTS.suspend : HINTS.plain\n}\n", "import process from 'node:process'\n\n/**\n * Ctrl-Z at the palette, from the process side. React-free on purpose: the palette is pure\n * presentation and must not reach for `node:process`, and this half is worth unit-testing with plain\n * vitest (inject `kill`, assert the signal) rather than through an Ink frame.\n *\n * It lives under `src/tui/` rather than `src/lib/session/` because `boot.tsx` is its only caller and\n * the whole `src/tui/**` tree is the lazily-imported Ink chunk \u2014 the session layer never imports it,\n * and parking it there would drag it into the eager CLI chunk for nothing.\n */\n\n/** Seams for the stop. Production passes nothing; tests inject fakes and assert the signal. */\nexport interface SuspendDeps {\n platform?: NodeJS.Platform\n kill?: (pid: number, signal: NodeJS.Signals) => void\n}\n\n/**\n * Stop the foreground PROCESS GROUP so the user's shell reclaims the tty and prints a prompt.\n * Returns when the job is resumed (`fg` \u2192 SIGCONT): the kill halts JS synchronously, and execution\n * continues at the next statement \u2014 so there is no SIGCONT handler and nothing to re-arm.\n *\n * **pid 0 is the whole process group, and that is load-bearing.** Under `pnpm exec infra-kit`, pnpm's\n * node wrapper shares our pgid and the interactive shell only ever waits on PNPM \u2014 we are a\n * grandchild it never reaps. Stopping only ourselves would leave pnpm blocked in `waitpid`, so the\n * job never reads as stopped, the shell never reclaims the tty, and the terminal wedges with no\n * prompt and no way back. Stopping the group suspends the job as a unit, exactly as the tty's own\n * Ctrl-Z would; on direct-bin invocation it degenerates to a self-stop, so this is one code path.\n *\n * Only ever called from inside Ink's `suspendTerminal`, which has already erased the frame, restored\n * the cursor and dropped raw mode by the time we get here.\n *\n * `bg` is NOT supported: on resume Ink re-arms raw mode, and a `tcsetattr` from a background process\n * group raises SIGTTOU, which stops the job again. Same as vim. Use `fg`.\n *\n * @example\n * const stopped: number[] = []\n * suspendForeground({ platform: 'darwin', kill: (pid) => stopped.push(pid) })\n * stopped // => [0] (the process group, not process.pid)\n */\nexport const suspendForeground = (deps: SuspendDeps = {}): void => {\n const platform = deps.platform ?? process.platform\n const kill =\n deps.kill ??\n ((pid: number, signal: NodeJS.Signals) => {\n process.kill(pid, signal)\n })\n\n // SIGSTOP does not exist on Windows: `process.kill` there goes to uv_kill, which fails with ENOSYS\n // and THROWS. That throw would surface inside an Ink input handler \u2192 the ErrorBoundary \u2192\n // `handleExit(error)` \u2192 the session shell would silently QUIT. And Windows really does reach this\n // code: `sessionGateEnabled` (lib/session/run-session.ts) gates on TTYs only, with no platform\n // check, so Windows Terminal enters the palette like any other. Belt to boot.tsx's braces.\n if (platform === 'win32') {\n return\n }\n\n // No cursor/newline work here, deliberately: Ink's `beginSuspend` has already erased its frame and\n // left the cursor at column 0, so the shell's \"suspended\" line lands on a clean row. Writing a\n // newline first only opens a gratuitous blank gap above it (verified on a real pty).\n try {\n kill(0, 'SIGSTOP')\n } catch {\n // A stop we could not perform must degrade to a no-op, never to a crash: we are called mid\n // terminal-restore, and throwing here would take the session down with the tty half-handed-back.\n }\n}\n"],
5
+ "mappings": "wCAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,OAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,GAAQ,YAAAC,GAAU,iBAAAC,OAAqB,MAC3D,OAAS,aAAAC,GAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,YAAAC,MAAgB,QA+B3B,IAAMC,EAAgB,CAAIC,EAAYC,IAA+C,CAC1F,GAAM,CAACC,EAAOC,CAAQ,EAAIL,EAAS,EAAE,EAC/B,CAACM,EAAOC,CAAQ,EAAIP,EAAS,CAAC,EAE9BQ,EAAWT,GAAQ,IAAM,CAC7B,IAAMU,EAAIL,EAAM,KAAK,EAAE,YAAY,EAEnC,OAAKK,EAIEP,EAAM,OAAQQ,GACZP,EAAOO,CAAI,EAAE,YAAY,EAAE,SAASD,CAAC,CAC7C,EALQP,CAMX,EAAG,CAACA,EAAOE,EAAOD,CAAM,CAAC,EAEnB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G,EAAaC,IAA2B,CACxCN,GAAQ,KAAKK,EAAKC,CAAM,CAC1B,GAOF,GAAIH,IAAa,QAOjB,GAAI,CACFC,EAAK,EAAG,SAAS,CACnB,MAAQ,CAGR,CACF,ENWI,cAAAG,MAAA,oBAvCJ,IAAMC,EAAiB,MAAOC,GAAyC,CACrE,IAAMC,EAASC,EAAW,EACpB,CAAE,cAAAC,CAAc,EAAIC,GAAOJ,EAAS,CACxC,OAAAC,EAOA,YAAa,GAOb,YAAa,EAAQA,EAAO,KAC9B,CAAC,EAED,GAAI,CACF,MAAME,EAAc,CACtB,MAAQ,CAGR,QAAE,CACAE,GAAQ,MAAM,IAAI,CACpB,CACF,EAOaC,GAAoB,MAAOC,GAAiD,CACvF,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACW,GAAA,CACC,MAAOF,EACP,SAAWG,GAAS,CAClBF,EAAWE,CACb,EACA,SAAU,IAAM,CACdF,EAAW,IACb,EAIA,UACEH,GAAQ,WAAa,QACjB,OACA,IAAM,CACJM,GAAkB,CACpB,EAER,CACF,EAEOH,CACT,EAMaI,GAAkB,MAAOL,GAAsD,CAC1F,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACe,GAAA,CACC,MAAON,EACP,SAAWO,GAAU,CACnBN,EAAWM,CACb,EACA,SAAU,IAAM,CACdN,EAAW,IACb,EACF,CACF,EAEOA,CACT,EAQaO,GAAuB,MAClCR,EACAS,IAC6B,CAC7B,IAAIR,EAA4B,KAEhC,aAAMT,EACJD,EAACmB,GAAA,CACC,MAAOV,EACP,SAAUS,GAAM,SAChB,eAAgBA,GAAM,eACtB,SAAWE,GAAW,CACpBV,EAAWU,CACb,EACA,SAAU,IAAM,CACdV,EAAW,IACb,EACF,CACF,EAEOA,CACT",
6
+ "names": ["render", "process", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "useMemo", "useState", "useListFilter", "items", "toText", "query", "setQuery", "index", "setIndex", "filtered", "q", "item", "activeIndex", "input", "key", "n", "NO_GROUPS", "listLayout", "rows", "extraChromeRows", "heightOf", "items", "start", "end", "groupOf", "height", "previousGroup", "index", "item", "group", "startsGroup", "endThatFits", "budget", "paletteWindow", "activeIndex", "opts", "first", "jsx", "jsxs", "BranchMultiPicker", "props", "items", "onSubmit", "onCancel", "required", "allowSelectAll", "T", "BRANCH_MULTI_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "toggleValue", "value", "prev", "next", "toggleSelectAll", "cancel", "submit", "useInput", "input", "key", "active", "Text", "Box", "position", "isActive", "isChecked", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "jsx", "jsxs", "BranchPicker", "props", "items", "onSelect", "onCancel", "T", "BRANCH_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "windowStart", "setWindowStart", "useState", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "cancel", "useInput", "input", "key", "selected", "Text", "Box", "position", "isActive", "labelColor", "type", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useMemo", "useState", "jsx", "jsxs", "CommandPalette", "props", "items", "onSelect", "onCancel", "onSuspend", "T", "hintFor", "nameWidth", "exit", "suspendTerminal", "useApp", "rows", "useWindowSize", "query", "setQuery", "useState", "index", "setIndex", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "filtered", "useMemo", "q", "item", "activeIndex", "layout", "listLayout", "view", "paletteWindow", "quit", "suspend", "handleCtrlKey", "input", "step", "delta", "n", "useInput", "key", "selected", "Text", "lastGroup", "Box", "position", "isActive", "showGroup", "HINTS", "canSuspend", "process", "suspendForeground", "deps", "platform", "kill", "pid", "signal", "jsx", "renderToStderr", "element", "stdout", "safeStderr", "waitUntilExit", "render", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "suspendForeground", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
7
+ }
@@ -1,4 +1,4 @@
1
- import{a as T}from"./chunk-6FU2TRU5.js";import{O as v,Q as S,c as E,i as C,v as u}from"./chunk-KZP2SY37.js";import W from"node:process";import{$ as w}from"zx";var $=async()=>{try{return await w`cmux --version`.quiet(),!0}catch{return!1}},N=async e=>{let{cwd:t,title:r,layout:n}=e,o=JSON.stringify(n),i=(await w({env:{...W.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${r} --cwd ${t} --focus false --layout ${o}`).stdout;return D(i)},_=async e=>{try{await w`cmux close-workspace --workspace ${e}`.quiet()}catch(t){u.debug({error:t,ref:e},"cmux: skipped closing dev workspace")}},D=e=>{let t=e.match(/workspace:\d+/);if(!t)throw new Error("cmux: could not locate workspace ref in new-workspace output");return t[0]};var I=/\bv(\d+\.\d+\.\d+)\b/g,l=e=>e.trim().replace(/\s+/g," ").replace(I,"$1");import{$ as A}from"zx";var M=async e=>{try{let t=(await A`cmux list-workspaces`.quiet()).stdout,r=B(t,e);if(!r)return;await A`cmux close-workspace --workspace ${r}`.quiet()}catch(t){u.debug({error:t,title:e},"cmux: skipped closing workspace")}},B=(e,t)=>{let r=l(t);for(let n of e.split(`
1
+ import{a as T}from"./chunk-A7FAXZGI.js";import{O as v,Q as S,c as E,i as C,v as u}from"./chunk-KHEUED4B.js";import W from"node:process";import{$ as w}from"zx";var $=async()=>{try{return await w`cmux --version`.quiet(),!0}catch{return!1}},N=async e=>{let{cwd:t,title:r,layout:n}=e,o=JSON.stringify(n),i=(await w({env:{...W.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${r} --cwd ${t} --focus false --layout ${o}`).stdout;return D(i)},_=async e=>{try{await w`cmux close-workspace --workspace ${e}`.quiet()}catch(t){u.debug({error:t,ref:e},"cmux: skipped closing dev workspace")}},D=e=>{let t=e.match(/workspace:\d+/);if(!t)throw new Error("cmux: could not locate workspace ref in new-workspace output");return t[0]};var I=/\bv(\d+\.\d+\.\d+)\b/g,l=e=>e.trim().replace(/\s+/g," ").replace(I,"$1");import{$ as A}from"zx";var M=async e=>{try{let t=(await A`cmux list-workspaces`.quiet()).stdout,r=B(t,e);if(!r)return;await A`cmux close-workspace --workspace ${r}`.quiet()}catch(t){u.debug({error:t,title:e},"cmux: skipped closing workspace")}},B=(e,t)=>{let r=l(t);for(let n of e.split(`
2
2
  `)){let o=n.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let s=o[1],i=o[2]?.trim()??"";if(l(i)===r)return s}};import{$ as U}from"zx";var F=async()=>{try{let e=(await U`cmux list-workspaces`.quiet()).stdout,t=new Set;for(let r of e.split(`
3
3
  `)){let n=r.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let o=n[1]?.trim();o&&t.add(l(o))}return t}catch(e){return u.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as p}from"zx";var q=async e=>{let{cwd:t,title:r}=e,n=v(await S()),o=(await p`cmux workspace create --cwd ${t}`).stdout,s=J(o),i=(await p`cmux list-pane-surfaces --workspace ${s}`).stdout,c=z(i);await p`cmux new-split right --workspace ${s} --surface ${c}`,n==="three-pane"&&await p`cmux new-split down --workspace ${s} --surface ${c}`,r&&await p`cmux workspace rename --workspace ${s} --title ${r}`},z=e=>{let t=e.match(/surface:\d+/);if(!t)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return t[0]},J=e=>{let t=e.match(/workspace:\d+/);if(!t)throw new Error("cmux: could not locate workspace ref in workspace create output");return t[0]};var j=e=>{let{repoName:t,branch:r}=e,n=E(r),o=n?C(n):r;return`${t} ${o}`};var H=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),R=e=>e instanceof Error&&H.has(e.name),je=e=>{if(R(e))return!0;let t=e?.cause;return R(t)};import{execFile as K}from"node:child_process";import{createHash as Q}from"node:crypto";import{existsSync as V,readFileSync as f}from"node:fs";import G from"node:http";import X from"node:https";import Y from"node:net";import{homedir as Z}from"node:os";import{dirname as k,join as m}from"node:path";import g from"node:process";import ee from"node:tls";import{fileURLToPath as te}from"node:url";import{promisify as re}from"node:util";var oe=re(K),ne=e=>{let t=JSON.parse(f(e,"utf-8")),r=typeof t.bin=="string"?t.bin:t.bin?.portless;return r==null||r===""?null:r},se=()=>{try{let e=k(te(import.meta.url));for(;;){let t=m(e,"node_modules","portless","package.json");if(V(t)){let n=ne(t);return n==null?null:m(k(t),n)}let r=k(e);if(r===e)return null;e=r}}catch{return null}},h,L=()=>(h===void 0&&(h=se()),h),ie=/^[\w@%+=:,./-]+$/,ae="'\\''",ce=e=>ie.test(e)?e:`'${e.replaceAll("'",ae)}'`,it=(e,t)=>{let r=[t.execPath??g.execPath,t.bin,...e];return(t.sudo===!0?"sudo ":"")+r.map(ce).join(" ")},ue=1500,y=1500,le="x-portless",P="127.0.0.1",me="localhost",pe=e=>new Promise(t=>{let r=Y.connect({host:P,port:e}),n=o=>{r.destroy(),t(o)};r.setTimeout(y),r.once("connect",()=>{n(!0)}),r.once("timeout",()=>{n(!1)}),r.once("error",()=>{n(!1)})}),fe=(e,t)=>new Promise(r=>{let o=(t?X.request:G.request)({host:P,port:e,method:"HEAD",path:"/",timeout:y,...t?{rejectUnauthorized:!1,servername:me}:{}},s=>{s.resume(),r(s.headers[le]==="1")});o.on("error",()=>{r(!1)}),o.on("timeout",()=>{o.destroy(),r(!1)}),o.end()}),de=async(e,{timeoutMs:t})=>{let r=L();if(r==null)throw new Error("portless is not installed (not resolvable from node_modules)");await oe(g.execPath,[r,...e],{signal:AbortSignal.timeout(t),encoding:"utf-8",env:T(g.env)})},b=()=>g.env.PORTLESS_STATE_DIR??m(Z(),".portless"),ge="ca.pem",xe="ca.trusted",O=()=>m(b(),ge),at=()=>{try{let e=f(m(b(),xe),"utf-8").trim();return e===""?!1:Q("sha256").update(f(O())).digest("hex")===e.toLowerCase()}catch{return!1}},ct=(e,t)=>new Promise(r=>{let n;try{n=f(O())}catch{r({ok:!1,code:"ENOENT"});return}let o=ee.connect({host:P,port:e,servername:t,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,i=o.authorized;o.destroy(),r(i?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(y),o.once("timeout",()=>{o.destroy(),r({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),r({ok:!1,code:s.code??"UNKNOWN"})})}),ut=()=>{try{let e=JSON.parse(f(m(b(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(t=>{let{hostname:r,port:n}=t??{};return typeof r!="string"||r===""||typeof n!="number"?[]:[{name:r,port:n}]}):[]}catch{return[]}},lt=(e={})=>{let t=e.bin===void 0?L():e.bin,r=e.run??de,n=e.isListening??pe,o=e.isProxyServing??fe,s=e.timeoutMs??ue,i=null,c=async a=>{try{return await r(a,{timeoutMs:s}),!0}catch{return!1}},d=async()=>(i??=await c(["--version"]),i);return{binPath:()=>t,isAvailable:d,isProxyServing:async(a,x)=>!await d()||!await n(a)?!1:o(a,x),registerAlias:async(a,x)=>await d()?c(["alias",a,String(x)]):!1,removeAlias:async a=>{await d()&&await c(["alias","--remove",a])}}};export{se as a,it as b,pe as c,fe as d,O as e,at as f,ct as g,ut as h,lt as i,l as j,M as k,F as l,$ as m,N as n,_ as o,q as p,j as q,je as r};
4
- //# sourceMappingURL=chunk-NC2TIQ3M.js.map
4
+ //# sourceMappingURL=chunk-7F5YKMWK.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/integrations/cmux/open-dev-workspace.ts", "../src/integrations/cmux/canonicalize-cmux-title.ts", "../src/integrations/cmux/close-workspace-by-title.ts", "../src/integrations/cmux/list-workspace-titles.ts", "../src/integrations/cmux/open-workspace-with-layout.ts", "../src/integrations/cmux/workspace-title.ts", "../src/lib/errors/is-prompt-cancellation.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-title.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", "/** Matches a `v`-prefixed semver token (e.g. `v1.48.0`) anchored on shape. */\nconst V_SEMVER_TOKEN_RE = /\\bv(\\d+\\.\\d+\\.\\d+)\\b/g\n\n/**\n * Canonicalizes a cmux workspace title into a stable dedup/close key.\n *\n * cmux workspace titles are human display strings built by\n * `buildCmuxWorkspaceTitle`, so the value stored when a workspace is created can\n * drift from the value rebuilt later \u2014 across whitespace and across CLI versions\n * (an older build titled version releases `v1.48.0`; the current build titles\n * them `1.48.0`). Keying dedup or close on the raw title silently creates\n * duplicate / unclosable workspaces whenever that drift occurs.\n *\n * Canonicalization collapses the known drift axes so both sides round-trip to an\n * equal key:\n * - trims and collapses internal whitespace to single spaces;\n * - normalizes a `v`-prefixed semver token to its bare form\n * (`v1.48.0` \u2192 `1.48.0`), anchored on semver shape so named releases that\n * merely start with `v` (e.g. `vega-redesign`) are left untouched.\n *\n * Non-release fallback titles (which may contain `/`, e.g. `feature/foo`) are\n * preserved as-is apart from whitespace normalization.\n *\n * @example\n * canonicalizeCmuxTitle('hulyo-monorepo v1.48.0') // => 'hulyo-monorepo 1.48.0'\n * canonicalizeCmuxTitle('hulyo-monorepo 1.48.0') // => 'hulyo-monorepo 1.48.0'\n * canonicalizeCmuxTitle('hulyo-monorepo vega-redesign') // => 'hulyo-monorepo vega-redesign'\n */\nexport const canonicalizeCmuxTitle = (raw: string): string => {\n return raw.trim().replace(/\\s+/g, ' ').replace(V_SEMVER_TOKEN_RE, '$1')\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeCmuxTitle } from './canonicalize-cmux-title'\n\n/**\n * Best-effort close of the cmux workspace whose title matches `title` (compared\n * via {@link canonicalizeCmuxTitle}, so a drifted stored title still resolves).\n * Silently no-ops if cmux isn't running, the workspace isn't found, or close fails.\n */\nexport const closeCmuxWorkspaceByTitle = async (title: string): Promise<void> => {\n try {\n const listOutput = (await $`cmux list-workspaces`.quiet()).stdout\n\n const ref = findWorkspaceRefByTitle(listOutput, title)\n\n if (!ref) {\n return\n }\n\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, title }, 'cmux: skipped closing workspace')\n }\n}\n\n/**\n * Parses `cmux list-workspaces` output and returns the workspace ref whose\n * title matches `title`, or undefined if no match. Both sides are compared via\n * {@link canonicalizeCmuxTitle} so a workspace stored under a drifted title\n * (whitespace, or an older CLI's `v`-prefixed semver) is still found \u2014 keeping\n * close symmetric with the cmux open dedup in `worktrees-reload`.\n *\n * Each line looks like:\n * \" workspace:8 hulyo-monorepo 1.48.0\"\n * \"* workspace:6 obsidian-workspace [selected]\"\n */\nconst findWorkspaceRefByTitle = (output: string, title: string): string | undefined => {\n const target = canonicalizeCmuxTitle(title)\n\n for (const rawLine of output.split('\\n')) {\n // eslint-disable-next-line sonarjs/super-linear-regex, regexp/no-super-linear-backtracking\n const match = rawLine.match(/^[* ]\\s*(workspace:\\d+)\\s+(.+?)(?:\\s+\\[selected\\])?\\s*$/)\n\n if (!match) {\n continue\n }\n\n const ref = match[1]\n const lineTitle = match[2]?.trim() ?? ''\n\n if (canonicalizeCmuxTitle(lineTitle) === target) {\n return ref\n }\n }\n\n return undefined\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeCmuxTitle } from './canonicalize-cmux-title'\n\n/**\n * Returns the set of **canonical** titles for all currently-open cmux\n * workspaces (see {@link canonicalizeCmuxTitle}). Keying on the canonical form\n * lets callers match a workspace even when its stored title drifted from the\n * title they rebuild (whitespace, or an older CLI's `v`-prefixed semver).\n * Returns an empty set if cmux isn't running, the call fails, or the output\n * can't be parsed \u2014 callers should treat \"empty\" as \"unknown, proceed as if\n * nothing is open\".\n *\n * Each line of `cmux list-workspaces` looks like:\n * \" workspace:8 hulyo-monorepo 1.48.0\"\n * \"* workspace:6 obsidian-workspace [selected]\"\n */\nexport const listCmuxWorkspaceTitles = async (): Promise<Set<string>> => {\n try {\n const output = (await $`cmux list-workspaces`.quiet()).stdout\n\n const titles = new Set<string>()\n\n for (const rawLine of output.split('\\n')) {\n // eslint-disable-next-line sonarjs/super-linear-regex, regexp/no-super-linear-backtracking\n const match = rawLine.match(/^[* ]\\s*workspace:\\d+\\s+(.+?)(?:\\s+\\[selected\\])?\\s*$/)\n\n if (!match) {\n continue\n }\n\n const title = match[1]?.trim()\n\n if (title) {\n titles.add(canonicalizeCmuxTitle(title))\n }\n }\n\n return titles\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspace titles')\n\n return new Set()\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\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.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<void> => {\n const { cwd, title } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = (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\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 repoName: string\n branch: string\n}\n\n/**\n * Builds the cmux workspace title used by `worktrees-add` and looked up by\n * `worktrees-remove`. Release branches are rendered via their release-id\n * display label so the title reads e.g. `\"hulyo-monorepo 1.48.0\"` for\n * `\"release/v1.48.0\"` and `\"hulyo-monorepo checkout-redesign\"` for\n * `\"release/checkout-redesign\"`. Non-release branches (cmux titles them too)\n * fall back to the raw branch string.\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { repoName, branch } = args\n\n const id = parseBranchName(branch)\n const label = id ? displayLabel(id) : branch\n\n return `${repoName} ${label}`\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 * 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\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 * 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 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 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 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 isAvailable,\n isProxyServing: serving,\n registerAlias,\n removeAlias,\n }\n}\n"],
5
+ "mappings": "4GAAA,OAAOA,MAAa,eACpB,OAAS,KAAAC,MAAS,KAgBX,IAAMC,EAAkB,SAA8B,CAC3D,GAAI,CACF,aAAMC,kBAAkB,MAAM,EAEvB,EACT,MAAQ,CACN,MAAO,EACT,CACF,EAOaC,EAAuB,MAAOC,GAAoD,CAC7F,GAAM,CAAE,IAAAC,EAAK,MAAAC,EAAO,OAAAC,CAAO,EAAIH,EACzBI,EAAa,KAAK,UAAUD,CAAM,EAGlCE,GAAU,MADFP,EAAE,CAAE,IAAK,CAAE,GAAGQ,EAAQ,IAAK,WAAY,GAAI,CAAE,CAAC,8BACJJ,CAAK,UAAUD,CAAG,2BAA2BG,CAAU,IAC5G,OAEH,OAAOG,EAAkBF,CAAM,CACjC,EAOaG,EAAwB,MAAOC,GAA+B,CACzE,GAAI,CACF,MAAMX,qCAAqCW,CAAG,GAAG,MAAM,CACzD,OAASC,EAAO,CACdC,EAAO,MAAM,CAAE,MAAAD,EAAO,IAAAD,CAAI,EAAG,qCAAqC,CACpE,CACF,EASMF,EAAqBF,GAA2B,C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,EAAY,GAEpB,CAAE,MAAMJ,EAAYrC,CAAI,EAAW,GAEhCsC,EAAetC,EAAMO,CAAG,EAoB/B,cAjBoB,MAAOmC,EAAc1C,IACnC,MAAMyC,EAAY,EAEjBD,EAAO,CAAC,QAASE,EAAM,OAAO1C,CAAI,CAAC,CAAC,EAFR,GAiBnC,YAZkB,MAAO0C,GAAgC,CACnD,MAAMD,EAAY,GACxB,MAAMD,EAAO,CAAC,QAAS,WAAYE,CAAI,CAAC,CAC1C,CAUA,CACF",
6
+ "names": ["process", "$", "isCmuxAvailable", "$", "openCmuxDevWorkspace", "args", "cwd", "title", "layout", "layoutJson", "output", "process", "parseWorkspaceRef", "closeCmuxDevWorkspace", "ref", "error", "logger", "match", "V_SEMVER_TOKEN_RE", "canonicalizeCmuxTitle", "raw", "$", "closeCmuxWorkspaceByTitle", "title", "listOutput", "$", "ref", "findWorkspaceRefByTitle", "error", "logger", "output", "target", "canonicalizeCmuxTitle", "rawLine", "match", "lineTitle", "$", "listCmuxWorkspaceTitles", "output", "$", "titles", "rawLine", "match", "title", "canonicalizeCmuxTitle", "error", "logger", "$", "openCmuxWorkspaceWithLayout", "args", "cwd", "title", "layout", "resolveCmuxLayout", "getInfraKitConfig", "newWorkspaceOutput", "$", "workspaceRef", "parseWorkspaceRef", "surfacesOutput", "leftTopRef", "parseFirstSurfaceRef", "output", "match", "buildCmuxWorkspaceTitle", "args", "repoName", "branch", "id", "parseBranchName", "label", "displayLabel", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "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", "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", "availability", "tryRun", "isAvailable", "name"]
7
+ }
@@ -0,0 +1,2 @@
1
+ var r=t=>Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("npm_")&&e!=="PNPM_SCRIPT_SRC_DIR")),o=/^npm_config_(?:prefix|registry)$/i,a=t=>{let e=r(t);for(let[n,s]of Object.entries(t))o.test(n)&&(e[n]=s);return e};export{r as a,a as b};
2
+ //# sourceMappingURL=chunk-A7FAXZGI.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/pm-env/pm-env.ts"],
4
+ "sourcesContent": ["/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install.\n *\n * Any child we launch through `node <bin>` (the portless driver, self-update, the mcp launcher) inherits\n * our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm dlx` and refuse\n * to work. portless is the motivating case; its guard (cli.js `main()`) is:\n *\n * isNpx = npm_command === 'exec' && !npm_lifecycle_event\n * isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n * if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) \u2192 abort\n *\n * `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n * transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is live.\n * `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event \u2192 `isNpx` \u2192 every\n * portless call exits 1 \u2192 `isAvailable()` is false \u2192 `ensureProxy` aborts the whole dev boot with\n * \"portless is not installed\", on a machine where it plainly is.\n *\n * `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n * `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n * `npm_*` removes that suppressor and *creates* an abort for the script-style invocation that\n * previously worked. Both markers go, or neither is safe.\n *\n * The result makes the child look exactly like a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n\n/**\n * npm's own configuration \u2014 as opposed to the npx/dlx *markers* above. Case-insensitive because npm reads\n * `npm_config_*` case-insensitively (its parser matches `/^npm_config_/i`) and real environments export\n * both forms: shells write the lowercase name, Dockerfiles and CI images overwhelmingly write the\n * uppercase one.\n */\nconst NPM_CONFIG_TO_PRESERVE = /^npm_config_(?:prefix|registry)$/i\n\n/**\n * The env for spawning a package-manager INSTALL: npx/dlx markers stripped, but npm's own config kept.\n *\n * {@link withoutPackageManagerEnv} is deliberately a blunt `npm_*` prefix filter, and it is the right tool\n * for the portless driver \u2014 but it is the WRONG tool for spawning an install, because it also drops the two\n * variables that tell the package manager *where* and *from where* to install:\n *\n * - `npm_config_prefix` is the npm matcher's ONLY signal (see `install-manager.ts`). Strip it and we\n * detect a global install rooted at prefix P, then run the install with P erased \u2014 so it lands in the\n * DEFAULT prefix instead. That is either a permanent EACCES, or a second global copy that is not the\n * one on PATH. Nothing notices: the install exits 0, we report `installed`, the version on PATH never\n * moves, and the whole cycle repeats every 24h forever. `export npm_config_prefix=~/.npm-global` is\n * npm's own documented EACCES workaround, so this is a mainstream layout, not an exotic one.\n * - `npm_config_registry` is what the update CHECK already used to pick a registry. Dropping it here\n * means we decide against a corporate mirror and then install from somewhere else.\n *\n * Preserving these cannot re-arm the dlx guard: that guard reads `npm_command`, `npm_lifecycle_event`, and\n * `PNPM_SCRIPT_SRC_DIR` \u2014 none of which are npm *config*, and all of which remain stripped.\n *\n * @example\n * packageManagerInstallEnv({ npm_command: 'exec', npm_config_prefix: '/p', PATH: '/bin' })\n * // => { npm_config_prefix: '/p', PATH: '/bin' }\n */\nexport const packageManagerInstallEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n const sanitised = withoutPackageManagerEnv(env)\n\n for (const [key, value] of Object.entries(env)) {\n if (NPM_CONFIG_TO_PRESERVE.test(key)) sanitised[key] = value\n }\n\n return sanitised\n}\n"],
5
+ "mappings": "AAwBO,IAAMA,EAA4BC,GAChC,OAAO,YACZ,OAAO,QAAQA,CAAG,EAAE,OAAO,CAAC,CAACC,CAAG,IACvB,CAACA,EAAI,WAAW,MAAM,GAAKA,IAAQ,qBAC3C,CACH,EASIC,EAAyB,oCAyBlBC,EAA4BH,GAA8C,CACrF,IAAMI,EAAYL,EAAyBC,CAAG,EAE9C,OAAW,CAACC,EAAKI,CAAK,IAAK,OAAO,QAAQL,CAAG,EACvCE,EAAuB,KAAKD,CAAG,IAAGG,EAAUH,CAAG,EAAII,GAGzD,OAAOD,CACT",
6
+ "names": ["withoutPackageManagerEnv", "env", "key", "NPM_CONFIG_TO_PRESERVE", "packageManagerInstallEnv", "sanitised", "value"]
7
+ }