@kaynooo/cli-check 0.27.0 → 0.28.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.
package/README.md CHANGED
@@ -11,6 +11,8 @@ check --timeout 5m # end a step still running after 5 minutes, exit 2
11
11
  check --no-slot # run the steps at once; by default each queues behind the machine-wide slots of `slot` (@kaynooo/cli-wait) when it is installed
12
12
  check --in app # run every step in this compose service, whatever is detected
13
13
  check --failed # run again only the steps that failed in this folder's last run
14
+ check --flaky 5 # run each step 5 times to detect flaky steps and report min/median/max durations
15
+ check --coverage # run tests with coverage and list only files below 80% (or pass a threshold, e.g. --coverage 90)
14
16
  check --quiet # print only the failing steps, nothing when all pass
15
17
  check --fix # run the fixers and formatters instead
16
18
  check --host # run on the host even when a compose service mounts the folder
@@ -59,13 +61,17 @@ SIGINT, SIGTERM and SIGHUP go to the running step's whole process group and `che
59
61
 
60
62
  Exit code 0 when every step passed, 1 when one failed, 2 on bad usage, when no step is found or when a step timed out.
61
63
 
62
- `--json` prints `[{name, command, in?, ok, ms, log, failed?}]` once every step ran, `in` naming the compose service the step ran in; `--list --json` prints `[{name, command, source, in?}]`, and `--fix --json` `{fixers: [{name, command, in?, ok, ms, log, failed?} or {name, command, skipped}], changed}`, `changed` being null outside a git repository.
64
+ `--json` prints `[{name, command, in?, ok, ms, log, failed?}]` once every step ran, `in` naming the compose service the step ran in; `--list --json` prints `[{name, command, source, in?}]`, `--fix --json` `{fixers: [{name, command, in?, ok, ms, log, failed?} or {name, command, skipped}], changed}` (`changed` being null outside a git repository), `--flaky <n> --json` `{runs, ok, steps}`, and `--coverage [threshold] --json` `{threshold, ok, steps}`.
63
65
 
64
66
  `--failed` reads the last finished run's folder of logs, where each run leaves a `results.json` of its steps' names and results, and runs the steps that failed there again. When that run had none, or there was no run, it says so and exits 2. The re-run leaves its own `results.json`.
65
67
 
68
+ `--flaky <n>` runs each selected step `<n>` times (`>= 2`), classifies it as `stable`, `FLAKY`, or `failing`, and reports pass counts plus min, median, and max durations. Exits 1 if any run failed, 0 if all runs passed.
69
+
70
+ `--coverage [threshold]` runs the `test` step with coverage (appending `--coverage` for `bun test`, `vitest`, or `jest`, or `--cov` for `pytest` when not already set), parses bun test, Vitest/V8/Istanbul, and pytest-cov coverage tables, and prints only files below the threshold (default `80%`) or the overall summary when all pass. Exits 1 if tests fail or overall or any file is below threshold.
71
+
66
72
  ## check --fix
67
73
 
68
- `--only` then names fixers, and `--changed`, `--failed`, `--slot`, `--no-slot` and `--parallel` are refused.
74
+ `--only` then names fixers, and `--changed`, `--failed`, `--flaky`, `--coverage`, `--slot`, `--no-slot` and `--parallel` are refused.
69
75
 
70
76
  ```sh
71
77
  check --fix # run every fixer that applies to this folder
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{isInteractive,tinted,activeTheme,paint,ANSI,truncate,textWidth,fail,cacheFolder}from"./chunk-7d3myeb5.js";var EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"]),BACKWARD_KILLS=new Set(["word","killword","clear"]),FORWARD_KILLS=new Set(["killnext","killend"]);function isEditKey(key){return EDIT_KEYS.has(key)}function endsKills(key){return typeof key!=="object"&&!isEditKey(key)}var WORD_CHARACTER=/[\p{L}\p{N}_]/u,SPACE=/\s/;function isWord(char){return char!==void 0&&WORD_CHARACTER.test(char)}function wordStart(chars,from){let at=from;while(at>0&&!isWord(chars[at-1]))at--;while(at>0&&isWord(chars[at-1]))at--;return at}function wordEnd(chars,from){let at=from;while(at<chars.length&&!isWord(chars[at]))at++;while(at<chars.length&&isWord(chars[at]))at++;return at}function spacedStart(chars,from){let at=from;while(at>0&&SPACE.test(chars[at-1]??""))at--;while(at>0&&!SPACE.test(chars[at-1]??""))at--;return at}function cut(chars,from,to){return{text:[...chars.slice(0,from),...chars.slice(to)].join(""),caret:from}}function insert(chars,at,text){let typed=[...text];return{text:[...chars.slice(0,at),...typed,...chars.slice(at)].join(""),caret:at+typed.length}}function editLine(line,key){let{killed="",chained=!1}=line,chars=[...line.text],at=Math.min(Math.max(line.caret,0),chars.length),edited=edit(chars,at,key,killed);if(typeof key==="object"||!BACKWARD_KILLS.has(key)&&!FORWARD_KILLS.has(key))return line.killed===void 0?edited:{...edited,killed};let taken=chars.slice(edited.caret,edited.caret+chars.length-[...edited.text].length).join("");if(taken==="")return{...edited,killed,chained};if(!chained)return{...edited,killed:taken,chained:!0};return{...edited,killed:BACKWARD_KILLS.has(key)?taken+killed:killed+taken,chained:!0}}function edit(chars,at,key,killed){let text=chars.join("");if(typeof key==="object")return insert(chars,at,key.text);switch(key){case"left":return{text,caret:Math.max(at-1,0)};case"right":return{text,caret:Math.min(at+1,chars.length)};case"wordleft":return{text,caret:wordStart(chars,at)};case"wordright":return{text,caret:wordEnd(chars,at)};case"linestart":return{text,caret:0};case"lineend":return{text,caret:chars.length};case"erase":return cut(chars,Math.max(at-1,0),at);case"delete":return cut(chars,at,Math.min(at+1,chars.length));case"word":return cut(chars,spacedStart(chars,at),at);case"killword":return cut(chars,wordStart(chars,at),at);case"killnext":return cut(chars,at,wordEnd(chars,at));case"clear":return cut(chars,0,at);case"killend":return cut(chars,at,chars.length);case"yank":return insert(chars,at,killed)}}function visible({text,caret},room){let chars=[...text],at=Math.min(Math.max(caret,0),chars.length),cells=at===chars.length?[...chars," "]:chars,widths=cells.map((char)=>Bun.stringWidth(char)),width=(from,to)=>widths.slice(from,to).reduce((sum,size)=>sum+size,0),fits=(from,to)=>(from>0?1:0)+width(from,to)+(to<cells.length?1:0)<=room,start=at,end=at+1;while(start>0&&fits(start-1,end))start--;while(end<cells.length&&fits(start,end+1))end++;let left=start>0?"\u2026":"",right=end<cells.length?"\u2026":"";return{before:left+chars.slice(start,at).join(""),at:chars[at],after:chars.slice(at+1,end).join("")+right,column:left.length+width(start,at)}}var BOUNDARY_AFTER=new Set([" ","/","-","_",".",":","\\","(","[",",","\t"]),UPPER=/\p{Lu}/u,LOWER=/\p{Ll}/u,NONE=Number.NEGATIVE_INFINITY;function startsWord(text,index){if(index===0)return!0;let before=text[index-1];return BOUNDARY_AFTER.has(before)||LOWER.test(before)&&UPPER.test(text[index])}function fuzzy(query,text){if(query==="")return{score:0,positions:[]};let exact=query!==query.toLowerCase(),needle=exact?query:query.toLowerCase(),haystack=exact?text:text.toLowerCase();if(haystack.length!==text.length||needle.length>haystack.length)return;let width=haystack.length,best=Array.from({length:needle.length},()=>Array(width).fill(NONE)),from=Array.from({length:needle.length},()=>Array(width).fill(-1));for(let j=0;j<needle.length;j++){let run=NONE,runAt=-1;for(let i=j;i<width;i++){if(j>0&&i-2>=j-1){let candidate=best[j-1][i-2]+(i-2)*1;if(candidate>run)run=candidate,runAt=i-2}if(haystack[i]!==needle[j])continue;let here=16+(startsWord(text,i)?10:0)+(i===0?8:0);if(j===0){best[0][i]=here-i*1;continue}let joined=best[j-1][i-1]+12,skipped=run-(i-1)*1;if(joined>NONE&&joined>=skipped)best[j][i]=joined+here,from[j][i]=i-1;else if(skipped>NONE)best[j][i]=skipped+here,from[j][i]=runAt}}let last=best[needle.length-1],end=-1;for(let i=0;i<width;i++)if(last[i]>NONE&&(end===-1||last[i]>last[end]))end=i;if(end===-1)return;let positions=[];for(let j=needle.length-1,i=end;j>=0;j--)positions.unshift(i),i=from[j][i];return{score:last[end],positions}}function rank(query,lines){if(query==="")return lines.map((_,index)=>({index,positions:[]}));let found=[];for(let[index,line]of lines.entries()){let match=fuzzy(query,line);if(match!==void 0)found.push({index,positions:match.positions,score:match.score})}return found.sort((a,b)=>b.score-a.score||lines[a.index].length-lines[b.index].length||a.index-b.index)}var CONTROL=/[\x00-\x1F\x7F-\x9F]/g,IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,SGR=/^\x1B\[[0-9;]*m$/,RESET=/^\x1B\[0?m$/,COLUMN_GAP=2,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,WHEEL_LINES=3,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"},CTRL_KEY=/^ctrl-[abd-gkln-z]$/;function repeat(value,count){return Array.from({length:count}).fill(value)}function styled(line){let text="",styles=[],active="",colored=!1,last=0;function add(chunk){let flat=chunk.replace(CONTROL," ");text+=flat,colored||=active!==""&&flat!=="",styles.push(...repeat(active,flat.length))}for(let found of line.matchAll(ANSI))if(add(line.slice(last,found.index)),last=found.index+found[0].length,SGR.test(found[0]))active=RESET.test(found[0])?"":active+found[0];return add(line.slice(last)),{text,styles:colored?styles:void 0}}function lay(rows,searched){let parsed=rows.map((row)=>row.cells.map(styled)),widths=(parsed[0]??[]).map((_,column)=>Math.max(...parsed.map((cells)=>Bun.stringWidth(cells[column]?.text??""))));return parsed.map((cells,at)=>{let text="",styles=[],colored=!1,searchEnd=0;for(let[column,cell]of cells.entries()){let last=column===cells.length-1,shown=cells.length>1&&last?cell.text.trimEnd():cell.text;if(text+=shown,colored||=cell.styles!==void 0,styles.push(...cell.styles?.slice(0,shown.length)??repeat("",shown.length)),column<searched)searchEnd=cells.length>1?text.trimEnd().length:text.length;if(!last){let pad=widths[column]-Bun.stringWidth(cell.text)+COLUMN_GAP;text+=" ".repeat(pad),styles.push(...repeat("",pad))}}return{text,styles:colored?styles:void 0,searchable:rows[at].search??text.slice(0,searchEnd)}})}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
2
+ import{isInteractive,tinted,activeTheme,paint,ANSI,truncate,textWidth,fail,cacheFolder}from"./chunk-qtqywtwc.js";var EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"]),BACKWARD_KILLS=new Set(["word","killword","clear"]),FORWARD_KILLS=new Set(["killnext","killend"]);function isEditKey(key){return EDIT_KEYS.has(key)}function endsKills(key){return typeof key!=="object"&&!isEditKey(key)}var WORD_CHARACTER=/[\p{L}\p{N}_]/u,SPACE=/\s/;function isWord(char){return char!==void 0&&WORD_CHARACTER.test(char)}function wordStart(chars,from){let at=from;while(at>0&&!isWord(chars[at-1]))at--;while(at>0&&isWord(chars[at-1]))at--;return at}function wordEnd(chars,from){let at=from;while(at<chars.length&&!isWord(chars[at]))at++;while(at<chars.length&&isWord(chars[at]))at++;return at}function spacedStart(chars,from){let at=from;while(at>0&&SPACE.test(chars[at-1]??""))at--;while(at>0&&!SPACE.test(chars[at-1]??""))at--;return at}function cut(chars,from,to){return{text:[...chars.slice(0,from),...chars.slice(to)].join(""),caret:from}}function insert(chars,at,text){let typed=[...text];return{text:[...chars.slice(0,at),...typed,...chars.slice(at)].join(""),caret:at+typed.length}}function editLine(line,key){let{killed="",chained=!1}=line,chars=[...line.text],at=Math.min(Math.max(line.caret,0),chars.length),edited=edit(chars,at,key,killed);if(typeof key==="object"||!BACKWARD_KILLS.has(key)&&!FORWARD_KILLS.has(key))return line.killed===void 0?edited:{...edited,killed};let taken=chars.slice(edited.caret,edited.caret+chars.length-[...edited.text].length).join("");if(taken==="")return{...edited,killed,chained};if(!chained)return{...edited,killed:taken,chained:!0};return{...edited,killed:BACKWARD_KILLS.has(key)?taken+killed:killed+taken,chained:!0}}function edit(chars,at,key,killed){let text=chars.join("");if(typeof key==="object")return insert(chars,at,key.text);switch(key){case"left":return{text,caret:Math.max(at-1,0)};case"right":return{text,caret:Math.min(at+1,chars.length)};case"wordleft":return{text,caret:wordStart(chars,at)};case"wordright":return{text,caret:wordEnd(chars,at)};case"linestart":return{text,caret:0};case"lineend":return{text,caret:chars.length};case"erase":return cut(chars,Math.max(at-1,0),at);case"delete":return cut(chars,at,Math.min(at+1,chars.length));case"word":return cut(chars,spacedStart(chars,at),at);case"killword":return cut(chars,wordStart(chars,at),at);case"killnext":return cut(chars,at,wordEnd(chars,at));case"clear":return cut(chars,0,at);case"killend":return cut(chars,at,chars.length);case"yank":return insert(chars,at,killed)}}function visible({text,caret},room){let chars=[...text],at=Math.min(Math.max(caret,0),chars.length),cells=at===chars.length?[...chars," "]:chars,widths=cells.map((char)=>Bun.stringWidth(char)),width=(from,to)=>widths.slice(from,to).reduce((sum,size)=>sum+size,0),fits=(from,to)=>(from>0?1:0)+width(from,to)+(to<cells.length?1:0)<=room,start=at,end=at+1;while(start>0&&fits(start-1,end))start--;while(end<cells.length&&fits(start,end+1))end++;let left=start>0?"\u2026":"",right=end<cells.length?"\u2026":"";return{before:left+chars.slice(start,at).join(""),at:chars[at],after:chars.slice(at+1,end).join("")+right,column:left.length+width(start,at)}}var BOUNDARY_AFTER=new Set([" ","/","-","_",".",":","\\","(","[",",","\t"]),UPPER=/\p{Lu}/u,LOWER=/\p{Ll}/u,NONE=Number.NEGATIVE_INFINITY;function startsWord(text,index){if(index===0)return!0;let before=text[index-1];return BOUNDARY_AFTER.has(before)||LOWER.test(before)&&UPPER.test(text[index])}function fuzzy(query,text){if(query==="")return{score:0,positions:[]};let exact=query!==query.toLowerCase(),needle=exact?query:query.toLowerCase(),haystack=exact?text:text.toLowerCase();if(haystack.length!==text.length||needle.length>haystack.length)return;let width=haystack.length,best=Array.from({length:needle.length},()=>Array(width).fill(NONE)),from=Array.from({length:needle.length},()=>Array(width).fill(-1));for(let j=0;j<needle.length;j++){let run=NONE,runAt=-1;for(let i=j;i<width;i++){if(j>0&&i-2>=j-1){let candidate=best[j-1][i-2]+(i-2)*1;if(candidate>run)run=candidate,runAt=i-2}if(haystack[i]!==needle[j])continue;let here=16+(startsWord(text,i)?10:0)+(i===0?8:0);if(j===0){best[0][i]=here-i*1;continue}let joined=best[j-1][i-1]+12,skipped=run-(i-1)*1;if(joined>NONE&&joined>=skipped)best[j][i]=joined+here,from[j][i]=i-1;else if(skipped>NONE)best[j][i]=skipped+here,from[j][i]=runAt}}let last=best[needle.length-1],end=-1;for(let i=0;i<width;i++)if(last[i]>NONE&&(end===-1||last[i]>last[end]))end=i;if(end===-1)return;let positions=[];for(let j=needle.length-1,i=end;j>=0;j--)positions.unshift(i),i=from[j][i];return{score:last[end],positions}}function rank(query,lines){if(query==="")return lines.map((_,index)=>({index,positions:[]}));let found=[];for(let[index,line]of lines.entries()){let match=fuzzy(query,line);if(match!==void 0)found.push({index,positions:match.positions,score:match.score})}return found.sort((a,b)=>b.score-a.score||lines[a.index].length-lines[b.index].length||a.index-b.index)}var CONTROL=/[\x00-\x1F\x7F-\x9F]/g,IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,SGR=/^\x1B\[[0-9;]*m$/,RESET=/^\x1B\[0?m$/,COLUMN_GAP=2,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,WHEEL_LINES=3,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"},CTRL_KEY=/^ctrl-[abd-gkln-z]$/;function repeat(value,count){return Array.from({length:count}).fill(value)}function styled(line){let text="",styles=[],active="",colored=!1,last=0;function add(chunk){let flat=chunk.replace(CONTROL," ");text+=flat,colored||=active!==""&&flat!=="",styles.push(...repeat(active,flat.length))}for(let found of line.matchAll(ANSI))if(add(line.slice(last,found.index)),last=found.index+found[0].length,SGR.test(found[0]))active=RESET.test(found[0])?"":active+found[0];return add(line.slice(last)),{text,styles:colored?styles:void 0}}function lay(rows,searched){let parsed=rows.map((row)=>row.cells.map(styled)),widths=(parsed[0]??[]).map((_,column)=>Math.max(...parsed.map((cells)=>Bun.stringWidth(cells[column]?.text??""))));return parsed.map((cells,at)=>{let text="",styles=[],colored=!1,searchEnd=0;for(let[column,cell]of cells.entries()){let last=column===cells.length-1,shown=cells.length>1&&last?cell.text.trimEnd():cell.text;if(text+=shown,colored||=cell.styles!==void 0,styles.push(...cell.styles?.slice(0,shown.length)??repeat("",shown.length)),column<searched)searchEnd=cells.length>1?text.trimEnd().length:text.length;if(!last){let pad=widths[column]-Bun.stringWidth(cell.text)+COLUMN_GAP;text+=" ".repeat(pad),styles.push(...repeat("",pad))}}return{text,styles:colored?styles:void 0,searchable:rows[at].search??text.slice(0,searchEnd)}})}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
3
3
  `))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}function createState(rows,{multi=!1,prompt="> ",query="",header="",expect=[],searched=Number.POSITIVE_INFINITY}={}){let state={rows:[],items:[],styles:[],searchable:[],searched,header,expect,key:"",status:"",query,caret:[...query].length,killed:"",chained:!1,matches:[],cursor:0,help:!1,page:10,marked:new Set,multi,prompt,done:void 0};return withRows(state,rows)}function withRows(state,rows,header=state.header){let cells=rows.map((row)=>typeof row==="string"?{hidden:[],cells:[row]}:row),laid=lay(cells,state.searched),searchable=laid.map((row)=>row.searchable),matches=rank(state.query,searchable);return{...state,rows:cells,items:laid.map((row)=>row.text),styles:laid.map((row)=>row.styles),searchable,header,matches,cursor:Math.max(0,Math.min(matches.length-1,state.cursor)),marked:new Set}}function appendRows(state,extra){if(extra.length===0)return state;let previous=highlighted(state),cells=[...state.rows,...extra.map((row)=>typeof row==="string"?{hidden:[],cells:[row]}:row)],laid=lay(cells,state.searched),searchable=laid.map((row)=>row.searchable),matches=rank(state.query,searchable),kept=previous===void 0?-1:matches.findIndex((match)=>match.index===previous),cursor=kept===-1?Math.max(0,Math.min(matches.length-1,state.cursor)):kept;return{...state,rows:cells,items:laid.map((row)=>row.text),styles:laid.map((row)=>row.styles),searchable,matches,cursor}}function withQuery(state,key){let{text,caret,killed="",chained=!1}=editLine({text:state.query,caret:state.caret,killed:state.killed,chained:state.chained},key);return text===state.query?{...state,caret,killed,chained}:{...state,query:text,caret,killed,chained,matches:rank(text,state.searchable),cursor:0}}function move(state,by){return{...state,cursor:Math.max(0,Math.min(state.matches.length-1,state.cursor+by))}}function highlighted(state){return state.matches[state.cursor]?.index}function press(state,key){if(state.done!==void 0)return state;if(state.chained&&endsKills(key))state={...state,chained:!1};if(state.help)return{...state,help:!1};if(typeof key==="object"){if("text"in key)return withQuery(state,key);return state.expect.includes(key.ctrl)?{...state,done:"accept",key:key.ctrl}:state}if(isEditKey(key))return withQuery(state,key);switch(key){case"up":return move(state,-1);case"down":return move(state,1);case"pageup":return move(state,-state.page);case"pagedown":return move(state,state.page);case"home":return move(state,-state.matches.length);case"end":return move(state,state.matches.length);case"cancel":return{...state,done:"cancel"};case"help":return{...state,help:!0};case"suspend":return state;case"enter":return state.matches.length===0&&state.marked.size===0?state:{...state,done:"accept"};case"tab":{let at=highlighted(state);if(!state.multi||at===void 0)return state;let marked=new Set(state.marked);if(!marked.delete(at))marked.add(at);return move({...state,marked},1)}}}function chosen(state){if(state.marked.size>0)return state.rows.filter((_,index)=>state.marked.has(index));let at=highlighted(state);return at===void 0?[]:[state.rows[at]]}import process from"process";function stopJob(){process.kill(0,"SIGTSTP")}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
4
4
  `)}function rowsTaken(lines,columns){return lines.reduce((rows,line)=>rows+Math.max(1,Math.ceil(textWidth(line)/columns)),0)}import process2 from"process";import{mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";var KEPT=50;function answersFile(){return join(cacheFolder(),"kaynooo-cli","answers.json")}function stored(){try{let parsed=JSON.parse(readFileSync(answersFile(),"utf-8"));if(typeof parsed!=="object"||parsed===null)return{};return Object.fromEntries(Object.entries(parsed).filter((entry)=>Array.isArray(entry[1])&&entry[1].every((answer)=>typeof answer==="string")))}catch{return{}}}function earlierAnswers(key){return stored()[key]??[]}function rememberAnswer(key,answer){let all=stored(),file=answersFile();all[key]=[answer,...(all[key]??[]).filter((earlier)=>earlier!==answer)].slice(0,KEPT);try{mkdirSync(dirname(file),{recursive:!0}),writeFileSync(file,JSON.stringify(all))}catch{}}var PROMPT_KEYS=new Set(["up","down","pageup","pagedown","home","end","enter","cancel","suspend","tab"]),MAX_LISTED=12;function readKeys(input,paste={active:!1}){return parseKeys(input,paste).filter((key)=>typeof key==="object"?"text"in key:PROMPT_KEYS.has(key)||isEditKey(key))}function roomAfter(question,columns){return Math.max(columns-textWidth(`? ${question} `)%columns-1,1)}function promptPalette(colors){let{theme}=activeTheme();return{accent:tinted(colors,theme.colors.accent),ok:tinted(colors,theme.colors.ok),problem:tinted(colors,theme.colors.problem),muted:tinted(colors,theme.colors.label),hair:tinted(colors,theme.colors.hairline),bold:colors.bold,inverse:colors.inverse}}function withCaret(colors,line,room,dim=!1){let palette=promptPalette(colors),{before,at,after}=visible(line,room),tone=dim?palette.muted:(text)=>text;return`${tone(before)}${at===void 0?palette.hair("\u2588"):palette.inverse(at)}${tone(after)}`}function sharedStart(texts){let[first=[],...rest]=texts.map((text)=>[...text]),length=first.length;for(let chars of rest){let differs=chars.findIndex((char,index)=>char!==first[index]);length=Math.min(length,differs===-1?chars.length:differs)}return first.slice(0,length).join("")}function listed(colors,found,columns){let shared=sharedStart(found),cut=Math.max(shared.lastIndexOf("/"),shared.lastIndexOf(" "))+1,names=found.slice(0,MAX_LISTED).map((each)=>each.slice(cut)),more=found.length>MAX_LISTED?` \u2026 ${found.length-MAX_LISTED} more`:"";return` ${promptPalette(colors).muted(truncate(names.join(" ")+more,Math.max(columns-3,1)))}`}async function input2(question,{default:fallback,mask=!1,validate,history,complete,...settings}){let line={text:"",caret:0},invalid,completions=[],remembered=history===void 0||mask?void 0:history,earlier=remembered===void 0?[]:earlierAnswers(remembered),recalled=-1,draft=line,taken=()=>line.text===""?fallback??"":line.text,shown=()=>mask?"*".repeat([...taken()].length):taken();if(!await ask(question,settings,(colors,state,{columns})=>{if(state!=="asking")return[answer(colors,question,state,shown())];let palette=promptPalette(colors),typed=line.text===""?{text:shown(),caret:[...shown()].length}:{text:shown(),caret:line.caret};return[`${palette.accent("?")} ${palette.bold(question)} ${withCaret(colors,typed,roomAfter(question,columns),line.text==="")}`,...invalid===void 0?[]:[` ${palette.problem(invalid)}`],...completions.length>1?[listed(colors,completions,columns)]:[]]},(key)=>{if(key==="cancel")return"cancel";if(invalid=void 0,completions=[],line.chained===!0&&endsKills(key))line={...line,chained:!1};if(key==="tab"){let chars=[...line.text],before=chars.slice(0,line.caret).join(""),found=complete?.(before)??[],filled=sharedStart(found);if([...filled].length>[...before].length)line={...line,text:filled+chars.slice(line.caret).join(""),caret:[...filled].length};else completions=found;return}if(key==="enter")return invalid=validate?.(taken()),invalid===void 0?"enter":void 0;if(key==="up"||key==="down"){let to=Math.min(Math.max(recalled+(key==="up"?1:-1),-1),earlier.length-1);if(recalled===-1)draft=line;recalled=to,line={...to===-1?draft:{text:earlier[to],caret:[...earlier[to]].length},killed:line.killed??""};return}let edit={home:"linestart",end:"lineend"}[key]??key;if(typeof edit==="object"||isEditKey(edit))line=editLine(line,edit);return}))return;if(remembered!==void 0&&taken()!=="")rememberAnswer(remembered,taken());return taken()}function answer(colors,question,state,picked){let palette=promptPalette(colors);return state==="enter"?`${palette.ok("\u2713")} ${question} ${palette.accent(picked)}`:`${palette.problem("\u2717")} ${question} ${palette.muted("cancelled")}`}async function ask(question,{hint,terminal=process2},render,press){let{stdin,stderr}=terminal;if(!isInteractive(terminal))fail(`cannot ask "${question}" off a terminal`,2,hint);let colors=paint(stderr),current="asking",outcome,columns=()=>stderr.columns||80,draw=(state,last=!1)=>{let frame=render(colors,state,{columns:columns(),rows:stderr.rows||24}),rows=rowsTaken(frame,columns());stderr.write(`${SYNC_START}\r${overwrite(frame,columns())}\x1B[0J${last||rows<2?"":`\x1B[${rows-1}A`}${last?"":"\r"}${SYNC_END}`),current=state},redraw=()=>draw(current),paste={active:!1},stop=terminal.stop??(terminal===process2?stopJob:void 0),suspend=()=>{if(stop===void 0)return;stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l"),stdin.setRawMode(!1),stop(),stdin.setRawMode(!0),stderr.write("\x1B[?25l\x1B[?2004h")};try{return stderr.on?.("resize",redraw),stdin.setRawMode(!0),stdin.resume(),stderr.write("\x1B[?25l\x1B[?2004h"),draw("asking"),await new Promise((resolve)=>{function onData(data){for(let key of readKeys(data.toString(),paste)){if(key==="suspend"){suspend();continue}let pressed=press(key);if(pressed!==void 0){settle(pressed);return}}draw("asking")}function onEnd(){settle("cancel")}function settle(settled){outcome=settled,stdin.off("data",onData),stdin.off("end",onEnd),resolve(settled==="enter")}stdin.on("data",onData),stdin.on("end",onEnd)})}finally{stderr.off?.("resize",redraw),draw(outcome??"cancel",!0),stderr.write(`
5
5
  \x1B[?25h\x1B[?2004l`),stdin.setRawMode(!1),stdin.pause()}}export{stopJob,visible,CTRL_KEY,styled,parseKeys,createState,withRows,appendRows,highlighted,press,chosen,SYNC_START,SYNC_END,overwrite,input2};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{outputMode,xdgFolder,tinted,activeTheme,takesControlCodes,paint,writeErr,warn,stripAnsi,formatDuration,Exit,fail,UsageError,HelpShown,Completing,completion,heading,parseContext,OUTPUT_OPTIONS,ignoredFolders}from"./chunk-7d3myeb5.js";import{readFileSync,realpathSync}from"fs";import{resolve}from"path";import process from"process";function commandLine(){try{return readFileSync("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve(word))}catch{return}}function scriptArgs(argv=process.argv.slice(2),cmdline=commandLine(),script=process.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}import{readFileSync as readFileSync2}from"fs";import{constants}from"os";import process2 from"process";var KILL_GRACE_MS=2000,SIGNALS=["SIGINT","SIGTERM","SIGHUP"],GROUP_SIGNALS=new Set(["SIGINT","SIGHUP"]);function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}function groupsOf(pid){try{let stat=readFileSync2(`/proc/${pid}/stat`,"utf8"),fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");return{group:Number(fields[2]),foreground:Number(fields[5])}}catch{return}}function heardTheTerminal(child){if(child.pid===void 0)return!1;let own=groupsOf("self");return own!==void 0&&own.group===own.foreground&&groupsOf(child.pid)?.group===own.group}function holdSignals(cleanup){let received,child,held={get signal(){return received},forward:(to)=>{child=to},release:()=>{for(let signal of SIGNALS)process2.off(signal,onSignal)}};function onSignal(signal){if(received=signal,child!==void 0){if(!GROUP_SIGNALS.has(signal)||!heardTheTerminal(child))child.kill(signal);return}if(cleanup===void 0)return;held.release(),cleanup(signal),process2.kill(process2.pid,signal)}for(let signal of SIGNALS)process2.on(signal,onSignal);return held}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process2.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}import{readFileSync as readFileSync4,realpathSync as realpathSync2}from"fs";import{dirname as dirname2,join as join3}from"path";import process6 from"process";var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
2
+ import{outputMode,xdgFolder,tinted,activeTheme,takesControlCodes,paint,writeErr,warn,stripAnsi,formatDuration,Exit,fail,UsageError,HelpShown,Completing,completion,heading,parseContext,OUTPUT_OPTIONS,ignoredFolders}from"./chunk-qtqywtwc.js";import{readFileSync,realpathSync}from"fs";import{resolve}from"path";import process from"process";function commandLine(){try{return readFileSync("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve(word))}catch{return}}function scriptArgs(argv=process.argv.slice(2),cmdline=commandLine(),script=process.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}import{readFileSync as readFileSync2}from"fs";import{constants}from"os";import process2 from"process";var KILL_GRACE_MS=2000,SIGNALS=["SIGINT","SIGTERM","SIGHUP"],GROUP_SIGNALS=new Set(["SIGINT","SIGHUP"]);function exitCodeOf(code,signal){if(code!==null)return code;if(typeof signal==="number")return 128+signal;return signal===null?129:128+constants.signals[signal]}function groupsOf(pid){try{let stat=readFileSync2(`/proc/${pid}/stat`,"utf8"),fields=stat.slice(stat.lastIndexOf(")")+2).split(" ");return{group:Number(fields[2]),foreground:Number(fields[5])}}catch{return}}function heardTheTerminal(child){if(child.pid===void 0)return!1;let own=groupsOf("self");return own!==void 0&&own.group===own.foreground&&groupsOf(child.pid)?.group===own.group}function holdSignals(cleanup){let received,child,held={get signal(){return received},forward:(to)=>{child=to},release:()=>{for(let signal of SIGNALS)process2.off(signal,onSignal)}};function onSignal(signal){if(received=signal,child!==void 0){if(!GROUP_SIGNALS.has(signal)||!heardTheTerminal(child))child.kill(signal);return}if(cleanup===void 0)return;held.release(),cleanup(signal),process2.kill(process2.pid,signal)}for(let signal of SIGNALS)process2.on(signal,onSignal);return held}async function runCommand(argv,{cwd,env,stdin="ignore",input,timeoutMs,signal,maxBytes=1/0,onChunk,onStart}={}){let chunks=[],grouped=timeoutMs!==void 0||signal!==void 0||onStart!==void 0||onChunk!==void 0,proc=Bun.spawn(argv,{...cwd===void 0?{}:{cwd},...env===void 0?{}:{env},stdin:input===void 0?stdin:new TextEncoder().encode(input),stdout:"pipe",stderr:"pipe",...grouped?{detached:!0}:{}}),state={kept:0,truncated:!1,timedOut:!1,failure:void 0,done:!1},timers=[],killGroup=(killing)=>{if(state.done)return;try{if(grouped)process2.kill(-proc.pid,killing);else proc.kill(killing)}catch{}},stop=()=>{killGroup("SIGTERM"),timers.push(setTimeout(killGroup,KILL_GRACE_MS,"SIGKILL"))},onAbort=()=>stop();if(timeoutMs!==void 0)timers.push(setTimeout(()=>{state.timedOut=!0,stop()},timeoutMs));if(signal?.aborted===!0)onAbort();else signal?.addEventListener("abort",onAbort,{once:!0});onStart?.({kill:(killing)=>killGroup(killing)});let drain=async(stream,name)=>{for await(let data of stream){if(state.failure!==void 0)continue;try{onChunk?.({stream:name,data})}catch(error){state.failure=error,stop();continue}if(state.truncated)continue;let kept=data;if(state.kept+data.length>maxBytes){let cut=maxBytes-state.kept;while(cut>0&&((data[cut]??0)&192)===128)cut--;kept=data.subarray(0,cut),state.truncated=!0}if(state.kept+=kept.length,kept.length>0)chunks.push({stream:name,data:kept})}};try{await Promise.all([drain(proc.stdout,"stdout"),drain(proc.stderr,"stderr")]),await proc.exited}finally{state.done=!0;for(let timer of timers)clearTimeout(timer);signal?.removeEventListener("abort",onAbort)}if(state.failure!==void 0)throw state.failure;let joined=()=>Buffer.concat(chunks.map(({data})=>data)),output,text,stdout;return{code:exitCodeOf(proc.exitCode,proc.signalCode),chunks,timedOut:state.timedOut,truncated:state.truncated,get output(){return output??=joined()},get text(){return text??=(output??=joined()).toString()},get stdout(){return stdout??=Buffer.concat(chunks.filter((chunk)=>chunk.stream==="stdout").map((chunk)=>chunk.data)).toString()}}}import{readFileSync as readFileSync4,realpathSync as realpathSync2}from"fs";import{dirname as dirname2,join as join3}from"path";import process6 from"process";var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
3
3
  functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
4
4
  set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
5
5
  set -l current (commandline -ct)
@@ -76,7 +76,7 @@ __kaynooo_cli_bins+=(${bins.join(" ")})
76
76
  `).trim()}}var tsc=(lines)=>{let kept=[],inError=!1;for(let line of lines)if(TSC_ERROR.test(line))inError=!0,kept.push(line);else if(TSC_SUMMARY.test(line))inError=!1,kept.push(line);else if(inError&&TSC_CONTINUATION.test(line)&&!TSC_FRAME.test(line))kept.push(line);else inError=!1;return kept.some((line)=>TSC_ERROR.test(line))?kept:void 0},eslint=(lines)=>{let kept=[],file="",shown="";for(let line of lines)if(ESLINT_PROBLEM.test(line)){if(file!==shown)kept.push(file),shown=file;kept.push(line)}else if(ESLINT_SUMMARY.test(line))kept.push(line);else if(line.trim()!=="")file=line;return kept.some((line)=>ESLINT_PROBLEM.test(line))?kept:void 0},phpstan=(lines)=>{let start=lines.findIndex((line)=>PHPSTAN_TABLE.test(line));return start===-1?void 0:lines.slice(start).filter((line)=>!PHPSTAN_NOISE.test(line))},php=(lines)=>{let start=lines.findIndex((line)=>PHP_FAILURES.test(line));return start===-1?void 0:lines.slice(start)},vitest=(lines)=>{let start=lines.findIndex((line)=>VITEST_FAIL_LINE.test(line));return start===-1?void 0:lines.slice(start)},playwright=(lines)=>{let start=lines.findIndex((line)=>PLAYWRIGHT_FAIL_LINE.test(line));return start===-1?void 0:lines.slice(start)},phpCsFixer=(lines)=>{let files=lines.filter((line)=>CS_FIXER_LINE.test(line)||CS_FIXER_TOTAL.test(line));return files.some((line)=>CS_FIXER_LINE.test(line))?files:void 0},PARSERS=[bunTest,bunCheck,tsc,eslint,vitest,playwright,phpCsFixer,phpstan,php];function squeeze(lines){let out=[];for(let line of lines.map((text)=>text.trimEnd()))if(line!==""||out.at(-1)!=="")out.push(line);while(out.at(-1)==="")out.pop();return out}function cut(shown){return shown.length>MAX_LINES?[...shown.slice(0,MAX_LINES),`... ${shown.length-MAX_LINES} more lines`].join(`
77
77
  `):shown.join(`
78
78
  `)}function recognised(lines,parsers){return parsers.map((parser)=>parser(lines)).find((result)=>result!==void 0&&result.some((line)=>line.trim()!==""))}function failureExcerpt(output){let lines=stripAnsi(output).split(`
79
- `);if(BASH_ECHO.test(lines[0]??""))lines.shift();return cut(squeeze(recognised(lines,PARSERS)??lines.slice(-TAIL)))}var LOG_PATTERNS={BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY};var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");import{basename as basename2,dirname as dirname4,join as join5,relative as relative2,sep}from"path";var PARENT=`..${sep}`;var version="0.27.0";import{existsSync as existsSync2,readFileSync as readFileSync5}from"fs";import{resolve as resolvePath}from"path";var MAKEFILES=["GNUmakefile","makefile","Makefile"],TARGET=/^([\w-]+(?:[ \t]+[\w-]+)*)[ \t]*::?(?!:?=)(.*)$/gm,PHONY_LINE=/^\.PHONY:((?:.*\\\n)*.*)$/gm,DEFINE_BLOCK=/^define\b.*\n(?:.*\n)*?endef\b.*$/gm,DEFINE_START=/^define\b/,DEFINE_END=/^endef\b/,BLANKS=/\s+/,CONTINUATION=/\\\n/g,EXTRA_BLANK_LINES=/\n\s*\n\s*\n/g,LEADING_BLANK_LINES=/^\s*\n/,TRAILING_WHITESPACE=/\s+$/,LEADING_HASHES=/^#*/,INCLUDE=/^(?:-|s)?include[ \t]+([^#]+)/,GLOB_CHARS=/[*?[]/,FILE_LIKE=/[./]/,PLACEHOLDER="\x00phony\x00";function withIncludes(source,dir,seen){return source.split(`
79
+ `);if(BASH_ECHO.test(lines[0]??""))lines.shift();return cut(squeeze(recognised(lines,PARSERS)??lines.slice(-TAIL)))}var LOG_PATTERNS={BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY};var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");import{basename as basename2,dirname as dirname4,join as join5,relative as relative2,sep}from"path";var PARENT=`..${sep}`;var version="0.28.2";import{existsSync as existsSync3,readdirSync,readFileSync as readFileSync6}from"fs";import{basename as basename3,dirname as dirname5,join as join6,resolve as resolvePath2}from"path";import{existsSync as existsSync2,readFileSync as readFileSync5}from"fs";import{resolve as resolvePath}from"path";var MAKEFILES=["GNUmakefile","makefile","Makefile"],TARGET=/^([\w-]+(?:[ \t]+[\w-]+)*)[ \t]*::?(?!:?=)(.*)$/gm,PHONY_LINE=/^\.PHONY:((?:.*\\\n)*.*)$/gm,DEFINE_BLOCK=/^define\b.*\n(?:.*\n)*?endef\b.*$/gm,DEFINE_START=/^define\b/,DEFINE_END=/^endef\b/,BLANKS=/\s+/,CONTINUATION=/\\\n/g,EXTRA_BLANK_LINES=/\n\s*\n\s*\n/g,LEADING_BLANK_LINES=/^\s*\n/,TRAILING_WHITESPACE=/\s+$/,LEADING_HASHES=/^#*/,INCLUDE=/^(?:-|s)?include[ \t]+([^#]+)/,GLOB_CHARS=/[*?[]/,FILE_LIKE=/[./]/,PLACEHOLDER="\x00phony\x00";function withIncludes(source,dir,seen){return source.split(`
80
80
  `).map((line)=>{let match=INCLUDE.exec(line);if(!match)return line;return match[1].trim().split(BLANKS).flatMap((path)=>GLOB_CHARS.test(path)?[...new Bun.Glob(path).scanSync({cwd:dir})].sort():[path]).map((path)=>resolvePath(dir,path)).filter((file)=>!seen.has(file)&&existsSync2(file)).map((file)=>(seen.add(file),withIncludes(readFileSync5(file,"utf-8"),dir,seen))).join(`
81
81
  `)}).join(`
82
82
  `)}function isRuleLine(rule){let colon=rule.indexOf(":");if(colon===-1)return-1;return rule[colon+1]==="="||rule.slice(colon+1).startsWith(":=")||rule.slice(0,colon).includes("=")?-1:colon}function makefileTargets(source){let found=new Map,pending=null,inDefine=!1;for(let line of source.split(`
@@ -87,7 +87,7 @@ __kaynooo_cli_bins+=(${bins.join(" ")})
87
87
  `).replace(LEADING_BLANK_LINES,""),line=targets.length===0?"":`.PHONY: ${targets.join(" ")}`;return{content:(body.includes(PLACEHOLDER)||line===""?body.replace(PLACEHOLDER,()=>line):`${line}
88
88
 
89
89
  ${body}`).replace(LEADING_BLANK_LINES,"").replace(TRAILING_WHITESPACE,`
90
- `),targets}}import{existsSync as existsSync3,readdirSync,readFileSync as readFileSync6}from"fs";import{basename as basename3,dirname as dirname5,join as join6,resolve as resolvePath2}from"path";var JUSTFILES=["justfile","Justfile",".justfile"],JUSTFILE_RE=/^\.?justfile$/i,DENO_FILES=["deno.json","deno.jsonc"],TASKFILES=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],MISE_FILES=["mise.toml",".mise.toml","mise.local.toml",".mise.local.toml","mise",".mise","mise-tasks",".mise-tasks",".config/mise.toml",".config/mise"],LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],TOOL_TIMEOUT_MS=1e4,JUST_FALLBACK_RECIPE=/^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm,TRAILING_SLASHES=/\/+$/,VERSION_SUFFIX=/@.*/;function listEntries(dir){try{return readdirSync(dir)}catch{return[]}}function table(value){return value!==null&&typeof value==="object"?value:{}}function textOf(value){if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((line)=>typeof line==="string"))return value.join(`
90
+ `),targets}}var JUSTFILES=["justfile","Justfile",".justfile"],JUSTFILE_RE=/^\.?justfile$/i,DENO_FILES=["deno.json","deno.jsonc"],TASKFILES=["Taskfile.yml","taskfile.yml","Taskfile.yaml","taskfile.yaml","Taskfile.dist.yml","taskfile.dist.yml","Taskfile.dist.yaml","taskfile.dist.yaml"],MISE_FILES=["mise.toml",".mise.toml","mise.local.toml",".mise.local.toml","mise",".mise","mise-tasks",".mise-tasks",".config/mise.toml",".config/mise"],LOCKFILES=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]],TOOL_TIMEOUT_MS=1e4,JUST_FALLBACK_RECIPE=/^@?([\w-]+)(?:[ \t][^:=\n]*)?:(?!=)/gm,TRAILING_SLASHES=/\/+$/,VERSION_SUFFIX=/@.*/;function listEntries(dir){try{return readdirSync(dir)}catch{return[]}}function table(value){return value!==null&&typeof value==="object"?value:{}}function textOf(value){if(typeof value==="string")return value;if(Array.isArray(value)&&value.every((line)=>typeof line==="string"))return value.join(`
91
91
  `);return Bun.YAML.stringify(value,null,2)??""}function field(value,key){let found=value!==null&&typeof value==="object"?value[key]:void 0;return typeof found==="string"?found:null}function locate(dir,climb,names){for(let current=dir;;current=join6(current,"..")){let found=names.find((name)=>existsSync3(join6(current,name)));if(found!==void 0)return join6(current,found);let absolute=resolvePath2(current);if(!climb||existsSync3(join6(current,".git"))||dirname5(absolute)===absolute)return}}function manager(dir,manifest){let declared=typeof manifest.packageManager==="string"?manifest.packageManager.replace(VERSION_SUFFIX,""):void 0,known=LOCKFILES.find(([,name])=>name===declared);if(known!==void 0)return known[1];for(let current=resolvePath2(dir);;current=dirname5(current)){let found=LOCKFILES.find(([file])=>existsSync3(join6(current,file)));if(found!==void 0)return found[1];if(dirname5(current)===current)return"bun"}}function children(dir=".",extraIgnored=[]){let ignored=ignoredFolders(extraIgnored);return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function readOr(read,fallback){try{return read()}catch{return fallback}}function workspaces(dir="."){let manifest=readOr(()=>JSON.parse(readFileSync6(join6(dir,"package.json"),"utf-8")),{}),declared=Array.isArray(manifest.workspaces)?manifest.workspaces:table(manifest.workspaces).packages,pnpm=readOr(()=>table(Bun.YAML.parse(readFileSync6(join6(dir,"pnpm-workspace.yaml"),"utf-8"))).packages,void 0),patterns=[declared,pnpm].flatMap((value)=>Array.isArray(value)?value.filter((pattern)=>typeof pattern==="string"):[]),excluded=patterns.filter((pattern)=>pattern.startsWith("!")).map((pattern)=>new Bun.Glob(pattern.slice(1)));return patterns.filter((pattern)=>!pattern.startsWith("!")).flatMap((pattern)=>[...new Bun.Glob(`${pattern.replace(TRAILING_SLASHES,"")}/package.json`).scanSync({cwd:dir})].map((file)=>dirname5(file))).filter((found)=>!found.split("/").includes("node_modules")&&!excluded.some((glob)=>glob.match(found)))}function folders(dir="."){return[...new Set([...children(dir),...workspaces(dir)])].filter((found)=>found!==".")}function dumpRecipes(tree){return[...Object.values(tree.recipes??{}).filter((recipe)=>!recipe.private),...Object.values(tree.modules??{}).flatMap((module)=>dumpRecipes(module))]}function justFlags(dir,here){if(here)return[];let file=listEntries(dir).find((name)=>JUSTFILE_RE.test(name));return file===void 0?void 0:["--justfile",join6(dir,file)]}function readPackageManifest(dir,climb=!1){let file=locate(dir,climb,["package.json"]);if(file===void 0)return;let manifest=table(JSON.parse(readFileSync6(file,"utf-8"))),manifestDir=dirname5(file),tool=manager(manifestDir,manifest),scripts=Object.entries(table(manifest.scripts)).map(([name,raw])=>({name,raw,body:textOf(raw)}));return{file,dir:manifestDir,tool,scripts}}function readComposerManifest(dir,climb=!1){let file=locate(dir,climb,["composer.json"]);if(file===void 0)return;let manifest=table(JSON.parse(readFileSync6(file,"utf-8"))),descriptions=table(manifest["scripts-descriptions"]),scripts=Object.entries(table(manifest.scripts)).map(([name,raw])=>({name,doc:field(descriptions,name),body:textOf(raw)}));return{file,dir:dirname5(file),scripts}}function readDenoManifest(dir,climb=!1){let file=locate(dir,climb,DENO_FILES);if(file===void 0)return;let manifest=table(Bun.JSONC.parse(readFileSync6(file,"utf-8"))),tasks=Object.entries(table(manifest.tasks)).map(([name,task])=>({name,doc:field(task,"description"),body:field(task,"command")??textOf(task)}));return{file,filename:basename3(file),dir:dirname5(file),tasks}}function readJustManifest(dir,climb=!1,fallbackText=!1){let localFile=climb?void 0:listEntries(dir).find((name)=>JUSTFILE_RE.test(name));if(!climb&&localFile===void 0)return;let fallback=()=>{if(!fallbackText||localFile===void 0)return;let recipes=[...readFileSync6(join6(dir,localFile),"utf-8").matchAll(JUST_FALLBACK_RECIPE)].map((match)=>({name:match[1]??"",doc:null,parameters:[]}));return{file:localFile,dir,recipes}};if(Bun.which("just")===null)return fallback();try{let argv=["just",...localFile===void 0?[]:["--justfile",localFile],"--dump","--dump-format","json"],proc=Bun.spawnSync(argv,{cwd:dir,stderr:"pipe",timeout:TOOL_TIMEOUT_MS});if(!proc.success)return fallback();let dump=JSON.parse(proc.stdout.toString()),recipes=dumpRecipes(dump).map((recipe)=>({name:recipe.namepath,doc:recipe.doc,parameters:recipe.parameters??[]}));return{...localFile===void 0?{}:{file:localFile},dir,recipes}}catch{return fallback()}}function readMakefileManifest(dir){let file=MAKEFILES.find((name)=>existsSync3(join6(dir,name)));if(file===void 0)return;let path=resolvePath2(dir,file),source=withIncludes(readFileSync6(path,"utf-8"),dir,new Set([path])),targets=makefileTargets(source).map((target)=>({...target,body:showMakefileTarget(source,target.name)}));return{file,dir,source,targets}}function readTaskfileManifest(dir,climb=!1){let file=locate(dir,climb,TASKFILES);if(file===void 0)return;let tasks=table(Bun.YAML.parse(readFileSync6(file,"utf-8"))?.tasks),items=Object.entries(tasks).filter(([,task])=>!(task!==null&&typeof task==="object"&&task.internal===!0)).map(([name,task])=>({name,doc:field(task,"desc")??field(task,"summary"),body:textOf(task)}));return{file,dir:dirname5(file),tasks:items}}function readMiseManifest(dir,climb=!1){if(Bun.which("mise")===null||!climb&&!MISE_FILES.some((name)=>existsSync3(join6(dir,name))))return[];try{let proc=Bun.spawnSync(["mise","tasks","ls","--json"],{cwd:dir,stderr:"pipe",timeout:TOOL_TIMEOUT_MS});if(!proc.success)return[];let root=`${resolvePath2(dir)}/`;return JSON.parse(proc.stdout.toString()).filter((task)=>!task.hide&&(climb||!task.global&&task.source.startsWith(root))).map((task)=>({name:task.name,doc:task.description||null,body:task.file??task.run.join(`
92
92
  `)}))}catch{return[]}}function readPyprojectManifest(dir,climb=!1){let file=locate(dir,climb,["pyproject.toml"]);if(file===void 0)return;let text=readFileSync6(file,"utf-8"),manifest=table(Bun.TOML.parse(text)),tool=table(manifest.tool),project=table(manifest.project),manifestDir=dirname5(file),uv=locate(manifestDir,!0,["uv.lock"])!==void 0,poe=Object.entries(table(table(tool.poe).tasks)).filter(([name])=>!name.startsWith("_")).map(([name,task])=>({name,doc:field(task,"help"),body:field(task,"cmd")??field(task,"shell")??textOf(task)})),scripts=Object.entries(table(project.scripts)).map(([name,target])=>({name,body:textOf(target)}));return{file,dir:manifestDir,text,uv,poe,scripts}}
93
93
  export{exitCodeOf,holdSignals,runCommand,privateLogDirectory,sweepLogs,runMain,shellQuote,captureOutput,findComposeDir,readServices,place,shellIn,argvIn,Stack,programOf,placeOptions,placeSettings,bunCheckFields,failureExcerpt,LOG_PATTERNS,version,MAKEFILES,declarePhony,JUSTFILES,locate,children,workspaces,folders,justFlags,readPackageManifest,readComposerManifest,readDenoManifest,readJustManifest,readMakefileManifest,readTaskfileManifest,readMiseManifest,readPyprojectManifest};
@@ -1,13 +1,13 @@
1
1
  // @bun
2
- import{AsyncLocalStorage}from"async_hooks";import process8 from"process";import{parseArgs}from"util";import process6 from"process";var Nt=/\s+\S*$/,Y=/\s/;function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t));import process from"process";var MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"];function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isHumanTerminal(stream=process.stdout,env=process.env){return outputMode(stream,env)==="terminal"}function isInteractive(streams=process,env=process.env){return streams.stdin?.isTTY===!0&&isHumanTerminal(streams.stderr??{},env)}import process5 from"process";var G2=/^[a-f0-9]+$/i;function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}var B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var o=Fe();import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";var FILE_CACHE=new Map;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function userConfigReadPath(bin,legacy=[],where={}){if(bin==="config")return mainConfigPath(where);let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}function readUserConfig(bin,where={},legacy=[]){if(bin==="config")return readMainConfig(where);let fileData=readCachedObject(userConfigReadPath(bin,legacy,where)),section=readMainConfig(where)[bin];return isRecord(section)?{...fileData,...section}:fileData}var DEFAULT={colors:{accent:"#7dd3fc",id:"#ecd8a6",path:"#93c5fd",label:"#9aa5b4",value:"bold",hairline:"#7e8a9c",ok:"#7ee787",warn:"#f2cc60",problem:"#ff8b8b",note:"#9aa5b4",plan:"#c4b5fd",passed:"#7ee787",failed:"#ff8b8b",running:"#7dd3fc",queued:"#f2cc60",skipped:"#9aa5b4"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",halfBar:"\u2578",track:"\u2500",rule:"\u2500",corner:"\u256D",head:"\u25B8",branch:"\u251C",last:"\u2514",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["#7dd3fc","#c4b5fd","#7ee787","#93c5fd","#f2cc60","#ff8b8b"],bins:{},gradient:["#a5b4fc","#7dd3fc"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",hairline:"white",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",hairline:"#a1a1aa",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",hairline:"dim",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",halfBar:"#",track:"-",rule:"-",corner:"+",head:">",branch:"+",last:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,MAX_FILE_BYTES=65536,SPACES=/\s+/;function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}var CUBE=[0,95,135,175,215,255];function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}var warned=new Set;function warnOnce(message){if(warned.has(message))return;warned.add(message),process4.stderr.write(`warning: theme ${message}
2
+ import{AsyncLocalStorage}from"async_hooks";import process8 from"process";import{parseArgs}from"util";import process6 from"process";var Nt=/\s+\S*$/,Y=/\s/;function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t));function rawBigint(_key,value){return typeof value==="bigint"?JSON.rawJSON(String(value)):value}import process from"process";var MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"];function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isHumanTerminal(stream=process.stdout,env=process.env){return outputMode(stream,env)==="terminal"}function isInteractive(streams=process,env=process.env){return streams.stdin?.isTTY===!0&&isHumanTerminal(streams.stderr??{},env)}import process5 from"process";var G2=/^[a-f0-9]+$/i;function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}var B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var o=Fe();import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";var FILE_CACHE=new Map;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function userConfigReadPath(bin,legacy=[],where={}){if(bin==="config")return mainConfigPath(where);let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}function readUserConfig(bin,where={},legacy=[]){if(bin==="config")return readMainConfig(where);let fileData=readCachedObject(userConfigReadPath(bin,legacy,where)),section=readMainConfig(where)[bin];return isRecord(section)?{...fileData,...section}:fileData}var DEFAULT={colors:{accent:"#7dd3fc",id:"#ecd8a6",path:"#93c5fd",label:"#9aa5b4",value:"bold",hairline:"#7e8a9c",ok:"#7ee787",warn:"#f2cc60",problem:"#ff8b8b",note:"#9aa5b4",plan:"#c4b5fd",passed:"#7ee787",failed:"#ff8b8b",running:"#7dd3fc",queued:"#f2cc60",skipped:"#9aa5b4"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",halfBar:"\u2578",track:"\u2500",rule:"\u2500",corner:"\u256D",head:"\u25B8",branch:"\u251C",last:"\u2514",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["#7dd3fc","#c4b5fd","#7ee787","#93c5fd","#f2cc60","#ff8b8b"],bins:{},gradient:["#a5b4fc","#7dd3fc"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",hairline:"white",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",hairline:"#a1a1aa",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",hairline:"dim",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",halfBar:"#",track:"-",rule:"-",corner:"+",head:">",branch:"+",last:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,MAX_FILE_BYTES=65536,SPACES=/\s+/;function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}var CUBE=[0,95,135,175,215,255];function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}var warned=new Set;function warnOnce(message){if(warned.has(message))return;warned.add(message),process4.stderr.write(`warning: theme ${message}
3
3
  `)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}var current,currentKey="";function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env);if(!takesControlCodes(stream,env))return`${MARK_WORDS[mark]} ${text}${detail===void 0?"":` ${detail}`}`;let{theme}=activeTheme(),head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark]),tail=detail===void 0?"":` ${tinted(colors,theme.colors.label,env)(detail)}`;return`${head} ${text}${tail}`}function writeErr(text=""){process5.stderr.write(`${text}
4
4
  `)}function warn(text,detail){writeErr(marked("warn",text,process5.stderr,detail))}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])));var GRAPHEMES=new Intl.Segmenter;function header(bin,context,stream,env=process5.env){if(!takesControlCodes(stream,env))return"";let colors=paint(stream,env),{theme}=activeTheme(),lead=`${theme.glyphs.head} ${bin}`,rest=context===void 0?"":tinted(colors,theme.colors.label,env)(` \xB7 ${context}`),pinned=theme.bins[bin];if(pinned===void 0)return`${colors.bold(lead)}${rest}`;return`${tinted(typeof pinned==="string"&&pinned.split(" ").includes("bold")?colors:colors.bold,pinned,env)(lead)}${rest}`}var ANSI=/\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;function stripAnsi(text){return text.replace(ANSI,"")}function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`;function wrapToWidth(text,width){let lines=[],current="";for(let word of text.split(" "))if(current!==""&&Bun.stringWidth(current)+1+Bun.stringWidth(word)>width)lines.push(current),current=word;else current=current===""?word:`${current} ${word}`;return current===""?lines:[...lines,current]}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var UNITS=[["d",86400],["h",3600],["m",60],["s",1]];function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}var LINE_BREAKS=/\s*\n\s*/g;function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
5
5
  `);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd());if(!header||!takesControlCodes(stream,env))return lines.join(`
6
6
  `);let{theme}=activeTheme(),headerTint=tinted(colors,theme.colors.label,env),ruleText=widths.map((width)=>theme.glyphs.rule.repeat(width)).join(" ").trimEnd(),rule=lines.length>1&&ruleText!==""?[tinted(colors,theme.colors.hairline,env)(ruleText)]:[];return lines.flatMap((line,index)=>index===0?[headerTint(line),...rule]:[line]).join(`
7
- `)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}import process7 from"process";var OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
7
+ `)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer??rawBigint,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}import process7 from"process";var OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
8
8
  `),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
9
9
  `)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
10
10
  `)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process7.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
11
11
  `)}function exitRows(exits,colors=paint(process7.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process7.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function describeOptions(options){return Object.entries(options).map(([name,{type,short,description:text,choices,multiple}])=>({name,type,...short===void 0?{}:{short},...text===void 0?{}:{description:text},...choices===void 0?{}:{choices:[...choices]},...multiple===!0?{multiple:!0}:{}}))}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
12
12
  `),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:describeOptions(options)}}}var MAX_AGENT_EXAMPLES=2;function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}var MAX_INLINE_CHOICES=24;function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapToWidth(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var WHOLE=/^\d+$/;function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}var BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000};function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var DASHES=/^-+/;function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}var EXIT=Symbol.for("@kaynooo/cli-kit/Exit");class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}}function badUsage(message){throw new UsageError(message)}class HelpShown extends Exit{constructor(){super("help shown",0)}}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}var completion={active:!1},heading={bin:void 0},parseContext=new AsyncLocalStorage,OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};function applyOutput(color,plain,env=process8.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process8.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,ctx=parseContext.getStore();if(ctx!==void 0)ctx.options=all,ctx.json=void 0;let parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(ctx!==void 0)ctx.json=values.json===!0;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process8.stdout)?process8.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}var UNKNOWN_OPTION=/^unknown option '(-[^']+)'/;function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}import{homedir as homedir3}from"os";import{join as join4}from"path";import process9 from"process";var SKIPPED_FOLDERS=new Set(["node_modules","vendor","dist","build","target","coverage","venv","__pycache__"]);function ignoredFolders(extra=[],where={}){let configured=readUserConfig("config",where).ignore,names=Array.isArray(configured)?configured.filter((name)=>typeof name==="string"&&name!==""):[];return new Set([...SKIPPED_FOLDERS,...extra,...names])}function cacheFolder({home=homedir3(),env=process9.env}={}){return xdgFolder(env.XDG_CACHE_HOME,join4(home,".cache"))}
13
- export{outputMode,isInteractive,xdgFolder,readUserConfig,tinted,activeTheme,takesControlCodes,paint,writeErr,warn,role,header,ANSI,stripAnsi,closest,formatDuration,truncate,textWidth,table,printJson,wholeNumber,duration,jsonOption,Exit,fail,UsageError,HelpShown,Completing,completion,heading,parseContext,OUTPUT_OPTIONS,parse,ignoredFolders,cacheFolder};
13
+ export{outputMode,isInteractive,xdgFolder,readUserConfig,tinted,activeTheme,takesControlCodes,paint,writeErr,warn,role,header,ANSI,stripAnsi,closest,formatDuration,truncate,textWidth,table,printJson,wholeNumber,duration,jsonOption,Exit,fail,UsageError,badUsage,HelpShown,Completing,completion,heading,parseContext,OUTPUT_OPTIONS,parse,ignoredFolders,cacheFolder};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{input2}from"./chunk-ctrqm3zy.js";import"./chunk-qtqywtwc.js";export{input2 as input};
package/dist/cli.js CHANGED
@@ -1,14 +1,20 @@
1
1
  #!/bin/sh
2
2
  // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
- import{paint,role,header,stripAnsi,formatDuration,table,printJson,wholeNumber,duration,jsonOption,fail,parse,ignoredFolders}from"./chunk-7d3myeb5.js";import{exitCodeOf,holdSignals,runCommand,privateLogDirectory,sweepLogs,runMain,place,shellIn,Stack,programOf,placeOptions,placeSettings,bunCheckFields,failureExcerpt,LOG_PATTERNS,version,MAKEFILES,declarePhony,JUSTFILES,locate,children,workspaces,folders,readPackageManifest,readComposerManifest,readDenoManifest,readJustManifest,readMakefileManifest,readTaskfileManifest,readMiseManifest,readPyprojectManifest}from"./chunk-ak7f4g3t.js";import process4 from"process";import{existsSync as existsSync4,watch}from"fs";import{writeFile as writeFile3}from"fs/promises";import{basename as basename4,join as join6,resolve as resolve3}from"path";import process3 from"process";var SAFE_WORD=/^[\w@%+=:,./-]+$/;var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);function shellQuote(word){return SAFE_WORD.test(word)&&!word.startsWith("=")?word:`'${word.replaceAll("'","'\\''")}'`}import{existsSync as existsSync3,statSync}from"fs";import{rename,writeFile as writeFile2}from"fs/promises";import{extname as extname2,join as join5}from"path";import process2 from"process";import{stat}from"fs/promises";import{join}from"path";var{$}=globalThis.Bun;async function dirtyFiles(dir){let listed=await $`git ls-files -z --modified --others --exclude-standard`.cwd(dir).quiet().nothrow();if(listed.exitCode!==0)return;let files=new Map;for(let path of listed.stdout.toString().split("\x00").filter(Boolean))try{let{size,mtimeMs}=await stat(join(dir,path));files.set(path,`${size}:${mtimeMs}`)}catch{files.set(path,"")}return files}function changedFiles(before,after){return[...after].filter(([path,hash])=>before.get(path)!==hash).map(([path])=>path)}import{existsSync as existsSync2,readFileSync as readFileSync2}from"fs";import{basename as basename2,dirname,extname,join as join3,resolve as resolve2}from"path";var{$:$2}=globalThis.Bun;import{existsSync,readFileSync}from"fs";import{basename,join as join2,relative,resolve}from"path";var STEP_NAMES=["check","typecheck","lint","fmt","test"],STEP_SOURCES={fmt:["fmt:check","format:check","fmt-check","format-check"]},CHECKRC_FILES=[".checkrc.jsonc",".checkrc.json"],TASK_RUNNERS=new Set(["Justfile","Makefile","Taskfile","mise"]),CS_FIXER_CONFIGS=[".php-cs-fixer.php",".php-cs-fixer.dist.php"],PHPSTAN_CONFIGS=["phpstan.neon","phpstan.neon.dist","phpstan.dist.neon"],PHPUNIT_CONFIGS=["phpunit.xml","phpunit.xml.dist","phpunit.dist.xml"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],PYTEST_CONFIGS=["pytest.ini","conftest.py"],MYPY_CONFIGS=["mypy.ini",".mypy.ini"],RUFF_SECTION=/^\[tool\.ruff/m,PYTEST_SECTION=/^\[tool\.pytest/m,MYPY_SECTION=/^\[tool\.mypy/m;async function readFirst(dir,files){for(let file of files){let handle=Bun.file(join2(dir,file));if(await handle.exists())return{file,text:await handle.text()}}return}async function read(dir,...files){for(let file of files){let handle=Bun.file(join2(dir,file));if(await handle.exists())return handle.text()}return}async function loadCheckConfig(dir){let found=await readFirst(dir,CHECKRC_FILES);if(found===void 0)return;try{let parsed=Bun.JSONC.parse(found.text);if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))fail(`${found.file} must be a JSON object`);return parsed}catch(error){fail(`${found.file} is not valid JSONC: ${error instanceof Error?error.message:String(error)}`)}}function callsSelf(value,bin){return typeof value==="string"&&(value===bin||value.startsWith(`${bin} `)||value.startsWith(`${bin} `))}function readJsonOrFail(file,reader){try{return reader()}catch{fail(`${file} is not valid JSON`)}}function readOptional(reader){try{return reader()}catch{return}}async function candidates(dir,bin,includeNative=!1){let steps=[],pkg=readJsonOrFail("package.json",()=>readPackageManifest(dir,!1));if(pkg!==void 0){for(let script of pkg.scripts)if(!callsSelf(script.raw,bin))steps.push({name:script.name,command:`${pkg.tool} run ${script.name}`,source:"package.json"})}let composer=readJsonOrFail("composer.json",()=>readComposerManifest(dir,!1));if(composer!==void 0)for(let script of composer.scripts)steps.push({name:script.name,command:`composer run ${script.name}`,source:"composer.json"});let deno=readOptional(()=>readDenoManifest(dir,!1));if(deno!==void 0)for(let task of deno.tasks)steps.push({name:task.name,command:`deno task ${task.name}`,source:deno.filename});let just=readJustManifest(dir,!1,!0);if(just!==void 0){for(let recipe of just.recipes)if(recipe.parameters.every((parameter)=>parameter.default!==null||parameter.kind==="star"))steps.push({name:recipe.name,command:`just ${recipe.name}`,source:"Justfile"})}let makefile=readOptional(()=>readMakefileManifest(dir));if(makefile!==void 0)for(let target of makefile.targets)steps.push({name:target.name,command:`make ${target.name}`,source:"Makefile"});let taskfile=readOptional(()=>readTaskfileManifest(dir,!1));if(taskfile!==void 0)for(let task of taskfile.tasks)steps.push({name:task.name,command:`task ${task.name}`,source:"Taskfile"});for(let task of readMiseManifest(dir,!1))steps.push({name:task.name,command:`mise run ${task.name}`,source:"mise"});let pyproject=readOptional(()=>readPyprojectManifest(dir,!1));if(pyproject!==void 0){let runner=pyproject.uv?"uv run poe":"poe";for(let task of pyproject.poe)steps.push({name:task.name,command:`${runner} ${task.name}`,source:"pyproject.toml"})}if(steps.push(...await phpSteps(dir)),includeNative)steps.push(...await nativeSteps(dir,pyproject?.text??await read(dir,"pyproject.toml")));return steps}async function firstFile(dir,names){for(let name of names)if(await Bun.file(join2(dir,name)).exists())return name;return}async function phpSteps(dir){let steps=[],phpstan=await firstFile(dir,PHPSTAN_CONFIGS),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),phpunit=await firstFile(dir,PHPUNIT_CONFIGS);if(phpstan!==void 0)steps.push({name:"typecheck",command:"vendor/bin/phpstan analyse --no-progress --memory-limit=1G",source:phpstan});if(csFixer!==void 0)steps.push({name:"lint",command:"vendor/bin/php-cs-fixer fix --dry-run -v",source:csFixer});if(phpunit!==void 0)steps.push({name:"test",command:"vendor/bin/phpunit",source:phpunit});return steps}async function nativeSteps(dir,pyprojectText){let steps=[];if(existsSync(join2(dir,"go.mod")))steps.push({name:"lint",command:"go vet ./...",source:"go.mod"}),steps.push({name:"test",command:"go test ./...",source:"go.mod"});if(existsSync(join2(dir,"Cargo.toml")))steps.push({name:"check",command:"cargo check",source:"Cargo.toml"}),steps.push({name:"lint",command:"cargo clippy",source:"Cargo.toml"}),steps.push({name:"fmt:check",command:"cargo fmt -- --check",source:"Cargo.toml"}),steps.push({name:"test",command:"cargo test",source:"Cargo.toml"});let pyPrefix=locate(dir,!0,["uv.lock"])!==void 0?"uv run ":"",ruffFile=await firstFile(dir,RUFF_CONFIGS),hasRuff=ruffFile!==void 0||pyprojectText!==void 0&&RUFF_SECTION.test(pyprojectText),hasMypy=await firstFile(dir,MYPY_CONFIGS)!==void 0||pyprojectText!==void 0&&MYPY_SECTION.test(pyprojectText),hasPytest=await firstFile(dir,PYTEST_CONFIGS)!==void 0||pyprojectText!==void 0&&PYTEST_SECTION.test(pyprojectText);if(hasMypy)steps.push({name:"typecheck",command:`${pyPrefix}mypy .`,source:"mypy"});if(hasRuff){let source=ruffFile??"pyproject.toml";steps.push({name:"lint",command:`${pyPrefix}ruff check .`,source}),steps.push({name:"fmt:check",command:`${pyPrefix}ruff format --check .`,source})}if(hasPytest)steps.push({name:"test",command:`${pyPrefix}pytest`,source:"pytest"});return steps}function packageNameOf(dir){let file=join2(dir,"package.json");if(!existsSync(file))return;try{let parsed=JSON.parse(readFileSync(file,"utf8"));return typeof parsed.name==="string"?parsed.name:void 0}catch{return}}function resolveTargetDirs(dir,targets){let known=folders(dir),resolved=[],seen=new Set;for(let target of targets){let direct=resolve(dir,target),matchedDir;if(existsSync(direct))matchedDir=direct;else{let hit=known.find((sub)=>sub===target||basename(sub)===target||packageNameOf(join2(dir,sub))===target);if(hit!==void 0)matchedDir=join2(dir,hit)}if(matchedDir===void 0)fail(`no path or workspace matching ${target}`);if(seen.has(matchedDir))continue;seen.add(matchedDir);let rel=relative(dir,matchedDir);resolved.push({...rel===""?{}:{name:rel},dir:matchedDir})}return resolved}function discoverableSubdirs(dir){let direct=children(dir,["var","tmp"]);return[...new Set([...direct,...workspaces(dir)])].filter((name)=>name!==".").toSorted((a,b)=>a.localeCompare(b))}async function resolveTargets(dir,targets){let projects=[];for(let target of resolveTargetDirs(dir,targets)){let steps=await discover(target.dir);if(steps.length===0)fail(`no check steps found in ${target.name??"."}`);projects.push({...target,steps})}return projects}async function discoverProjects(dir,targets){if(targets!==void 0&&targets.length>0)return resolveTargets(dir,targets);let own=await discover(dir);if(own.length>0)return[{dir,steps:own}];let projects=[];for(let sub of discoverableSubdirs(dir)){let steps=await discover(join2(dir,sub));if(steps.length>0)projects.push({name:sub,dir:join2(dir,sub),steps})}return projects}async function discover(dir){let found=await candidates(dir,"check",!0),overrides=(await loadCheckConfig(dir))?.steps??{},runnerCheck=found.find((candidate)=>candidate.name==="check"&&TASK_RUNNERS.has(candidate.source)),base=STEP_NAMES.flatMap((name)=>{if(name in overrides){let custom=overrides[name];return custom===null||custom===void 0?[]:[{name,command:custom,source:".checkrc.json"}]}let step=name==="check"&&runnerCheck!==void 0?runnerCheck:(STEP_SOURCES[name]??[name]).map((each)=>found.find((candidate)=>candidate.name===each)).find((each)=>each!==void 0);return step===void 0?[]:[{...step,name}]});for(let[name,command]of Object.entries(overrides))if(!STEP_NAMES.includes(name)&&typeof command==="string"&&command!=="")base.push({name,command,source:".checkrc.json"});return base}var WRAPPER_PREFIX=/^(?:(?:bunx|npx|pnpm\s+exec|yarn|uv\s+run)\s+)+/,LINTERS=/^(?:keslint|eslint|oxlint|biome\s+check|biome\s+lint)\b/,LINTABLE=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PYTHON_EXT=new Set([".py",".pyi"]),TEST_RUNNER=/^(?:bun test|\$npm_execpath test)\b/,VITEST_RUNNER=/^vitest(?:\s+run)?\b/,PYTEST_RUNNER=/^pytest\b/,RUFF_CHECK=/^ruff\s+check\b/,RUFF_FORMAT=/^ruff\s+format\b/,GO_TEST=/^go\s+test\s+\.\.\.\/?$|^go\s+test\s+\.\/\.\.\./,TRAILING_DOT=/\s+\.\/?$/,TEST_FILE=/\.(?:test|spec)\.[jt]sx?$/,PY_TEST_FILE=/(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/,IMPORT_SPEC=/(?:from|import)\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\)/g,WHITESPACE=/\s+/;async function changedPaths(dir,base="HEAD"){let tracked=await $2`git diff --name-only --relative -z ${base}`.cwd(dir).quiet().nothrow(),untracked=await $2`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();if(tracked.exitCode!==0||untracked.exitCode!==0)return;return[...new Set([...tracked.stdout.toString().split("\x00"),...untracked.stdout.toString().split("\x00")])].filter((path)=>path!==""&&existsSync2(join3(dir,path)))}function siblingTests(path,exists){let extension=extname(path),name=basename2(path,extension),dir=dirname(path),folders=[dir,join3(dir,"tests"),join3(dir,"..","tests"),join3(dir,"__tests__")],found=new Set;for(let folder of folders)for(let kind of["test","spec"])for(let candidate of[`${name}.${kind}${extension}`,`${name}.${kind}.ts`].map((file)=>join3(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function siblingPyTests(path,exists){let extension=extname(path),name=basename2(path,extension),dir=dirname(path),folders=[dir,join3(dir,"tests"),join3(dir,"..","tests"),"tests"],found=new Set;for(let folder of folders)for(let candidate of[`test_${name}.py`,`${name}_test.py`].map((file)=>join3(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function reverseImportTests(dir,changedSources){if(changedSources.length===0)return[];let targets=new Set(changedSources.map((file)=>{let abs=resolve2(dir,file),ext=extname(abs);return ext===""?abs:abs.slice(0,-ext.length)})),found=new Set,glob=new Bun.Glob("**/*.{test,spec}.{ts,tsx,js,jsx}");for(let testFile of glob.scanSync({cwd:dir})){if(testFile.split("/").includes("node_modules")||testFile.startsWith(".git/"))continue;let text;try{text=readFileSync2(join3(dir,testFile),"utf8")}catch{continue}let testDir=dirname(resolve2(dir,testFile));for(let match of text.matchAll(IMPORT_SPEC)){let specifier=match[1]??match[2]??"";if(!specifier.startsWith("."))continue;let imported=resolve2(testDir,specifier),ext=extname(imported),stem=ext===""?imported:imported.slice(0,-ext.length);if(targets.has(stem)||targets.has(join3(stem,"index"))){found.add(testFile);break}}}return[...found]}function isBare(script,tool,allowDot=!1){let unwrapped=script.trim().replace(WRAPPER_PREFIX,"");if(!tool.test(unwrapped))return!1;let rest=unwrapped.replace(tool,"").trim();if(rest==="")return!0;return rest.split(WHITESPACE).every((word)=>word===""||word.startsWith("-")||allowDot&&(word==="."||word==="./"))}function stripTrailingDot(command){return command.replace(TRAILING_DOT,"")}function jsTestFiles(dir,changed){let tests=new Set,nonTests=[];for(let path of changed)if(TEST_FILE.test(path))tests.add(path);else{if(LINTABLE.has(extname(path)))nonTests.push(path);for(let test of siblingTests(path,(candidate)=>existsSync2(join3(dir,candidate))))tests.add(test)}for(let imported of reverseImportTests(dir,nonTests))tests.add(imported);return[...tests]}async function narrow(step,dir,changed){let script=step.source==="package.json"?(await scriptText(dir,step.name))?.trim():void 0,effective=script??step.command.trim(),full=(why)=>({command:step.command,note:`in full, ${why}`});if(script!==void 0&&step.name==="lint"&&isBare(script,LINTERS,!0)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return{command:"true",note:"nothing changed to lint"};return{command:TRAILING_DOT.test(script)?`${stripTrailingDot(script)} ${files.map(shellQuote).join(" ")}`:`${step.command} -- ${files.map(shellQuote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="lint"&&isBare(effective,RUFF_CHECK,!0)||step.name==="fmt"&&isBare(effective,RUFF_FORMAT,!0)){let files=changed.filter((path)=>PYTHON_EXT.has(extname(path)));if(files.length===0)return{command:"true",note:`nothing changed to ${step.name}`};return{command:`${stripTrailingDot(effective)} ${files.map(shellQuote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,VITEST_RUNNER)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return full("no JS/TS file changed");return{command:`${step.command} -- --related ${files.map(shellQuote).join(" ")}`,note:`${files.length} related file${files.length===1?"":"s"}`}}if(script!==void 0&&step.name==="test"&&isBare(script,TEST_RUNNER)){let tests=jsTestFiles(dir,changed);if(tests.length===0)return full("no test sits next to the changed files");return{command:`${step.command} -- ${tests.map((test)=>shellQuote(`./${test}`)).join(" ")}`,note:`${tests.length} test file${tests.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,PYTEST_RUNNER,!0)){let tests=new Set;for(let path of changed)if(PY_TEST_FILE.test(path))tests.add(path);else if(PYTHON_EXT.has(extname(path)))for(let test of siblingPyTests(path,(candidate)=>existsSync2(join3(dir,candidate))))tests.add(test);if(tests.size===0)return full("no test sits next to the changed files");return{command:`${stripTrailingDot(effective)} ${[...tests].map(shellQuote).join(" ")}`,note:`${tests.size} test file${tests.size===1?"":"s"}`}}if(step.name==="test"&&GO_TEST.test(effective)){let pkgs=[...new Set(changed.filter((path)=>extname(path)===".go").map((path)=>{let folder=dirname(path);return folder==="."?".":`./${folder}`}))];if(pkgs.length===0)return{command:"true",note:"no Go files changed"};return{command:`go test ${pkgs.map(shellQuote).join(" ")}`,note:`${pkgs.length} Go package${pkgs.length===1?"":"s"}`}}return full(`${step.name} cannot be narrowed`)}async function scriptText(dir,name){let text=await read(dir,"package.json");if(text===void 0)return;try{let value=JSON.parse(text).scripts?.[name];return typeof value==="string"?value:void 0}catch{return}}var options={list:{type:"boolean",short:"l",description:"print the steps (or, with --fix, the fixers) found, the commands that run them and where (host or service), without running them"},only:{type:"string",short:"o",description:`comma separated steps to run, among ${STEP_NAMES.join(", ")}; with --fix the fixers to run, by the names --list prints`,candidates:()=>[...STEP_NAMES]},timeout:{type:"string",short:"t",description:"longest a step or fixer may run before it is ended (30s, 5m, 1h), none by default"},...placeOptions,json:jsonOption("[{name, command, in?, ok, ms, log, failed?, errors?}], with --list [{name, command, source, in?}], with --fix {fixers, changed}"),fix:{type:"boolean",short:"f",description:"run the folder's fixers and formatters instead of the steps"},quiet:{type:"boolean",short:"q",description:"print nothing for a passing step, and nothing at all when every step passes"},failed:{type:"boolean",description:"run only the steps that failed in the last run of this folder, read from the run folder"},changed:{type:"boolean",short:"c",description:"narrow lint, fmt, fix, and test to files changed against --base (default HEAD), with 1-hop reverse-import test selection"},base:{type:"string",description:"git ref to diff against with --changed (default HEAD)"},"fail-fast":{type:"boolean",short:"x",description:"stop after the first failing step"},retry:{type:"string",description:"retry a failing step up to N times before reporting failure"},lock:{type:"string",description:"named slot lock to hold alongside the slot (visible in slot ls); refused without the slot bin"},watch:{type:"boolean",short:"w",description:"watch project files and re-run on changes"},slot:{type:"boolean",description:"run each step through slot, queued behind the machine-wide slots of the other sessions, as it does by default when the slot bin is installed; without the bin it warns and runs unqueued",negative:"run the steps at once, without queueing behind the other sessions' slots"},parallel:{type:"boolean",description:"run the steps at the same time, printing each one's output in step order",negative:"run the steps one at a time, overriding parallel in .checkrc.json"}},COMMA=/\s*,\s*/;function pick(steps,only,noun="step"){if(only===void 0)return steps;let names=only.split(COMMA).filter((name)=>name!=="");if(names.length===0)fail(`--only names no ${noun}, found ${steps.map((step)=>step.label??step.name).join(", ")}`);let matches=(step,wanted)=>step.name===wanted||step.label===wanted,unknown=names.filter((name)=>!steps.some((step)=>matches(step,name)));if(unknown.length>0)fail(`no ${unknown.join(", ")} ${noun} here, found ${[...new Set(steps.map((step)=>step.label??step.name))].join(", ")}`);return steps.filter((step)=>names.some((wanted)=>matches(step,wanted)))}import{mkdir,readdir,stat as stat2,writeFile}from"fs/promises";import{basename as basename3,join as join4}from"path";import process from"process";import{relative as relative2}from"path";var E2E_NOISE=[/^(?:Running \d+ tests? using|\(node:\d+\) Warning|\(Use `node|\[\d+\/\d+\] |\s+[-\u2713\u2718\u00B0\u00D7]\s+\d+|To open last HTML|Serving HTML report|\s*npx playwright show-report)/,/^[\u00B7F\u00D7\u00B0T\u00B1]+$/,/^(?: RUN {2}v|\s*[\u276F\u2713\u00D7\u2193] |\s+(?:Test Files|Tests|Start at|Duration|Errors) {2}|\u23AF)/],PLAYWRIGHT_HEADER=/^ {2}\d+\) (?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_SUMMARY=/^ {2}\d+ (failed|flaky|passed|skipped|did not run|interrupted)\b/,PLAYWRIGHT_ENTRY=/^ {4}(?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_RETRY=/^\s+Retry #\d+ \u2500+$/,FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,EXPECTED=/^\s+Expected: (.*)$/,RECEIVED=/^\s+Received: (.*)$/,VITEST_FAIL=/^ FAIL {2}(?:\|[^|]+\| )?(.+)$/,VITEST_SUITE=/^(.+?) \[ .+ \]$/,VITEST_FRAME=/^\s*\u276F (\S+):(\d+):(\d+)$/;function key(project,file,line,column,title){return`${project??""}|${file}:${line}:${column} \u203A ${title}`}function firstFrame(block){return block.map((line)=>FRAME.exec(line)).find((match)=>match!==null&&!match[1]?.includes("node_modules"))??void 0}var collectPlaywright=(lines,used)=>{let flaky=new Set,section="";for(let[index,line]of lines.entries()){let summary=PLAYWRIGHT_SUMMARY.exec(line),entry=PLAYWRIGHT_ENTRY.exec(line);if(summary!==null)section=summary[1]??"",used.add(index);else if(entry!==null&&section!==""){if(section==="flaky")flaky.add(key(entry[1],entry[2],entry[3],entry[4],entry[5]));used.add(index)}}let errors=[];for(let index=0;index<lines.length;index++){let header=PLAYWRIGHT_HEADER.exec(lines[index]??"");if(header===null)continue;let end=index+1;while(end<lines.length&&!PLAYWRIGHT_HEADER.test(lines[end]??"")&&!PLAYWRIGHT_SUMMARY.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let[,project,file,line,column,title]=header,retry=lines.findIndex((text,at)=>at>index&&at<end&&PLAYWRIGHT_RETRY.test(text)),block=lines.slice(index+1,retry===-1?end:retry),frame=firstFrame(block),message=block.find((text)=>text.trim()!=="")?.trim()??"failed",expected=block.map((text)=>EXPECTED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),received=block.map((text)=>RECEIVED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;if(index=end-1,flaky.has(key(project,file,line,column,title)))continue;errors.push({tool:"playwright",file:frame?.[1]??file??"",line:Number(frame?.[2]??line),column:Number(frame?.[3]??column),severity:"error",message:`${message}${values}`,test:`${project===void 0?"":`[${project}] `}${title}`})}return errors},collectVitest=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let header=VITEST_FAIL.exec(lines[index]??"")?.[1];if(header===void 0)continue;let end=index+1;while(end<lines.length&&!(lines[end]??"").startsWith("\u23AF")&&!VITEST_FAIL.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let block=lines.slice(index+1,end),frame=block.map((text)=>VITEST_FRAME.exec(text)).find((match)=>match!==null&&!match[1]?.includes("node_modules")),suite=VITEST_SUITE.exec(header)?.[1],[file="",...names]=(suite??header).split(" > ");errors.push({tool:"vitest",file:frame?.[1]??file,line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:block.find((text)=>text.trim()!=="")?.trim()??"failed",...suite===void 0&&names.length>0?{test:names.join(" > ")}:{}}),index=end-1}return errors};var PHP_NOISE=[/^(?:PHPUnit \d|ParaTest v|Runtime: |Configuration: |Processes: |Random Seed: |Time: |Tests: |OK(?:,| \()|FAILURES!|ERRORS!|WARNINGS!|No tests executed|--$)/,/^[.FEWRISD]+\s+\d+ \/ \d+ \(\d+%\)$/,/^ -{3,}(?: -{3,})*\s*$/,/^\s*\d+\/\d+ \[[=>\-\u2593\u2591 ]*\]\s+\d+%/,/^(?:Note: Using configuration file|\s*\[(?:OK|ERROR)\] )/,/^(?:Loaded config|PHP runtime:|PHP CS Fixer \d|Running analysis|Parallel runner|Using cache file|Paths from configuration|Rules from configuration|Setting PHP_CS_FIXER|Unable to determine minimum|If you need help|Found \d+ of \d+ files|Checked all files|Fixed \d+ of \d+ files|Legend:)/];var PHPUNIT_HEADER=/^There (?:was|were) \d+ ([a-z ]+?)s?:$/i,PHPUNIT_TRIGGERED=/^\d+ tests? triggered \d+ [\w ]+?s?:$/,PHPUNIT_END=/^(?:--|FAILURES!|ERRORS!|WARNINGS!|OK\b.*|Tests: .*|No tests executed!)$/,PHPUNIT_ITEM=/^\d+\) (.*)$/,PHP_LOCATION=/^([\w./-]+\.php):(\d+)$/,PHPSTAN_FILE=/^ {2}Line {3}(\S.*)$/,PHPSTAN_GENERAL=/^ {2}Error\s*$/,PHPSTAN_MESSAGE=/^ {2}(\S.*)$/,PHPSTAN_ROW=/^ {2}(\d+|-) +(\S.*)$/,PHPSTAN_CONTINUATION=/^ {9}(\S.*)$/,PHPSTAN_IDENTIFIER=/^ {9}\uD83E\uDEAA\s+(\S+)\s*$/,PHPSTAN_TIP=/^ {9}\uD83D\uDCA1/,PHPSTAN_BORDER=/^ -{3,}(?: -{3,})*\s*$/,PHPSTAN_RAW=/^(\S.*?\.(?:php|phtml|twig|neon|inc)):(\d+):(\S.*)$/,PHPSTAN_JSON=/^\{.*"totals"/,CS_FIXER_FILE=/^\s+\d+\) (\S.*?\.php)(?: \((.+)\))?$/,CS_FIXER_DIFF_START=/^\s+-+ begin diff -+$/,CS_FIXER_DIFF_END=/^\s+-+ end diff -+$/;function isHeader(line){return PHPUNIT_HEADER.test(line)||PHPUNIT_TRIGGERED.test(line)}function diffSummary(message){let start=message.findIndex((line)=>line==="+++ Actual");if(start===-1)return"";let changed=message.slice(start+1).filter((line)=>line.startsWith("-")||line.startsWith("+")).map((line)=>`${line[0]} ${line.slice(1).trim()}`),shown=changed.slice(0,6).join(" | ");return changed.length===0?"":` (${shown}${changed.length>6?" | ...":""})`}function phpunitError(test,body){let at=body.findIndex((line)=>PHP_LOCATION.test(line)),location=PHP_LOCATION.exec(body[at]??""),message=body.slice(0,at===-1?body.length:at).map((line)=>line.trimEnd()),first=message.find((line)=>line.trim()!=="")??"failed";return{tool:"phpunit",file:location?.[1]??"",line:Number(location?.[2]??0),column:0,severity:"error",message:`${first}${diffSummary(message)}`,test}}var collectPhpunit=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let line=lines[index]??"",kind=PHPUNIT_HEADER.exec(line)?.[1];if(kind===void 0&&!PHPUNIT_TRIGGERED.test(line))continue;let end=index+1;while(end<lines.length&&!PHPUNIT_END.test(lines[end]??"")&&!isHeader(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);if(kind==="error"||kind==="failure"){let starts=Array.from({length:end-index-1},(_,at)=>index+1+at).filter((at)=>PHPUNIT_ITEM.test(lines[at]??""));for(let[position,start]of starts.entries())errors.push(phpunitError(PHPUNIT_ITEM.exec(lines[start]??"")?.[1]??"",lines.slice(start+1,starts[position+1]??end)))}index=end-1}return errors};function appendMessage(error,text){error.message=`${error.message} ${text}`}function phpstanJson(text){try{let report=JSON.parse(text);return[...Object.entries(report.files??{}).flatMap(([file,entry])=>entry.messages.map((message)=>({file,line:message.line??0,message:message.message,...message.identifier===void 0?{}:{rule:message.identifier}}))),...(report.errors??[]).map((message)=>({file:"",line:0,message}))]}catch{return}}var collectPhpstan=(lines,used)=>{let errors=[],file,current,rows=0,tip=!1,general=!1;for(let[index,text]of lines.entries()){let line=text.trimEnd();if(used.has(index))continue;if(PHPSTAN_JSON.test(line)){let parsed=phpstanJson(line);for(let entry of parsed??[])errors.push({tool:"phpstan",file:entry.file,line:entry.line,column:0,severity:"error",message:entry.message,...entry.rule===void 0?{}:{rule:entry.rule}});if(parsed!==void 0)used.add(index);continue}let raw=PHPSTAN_RAW.exec(line);if(raw!==null){errors.push({tool:"phpstan",file:raw[1]??"",line:Number(raw[2]),column:0,severity:"error",message:raw[3]??""}),used.add(index);continue}let header=PHPSTAN_FILE.exec(line);if(header!==null||PHPSTAN_GENERAL.test(line)){file=header?.[1]??"",general=header===null,current=void 0,rows=0,used.add(index);continue}if(file===void 0)continue;let message=PHPSTAN_MESSAGE.exec(line)?.[1];if(general&&message!==void 0&&!PHPSTAN_BORDER.test(line)){errors.push({tool:"phpstan",file:"",line:0,column:0,severity:"error",message}),rows++,used.add(index);continue}let row=PHPSTAN_ROW.exec(line),identifier=PHPSTAN_IDENTIFIER.exec(line)?.[1],continuation=PHPSTAN_CONTINUATION.exec(line)?.[1];if(PHPSTAN_BORDER.test(line)&&rows>0)file=void 0,general=!1,current=void 0;else if(row!==null)current={tool:"phpstan",file,line:row[1]==="-"?0:Number(row[1]),column:0,severity:"error",message:row[2]??""},errors.push(current),rows++,tip=!1,used.add(index);else if(identifier!==void 0&&current!==void 0)current.rule=identifier,used.add(index);else if(PHPSTAN_TIP.test(line))tip=!0,used.add(index);else if(continuation!==void 0&&current!==void 0){if(!tip)appendMessage(current,continuation);used.add(index)}}return errors},collectCsFixer=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let match=CS_FIXER_FILE.exec(lines[index]??"");if(match===null)continue;if(errors.push({tool:"php-cs-fixer",file:match[1]??"",line:0,column:0,...match[2]===void 0?{}:{rule:match[2]},severity:"error",message:"style issues to fix"}),used.add(index),!CS_FIXER_DIFF_START.test(lines[index+1]??""))continue;let end=lines.findIndex((text,at)=>at>index&&CS_FIXER_DIFF_END.test(text));for(let at=index+1;at<=(end===-1?index+1:end);at++)used.add(at);index=end===-1?index+1:end}return errors};var{BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY}=LOG_PATTERNS,TSC_PLAIN_ERROR=/^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/,TSC_PRETTY_ERROR=/^(.+?):(\d+):(\d+) - error (TS\d+): (.*)$/,TSC_SOURCE_LINE=/^\d+ /,ESLINT_FIELDS=/^ +(\d+):(\d+) +(error|warning) +(\S.*)$/,ESLINT_RULE=/ {2,}(\S+)$/,ESLINT_FILE=/^(?:\/|~\/|\.{1,2}[/\\]|[a-z]:\\)|^[^\s/\\]+[/\\]\S*$/i,BUN_TEST_EXPECTED=/^Expected: (.*)$/,BUN_TEST_RECEIVED=/^Received: (.*)$/,BUN_TEST_FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,BUN_TEST_FILE=/^\S+\.test\.[jt]sx?:$/,GO_ERROR=/^\s*(?:vet: )?(\S+\.go):(\d+):(?:(\d+):)? (.+)$/,GO_LINTER=/^(.*\S)\s+\(([a-z][\w-]*)\)$/,GO_NOISE=/^# \S+(?: \[\S+\])?$/,ARROW=/^\s*--> (.+?):(\d+):(\d+)$/,CARGO_HEADER=/^(error|warning)(?:\[([\w-]+)\])?: (.*)$/,LINE_BREAK=/\r?\n/,CONTINUATION=/^\s+\S/,MAX_CONTINUATION=20,KAY_SUMMARY=/^(?:\d+ errors?(?:, \d+ warnings?)?|\d+ warnings?)(?:, failing under --deny-warnings)?$|^checked with /,CARGO_NOISE=/^(?:\s+(?:Compiling|Finished|Checking|Fresh|Running|Blocking) |error: (?:aborting due to|could not compile)|warning: .* generated \d+ warnings?|Some errors have detailed explanations|For more information about (?:this|an) error|To learn more, run the command again)/,RUFF_CONCISE=/^(\S+\.pyi?):(\d+):(\d+): ([A-Z]+\d+) (?:\[\*\] )?(.*)$/,RUFF_HEADER=/^([A-Z]{1,5}\d{1,4}) (?:\[\*\] )?(.+)$/,RUFF_NOISE=/^(?:Found \d+ errors?\.|\[\*\] \d+ fixable|No fixes available|All checks passed|help: |\s*(?:\|\s*)?$)/,PYTEST_LOCATION=/^(\S+\.py):(\d+): (\S.*)$/,PYTEST_E_LINE=/^E {3}(.*)$/,PYTEST_BANNER=/^={3,} (.*?) ={3,}$/,PYTEST_FAILURES=new Set(["FAILURES","ERRORS"]),PYTEST_SUMMARY_LINE=/^(?:FAILED|ERROR) \S/,PYTEST_FRAME=/^in \S/,PYTEST_SECTION2=/^_{3,} (.*) _{3,}$/,PYTEST_SUMMARY=/^(?:FAILED|ERROR) ([^\s:]+?\.py)(?:::(.*)| - (.*))?$/,PYTEST_ERROR_SECTION=/^ERROR (?:at (?:setup|teardown) of |collecting )/,PYTEST_EXCEPTION_END=/[\s:]/,PYTEST_NOISE=/^(?:platform |rootdir: |collected |plugins: |configfile: |cachedir: |\S+\.pyi? [.FEsxXR]+ +\[ *\d+%\]$|\S+\.py:\d+: $)/,GENERIC_LINE=/^(\S[^:]*):(\d+)(?::(\d+))?: (?:fatal )?(error|warning|note): (.*)$/,GENERIC_RULE=/\s(?:\[([\w-]+)\]|\(([a-z][\w-]*)\))$/,NOISE=/^(?:bun test v|Errors {2}Files$|Ran \d+ tests?|note: |\s*\d+ expect\(\) calls|\s+\d+\s+\S+:\d+$|\s*\d+ errors? and \d+ warnings? potentially fixable|error: script ".+" exited with code \d+$)/;function isNoise(line){return line.trim()===""||[NOISE,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_SUMMARY,ESLINT_SUMMARY,BOUNDARY,BASH_ECHO,GO_NOISE,CARGO_NOISE,KAY_SUMMARY,RUFF_NOISE,PYTEST_NOISE,PYTEST_BANNER,...PHP_NOISE,...E2E_NOISE].some((pattern)=>pattern.test(line))}var collectBunCheck=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){if(!(lines[index]??"").startsWith("<error file="))continue;let end=lines.findIndex((line,at)=>at>=index&&line==="</error>");if(end===-1)break;let{file,line,column,code,message}=bunCheckFields(lines.slice(index,end+1).join(`
4
- `));errors.push({tool:"bun check",file,line:Number(line),column:Number(column),rule:code,severity:"error",message:message.replaceAll(/\s*\n\s*/g," ")});for(let at=index;at<=end;at++)used.add(at);index=end}return errors},collectBunTest=(lines,used)=>{let errors=[],seen=new Set,names=new Set;for(let[index,line]of lines.entries()){if(!line.startsWith("(fail) "))continue;used.add(index);let test=line.slice(7).replace(DURATION,""),start=lines.findLastIndex((text,at)=>at<index&&BOUNDARY.test(text))+1,block=lines.slice(start,index),failure=block.findIndex((text)=>text.startsWith("error:"));for(let at=start;at<index;at++)used.add(at);let frame=block.slice(Math.max(failure,0)).map((text)=>BUN_TEST_FRAME.exec(text)).find((match)=>match!==null),header=lines.slice(0,index).findLast((text)=>BUN_TEST_FILE.test(text)),key=`${header??""}\x00${test}`;if(seen.has(key)||failure===-1&&names.has(test))continue;seen.add(key),names.add(test);let expected=block.map((text)=>BUN_TEST_EXPECTED.exec(text)?.[1]).find((text)=>text!==void 0),received=block.map((text)=>BUN_TEST_RECEIVED.exec(text)?.[1]).find((text)=>text!==void 0),reason=failure===-1?"failed":(block[failure]??"").slice(6).trim(),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;errors.push({tool:"bun test",file:frame?.[1]??header?.replace(":","")??"",line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:`${reason}${values}`,test})}return errors},collectTsc=(lines,used)=>{let errors=[],current,pretty=!1;for(let[index,line]of lines.entries()){if(used.has(index))continue;let plain=TSC_PLAIN_ERROR.exec(line),match=plain??TSC_PRETTY_ERROR.exec(line);if(match!==null)current={tool:"tsc",file:match[1]??"",line:Number(match[2]),column:Number(match[3]),rule:match[4],severity:"error",message:match[5]??""},pretty=plain===null,errors.push(current),used.add(index);else if(current!==void 0&&TSC_CONTINUATION.test(line)&&!TSC_FRAME.test(line))current.message+=` ${line.trim()}`,used.add(index);else if(current!==void 0&&pretty&&(TSC_FRAME.test(line)||TSC_SOURCE_LINE.test(line)))used.add(index);else if(!(pretty&&line.trim()===""))current=void 0}return errors},collectEslint=(lines,used)=>{let errors=[],file;for(let[index,line]of lines.entries()){if(used.has(index))continue;let match=ESLINT_PROBLEM.test(line)?ESLINT_FIELDS.exec(line):null;if(match!==null&&file!==void 0){let text=match[4]??"",rule=ESLINT_RULE.exec(text);errors.push({tool:"eslint",file:(lines[file]??"").trim(),line:Number(match[1]),column:Number(match[2]),rule:rule?.[1],severity:match[3]==="warning"?"warning":"error",message:rule===null?text:text.slice(0,rule.index)}),used.add(index),used.add(file)}else if(!isNoise(line)&&!line.includes(": ")&&ESLINT_FILE.test(line.trimEnd()))file=index}return errors},collectGo=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:GO_ERROR.exec(line);if(match===null)continue;let linter=GO_LINTER.exec(match[4]??"");errors.push({tool:"go",file:match[1]??"",line:Number(match[2]),column:Number(match[3]??0),...linter===null?{}:{rule:linter[2]},severity:"error",message:linter===null?match[4]??"":linter[1]??""}),used.add(index)}return errors};function headerAbove(lines,arrow,used){let at=arrow-1;while(at>0&&arrow-at<=MAX_CONTINUATION&&!used.has(at)&&CONTINUATION.test(lines[at]??"")&&!ARROW.test(lines[at]??""))at--;return at}var collectArrowed=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let arrow=used.has(index)||index===0?null:ARROW.exec(line),at=arrow===null?-1:headerAbove(lines,index,used),header=at===-1?null:lines[at]??"",cargo=header===null?null:CARGO_HEADER.exec(header),ruff=header===null||cargo!==null?null:RUFF_HEADER.exec(header);if(arrow===null||cargo===null&&ruff===null||used.has(at))continue;let[,file="",row,column]=arrow,fields={file,line:Number(row),column:Number(column)};errors.push(cargo===null?{tool:"ruff",...fields,rule:ruff?.[1],severity:"error",message:ruff?.[2]??""}:{tool:file.endsWith(".rs")?"cargo":"kay check",...fields,rule:cargo[2],severity:cargo[1]==="warning"?"warning":"error",message:cargo[3]??""});for(let taken=at;taken<=index;taken++)used.add(taken);for(let frame=index+1;frame<lines.length&&(lines[frame]??"").trim()!=="";frame++){if(CARGO_HEADER.test(lines[frame]??"")||RUFF_HEADER.test(lines[frame]??""))break;used.add(frame)}}return errors},collectRuff=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:RUFF_CONCISE.exec(line);if(match===null)continue;errors.push({tool:"ruff",file:match[1]??"",line:Number(match[2]),column:Number(match[3]),rule:match[4],severity:"error",message:match[5]??""}),used.add(index)}return errors},collectPytest=(lines,used)=>{let errors=[],silent=new Map,section,closeSection=()=>{if(section===void 0||errors.length!==section.errors)return;let key=section.title.replace(PYTEST_ERROR_SECTION,"");silent.set(key,(silent.get(key)??0)+1)},title=(line)=>PYTEST_BANNER.exec(line??"")?.[1],start=lines.findIndex((line)=>PYTEST_FAILURES.has(title(line)??""));if(start===-1)return errors;let end=lines.findIndex((line,index)=>index>start&&title(line)!==void 0&&!PYTEST_FAILURES.has(title(line)??"")),stop=end===-1?lines.length:end,message=[],frame;for(let index=start;index<stop;index++){let line=lines[index]??"",failure=PYTEST_E_LINE.exec(line);if(failure!==null)message.push((failure[1]??"").trim());else{if(frame!==void 0&&message.length>0)errors.push({tool:"pytest",...frame,column:0,severity:"error",message:message[0]??""}),frame=void 0;let location=PYTEST_LOCATION.exec(line);if(location!==null&&PYTEST_FRAME.test(location[3]??""))frame={file:location[1]??"",line:Number(location[2])};else if(location!==null){let[exception=""]=(location[3]??"").split(PYTEST_EXCEPTION_END),first=message[0]??"",text=first===""||first.startsWith(exception)?first||(location[3]??""):`${location[3]??""}: ${first}`;errors.push({tool:"pytest",file:location[1]??"",line:Number(location[2]),column:0,severity:"error",message:text})}let opened=PYTEST_SECTION2.exec(line);if(opened!==null)frame=void 0,closeSection(),section={title:opened[1]??"",errors:errors.length};if(line.trim()!=="")message=[]}used.add(index)}if(frame!==void 0&&message.length>0)errors.push({tool:"pytest",...frame,column:0,severity:"error",message:message[0]??""});closeSection();for(let index=stop;index<lines.length;index++){if(!PYTEST_SUMMARY_LINE.test(lines[index]??""))continue;used.add(index);let[,file="",rest,fileReason]=PYTEST_SUMMARY.exec(lines[index]??"")??[],parts=summaryParts(file,rest,fileReason,silent);if(parts===void 0)continue;let{key,name,reason}=parts,left=silent.get(key)??0;silent.set(key,left-1),errors.push({tool:"pytest",file,line:0,column:0,severity:"error",message:reason??"failed",test:name===void 0?file:`${file}::${name}`})}return errors};function summaryParts(file,rest,fileReason,silent){let keyOf=(name)=>name===void 0?file:name.replaceAll("::","."),candidates=[];if(rest===void 0)candidates.push({name:void 0,reason:fileReason});else{for(let at=rest.indexOf(" - ");at!==-1;at=rest.indexOf(" - ",at+1))candidates.push({name:rest.slice(0,at),reason:rest.slice(at+3)});candidates.push({name:rest,reason:void 0})}let found=candidates.find((candidate)=>(silent.get(keyOf(candidate.name))??0)>0);return found===void 0?void 0:{key:keyOf(found.name),...found}}var collectGeneric=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:GENERIC_LINE.exec(line);if(match===null)continue;if(used.add(index),match[4]==="note")continue;let text=match[5]??"",ruled=GENERIC_RULE.exec(text),rule=ruled?.[1]??ruled?.[2];errors.push({tool:"generic",file:match[1]??"",line:Number(match[2]),column:Number(match[3]??0),rule,severity:match[4]==="warning"?"warning":"error",message:ruled===null?text:text.slice(0,ruled.index).trimEnd()})}return errors},COLLECTORS=[collectBunCheck,collectBunTest,collectVitest,collectPlaywright,collectPhpunit,collectPhpstan,collectCsFixer,collectPytest,collectArrowed,collectRuff,collectGo,collectTsc,collectEslint,collectGeneric];function parseErrors(output){let lines=stripAnsi(output).split(LINE_BREAK);if(BASH_ECHO.test(lines[0]??""))lines.shift();let used=new Set,seen=new Set,errors=COLLECTORS.flatMap((collect)=>collect(lines,used)).filter((error)=>{let key=[error.file,error.line,error.column,error.message,error.test].join("\x00");if(seen.has(key))return!1;return seen.add(key),!0}),unrecognisedLines=lines.filter((line,index)=>!used.has(index)&&!isNoise(line));return{errors,unrecognised:unrecognisedLines.length,unrecognisedLines}}function formatError(error,cwd){let path=error.file.startsWith("/")?relative2(cwd,error.file):error.file,where=`${path.startsWith("..")?error.file:path}:${error.line}:${error.column}`,label=error.test===void 0?"":`${error.test}: `,level=error.severity==="warning"?"warning: ":"",rule=error.rule===void 0?"":` (${error.rule})`;return`${where}: ${level}${label}${error.message}${rule}`}var LOG_MAX_AGE_MS=259200000,RESULTS_FILE="results.json",runPrefix=(cwd)=>`${basename3(cwd)}-${Bun.hash(cwd).toString(36)}-`;async function logDirectory(cwd){let root=await privateLogDirectory("check");await sweepLogs(root,LOG_MAX_AGE_MS);let path=join4(root,`${runPrefix(cwd)}${Date.now().toString(36)}-${process.pid}`);return await mkdir(path,{mode:448}),path}async function lastResults(cwd){let root=await privateLogDirectory("check"),prefix=runPrefix(cwd),latest;for(let name of await readdir(root)){if(!name.startsWith(prefix))continue;let file=join4(root,name,RESULTS_FILE);try{let{mtimeMs}=await stat2(file);if(latest===void 0||mtimeMs>latest.time)latest={time:mtimeMs,file}}catch{}}if(latest===void 0)return;return JSON.parse(await Bun.file(latest.file).text())}async function lastFailed(cwd){return(await lastResults(cwd))?.filter((result)=>!result.ok).map((result)=>result.name)}async function runStep(command,cwd,logFile,{env={},timeoutMs,held}={}){let started=Date.now(),{code,text,timedOut}=await runCommand(["sh","-c",`${command} 2>&1`],{cwd,env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0",...env},...timeoutMs===void 0?{}:{timeoutMs},...held===void 0?{}:{onStart:(child)=>held.forward(child)}}),output=stripAnsi(text);return await writeFile(logFile,output,{mode:384,flag:"wx"}),{ok:code===0,ms:Date.now()-started,output,...timedOut?{timedOut}:{}}}async function refusedStep(reason,logFile){return await writeFile(logFile,reason,{mode:384,flag:"wx"}),{ok:!1,ms:0,output:reason}}var MAX_INLINE_ERRORS=40;function formattedFailure(output,cwd=process.cwd()){let{errors,unrecognised}=parseErrors(output);if(errors.length===0)return{text:failureExcerpt(output),errors,unrecognised};let shown=errors.slice(0,MAX_INLINE_ERRORS).map((error)=>formatError(error,cwd)),more=errors.length>MAX_INLINE_ERRORS?[`... +${errors.length-MAX_INLINE_ERRORS} more errors`]:[],extra=unrecognised>0?[`(${unrecognised} unrecognised ${unrecognised===1?"line":"lines"} in full log)`]:[];return{text:[...shown,...more,...extra].join(`
3
+ import{paint,role,header,stripAnsi,formatDuration,table,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,ignoredFolders}from"./chunk-qtqywtwc.js";import{exitCodeOf,holdSignals,runCommand,privateLogDirectory,sweepLogs,runMain,place,shellIn,Stack,programOf,placeOptions,placeSettings,bunCheckFields,failureExcerpt,LOG_PATTERNS,version,MAKEFILES,declarePhony,JUSTFILES,locate,children,workspaces,folders,readPackageManifest,readComposerManifest,readDenoManifest,readJustManifest,readMakefileManifest,readTaskfileManifest,readMiseManifest,readPyprojectManifest}from"./chunk-nkztmk15.js";import process6 from"process";import{existsSync as existsSync4,watch}from"fs";import{basename as basename6,join as join8,resolve as resolve3}from"path";import process5 from"process";import{basename as basename3,join as join3}from"path";import process2 from"process";import{mkdir,readdir,stat,writeFile}from"fs/promises";import{basename,join}from"path";import process from"process";import{relative}from"path";var E2E_NOISE=[/^(?:Running \d+ tests? using|\(node:\d+\) Warning|\(Use `node|\[\d+\/\d+\] |\s+[-\u2713\u2718\u00B0\u00D7]\s+\d+|To open last HTML|Serving HTML report|\s*npx playwright show-report)/,/^[\u00B7F\u00D7\u00B0T\u00B1]+$/,/^(?: RUN {2}v|\s*[\u276F\u2713\u00D7\u2193] |\s+(?:Test Files|Tests|Start at|Duration|Errors) {2}|\u23AF)/],PLAYWRIGHT_HEADER=/^ {2}\d+\) (?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_SUMMARY=/^ {2}\d+ (failed|flaky|passed|skipped|did not run|interrupted)\b/,PLAYWRIGHT_ENTRY=/^ {4}(?:\[([^\]]+)\] \u203A )?(.+?):(\d+):(\d+) \u203A (.+?) \u2500+$/,PLAYWRIGHT_RETRY=/^\s+Retry #\d+ \u2500+$/,FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,EXPECTED=/^\s+Expected: (.*)$/,RECEIVED=/^\s+Received: (.*)$/,VITEST_FAIL=/^ FAIL {2}(?:\|[^|]+\| )?(.+)$/,VITEST_SUITE=/^(.+?) \[ .+ \]$/,VITEST_FRAME=/^\s*\u276F (\S+):(\d+):(\d+)$/;function key(project,file,line,column,title){return`${project??""}|${file}:${line}:${column} \u203A ${title}`}function firstFrame(block){return block.map((line)=>FRAME.exec(line)).find((match)=>match!==null&&!match[1]?.includes("node_modules"))??void 0}var collectPlaywright=(lines,used)=>{let flaky=new Set,section="";for(let[index,line]of lines.entries()){let summary=PLAYWRIGHT_SUMMARY.exec(line),entry=PLAYWRIGHT_ENTRY.exec(line);if(summary!==null)section=summary[1]??"",used.add(index);else if(entry!==null&&section!==""){if(section==="flaky")flaky.add(key(entry[1],entry[2],entry[3],entry[4],entry[5]));used.add(index)}}let errors=[];for(let index=0;index<lines.length;index++){let header=PLAYWRIGHT_HEADER.exec(lines[index]??"");if(header===null)continue;let end=index+1;while(end<lines.length&&!PLAYWRIGHT_HEADER.test(lines[end]??"")&&!PLAYWRIGHT_SUMMARY.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let[,project,file,line,column,title]=header,retry=lines.findIndex((text,at)=>at>index&&at<end&&PLAYWRIGHT_RETRY.test(text)),block=lines.slice(index+1,retry===-1?end:retry),frame=firstFrame(block),message=block.find((text)=>text.trim()!=="")?.trim()??"failed",expected=block.map((text)=>EXPECTED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),received=block.map((text)=>RECEIVED.exec(text)?.[1]?.trim()).find((text)=>text!==void 0),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;if(index=end-1,flaky.has(key(project,file,line,column,title)))continue;errors.push({tool:"playwright",file:frame?.[1]??file??"",line:Number(frame?.[2]??line),column:Number(frame?.[3]??column),severity:"error",message:`${message}${values}`,test:`${project===void 0?"":`[${project}] `}${title}`})}return errors},collectVitest=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let header=VITEST_FAIL.exec(lines[index]??"")?.[1];if(header===void 0)continue;let end=index+1;while(end<lines.length&&!(lines[end]??"").startsWith("\u23AF")&&!VITEST_FAIL.test(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);let block=lines.slice(index+1,end),frame=block.map((text)=>VITEST_FRAME.exec(text)).find((match)=>match!==null&&!match[1]?.includes("node_modules")),suite=VITEST_SUITE.exec(header)?.[1],[file="",...names]=(suite??header).split(" > ");errors.push({tool:"vitest",file:frame?.[1]??file,line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:block.find((text)=>text.trim()!=="")?.trim()??"failed",...suite===void 0&&names.length>0?{test:names.join(" > ")}:{}}),index=end-1}return errors};var PHP_NOISE=[/^(?:PHPUnit \d|ParaTest v|Runtime: |Configuration: |Processes: |Random Seed: |Time: |Tests: |OK(?:,| \()|FAILURES!|ERRORS!|WARNINGS!|No tests executed|--$)/,/^[.FEWRISD]+\s+\d+ \/ \d+ \(\d+%\)$/,/^ -{3,}(?: -{3,})*\s*$/,/^\s*\d+\/\d+ \[[=>\-\u2593\u2591 ]*\]\s+\d+%/,/^(?:Note: Using configuration file|\s*\[(?:OK|ERROR)\] )/,/^(?:Loaded config|PHP runtime:|PHP CS Fixer \d|Running analysis|Parallel runner|Using cache file|Paths from configuration|Rules from configuration|Setting PHP_CS_FIXER|Unable to determine minimum|If you need help|Found \d+ of \d+ files|Checked all files|Fixed \d+ of \d+ files|Legend:)/];var PHPUNIT_HEADER=/^There (?:was|were) \d+ ([a-z ]+?)s?:$/i,PHPUNIT_TRIGGERED=/^\d+ tests? triggered \d+ [\w ]+?s?:$/,PHPUNIT_END=/^(?:--|FAILURES!|ERRORS!|WARNINGS!|OK\b.*|Tests: .*|No tests executed!)$/,PHPUNIT_ITEM=/^\d+\) (.*)$/,PHP_LOCATION=/^([\w./-]+\.php):(\d+)$/,PHPSTAN_FILE=/^ {2}Line {3}(\S.*)$/,PHPSTAN_GENERAL=/^ {2}Error\s*$/,PHPSTAN_MESSAGE=/^ {2}(\S.*)$/,PHPSTAN_ROW=/^ {2}(\d+|-) +(\S.*)$/,PHPSTAN_CONTINUATION=/^ {9}(\S.*)$/,PHPSTAN_IDENTIFIER=/^ {9}\uD83E\uDEAA\s+(\S+)\s*$/,PHPSTAN_TIP=/^ {9}\uD83D\uDCA1/,PHPSTAN_BORDER=/^ -{3,}(?: -{3,})*\s*$/,PHPSTAN_RAW=/^(\S.*?\.(?:php|phtml|twig|neon|inc)):(\d+):(\S.*)$/,PHPSTAN_JSON=/^\{.*"totals"/,CS_FIXER_FILE=/^\s+\d+\) (\S.*?\.php)(?: \((.+)\))?$/,CS_FIXER_DIFF_START=/^\s+-+ begin diff -+$/,CS_FIXER_DIFF_END=/^\s+-+ end diff -+$/;function isHeader(line){return PHPUNIT_HEADER.test(line)||PHPUNIT_TRIGGERED.test(line)}function diffSummary(message){let start=message.findIndex((line)=>line==="+++ Actual");if(start===-1)return"";let changed=message.slice(start+1).filter((line)=>line.startsWith("-")||line.startsWith("+")).map((line)=>`${line[0]} ${line.slice(1).trim()}`),shown=changed.slice(0,6).join(" | ");return changed.length===0?"":` (${shown}${changed.length>6?" | ...":""})`}function phpunitError(test,body){let at=body.findIndex((line)=>PHP_LOCATION.test(line)),location=PHP_LOCATION.exec(body[at]??""),message=body.slice(0,at===-1?body.length:at).map((line)=>line.trimEnd()),first=message.find((line)=>line.trim()!=="")??"failed";return{tool:"phpunit",file:location?.[1]??"",line:Number(location?.[2]??0),column:0,severity:"error",message:`${first}${diffSummary(message)}`,test}}var collectPhpunit=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let line=lines[index]??"",kind=PHPUNIT_HEADER.exec(line)?.[1];if(kind===void 0&&!PHPUNIT_TRIGGERED.test(line))continue;let end=index+1;while(end<lines.length&&!PHPUNIT_END.test(lines[end]??"")&&!isHeader(lines[end]??""))end++;for(let at=index;at<end;at++)used.add(at);if(kind==="error"||kind==="failure"){let starts=Array.from({length:end-index-1},(_,at)=>index+1+at).filter((at)=>PHPUNIT_ITEM.test(lines[at]??""));for(let[position,start]of starts.entries())errors.push(phpunitError(PHPUNIT_ITEM.exec(lines[start]??"")?.[1]??"",lines.slice(start+1,starts[position+1]??end)))}index=end-1}return errors};function appendMessage(error,text){error.message=`${error.message} ${text}`}function phpstanJson(text){try{let report=JSON.parse(text);return[...Object.entries(report.files??{}).flatMap(([file,entry])=>entry.messages.map((message)=>({file,line:message.line??0,message:message.message,...message.identifier===void 0?{}:{rule:message.identifier}}))),...(report.errors??[]).map((message)=>({file:"",line:0,message}))]}catch{return}}var collectPhpstan=(lines,used)=>{let errors=[],file,current,rows=0,tip=!1,general=!1;for(let[index,text]of lines.entries()){let line=text.trimEnd();if(used.has(index))continue;if(PHPSTAN_JSON.test(line)){let parsed=phpstanJson(line);for(let entry of parsed??[])errors.push({tool:"phpstan",file:entry.file,line:entry.line,column:0,severity:"error",message:entry.message,...entry.rule===void 0?{}:{rule:entry.rule}});if(parsed!==void 0)used.add(index);continue}let raw=PHPSTAN_RAW.exec(line);if(raw!==null){errors.push({tool:"phpstan",file:raw[1]??"",line:Number(raw[2]),column:0,severity:"error",message:raw[3]??""}),used.add(index);continue}let header=PHPSTAN_FILE.exec(line);if(header!==null||PHPSTAN_GENERAL.test(line)){file=header?.[1]??"",general=header===null,current=void 0,rows=0,used.add(index);continue}if(file===void 0)continue;let message=PHPSTAN_MESSAGE.exec(line)?.[1];if(general&&message!==void 0&&!PHPSTAN_BORDER.test(line)){errors.push({tool:"phpstan",file:"",line:0,column:0,severity:"error",message}),rows++,used.add(index);continue}let row=PHPSTAN_ROW.exec(line),identifier=PHPSTAN_IDENTIFIER.exec(line)?.[1],continuation=PHPSTAN_CONTINUATION.exec(line)?.[1];if(PHPSTAN_BORDER.test(line)&&rows>0)file=void 0,general=!1,current=void 0;else if(row!==null)current={tool:"phpstan",file,line:row[1]==="-"?0:Number(row[1]),column:0,severity:"error",message:row[2]??""},errors.push(current),rows++,tip=!1,used.add(index);else if(identifier!==void 0&&current!==void 0)current.rule=identifier,used.add(index);else if(PHPSTAN_TIP.test(line))tip=!0,used.add(index);else if(continuation!==void 0&&current!==void 0){if(!tip)appendMessage(current,continuation);used.add(index)}}return errors},collectCsFixer=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){let match=CS_FIXER_FILE.exec(lines[index]??"");if(match===null)continue;if(errors.push({tool:"php-cs-fixer",file:match[1]??"",line:0,column:0,...match[2]===void 0?{}:{rule:match[2]},severity:"error",message:"style issues to fix"}),used.add(index),!CS_FIXER_DIFF_START.test(lines[index+1]??""))continue;let end=lines.findIndex((text,at)=>at>index&&CS_FIXER_DIFF_END.test(text));for(let at=index+1;at<=(end===-1?index+1:end);at++)used.add(at);index=end===-1?index+1:end}return errors};var{BASH_ECHO,DURATION,BOUNDARY,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_CONTINUATION,TSC_FRAME,TSC_SUMMARY,ESLINT_PROBLEM,ESLINT_SUMMARY}=LOG_PATTERNS,TSC_PLAIN_ERROR=/^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/,TSC_PRETTY_ERROR=/^(.+?):(\d+):(\d+) - error (TS\d+): (.*)$/,TSC_SOURCE_LINE=/^\d+ /,ESLINT_FIELDS=/^ +(\d+):(\d+) +(error|warning) +(\S.*)$/,ESLINT_RULE=/ {2,}(\S+)$/,ESLINT_FILE=/^(?:\/|~\/|\.{1,2}[/\\]|[a-z]:\\)|^[^\s/\\]+[/\\]\S*$/i,BUN_TEST_EXPECTED=/^Expected: (.*)$/,BUN_TEST_RECEIVED=/^Received: (.*)$/,BUN_TEST_FRAME=/^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/,BUN_TEST_FILE=/^\S+\.test\.[jt]sx?:$/,GO_ERROR=/^\s*(?:vet: )?(\S+\.go):(\d+):(?:(\d+):)? (.+)$/,GO_LINTER=/^(.*\S)\s+\(([a-z][\w-]*)\)$/,GO_NOISE=/^# \S+(?: \[\S+\])?$/,ARROW=/^\s*--> (.+?):(\d+):(\d+)$/,CARGO_HEADER=/^(error|warning)(?:\[([\w-]+)\])?: (.*)$/,LINE_BREAK=/\r?\n/,CONTINUATION=/^\s+\S/,MAX_CONTINUATION=20,KAY_SUMMARY=/^(?:\d+ errors?(?:, \d+ warnings?)?|\d+ warnings?)(?:, failing under --deny-warnings)?$|^checked with /,CARGO_NOISE=/^(?:\s+(?:Compiling|Finished|Checking|Fresh|Running|Blocking) |error: (?:aborting due to|could not compile)|warning: .* generated \d+ warnings?|Some errors have detailed explanations|For more information about (?:this|an) error|To learn more, run the command again)/,RUFF_CONCISE=/^(\S+\.pyi?):(\d+):(\d+): ([A-Z]+\d+) (?:\[\*\] )?(.*)$/,RUFF_HEADER=/^([A-Z]{1,5}\d{1,4}) (?:\[\*\] )?(.+)$/,RUFF_NOISE=/^(?:Found \d+ errors?\.|\[\*\] \d+ fixable|No fixes available|All checks passed|help: |\s*(?:\|\s*)?$)/,PYTEST_LOCATION=/^(\S+\.py):(\d+): (\S.*)$/,PYTEST_E_LINE=/^E {3}(.*)$/,PYTEST_BANNER=/^={3,} (.*?) ={3,}$/,PYTEST_FAILURES=new Set(["FAILURES","ERRORS"]),PYTEST_SUMMARY_LINE=/^(?:FAILED|ERROR) \S/,PYTEST_FRAME=/^in \S/,PYTEST_SECTION=/^_{3,} (.*) _{3,}$/,PYTEST_SUMMARY=/^(?:FAILED|ERROR) ([^\s:]+?\.py)(?:::(.*)| - (.*))?$/,PYTEST_ERROR_SECTION=/^ERROR (?:at (?:setup|teardown) of |collecting )/,PYTEST_EXCEPTION_END=/[\s:]/,PYTEST_NOISE=/^(?:platform |rootdir: |collected |plugins: |configfile: |cachedir: |\S+\.pyi? [.FEsxXR]+ +\[ *\d+%\]$|\S+\.py:\d+: $)/,GENERIC_LINE=/^(\S[^:]*):(\d+)(?::(\d+))?: (?:fatal )?(error|warning|note): (.*)$/,GENERIC_RULE=/\s(?:\[([\w-]+)\]|\(([a-z][\w-]*)\))$/,NOISE=/^(?:bun test v|Errors {2}Files$|Ran \d+ tests?|note: |\s*\d+ expect\(\) calls|\s+\d+\s+\S+:\d+$|\s*\d+ errors? and \d+ warnings? potentially fixable|error: script ".+" exited with code \d+$)/;function isNoise(line){return line.trim()===""||[NOISE,BUN_TEST_SUMMARY,BUN_CHECK_SUMMARY,TSC_SUMMARY,ESLINT_SUMMARY,BOUNDARY,BASH_ECHO,GO_NOISE,CARGO_NOISE,KAY_SUMMARY,RUFF_NOISE,PYTEST_NOISE,PYTEST_BANNER,...PHP_NOISE,...E2E_NOISE].some((pattern)=>pattern.test(line))}var collectBunCheck=(lines,used)=>{let errors=[];for(let index=0;index<lines.length;index++){if(!(lines[index]??"").startsWith("<error file="))continue;let end=lines.findIndex((line,at)=>at>=index&&line==="</error>");if(end===-1)break;let{file,line,column,code,message}=bunCheckFields(lines.slice(index,end+1).join(`
4
+ `));errors.push({tool:"bun check",file,line:Number(line),column:Number(column),rule:code,severity:"error",message:message.replaceAll(/\s*\n\s*/g," ")});for(let at=index;at<=end;at++)used.add(at);index=end}return errors},collectBunTest=(lines,used)=>{let errors=[],seen=new Set,names=new Set;for(let[index,line]of lines.entries()){if(!line.startsWith("(fail) "))continue;used.add(index);let test=line.slice(7).replace(DURATION,""),start=lines.findLastIndex((text,at)=>at<index&&BOUNDARY.test(text))+1,block=lines.slice(start,index),failure=block.findIndex((text)=>text.startsWith("error:"));for(let at=start;at<index;at++)used.add(at);let frame=block.slice(Math.max(failure,0)).map((text)=>BUN_TEST_FRAME.exec(text)).find((match)=>match!==null),header=lines.slice(0,index).findLast((text)=>BUN_TEST_FILE.test(text)),key=`${header??""}\x00${test}`;if(seen.has(key)||failure===-1&&names.has(test))continue;seen.add(key),names.add(test);let expected=block.map((text)=>BUN_TEST_EXPECTED.exec(text)?.[1]).find((text)=>text!==void 0),received=block.map((text)=>BUN_TEST_RECEIVED.exec(text)?.[1]).find((text)=>text!==void 0),reason=failure===-1?"failed":(block[failure]??"").slice(6).trim(),values=expected===void 0||received===void 0?"":` (expected ${expected}, received ${received})`;errors.push({tool:"bun test",file:frame?.[1]??header?.replace(":","")??"",line:Number(frame?.[2]??0),column:Number(frame?.[3]??0),severity:"error",message:`${reason}${values}`,test})}return errors},collectTsc=(lines,used)=>{let errors=[],current,pretty=!1;for(let[index,line]of lines.entries()){if(used.has(index))continue;let plain=TSC_PLAIN_ERROR.exec(line),match=plain??TSC_PRETTY_ERROR.exec(line);if(match!==null)current={tool:"tsc",file:match[1]??"",line:Number(match[2]),column:Number(match[3]),rule:match[4],severity:"error",message:match[5]??""},pretty=plain===null,errors.push(current),used.add(index);else if(current!==void 0&&TSC_CONTINUATION.test(line)&&!TSC_FRAME.test(line))current.message+=` ${line.trim()}`,used.add(index);else if(current!==void 0&&pretty&&(TSC_FRAME.test(line)||TSC_SOURCE_LINE.test(line)))used.add(index);else if(!(pretty&&line.trim()===""))current=void 0}return errors},collectEslint=(lines,used)=>{let errors=[],file;for(let[index,line]of lines.entries()){if(used.has(index))continue;let match=ESLINT_PROBLEM.test(line)?ESLINT_FIELDS.exec(line):null;if(match!==null&&file!==void 0){let text=match[4]??"",rule=ESLINT_RULE.exec(text);errors.push({tool:"eslint",file:(lines[file]??"").trim(),line:Number(match[1]),column:Number(match[2]),rule:rule?.[1],severity:match[3]==="warning"?"warning":"error",message:rule===null?text:text.slice(0,rule.index)}),used.add(index),used.add(file)}else if(!isNoise(line)&&!line.includes(": ")&&ESLINT_FILE.test(line.trimEnd()))file=index}return errors},collectGo=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:GO_ERROR.exec(line);if(match===null)continue;let linter=GO_LINTER.exec(match[4]??"");errors.push({tool:"go",file:match[1]??"",line:Number(match[2]),column:Number(match[3]??0),...linter===null?{}:{rule:linter[2]},severity:"error",message:linter===null?match[4]??"":linter[1]??""}),used.add(index)}return errors};function headerAbove(lines,arrow,used){let at=arrow-1;while(at>0&&arrow-at<=MAX_CONTINUATION&&!used.has(at)&&CONTINUATION.test(lines[at]??"")&&!ARROW.test(lines[at]??""))at--;return at}var collectArrowed=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let arrow=used.has(index)||index===0?null:ARROW.exec(line),at=arrow===null?-1:headerAbove(lines,index,used),header=at===-1?null:lines[at]??"",cargo=header===null?null:CARGO_HEADER.exec(header),ruff=header===null||cargo!==null?null:RUFF_HEADER.exec(header);if(arrow===null||cargo===null&&ruff===null||used.has(at))continue;let[,file="",row,column]=arrow,fields={file,line:Number(row),column:Number(column)};errors.push(cargo===null?{tool:"ruff",...fields,rule:ruff?.[1],severity:"error",message:ruff?.[2]??""}:{tool:file.endsWith(".rs")?"cargo":"kay check",...fields,rule:cargo[2],severity:cargo[1]==="warning"?"warning":"error",message:cargo[3]??""});for(let taken=at;taken<=index;taken++)used.add(taken);for(let frame=index+1;frame<lines.length&&(lines[frame]??"").trim()!=="";frame++){if(CARGO_HEADER.test(lines[frame]??"")||RUFF_HEADER.test(lines[frame]??""))break;used.add(frame)}}return errors},collectRuff=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:RUFF_CONCISE.exec(line);if(match===null)continue;errors.push({tool:"ruff",file:match[1]??"",line:Number(match[2]),column:Number(match[3]),rule:match[4],severity:"error",message:match[5]??""}),used.add(index)}return errors},collectPytest=(lines,used)=>{let errors=[],silent=new Map,section,closeSection=()=>{if(section===void 0||errors.length!==section.errors)return;let key=section.title.replace(PYTEST_ERROR_SECTION,"");silent.set(key,(silent.get(key)??0)+1)},title=(line)=>PYTEST_BANNER.exec(line??"")?.[1],start=lines.findIndex((line)=>PYTEST_FAILURES.has(title(line)??""));if(start===-1)return errors;let end=lines.findIndex((line,index)=>index>start&&title(line)!==void 0&&!PYTEST_FAILURES.has(title(line)??"")),stop=end===-1?lines.length:end,message=[],frame;for(let index=start;index<stop;index++){let line=lines[index]??"",failure=PYTEST_E_LINE.exec(line);if(failure!==null)message.push((failure[1]??"").trim());else{if(frame!==void 0&&message.length>0)errors.push({tool:"pytest",...frame,column:0,severity:"error",message:message[0]??""}),frame=void 0;let location=PYTEST_LOCATION.exec(line);if(location!==null&&PYTEST_FRAME.test(location[3]??""))frame={file:location[1]??"",line:Number(location[2])};else if(location!==null){let[exception=""]=(location[3]??"").split(PYTEST_EXCEPTION_END),first=message[0]??"",text=first===""||first.startsWith(exception)?first||(location[3]??""):`${location[3]??""}: ${first}`;errors.push({tool:"pytest",file:location[1]??"",line:Number(location[2]),column:0,severity:"error",message:text})}let opened=PYTEST_SECTION.exec(line);if(opened!==null)frame=void 0,closeSection(),section={title:opened[1]??"",errors:errors.length};if(line.trim()!=="")message=[]}used.add(index)}if(frame!==void 0&&message.length>0)errors.push({tool:"pytest",...frame,column:0,severity:"error",message:message[0]??""});closeSection();for(let index=stop;index<lines.length;index++){if(!PYTEST_SUMMARY_LINE.test(lines[index]??""))continue;used.add(index);let[,file="",rest,fileReason]=PYTEST_SUMMARY.exec(lines[index]??"")??[],parts=summaryParts(file,rest,fileReason,silent);if(parts===void 0)continue;let{key,name,reason}=parts,left=silent.get(key)??0;silent.set(key,left-1),errors.push({tool:"pytest",file,line:0,column:0,severity:"error",message:reason??"failed",test:name===void 0?file:`${file}::${name}`})}return errors};function summaryParts(file,rest,fileReason,silent){let keyOf=(name)=>name===void 0?file:name.replaceAll("::","."),candidates=[];if(rest===void 0)candidates.push({name:void 0,reason:fileReason});else{for(let at=rest.indexOf(" - ");at!==-1;at=rest.indexOf(" - ",at+1))candidates.push({name:rest.slice(0,at),reason:rest.slice(at+3)});candidates.push({name:rest,reason:void 0})}let found=candidates.find((candidate)=>(silent.get(keyOf(candidate.name))??0)>0);return found===void 0?void 0:{key:keyOf(found.name),...found}}var collectGeneric=(lines,used)=>{let errors=[];for(let[index,line]of lines.entries()){let match=used.has(index)?null:GENERIC_LINE.exec(line);if(match===null)continue;if(used.add(index),match[4]==="note")continue;let text=match[5]??"",ruled=GENERIC_RULE.exec(text),rule=ruled?.[1]??ruled?.[2];errors.push({tool:"generic",file:match[1]??"",line:Number(match[2]),column:Number(match[3]??0),rule,severity:match[4]==="warning"?"warning":"error",message:ruled===null?text:text.slice(0,ruled.index).trimEnd()})}return errors},COLLECTORS=[collectBunCheck,collectBunTest,collectVitest,collectPlaywright,collectPhpunit,collectPhpstan,collectCsFixer,collectPytest,collectArrowed,collectRuff,collectGo,collectTsc,collectEslint,collectGeneric];function parseErrors(output){let lines=stripAnsi(output).split(LINE_BREAK);if(BASH_ECHO.test(lines[0]??""))lines.shift();let used=new Set,seen=new Set,errors=COLLECTORS.flatMap((collect)=>collect(lines,used)).filter((error)=>{let key=[error.file,error.line,error.column,error.message,error.test].join("\x00");if(seen.has(key))return!1;return seen.add(key),!0}),unrecognisedLines=lines.filter((line,index)=>!used.has(index)&&!isNoise(line));return{errors,unrecognised:unrecognisedLines.length,unrecognisedLines}}function formatError(error,cwd){let path=error.file.startsWith("/")?relative(cwd,error.file):error.file,where=`${path.startsWith("..")?error.file:path}:${error.line}:${error.column}`,label=error.test===void 0?"":`${error.test}: `,level=error.severity==="warning"?"warning: ":"",rule=error.rule===void 0?"":` (${error.rule})`;return`${where}: ${level}${label}${error.message}${rule}`}var SAFE_WORD=/^[\w@%+=:,./-]+$/;var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);function shellQuote(word){return SAFE_WORD.test(word)&&!word.startsWith("=")?word:`'${word.replaceAll("'","'\\''")}'`}function slotted(command,lock){return`slot ${lock===void 0?"":`--lock ${shellQuote(lock)} `}-- sh -c ${shellQuote(command)}`}function launch(step){return step.placement===void 0?step.command:shellIn(step.placement,step.command)}var LOG_MAX_AGE_MS=259200000,RESULTS_FILE="results.json",runPrefix=(cwd)=>`${basename(cwd)}-${Bun.hash(cwd).toString(36)}-`;async function logDirectory(cwd){let root=await privateLogDirectory("check");await sweepLogs(root,LOG_MAX_AGE_MS);let path=join(root,`${runPrefix(cwd)}${Date.now().toString(36)}-${process.pid}`);return await mkdir(path,{mode:448}),path}async function lastResults(cwd){let root=await privateLogDirectory("check"),prefix=runPrefix(cwd),latest;for(let name of await readdir(root)){if(!name.startsWith(prefix))continue;let file=join(root,name,RESULTS_FILE);try{let{mtimeMs}=await stat(file);if(latest===void 0||mtimeMs>latest.time)latest={time:mtimeMs,file}}catch{}}if(latest===void 0)return;return JSON.parse(await Bun.file(latest.file).text())}async function lastFailed(cwd){return(await lastResults(cwd))?.filter((result)=>!result.ok).map((result)=>result.name)}async function saveResults(cwd,directory,ran){let kept=(await lastResults(cwd)??[]).filter(({name})=>!ran.some((each)=>each.name===name));await writeFile(join(directory,RESULTS_FILE),JSON.stringify([...kept,...ran]),{mode:384})}async function runStep(command,cwd,logFile,{env={},timeoutMs,held}={}){let started=Date.now(),{code,text,timedOut}=await runCommand(["sh","-c",`${command} 2>&1`],{cwd,env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0",...env},...timeoutMs===void 0?{}:{timeoutMs},...held===void 0?{}:{onStart:(child)=>held.forward(child)}}),output=stripAnsi(text);return await writeFile(logFile,output,{mode:384,flag:"wx"}),{ok:code===0,ms:Date.now()-started,output,...timedOut?{timedOut}:{}}}async function refusedStep(reason,logFile){return await writeFile(logFile,reason,{mode:384,flag:"wx"}),{ok:!1,ms:0,output:reason}}var MAX_INLINE_ERRORS=40;function formattedFailure(output,cwd=process.cwd()){let{errors,unrecognised}=parseErrors(output);if(errors.length===0)return{text:failureExcerpt(output),errors,unrecognised};let shown=errors.slice(0,MAX_INLINE_ERRORS).map((error)=>formatError(error,cwd)),more=errors.length>MAX_INLINE_ERRORS?[`... +${errors.length-MAX_INLINE_ERRORS} more errors`]:[],extra=unrecognised>0?[`(${unrecognised} unrecognised ${unrecognised===1?"line":"lines"} in full log)`]:[];return{text:[...shown,...more,...extra].join(`
5
5
  `),errors,unrecognised}}function outcomeJson(name,command,logFile,outcome,service,cwd=process.cwd()){if(outcome.ok)return{name,command,...service===void 0?{}:{in:service},ok:!0,ms:outcome.ms,log:logFile};let{text,errors,unrecognised}=formattedFailure(outcome.output,cwd);return{name,command,...service===void 0?{}:{in:service},ok:!1,ms:outcome.ms,log:logFile,...outcome.timedOut===!0?{timedOut:!0}:{},failed:text,errors,unrecognised}}function printOutcome(name,width,command,logFile,outcome,cwd=process.cwd(),failed){let colors=paint(process.stdout),path=role("path",process.stdout),took=colors.dim(formatDuration(outcome.ms));if(outcome.ok){console.log(`${colors.bold(colors.green("ok "))} ${name.padEnd(width)} ${took} ${path(logFile)}`);return}let label=outcome.timedOut===!0?colors.bold(colors.yellow("TIME ")):colors.bold(colors.red("FAIL "));if(console.log(`${label} ${name.padEnd(width)} ${took} ${colors.dim(command)} ${path(logFile)}`),outcome.timedOut===!0)console.log(colors.yellow(` timed out after ${formatDuration(outcome.ms)}, the step and what it started were ended`));let failureText=failed??formattedFailure(outcome.output,cwd).text;console.log(failureText.split(`
6
6
  `).map((line)=>` ${line}`.trimEnd()).join(`
7
- `))}var RUNNING="KAYNOOO_CLI_FIX",RUFF_CONFIGS2=["ruff.toml",".ruff.toml"],RUFF_SECTION2=/^\[tool\.ruff/m,MAX_CHANGED=30,JS_EXTS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PY_EXTS=new Set([".py",".pyi"]),PHP_EXTS=new Set([".php"]),GO_EXTS=new Set([".go"]),RS_EXTS=new Set([".rs"]),JS_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:keslint|eslint|oxlint|prettier|biome)\b/,TRAILING_DOT2=/\s+\.\/?$/;async function narrowProjectFixers(found,dir,base){let paths=await changedPaths(dir,base);if(paths===void 0)fail("--changed needs a git repository");let result=[],pkgText=await read(dir,"package.json"),scripts=pkgText===void 0?{}:JSON.parse(pkgText).scripts??{};for(let fixer of found){if(fixer.name==="python"){let files=paths.filter((path)=>PY_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`ruff check --fix ${files.map(shellQuote).join(" ")} && ruff format ${files.map(shellQuote).join(" ")}`});continue}if(fixer.name==="php-cs-fixer"){let files=paths.filter((path)=>PHP_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`vendor/bin/php-cs-fixer fix ${files.map(shellQuote).join(" ")}`});continue}if(fixer.name==="go"){if(paths.some((path)=>GO_EXTS.has(extname2(path))||path==="go.mod"))result.push(fixer);continue}if(fixer.name==="rust"){if(paths.some((path)=>RS_EXTS.has(extname2(path))||path==="Cargo.toml"))result.push(fixer);continue}if(fixer.name==="makefile"||fixer.name==="justfile"){if(paths.includes(fixer.source))result.push(fixer);continue}if(fixer.source==="package.json"){let script=scripts[fixer.name]?.trim()??"",files=paths.filter((path)=>JS_EXTS.has(extname2(path)));if(JS_FIXER.test(script)){if(files.length>0){let stripped=script.replace(TRAILING_DOT2,"");result.push({...fixer,command:TRAILING_DOT2.test(script)?`${stripped} ${files.map(shellQuote).join(" ")}`:`${fixer.command} -- ${files.map(shellQuote).join(" ")}`})}continue}}result.push(fixer)}return result}async function narrowFixers(found,cliBase,rootBase){let byDir=new Map;for(let fixer of found){let group=byDir.get(fixer.dir)??[];group.push(fixer),byDir.set(fixer.dir,group)}let result=[];for(let[dir,group]of byDir){let projectRc=await loadCheckConfig(dir),base=cliBase??projectRc?.base??rootBase;result.push(...await narrowProjectFixers(group,dir,base))}return result}async function replaceFile(path,content){let temporary=`${path}.${process2.pid}.tmp`;await writeFile2(temporary,content,{mode:statSync(path).mode&511}),await rename(temporary,path)}var LINT_FIXERS=["lint:fix","lint-fix","fix:lint","fix-lint","eslint:fix","eslint-fix","biome:fix","oxlint:fix"],FORMAT_FIXERS=["fmt","format","format:fix","format-fix","fmt:fix","fmt-fix","fix:format","fix:fmt","prettier","biome"],WRITING_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:(?:keslint|eslint|oxlint)\b.*\s--fix\b|prettier\b.*\s--write\b|biome\s+(?:check|format|lint)\b.*\s--(?:write|apply)\b)/;async function projectFixers(dir){let found=await candidates(dir,"check"),named=(names)=>names.map((name)=>found.find((step)=>step.name===name)).find((step)=>step!==void 0),all=named(["fix"]);if(all!==void 0)return[all];let byName=[named(LINT_FIXERS),named(FORMAT_FIXERS)].filter((step)=>step!==void 0);if(byName.length>0)return byName;let text=await read(dir,"package.json"),scripts=text===void 0?{}:JSON.parse(text).scripts??{};return found.filter((step)=>step.source==="package.json"&&typeof scripts[step.name]==="string"&&WRITING_FIXER.test(scripts[step.name]))}async function toolFixers(dir){let fixers=[],makefile=await firstFile(dir,MAKEFILES),justfile=await firstFile(dir,JUSTFILES),ruff=await firstFile(dir,RUFF_CONFIGS2)!==void 0||RUFF_SECTION2.test(await read(dir,"pyproject.toml")??"");if(makefile!==void 0)fixers.push({name:"makefile",command:"declare every target .PHONY",source:makefile,write:async(cwd)=>{let path=join5(cwd,makefile),current=await Bun.file(path).text(),{content,targets}=declarePhony(current,(name)=>existsSync3(join5(cwd,name)));if(content!==current)await replaceFile(path,content);return`.PHONY: ${targets.join(" ")}`}});if(justfile!==void 0)fixers.push({name:"justfile",command:`just --justfile ${justfile} --fmt`,source:justfile,requires:"just"});if(await Bun.file(join5(dir,"go.mod")).exists())fixers.push({name:"go",command:"go fmt ./... && go mod tidy",source:"go.mod",requires:"go"});if(await Bun.file(join5(dir,"Cargo.toml")).exists())fixers.push({name:"rust",command:"cargo fmt",source:"Cargo.toml",requires:"cargo"});if(ruff)fixers.push({name:"python",command:"ruff check --fix . && ruff format .",source:"ruff",requires:"ruff"});return fixers}async function fixers(dir){let project=await projectFixers(dir),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),php=csFixer===void 0||project.some((fixer)=>fixer.source==="composer.json")?[]:[{name:"php-cs-fixer",command:"vendor/bin/php-cs-fixer fix",source:csFixer}],discovered=[...project,...php,...await toolFixers(dir)],overrides=(await loadCheckConfig(dir))?.fixers;if(overrides===void 0)return discovered;let result=[],seen=new Set;for(let fixer of discovered)if(seen.add(fixer.name),fixer.name in overrides){let custom=overrides[fixer.name];if(typeof custom==="string"&&custom!=="")result.push({name:fixer.name,command:custom,source:".checkrc.json"})}else result.push(fixer);for(let[name,command]of Object.entries(overrides))if(!seen.has(name)&&typeof command==="string"&&command!=="")result.push({name,command,source:".checkrc.json"});return result}async function discoverFixerProjects(dir,targets){if(targets!==void 0&&targets.length>0){let projects=[];for(let target of resolveTargetDirs(dir,targets)){let found=await fixers(target.dir);if(found.length===0)fail(`nothing to fix in ${target.name??"."}`);projects.push({...target,fixers:found})}return projects}let own=await fixers(dir);if(own.length>0)return[{dir,fixers:own}];let projects=[];for(let sub of discoverableSubdirs(dir)){let found=await fixers(join5(dir,sub));if(found.length>0)projects.push({name:sub,dir:join5(dir,sub),fixers:found})}return projects}function runsInService(fixer){return fixer.write===void 0&&fixer.requires===void 0}async function runFixer(fixer,placement,cwd,logFile,settings){if(fixer.write===void 0&&placement!==void 0)return runStep(shellIn(placement,fixer.command,{[RUNNING]:"1"}),cwd,logFile,{...settings,env:{[RUNNING]:"1"}});if(fixer.write===void 0)return runStep(fixer.command,cwd,logFile,{...settings,env:{[RUNNING]:"1"}});let started=Date.now(),outcome;try{outcome={ok:!0,ms:0,output:await fixer.write(cwd)}}catch(error){outcome={ok:!1,ms:0,output:error instanceof Error?error.message:String(error)}}return await writeFile2(logFile,outcome.output,{mode:384,flag:"wx"}),{...outcome,ms:Date.now()-started}}function printChanged(changed){if(changed.length===0){console.log("nothing changed");return}console.log(`changed ${changed.length} file${changed.length===1?"":"s"}:`);for(let path of changed.slice(0,MAX_CHANGED))console.log(` ${path}`);if(changed.length>MAX_CHANGED)console.log(` and ${changed.length-MAX_CHANGED} more`)}async function runFixers(values,cwd,targets=[],rootConfig){let settings=placeSettings(values);if(process2.env[RUNNING]!==void 0)fail("a fixer called check --fix again, which would recurse: give its script another command");let projects=await discoverFixerProjects(cwd,targets),found=projects.flatMap((project)=>project.fixers.map((fixer)=>({...fixer,dir:project.dir,label:project.name===void 0?fixer.name:`${project.name}/${fixer.name}`})));if(found.length===0)fail("nothing to fix here: no fix, lint:fix, fmt or format script (nor one running prettier --write, biome --write or eslint --fix), php-cs-fixer config, Makefile, Justfile, go.mod, Cargo.toml nor ruff config");let singleConfig=projects.length===1&&projects[0].dir!==cwd?await loadCheckConfig(projects[0].dir):void 0,timeoutRaw=values.timeout??singleConfig?.timeout??rootConfig?.timeout,timeoutMs=timeoutRaw===void 0?void 0:duration(timeoutRaw,"timeout",0),pickedAll=pick(found,values.only,"fixer"),picked=values.changed===!0?await narrowFixers(pickedAll,values.base,rootConfig?.base):pickedAll;if(picked.length===0){if(values.json===!0)printJson(values.list===!0?[]:{fixers:[],changed:[]});else console.log("nothing changed to fix");return 0}let placements=new Map;for(let fixer of picked)placements.set(fixer,runsInService(fixer)?await place(fixer.dir,programOf(fixer.command),settings):void 0);let json=values.json===!0,missing=(fixer)=>fixer.requires!==void 0&&Bun.which(fixer.requires)===null;if(values.list===!0){if(json)printJson(picked.map((fixer)=>({name:fixer.label,command:fixer.command,source:fixer.source,...placements.get(fixer)===void 0?{}:{in:placements.get(fixer)?.service},...missing(fixer)?{needs:fixer.requires}:{}})));else console.log(table(picked.map((fixer)=>[fixer.label,fixer.command,missing(fixer)?`${fixer.source}, needs ${fixer.requires}`:fixer.source,placements.get(fixer)?.service??"host"])));return 0}let directory=await logDirectory(cwd),held=holdSignals(),runSettings={...timeoutMs===void 0?{}:{timeoutMs},held},stack=new Stack,width=Math.max(...picked.map((fixer)=>fixer.label.length)),fallbackGitRoot=projects.length===1?projects[0].dir:cwd,gitRoot=await dirtyFiles(cwd)!==void 0?cwd:fallbackGitRoot,before=await dirtyFiles(gitRoot),ran=[],failed=0,timedOut=!1;try{for(let fixer of picked){if(held.signal!==void 0)break;if(missing(fixer)){if(!json)console.log(`${paint(process2.stdout).yellow("skip ")} ${fixer.label.padEnd(width)} ${fixer.requires} is not installed`);ran.push({name:fixer.label,command:fixer.command,skipped:`${fixer.requires} is not installed`});continue}let logFile=join5(directory,`fix-${fixer.label.replaceAll(/[/:]/g,"-")}.log`),placement=placements.get(fixer),down=placement===void 0?void 0:await stack.problem(placement),outcome=down===void 0?await runFixer(fixer,placement,fixer.dir,logFile,runSettings):await refusedStep(down,logFile),entry=outcomeJson(fixer.label,fixer.command,logFile,outcome,placement?.service,fixer.dir);if(!json)printOutcome(fixer.label,width,placement===void 0?fixer.command:`${fixer.command} (in ${placement.service})`,logFile,outcome,fixer.dir,entry.failed);if(ran.push(entry),outcome.timedOut===!0)timedOut=!0;if(!outcome.ok)failed++}}finally{held.release()}let after=before&&await dirtyFiles(gitRoot),changed=before!==void 0&&after!==void 0?changedFiles(before,after):null;if(json)printJson({fixers:ran,changed});else if(changed!==null)printChanged(changed);if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(timedOut)return 2;return failed===0?0:1}var usage=`check [path|workspace...] [--only <steps>] [--changed [--base <ref>]] [--failed] [--fail-fast] [--retry <n>] [--watch] [--quiet] [--timeout <duration>] [--slot | --no-slot] [--lock <name>] [--parallel | --no-parallel] [--in <service> | --host] [--list]
7
+ `))}import{existsSync,readFileSync}from"fs";import{basename as basename2,join as join2,relative as relative2,resolve}from"path";var STEP_NAMES=["check","typecheck","lint","fmt","test"],STEP_SOURCES={fmt:["fmt:check","format:check","fmt-check","format-check"]},CHECKRC_FILES=[".checkrc.jsonc",".checkrc.json"],TASK_RUNNERS=new Set(["Justfile","Makefile","Taskfile","mise"]),CS_FIXER_CONFIGS=[".php-cs-fixer.php",".php-cs-fixer.dist.php"],PHPSTAN_CONFIGS=["phpstan.neon","phpstan.neon.dist","phpstan.dist.neon"],PHPUNIT_CONFIGS=["phpunit.xml","phpunit.xml.dist","phpunit.dist.xml"],RUFF_CONFIGS=["ruff.toml",".ruff.toml"],PYTEST_CONFIGS=["pytest.ini","conftest.py"],MYPY_CONFIGS=["mypy.ini",".mypy.ini"],RUFF_SECTION=/^\[tool\.ruff/m,PYTEST_SECTION2=/^\[tool\.pytest/m,MYPY_SECTION=/^\[tool\.mypy/m;async function readFirst(dir,files){for(let file of files){let handle=Bun.file(join2(dir,file));if(await handle.exists())return{file,text:await handle.text()}}return}async function read(dir,...files){for(let file of files){let handle=Bun.file(join2(dir,file));if(await handle.exists())return handle.text()}return}async function loadCheckConfig(dir){let found=await readFirst(dir,CHECKRC_FILES);if(found===void 0)return;try{let parsed=Bun.JSONC.parse(found.text);if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))fail(`${found.file} must be a JSON object`);return parsed}catch(error){fail(`${found.file} is not valid JSONC: ${error instanceof Error?error.message:String(error)}`)}}function callsSelf(value,bin){return typeof value==="string"&&(value===bin||value.startsWith(`${bin} `)||value.startsWith(`${bin} `))}function readJsonOrFail(file,reader){try{return reader()}catch{fail(`${file} is not valid JSON`)}}function readOptional(reader){try{return reader()}catch{return}}async function candidates(dir,bin,includeNative=!1){let steps=[],pkg=readJsonOrFail("package.json",()=>readPackageManifest(dir,!1));if(pkg!==void 0){for(let script of pkg.scripts)if(!callsSelf(script.raw,bin))steps.push({name:script.name,command:`${pkg.tool} run ${script.name}`,source:"package.json"})}let composer=readJsonOrFail("composer.json",()=>readComposerManifest(dir,!1));if(composer!==void 0)for(let script of composer.scripts)steps.push({name:script.name,command:`composer run ${script.name}`,source:"composer.json"});let deno=readOptional(()=>readDenoManifest(dir,!1));if(deno!==void 0)for(let task of deno.tasks)steps.push({name:task.name,command:`deno task ${task.name}`,source:deno.filename});let just=readJustManifest(dir,!1,!0);if(just!==void 0){for(let recipe of just.recipes)if(recipe.parameters.every((parameter)=>parameter.default!==null||parameter.kind==="star"))steps.push({name:recipe.name,command:`just ${recipe.name}`,source:"Justfile"})}let makefile=readOptional(()=>readMakefileManifest(dir));if(makefile!==void 0)for(let target of makefile.targets)steps.push({name:target.name,command:`make ${target.name}`,source:"Makefile"});let taskfile=readOptional(()=>readTaskfileManifest(dir,!1));if(taskfile!==void 0)for(let task of taskfile.tasks)steps.push({name:task.name,command:`task ${task.name}`,source:"Taskfile"});for(let task of readMiseManifest(dir,!1))steps.push({name:task.name,command:`mise run ${task.name}`,source:"mise"});let pyproject=readOptional(()=>readPyprojectManifest(dir,!1));if(pyproject!==void 0){let runner=pyproject.uv?"uv run poe":"poe";for(let task of pyproject.poe)steps.push({name:task.name,command:`${runner} ${task.name}`,source:"pyproject.toml"})}if(steps.push(...await phpSteps(dir)),includeNative)steps.push(...await nativeSteps(dir,pyproject?.text??await read(dir,"pyproject.toml")));return steps}async function firstFile(dir,names){for(let name of names)if(await Bun.file(join2(dir,name)).exists())return name;return}async function phpSteps(dir){let steps=[],phpstan=await firstFile(dir,PHPSTAN_CONFIGS),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),phpunit=await firstFile(dir,PHPUNIT_CONFIGS);if(phpstan!==void 0)steps.push({name:"typecheck",command:"vendor/bin/phpstan analyse --no-progress --memory-limit=1G",source:phpstan});if(csFixer!==void 0)steps.push({name:"lint",command:"vendor/bin/php-cs-fixer fix --dry-run -v",source:csFixer});if(phpunit!==void 0)steps.push({name:"test",command:"vendor/bin/phpunit",source:phpunit});return steps}async function nativeSteps(dir,pyprojectText){let steps=[];if(existsSync(join2(dir,"go.mod")))steps.push({name:"lint",command:"go vet ./...",source:"go.mod"}),steps.push({name:"test",command:"go test ./...",source:"go.mod"});if(existsSync(join2(dir,"Cargo.toml")))steps.push({name:"check",command:"cargo check",source:"Cargo.toml"}),steps.push({name:"lint",command:"cargo clippy",source:"Cargo.toml"}),steps.push({name:"fmt:check",command:"cargo fmt -- --check",source:"Cargo.toml"}),steps.push({name:"test",command:"cargo test",source:"Cargo.toml"});let pyPrefix=locate(dir,!0,["uv.lock"])!==void 0?"uv run ":"",ruffFile=await firstFile(dir,RUFF_CONFIGS),hasRuff=ruffFile!==void 0||pyprojectText!==void 0&&RUFF_SECTION.test(pyprojectText),hasMypy=await firstFile(dir,MYPY_CONFIGS)!==void 0||pyprojectText!==void 0&&MYPY_SECTION.test(pyprojectText),hasPytest=await firstFile(dir,PYTEST_CONFIGS)!==void 0||pyprojectText!==void 0&&PYTEST_SECTION2.test(pyprojectText);if(hasMypy)steps.push({name:"typecheck",command:`${pyPrefix}mypy .`,source:"mypy"});if(hasRuff){let source=ruffFile??"pyproject.toml";steps.push({name:"lint",command:`${pyPrefix}ruff check .`,source}),steps.push({name:"fmt:check",command:`${pyPrefix}ruff format --check .`,source})}if(hasPytest)steps.push({name:"test",command:`${pyPrefix}pytest`,source:"pytest"});return steps}function packageNameOf(dir){let file=join2(dir,"package.json");if(!existsSync(file))return;try{let parsed=JSON.parse(readFileSync(file,"utf8"));return typeof parsed.name==="string"?parsed.name:void 0}catch{return}}function resolveTargetDirs(dir,targets){let known=folders(dir),resolved=[],seen=new Set;for(let target of targets){let direct=resolve(dir,target),matchedDir;if(existsSync(direct))matchedDir=direct;else{let hit=known.find((sub)=>sub===target||basename2(sub)===target||packageNameOf(join2(dir,sub))===target);if(hit!==void 0)matchedDir=join2(dir,hit)}if(matchedDir===void 0)fail(`no path or workspace matching ${target}`);if(seen.has(matchedDir))continue;seen.add(matchedDir);let rel=relative2(dir,matchedDir);resolved.push({...rel===""?{}:{name:rel},dir:matchedDir})}return resolved}function discoverableSubdirs(dir){let direct=children(dir,["var","tmp"]);return[...new Set([...direct,...workspaces(dir)])].filter((name)=>name!==".").toSorted((a,b)=>a.localeCompare(b))}async function resolveTargets(dir,targets){let projects=[];for(let target of resolveTargetDirs(dir,targets)){let steps=await discover(target.dir);if(steps.length===0)fail(`no check steps found in ${target.name??"."}`);projects.push({...target,steps})}return projects}async function discoverProjects(dir,targets){if(targets!==void 0&&targets.length>0)return resolveTargets(dir,targets);let own=await discover(dir);if(own.length>0)return[{dir,steps:own}];let projects=[];for(let sub of discoverableSubdirs(dir)){let steps=await discover(join2(dir,sub));if(steps.length>0)projects.push({name:sub,dir:join2(dir,sub),steps})}return projects}async function discover(dir){let found=await candidates(dir,"check",!0),overrides=(await loadCheckConfig(dir))?.steps??{},runnerCheck=found.find((candidate)=>candidate.name==="check"&&TASK_RUNNERS.has(candidate.source)),base=STEP_NAMES.flatMap((name)=>{if(name in overrides){let custom=overrides[name];return custom===null||custom===void 0?[]:[{name,command:custom,source:".checkrc.json"}]}let step=name==="check"&&runnerCheck!==void 0?runnerCheck:(STEP_SOURCES[name]??[name]).map((each)=>found.find((candidate)=>candidate.name===each)).find((each)=>each!==void 0);return step===void 0?[]:[{...step,name}]});for(let[name,command]of Object.entries(overrides))if(!STEP_NAMES.includes(name)&&typeof command==="string"&&command!=="")base.push({name,command,source:".checkrc.json"});return base}var THRESHOLD_NUMBER=/^\d+(?:\.\d+)?$/,WRAPPER_PREFIX=/^(?:(?:bunx|npx|pnpm\s+exec|yarn|uv\s+run)\s+)+/,HAS_COVERAGE_FLAG=/(?:^|\s)(?:--coverage|--cov\b|--collectCoverage|-cover\b)/,BUN_TEST_RUNNER=/^(?:bun test|\$npm_execpath test)\b/,VITEST_RUNNER=/^vitest\b/,VITEST_RUN_SUBCMD=/\brun\b|--run\b/,JEST_RUNNER=/^jest\b/,PYTEST_RUNNER=/^pytest\b/,PIPE_SEPARATOR=/^[-|]+$/,PERCENT_VALUE=/^(\d+(?:\.\d+)?)%?$/,HEADER_FILE=/^file$/i,HEADER_LINES=/^%?\s*lines$/i,HEADER_FUNCS=/^%?\s*funcs?$/i,HEADER_STMTS=/^%?\s*stmts?$/i,HEADER_BRANCH=/^%?\s*branch(?:es)?$/i,HEADER_UNCOVERED=/^uncovered/i,PYTEST_HEADER=/^\s*Name\s+Stmts\s+Miss(?:\s+Branch\s+BrPart)?\s+Cover(?:\s+Missing)?\s*$/,PYTEST_BRANCH_COL=/\bBranch\b/,PYTEST_SEPARATOR=/^-{3,}\s*$/,PYTEST_SKIPPED=/^\d+\s+files?\s+skipped\b/i,PYTEST_COLS=/[ \t]+\d+[ \t]+\d+[ \t]+(\d+(?:\.\d+)?)%(?:[ \t]+(\S.*))?$/,PYTEST_BRANCH_COLS=/[ \t]+\d+[ \t]+\d+[ \t]+\d+[ \t]+\d+[ \t]+(\d+(?:\.\d+)?)%(?:[ \t]+(\S.*))?$/;function parseThreshold(raw){let trimmed=raw.trim();if(!THRESHOLD_NUMBER.test(trimmed))badUsage(`--coverage takes a percentage between 0 and 100, not ${raw}`);let value=Number(trimmed);if(!Number.isFinite(value)||value<0||value>100)badUsage(`--coverage takes a percentage between 0 and 100, not ${raw}`);return value}async function scriptText(dir,name){let text=await read(dir,"package.json");if(text===void 0)return;try{let value=JSON.parse(text).scripts?.[name];return typeof value==="string"?value:void 0}catch{return}}function appendFlags(command,flags,isScript){if(!isScript)return`${command} ${flags}`;return command.includes(" -- ")?`${command} ${flags}`:`${command} -- ${flags}`}async function withCoverageCommand(step,dir){let isScript=step.source==="package.json",effective=(isScript?(await scriptText(dir,step.name))?.trim():void 0)??step.command.trim();if(HAS_COVERAGE_FLAG.test(effective)||HAS_COVERAGE_FLAG.test(step.command))return{command:step.command};let unwrapped=effective.replace(WRAPPER_PREFIX,"");if(BUN_TEST_RUNNER.test(unwrapped))return{command:appendFlags(step.command,"--coverage",isScript),note:"coverage"};if(VITEST_RUNNER.test(unwrapped)){let flags=VITEST_RUN_SUBCMD.test(unwrapped)?"--coverage":"--run --coverage";return{command:appendFlags(step.command,flags,isScript),note:"coverage"}}if(JEST_RUNNER.test(unwrapped))return{command:appendFlags(step.command,"--coverage",isScript),note:"coverage"};if(PYTEST_RUNNER.test(unwrapped))return{command:appendFlags(step.command,"--cov",isScript),note:"coverage"};return{command:step.command}}function parsePercent(cell){if(cell===void 0)return;let match=PERCENT_VALUE.exec(cell.trim());return match===null?void 0:Number(match[1])}function parsePipeTable(lines){for(let i=0;i<lines.length-1;i++){let headerLine=lines[i]??"";if(!headerLine.includes("|"))continue;let nextLine=(lines[i+1]??"").trim();if(!PIPE_SEPARATOR.test(nextLine)||!nextLine.includes("|")||!nextLine.includes("---"))continue;let headers=headerLine.split("|").map((cell)=>cell.trim()),fileIdx=headers.findIndex((cell)=>HEADER_FILE.test(cell)),linesIdx=headers.findIndex((cell)=>HEADER_LINES.test(cell));if(fileIdx===-1||linesIdx===-1)continue;let funcsIdx=headers.findIndex((cell)=>HEADER_FUNCS.test(cell)),stmtsIdx=headers.findIndex((cell)=>HEADER_STMTS.test(cell)),branchIdx=headers.findIndex((cell)=>HEADER_BRANCH.test(cell)),uncoveredIdx=headers.findIndex((cell)=>HEADER_UNCOVERED.test(cell)),format=stmtsIdx!==-1||branchIdx!==-1?"istanbul":"bun",rawRows=[];for(let j=i+2;j<lines.length;j++){let line=lines[j]??"",trimmed=line.trim();if(trimmed===""||PIPE_SEPARATOR.test(trimmed)&&trimmed.includes("|")&&trimmed.includes("---"))break;if(!line.includes("|"))break;let cells=line.split("|"),rawFile=cells[fileIdx]??"",name=rawFile.trim(),linePct=parsePercent(cells[linesIdx]);if(name===""||linePct===void 0)continue;let indent=rawFile.length-rawFile.trimStart().length,funcs=funcsIdx===-1?void 0:parsePercent(cells[funcsIdx]),stmts=stmtsIdx===-1?void 0:parsePercent(cells[stmtsIdx]),branch=branchIdx===-1?void 0:parsePercent(cells[branchIdx]),uncovered=uncoveredIdx===-1?void 0:(cells[uncoveredIdx]??"").trim();rawRows.push({indent,name,lines:linePct,...funcs===void 0?{}:{functions:funcs},...stmts===void 0?{}:{statements:stmts},...branch===void 0?{}:{branches:branch},...uncovered===void 0||uncovered===""?{}:{uncovered}})}if(rawRows.length===0)continue;let allIdx=rawRows.findIndex((row)=>row.name.toLowerCase()==="all files"),allRow=allIdx===-1?void 0:rawRows[allIdx],body=rawRows.filter((_row,index)=>index!==allIdx),files=[],currentDir;for(let k=0;k<body.length;k++){let row=body[k],next=body[k+1];if(row.indent===1&&next!==void 0&&next.indent>row.indent){currentDir=row.name;continue}if(row.indent<=1)currentDir=void 0;let filePath=row.indent>=2&&currentDir!==void 0?`${currentDir}/${row.name}`:row.name;files.push({file:filePath,lines:row.lines,...row.functions===void 0?{}:{functions:row.functions},...row.statements===void 0?{}:{statements:row.statements},...row.branches===void 0?{}:{branches:row.branches},...row.uncovered===void 0?{}:{uncovered:row.uncovered}})}let overall;if(allRow!==void 0)overall={lines:allRow.lines,...allRow.functions===void 0?{}:{functions:allRow.functions},...allRow.statements===void 0?{}:{statements:allRow.statements},...allRow.branches===void 0?{}:{branches:allRow.branches}};else overall={lines:files.length===0?0:Math.round(files.reduce((sum,file)=>sum+file.lines,0)/files.length*100)/100};return{format,overall,files}}return}function parsePytestTable(lines){for(let i=0;i<lines.length-1;i++){let headerLine=lines[i]??"";if(!PYTEST_HEADER.test(headerLine))continue;if(!PYTEST_SEPARATOR.test((lines[i+1]??"").trim()))continue;let colsPattern=PYTEST_BRANCH_COL.test(headerLine)?PYTEST_BRANCH_COLS:PYTEST_COLS,files=[],overall;for(let j=i+2;j<lines.length;j++){let trimmed=(lines[j]??"").trim();if(trimmed==="")break;if(PYTEST_SEPARATOR.test(trimmed)||PYTEST_SKIPPED.test(trimmed))continue;let match=colsPattern.exec(trimmed);if(match===null)break;let name=trimmed.slice(0,match.index).trim();if(name==="")break;let cover=Number(match[1]),missing=(match[2]??"").trim();if(name==="TOTAL"){overall={lines:cover};break}files.push({file:name,lines:cover,...missing===""?{}:{uncovered:missing}})}if(overall!==void 0)return{format:"pytest",overall,files};if(files.length>0)return{format:"pytest",overall:{lines:Math.round(files.reduce((sum,file)=>sum+file.lines,0)/files.length*100)/100},files}}return}function parseCoverage(output){let lines=stripAnsi(output).split(`
8
+ `);return parsePipeTable(lines)??parsePytestTable(lines)}function isBelowThreshold(metrics,threshold){return metrics.lines<threshold||metrics.functions!==void 0&&metrics.functions<threshold}function evaluateCoverage(report,threshold){let below=report.files.filter((file)=>isBelowThreshold(file,threshold));return{ok:!isBelowThreshold(report.overall,threshold)&&below.length===0,below}}function formatPct(value){return`${value.toFixed(1)}%`}function formatCoverageDetails(report,threshold,below){let colors=paint(process2.stdout),overallText=[`${formatPct(report.overall.lines)} lines`,...report.overall.functions===void 0?[]:[`${formatPct(report.overall.functions)} funcs`]].join(" \xB7 "),fileCount=`${report.files.length} ${report.files.length===1?"file":"files"}`;if(!isBelowThreshold(report.overall,threshold)&&below.length===0)return` ${colors.dim("coverage")} ${colors.green(overallText)} ${colors.dim(`(threshold ${threshold}%, ${fileCount} \u2014 all above threshold)`)}`;let reason=below.length===0?"below threshold":`${below.length} of ${fileCount} below`,lead=` ${colors.dim("coverage")} ${colors.red(overallText)} ${colors.dim(`(threshold ${threshold}%, ${reason})`)}`;if(below.length===0)return lead;let showFuncs=below.some((file)=>file.functions!==void 0),showUncovered=below.some((file)=>file.uncovered!==void 0&&file.uncovered!==""),headerRow=["File","Lines",...showFuncs?["Funcs"]:[],...showUncovered?["Uncovered"]:[]],align=["left","right",...showFuncs?["right"]:[],...showUncovered?["left"]:[]],formatCell=(value)=>{if(value===void 0)return"-";return value<threshold?colors.red(formatPct(value)):formatPct(value)},rows=below.map((file)=>[file.file,formatCell(file.lines),...showFuncs?[formatCell(file.functions)]:[],...showUncovered?[colors.dim(file.uncovered??"")]:[]]),rendered=table([headerRow,...rows],{header:!0,align});return`${lead}
9
+ ${rendered.split(`
10
+ `).map((line)=>` ${line}`.trimEnd()).join(`
11
+ `)}`}async function runCoverage(config,held){let{cwd,steps,threshold,slotting,lock,timeoutMs,parallel,json,quiet}=config,directory=await logDirectory(cwd),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),heading=json||quiet?"":header("check",`${basename3(cwd)} \xB7 coverage >= ${threshold}% \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process2.stdout);if(heading!=="")console.log(heading);let execute=async(step,signals)=>{let down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step),lock):launch(step),logFile=join3(directory,`${step.label.replaceAll("/","-")}.log`),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile);return{step,logFile,outcome}},reports=[],reportStep=({step,logFile,outcome})=>{let base=outcomeJson(step.label,step.command,logFile,outcome,step.placement?.service,step.dir),parsed=parseCoverage(outcome.output),evaluated=parsed===void 0?void 0:evaluateCoverage(parsed,threshold),coverageOk=evaluated!==void 0&&evaluated.ok,ok=outcome.ok&&coverageOk,entry={name:base.name,command:base.command,...base.in===void 0?{}:{in:base.in},ok,testsOk:outcome.ok,coverageOk,ms:base.ms,log:base.log,...base.timedOut===!0?{timedOut:!0}:{},...base.failed===void 0?{}:{failed:base.failed},...base.errors===void 0?{}:{errors:base.errors},...base.unrecognised===void 0?{}:{unrecognised:base.unrecognised},coverage:parsed===void 0||evaluated===void 0?null:{...parsed,below:evaluated.below}};if(reports.push(entry),json||quiet&&ok)return;let colors=paint(process2.stdout),path=role("path",process2.stdout),took=colors.dim(formatDuration(outcome.ms)),notes=[step.note,step.placement===void 0?void 0:`in ${step.placement.service}`].filter((each)=>each!==void 0),described=notes.length===0?step.command:`${step.command} (${notes.join(", ")})`;if(ok)console.log(`${colors.bold(colors.green("ok "))} ${step.label.padEnd(width)} ${took} ${path(logFile)}`);else{let label=outcome.timedOut===!0?colors.bold(colors.yellow("TIME ")):colors.bold(colors.red("FAIL "));if(console.log(`${label} ${step.label.padEnd(width)} ${took} ${colors.dim(described)} ${path(logFile)}`),outcome.timedOut===!0)console.log(colors.yellow(` timed out after ${formatDuration(outcome.ms)}, the step and what it started were ended`));if(!outcome.ok&&base.failed!==void 0)console.log(base.failed.split(`
12
+ `).map((line)=>` ${line}`.trimEnd()).join(`
13
+ `))}if(parsed!==void 0&&evaluated!==void 0)console.log(formatCoverageDetails(parsed,threshold,evaluated.below));else if(outcome.ok)console.log(` ${colors.red("no coverage report found in output")}`)};if(parallel&&steps.length>1){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});let tasks=steps.map(async(step)=>execute(step,shared));for(let task of tasks)reportStep(await task)}else for(let step of steps)if(reportStep(await execute(step,held)),held.signal!==void 0)break;await saveResults(cwd,directory,reports.map(({name,ok})=>({name,ok})));let allOk=reports.every((report)=>report.ok),anyTimedOut=reports.some((report)=>report.timedOut===!0);if(json)printJson({threshold,ok:allOk,steps:reports});if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(anyTimedOut)return 2;return allOk?0:1}import{existsSync as existsSync3,statSync}from"fs";import{rename,writeFile as writeFile2}from"fs/promises";import{extname as extname2,join as join6}from"path";import process3 from"process";import{stat as stat2}from"fs/promises";import{join as join4}from"path";var{$}=globalThis.Bun;async function dirtyFiles(dir){let listed=await $`git ls-files -z --modified --others --exclude-standard`.cwd(dir).quiet().nothrow();if(listed.exitCode!==0)return;let files=new Map;for(let path of listed.stdout.toString().split("\x00").filter(Boolean))try{let{size,mtimeMs}=await stat2(join4(dir,path));files.set(path,`${size}:${mtimeMs}`)}catch{files.set(path,"")}return files}function changedFiles(before,after){return[...after].filter(([path,hash])=>before.get(path)!==hash).map(([path])=>path)}import{existsSync as existsSync2,readFileSync as readFileSync2}from"fs";import{basename as basename4,dirname,extname,join as join5,resolve as resolve2}from"path";var{$:$2}=globalThis.Bun;var WRAPPER_PREFIX2=/^(?:(?:bunx|npx|pnpm\s+exec|yarn|uv\s+run)\s+)+/,LINTERS=/^(?:keslint|eslint|oxlint|biome\s+check|biome\s+lint)\b/,LINTABLE=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PYTHON_EXT=new Set([".py",".pyi"]),TEST_RUNNER=/^(?:bun test|\$npm_execpath test)\b/,VITEST_RUNNER2=/^vitest(?:\s+run)?\b/,PYTEST_RUNNER2=/^pytest\b/,RUFF_CHECK=/^ruff\s+check\b/,RUFF_FORMAT=/^ruff\s+format\b/,GO_TEST=/^go\s+test\s+\.\.\.\/?$|^go\s+test\s+\.\/\.\.\./,TRAILING_DOT=/\s+\.\/?$/,TEST_FILE=/\.(?:test|spec)\.[jt]sx?$/,PY_TEST_FILE=/(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/,IMPORT_SPEC=/(?:from|import)\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\)/g,WHITESPACE=/\s+/;async function changedPaths(dir,base="HEAD"){let tracked=await $2`git diff --name-only --relative -z ${base}`.cwd(dir).quiet().nothrow(),untracked=await $2`git ls-files -z --others --exclude-standard`.cwd(dir).quiet().nothrow();if(tracked.exitCode!==0||untracked.exitCode!==0)return;return[...new Set([...tracked.stdout.toString().split("\x00"),...untracked.stdout.toString().split("\x00")])].filter((path)=>path!==""&&existsSync2(join5(dir,path)))}function siblingTests(path,exists){let extension=extname(path),name=basename4(path,extension),dir=dirname(path),folders=[dir,join5(dir,"tests"),join5(dir,"..","tests"),join5(dir,"__tests__")],found=new Set;for(let folder of folders)for(let kind of["test","spec"])for(let candidate of[`${name}.${kind}${extension}`,`${name}.${kind}.ts`].map((file)=>join5(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function siblingPyTests(path,exists){let extension=extname(path),name=basename4(path,extension),dir=dirname(path),folders=[dir,join5(dir,"tests"),join5(dir,"..","tests"),"tests"],found=new Set;for(let folder of folders)for(let candidate of[`test_${name}.py`,`${name}_test.py`].map((file)=>join5(folder,file)))if(exists(candidate))found.add(candidate);return[...found]}function reverseImportTests(dir,changedSources){if(changedSources.length===0)return[];let targets=new Set(changedSources.map((file)=>{let abs=resolve2(dir,file),ext=extname(abs);return ext===""?abs:abs.slice(0,-ext.length)})),found=new Set,glob=new Bun.Glob("**/*.{test,spec}.{ts,tsx,js,jsx}");for(let testFile of glob.scanSync({cwd:dir})){if(testFile.split("/").includes("node_modules")||testFile.startsWith(".git/"))continue;let text;try{text=readFileSync2(join5(dir,testFile),"utf8")}catch{continue}let testDir=dirname(resolve2(dir,testFile));for(let match of text.matchAll(IMPORT_SPEC)){let specifier=match[1]??match[2]??"";if(!specifier.startsWith("."))continue;let imported=resolve2(testDir,specifier),ext=extname(imported),stem=ext===""?imported:imported.slice(0,-ext.length);if(targets.has(stem)||targets.has(join5(stem,"index"))){found.add(testFile);break}}}return[...found]}function isBare(script,tool,allowDot=!1){let unwrapped=script.trim().replace(WRAPPER_PREFIX2,"");if(!tool.test(unwrapped))return!1;let rest=unwrapped.replace(tool,"").trim();if(rest==="")return!0;return rest.split(WHITESPACE).every((word)=>word===""||word.startsWith("-")||allowDot&&(word==="."||word==="./"))}function stripTrailingDot(command){return command.replace(TRAILING_DOT,"")}function jsTestFiles(dir,changed){let tests=new Set,nonTests=[];for(let path of changed)if(TEST_FILE.test(path))tests.add(path);else{if(LINTABLE.has(extname(path)))nonTests.push(path);for(let test of siblingTests(path,(candidate)=>existsSync2(join5(dir,candidate))))tests.add(test)}for(let imported of reverseImportTests(dir,nonTests))tests.add(imported);return[...tests]}async function narrow(step,dir,changed){let script=step.source==="package.json"?(await scriptText2(dir,step.name))?.trim():void 0,effective=script??step.command.trim(),full=(why)=>({command:step.command,note:`in full, ${why}`});if(script!==void 0&&step.name==="lint"&&isBare(script,LINTERS,!0)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return{command:"true",note:"nothing changed to lint"};return{command:TRAILING_DOT.test(script)?`${stripTrailingDot(script)} ${files.map(shellQuote).join(" ")}`:`${step.command} -- ${files.map(shellQuote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="lint"&&isBare(effective,RUFF_CHECK,!0)||step.name==="fmt"&&isBare(effective,RUFF_FORMAT,!0)){let files=changed.filter((path)=>PYTHON_EXT.has(extname(path)));if(files.length===0)return{command:"true",note:`nothing changed to ${step.name}`};return{command:`${stripTrailingDot(effective)} ${files.map(shellQuote).join(" ")}`,note:`${files.length} changed file${files.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,VITEST_RUNNER2)){let files=changed.filter((path)=>LINTABLE.has(extname(path)));if(files.length===0)return full("no JS/TS file changed");return{command:`${step.command} -- --related ${files.map(shellQuote).join(" ")}`,note:`${files.length} related file${files.length===1?"":"s"}`}}if(script!==void 0&&step.name==="test"&&isBare(script,TEST_RUNNER)){let tests=jsTestFiles(dir,changed);if(tests.length===0)return full("no test sits next to the changed files");return{command:`${step.command} -- ${tests.map((test)=>shellQuote(`./${test}`)).join(" ")}`,note:`${tests.length} test file${tests.length===1?"":"s"}`}}if(step.name==="test"&&isBare(effective,PYTEST_RUNNER2,!0)){let tests=new Set;for(let path of changed)if(PY_TEST_FILE.test(path))tests.add(path);else if(PYTHON_EXT.has(extname(path)))for(let test of siblingPyTests(path,(candidate)=>existsSync2(join5(dir,candidate))))tests.add(test);if(tests.size===0)return full("no test sits next to the changed files");return{command:`${stripTrailingDot(effective)} ${[...tests].map(shellQuote).join(" ")}`,note:`${tests.size} test file${tests.size===1?"":"s"}`}}if(step.name==="test"&&GO_TEST.test(effective)){let pkgs=[...new Set(changed.filter((path)=>extname(path)===".go").map((path)=>{let folder=dirname(path);return folder==="."?".":`./${folder}`}))];if(pkgs.length===0)return{command:"true",note:"no Go files changed"};return{command:`go test ${pkgs.map(shellQuote).join(" ")}`,note:`${pkgs.length} Go package${pkgs.length===1?"":"s"}`}}return full(`${step.name} cannot be narrowed`)}async function scriptText2(dir,name){let text=await read(dir,"package.json");if(text===void 0)return;try{let value=JSON.parse(text).scripts?.[name];return typeof value==="string"?value:void 0}catch{return}}var COVERAGE_THRESHOLD=/^\d+(?:\.\d+)?$/,options={list:{type:"boolean",short:"l",description:"print the steps (or, with --fix, the fixers) found, the commands that run them and where (host or service), without running them"},only:{type:"string",short:"o",description:`comma separated steps to run, among ${STEP_NAMES.join(", ")}; with --fix the fixers to run, by the names --list prints`,candidates:()=>[...STEP_NAMES]},timeout:{type:"string",short:"t",description:"longest a step or fixer may run before it is ended (30s, 5m, 1h), none by default"},...placeOptions,json:jsonOption("[{name, command, in?, ok, ms, log, failed?, errors?}], with --list [{name, command, source, in?}], with --fix {fixers, changed}, with --flaky {runs, ok, steps}, with --coverage {threshold, ok, steps}"),fix:{type:"boolean",short:"f",description:"run the folder's fixers and formatters instead of the steps"},quiet:{type:"boolean",short:"q",description:"print nothing for a passing step, and nothing at all when every step passes"},failed:{type:"boolean",description:"run only the steps that failed in the last run of this folder, read from the run folder"},changed:{type:"boolean",short:"c",description:"narrow lint, fmt, fix, and test to files changed against --base (default HEAD), with 1-hop reverse-import test selection"},base:{type:"string",description:"git ref to diff against with --changed (default HEAD)"},"fail-fast":{type:"boolean",short:"x",description:"stop after the first failing step"},retry:{type:"string",description:"retry a failing step up to N times before reporting failure"},flaky:{type:"string",conflicts:["watch","retry","coverage"],description:"run each step N times (>= 2) to detect flaky steps and report pass rate and min/median/max durations"},coverage:{type:"string",optional:{bare:"80",accepts:COVERAGE_THRESHOLD},conflicts:["watch","flaky"],description:"run tests with coverage and report files below the threshold percentage (default 80)"},lock:{type:"string",description:"named slot lock to hold alongside the slot (visible in slot ls); refused without the slot bin"},watch:{type:"boolean",short:"w",description:"watch project files and re-run on changes"},slot:{type:"boolean",description:"run each step through slot, queued behind the machine-wide slots of the other sessions, as it does by default when the slot bin is installed; without the bin it warns and runs unqueued",negative:"run the steps at once, without queueing behind the other sessions' slots"},parallel:{type:"boolean",description:"run the steps at the same time, printing each one's output in step order",negative:"run the steps one at a time, overriding parallel in .checkrc.json"}},COMMA=/\s*,\s*/;function pick(steps,only,noun="step"){if(only===void 0)return steps;let names=only.split(COMMA).filter((name)=>name!=="");if(names.length===0)fail(`--only names no ${noun}, found ${steps.map((step)=>step.label??step.name).join(", ")}`);let matches=(step,wanted)=>step.name===wanted||step.label===wanted,unknown=names.filter((name)=>!steps.some((step)=>matches(step,name)));if(unknown.length>0)fail(`no ${unknown.join(", ")} ${noun} here, found ${[...new Set(steps.map((step)=>step.label??step.name))].join(", ")}`);return steps.filter((step)=>names.some((wanted)=>matches(step,wanted)))}var RUNNING="KAYNOOO_CLI_FIX",RUFF_CONFIGS2=["ruff.toml",".ruff.toml"],RUFF_SECTION2=/^\[tool\.ruff/m,MAX_CHANGED=30,JS_EXTS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".svelte"]),PY_EXTS=new Set([".py",".pyi"]),PHP_EXTS=new Set([".php"]),GO_EXTS=new Set([".go"]),RS_EXTS=new Set([".rs"]),JS_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:keslint|eslint|oxlint|prettier|biome)\b/,TRAILING_DOT2=/\s+\.\/?$/;async function narrowProjectFixers(found,dir,base){let paths=await changedPaths(dir,base);if(paths===void 0)fail("--changed needs a git repository");let result=[],pkgText=await read(dir,"package.json"),scripts=pkgText===void 0?{}:JSON.parse(pkgText).scripts??{};for(let fixer of found){if(fixer.name==="python"){let files=paths.filter((path)=>PY_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`ruff check --fix ${files.map(shellQuote).join(" ")} && ruff format ${files.map(shellQuote).join(" ")}`});continue}if(fixer.name==="php-cs-fixer"){let files=paths.filter((path)=>PHP_EXTS.has(extname2(path)));if(files.length>0)result.push({...fixer,command:`vendor/bin/php-cs-fixer fix ${files.map(shellQuote).join(" ")}`});continue}if(fixer.name==="go"){if(paths.some((path)=>GO_EXTS.has(extname2(path))||path==="go.mod"))result.push(fixer);continue}if(fixer.name==="rust"){if(paths.some((path)=>RS_EXTS.has(extname2(path))||path==="Cargo.toml"))result.push(fixer);continue}if(fixer.name==="makefile"||fixer.name==="justfile"){if(paths.includes(fixer.source))result.push(fixer);continue}if(fixer.source==="package.json"){let script=scripts[fixer.name]?.trim()??"",files=paths.filter((path)=>JS_EXTS.has(extname2(path)));if(JS_FIXER.test(script)){if(files.length>0){let stripped=script.replace(TRAILING_DOT2,"");result.push({...fixer,command:TRAILING_DOT2.test(script)?`${stripped} ${files.map(shellQuote).join(" ")}`:`${fixer.command} -- ${files.map(shellQuote).join(" ")}`})}continue}}result.push(fixer)}return result}async function narrowFixers(found,cliBase,rootBase){let byDir=new Map;for(let fixer of found){let group=byDir.get(fixer.dir)??[];group.push(fixer),byDir.set(fixer.dir,group)}let result=[];for(let[dir,group]of byDir){let projectRc=await loadCheckConfig(dir),base=cliBase??projectRc?.base??rootBase;result.push(...await narrowProjectFixers(group,dir,base))}return result}async function replaceFile(path,content){let temporary=`${path}.${process3.pid}.tmp`;await writeFile2(temporary,content,{mode:statSync(path).mode&511}),await rename(temporary,path)}var LINT_FIXERS=["lint:fix","lint-fix","fix:lint","fix-lint","eslint:fix","eslint-fix","biome:fix","oxlint:fix"],FORMAT_FIXERS=["fmt","format","format:fix","format-fix","fmt:fix","fmt-fix","fix:format","fix:fmt","prettier","biome"],WRITING_FIXER=/^(?:(?:bunx|npx|pnpm\s+exec|yarn)\s+)?(?:(?:keslint|eslint|oxlint)\b.*\s--fix\b|prettier\b.*\s--write\b|biome\s+(?:check|format|lint)\b.*\s--(?:write|apply)\b)/;async function projectFixers(dir){let found=await candidates(dir,"check"),named=(names)=>names.map((name)=>found.find((step)=>step.name===name)).find((step)=>step!==void 0),all=named(["fix"]);if(all!==void 0)return[all];let byName=[named(LINT_FIXERS),named(FORMAT_FIXERS)].filter((step)=>step!==void 0);if(byName.length>0)return byName;let text=await read(dir,"package.json"),scripts=text===void 0?{}:JSON.parse(text).scripts??{};return found.filter((step)=>step.source==="package.json"&&typeof scripts[step.name]==="string"&&WRITING_FIXER.test(scripts[step.name]))}async function toolFixers(dir){let fixers=[],makefile=await firstFile(dir,MAKEFILES),justfile=await firstFile(dir,JUSTFILES),ruff=await firstFile(dir,RUFF_CONFIGS2)!==void 0||RUFF_SECTION2.test(await read(dir,"pyproject.toml")??"");if(makefile!==void 0)fixers.push({name:"makefile",command:"declare every target .PHONY",source:makefile,write:async(cwd)=>{let path=join6(cwd,makefile),current=await Bun.file(path).text(),{content,targets}=declarePhony(current,(name)=>existsSync3(join6(cwd,name)));if(content!==current)await replaceFile(path,content);return`.PHONY: ${targets.join(" ")}`}});if(justfile!==void 0)fixers.push({name:"justfile",command:`just --justfile ${justfile} --fmt`,source:justfile,requires:"just"});if(await Bun.file(join6(dir,"go.mod")).exists())fixers.push({name:"go",command:"go fmt ./... && go mod tidy",source:"go.mod",requires:"go"});if(await Bun.file(join6(dir,"Cargo.toml")).exists())fixers.push({name:"rust",command:"cargo fmt",source:"Cargo.toml",requires:"cargo"});if(ruff)fixers.push({name:"python",command:"ruff check --fix . && ruff format .",source:"ruff",requires:"ruff"});return fixers}async function fixers(dir){let project=await projectFixers(dir),csFixer=await firstFile(dir,CS_FIXER_CONFIGS),php=csFixer===void 0||project.some((fixer)=>fixer.source==="composer.json")?[]:[{name:"php-cs-fixer",command:"vendor/bin/php-cs-fixer fix",source:csFixer}],discovered=[...project,...php,...await toolFixers(dir)],overrides=(await loadCheckConfig(dir))?.fixers;if(overrides===void 0)return discovered;let result=[],seen=new Set;for(let fixer of discovered)if(seen.add(fixer.name),fixer.name in overrides){let custom=overrides[fixer.name];if(typeof custom==="string"&&custom!=="")result.push({name:fixer.name,command:custom,source:".checkrc.json"})}else result.push(fixer);for(let[name,command]of Object.entries(overrides))if(!seen.has(name)&&typeof command==="string"&&command!=="")result.push({name,command,source:".checkrc.json"});return result}async function discoverFixerProjects(dir,targets){if(targets!==void 0&&targets.length>0){let projects=[];for(let target of resolveTargetDirs(dir,targets)){let found=await fixers(target.dir);if(found.length===0)fail(`nothing to fix in ${target.name??"."}`);projects.push({...target,fixers:found})}return projects}let own=await fixers(dir);if(own.length>0)return[{dir,fixers:own}];let projects=[];for(let sub of discoverableSubdirs(dir)){let found=await fixers(join6(dir,sub));if(found.length>0)projects.push({name:sub,dir:join6(dir,sub),fixers:found})}return projects}function runsInService(fixer){return fixer.write===void 0&&fixer.requires===void 0}async function runFixer(fixer,placement,cwd,logFile,settings){if(fixer.write===void 0&&placement!==void 0)return runStep(shellIn(placement,fixer.command,{[RUNNING]:"1"}),cwd,logFile,{...settings,env:{[RUNNING]:"1"}});if(fixer.write===void 0)return runStep(fixer.command,cwd,logFile,{...settings,env:{[RUNNING]:"1"}});let started=Date.now(),outcome;try{outcome={ok:!0,ms:0,output:await fixer.write(cwd)}}catch(error){outcome={ok:!1,ms:0,output:error instanceof Error?error.message:String(error)}}return await writeFile2(logFile,outcome.output,{mode:384,flag:"wx"}),{...outcome,ms:Date.now()-started}}function printChanged(changed){if(changed.length===0){console.log("nothing changed");return}console.log(`changed ${changed.length} file${changed.length===1?"":"s"}:`);for(let path of changed.slice(0,MAX_CHANGED))console.log(` ${path}`);if(changed.length>MAX_CHANGED)console.log(` and ${changed.length-MAX_CHANGED} more`)}async function runFixers(values,cwd,targets=[],rootConfig){let settings=placeSettings(values);if(process3.env[RUNNING]!==void 0)fail("a fixer called check --fix again, which would recurse: give its script another command");let projects=await discoverFixerProjects(cwd,targets),found=projects.flatMap((project)=>project.fixers.map((fixer)=>({...fixer,dir:project.dir,label:project.name===void 0?fixer.name:`${project.name}/${fixer.name}`})));if(found.length===0)fail("nothing to fix here: no fix, lint:fix, fmt or format script (nor one running prettier --write, biome --write or eslint --fix), php-cs-fixer config, Makefile, Justfile, go.mod, Cargo.toml nor ruff config");let singleConfig=projects.length===1&&projects[0].dir!==cwd?await loadCheckConfig(projects[0].dir):void 0,timeoutRaw=values.timeout??singleConfig?.timeout??rootConfig?.timeout,timeoutMs=timeoutRaw===void 0?void 0:duration(timeoutRaw,"timeout",0),pickedAll=pick(found,values.only,"fixer"),picked=values.changed===!0?await narrowFixers(pickedAll,values.base,rootConfig?.base):pickedAll;if(picked.length===0){if(values.json===!0)printJson(values.list===!0?[]:{fixers:[],changed:[]});else console.log("nothing changed to fix");return 0}let placements=new Map;for(let fixer of picked)placements.set(fixer,runsInService(fixer)?await place(fixer.dir,programOf(fixer.command),settings):void 0);let json=values.json===!0,missing=(fixer)=>fixer.requires!==void 0&&Bun.which(fixer.requires)===null;if(values.list===!0){if(json)printJson(picked.map((fixer)=>({name:fixer.label,command:fixer.command,source:fixer.source,...placements.get(fixer)===void 0?{}:{in:placements.get(fixer)?.service},...missing(fixer)?{needs:fixer.requires}:{}})));else console.log(table(picked.map((fixer)=>[fixer.label,fixer.command,missing(fixer)?`${fixer.source}, needs ${fixer.requires}`:fixer.source,placements.get(fixer)?.service??"host"])));return 0}let directory=await logDirectory(cwd),held=holdSignals(),runSettings={...timeoutMs===void 0?{}:{timeoutMs},held},stack=new Stack,width=Math.max(...picked.map((fixer)=>fixer.label.length)),fallbackGitRoot=projects.length===1?projects[0].dir:cwd,gitRoot=await dirtyFiles(cwd)!==void 0?cwd:fallbackGitRoot,before=await dirtyFiles(gitRoot),ran=[],failed=0,timedOut=!1;try{for(let fixer of picked){if(held.signal!==void 0)break;if(missing(fixer)){if(!json)console.log(`${paint(process3.stdout).yellow("skip ")} ${fixer.label.padEnd(width)} ${fixer.requires} is not installed`);ran.push({name:fixer.label,command:fixer.command,skipped:`${fixer.requires} is not installed`});continue}let logFile=join6(directory,`fix-${fixer.label.replaceAll(/[/:]/g,"-")}.log`),placement=placements.get(fixer),down=placement===void 0?void 0:await stack.problem(placement),outcome=down===void 0?await runFixer(fixer,placement,fixer.dir,logFile,runSettings):await refusedStep(down,logFile),entry=outcomeJson(fixer.label,fixer.command,logFile,outcome,placement?.service,fixer.dir);if(!json)printOutcome(fixer.label,width,placement===void 0?fixer.command:`${fixer.command} (in ${placement.service})`,logFile,outcome,fixer.dir,entry.failed);if(ran.push(entry),outcome.timedOut===!0)timedOut=!0;if(!outcome.ok)failed++}}finally{held.release()}let after=before&&await dirtyFiles(gitRoot),changed=before!==void 0&&after!==void 0?changedFiles(before,after):null;if(json)printJson({fixers:ran,changed});else if(changed!==null)printChanged(changed);if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(timedOut)return 2;return failed===0?0:1}import{basename as basename5,join as join7}from"path";import process4 from"process";function durationStats(durations){if(durations.length===0)return{min:0,median:0,max:0};let sorted=durations.toSorted((a,b)=>a-b),mid=Math.floor(sorted.length/2),median=sorted.length%2===1?sorted[mid]:(sorted[mid-1]+sorted[mid])/2;return{min:sorted[0],median,max:sorted.at(-1)}}function classifyFlaky(passed,total){if(passed===total)return"stable";return passed===0?"failing":"flaky"}function formatFlakyDuration(ms){return ms<1000?`${Math.round(Math.max(0,ms))}ms`:formatDuration(ms)}function formatFlakyLine(report,width){let colors=paint(process4.stdout),{min,median,max}=report.durations,stats=colors.dim(`min ${formatFlakyDuration(min)} \xB7 median ${formatFlakyDuration(median)} \xB7 max ${formatFlakyDuration(max)}`),badge,verdict;if(report.status==="stable")badge=colors.bold(colors.green("ok ")),verdict=colors.green(`${report.passed}/${report.runs} passed \u2014 stable`);else if(report.status==="flaky")badge=colors.bold(colors.yellow("FLAKY")),verdict=colors.bold(colors.yellow(`${report.passed}/${report.runs} passed \u2014 FLAKY`));else badge=colors.bold(colors.red("FAIL ")),verdict=colors.red(`${report.passed}/${report.runs} passed \u2014 failing`);return`${badge} ${report.name.padEnd(width)} ${verdict} ${stats}`}function flakySummaryLine(steps){let colors=paint(process4.stdout),stable=steps.filter((step)=>step.status==="stable").length,flaky=steps.filter((step)=>step.status==="flaky").length,failing=steps.filter((step)=>step.status==="failing").length;return[...stable>0?[colors.green(`${stable} stable`)]:[],...flaky>0?[colors.yellow(`${flaky} flaky`)]:[],...failing>0?[colors.red(`${failing} failing`)]:[]].join(colors.dim(" \xB7 "))}async function runFlaky(config,held){let{cwd,steps,runs,slotting,lock,timeoutMs,parallel,json,quiet}=config,directory=await logDirectory(cwd),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),heading=json||quiet?"":header("check",`${basename5(cwd)} \xB7 flaky \xD7${runs} \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process4.stdout);if(heading!=="")console.log(heading);let executeStep=async(step,signals)=>{let down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step),lock):launch(step),results=[];for(let attempt=1;attempt<=runs;attempt++){if(signals.signal!==void 0)break;let logFile=join7(directory,`${step.label.replaceAll("/","-")}-run${attempt}.log`),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile);results.push({run:attempt,ok:outcome.ok,ms:outcome.ms,log:logFile,...outcome.timedOut===!0?{timedOut:!0}:{}})}let passed=results.filter((entry)=>entry.ok).length,total=results.length,failed=total-passed,status=classifyFlaky(passed,total);return{name:step.label,command:step.command,...step.placement===void 0?{}:{in:step.placement.service},runs:total,passed,failed,status,ok:failed===0&&total===runs,durations:durationStats(results.map((entry)=>entry.ms)),results}},reports=[],printStep=(report)=>{if(reports.push(report),json||quiet&&report.ok)return;console.log(formatFlakyLine(report,width));let failedEntries=report.results.filter((entry)=>!entry.ok);if(failedEntries.length>0){let colors=paint(process4.stdout),path=role("path",process4.stdout),ids=failedEntries.map((entry)=>`#${entry.run}`).join(", ");console.log(` ${colors.dim(`failed runs: ${ids}`)} ${path(failedEntries[0].log)}`)}};if(parallel&&steps.length>1){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});let tasks=steps.map(async(step)=>executeStep(step,shared));for(let task of tasks)printStep(await task)}else for(let step of steps)if(printStep(await executeStep(step,held)),held.signal!==void 0)break;await saveResults(cwd,directory,reports.map(({name,ok})=>({name,ok})));let allOk=reports.every((report)=>report.ok),anyTimedOut=reports.some((report)=>report.results.some((entry)=>entry.timedOut===!0));if(json)printJson({runs,ok:allOk,steps:reports});else if(heading!==""||quiet&&!allOk)console.log(flakySummaryLine(reports));if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(anyTimedOut)return 2;return allOk?0:1}var usage=`check [path|workspace...] [--only <steps>] [--changed [--base <ref>]] [--failed] [--fail-fast] [--retry <n>] [--flaky <n>] [--coverage [threshold]] [--watch] [--quiet] [--timeout <duration>] [--slot | --no-slot] [--lock <name>] [--parallel | --no-parallel] [--in <service> | --host] [--list]
8
14
  check --fix [path|workspace...] [--only <fixers>] [--changed [--base <ref>]] [--timeout <duration>] [--in <service> | --host] [--list]
9
15
  check fix [path|workspace...] [...]
10
16
 
11
17
  Runs the repo's typecheck, lint, fmt and test steps (\`check --fix\` to auto-fix and format) across package.json, composer.json, deno.json, Justfile, Makefile, Taskfile, mise, pyproject.toml, Go, Rust, Python, PHP or .checkrc.json; a folder with no steps runs its subfolders and workspaces.
12
18
  A step runs inside the running compose service that mounts its folder and never starts one, and queues for a machine-wide slot when \`slot\` is installed.
13
19
  A passing step prints one line, a failing one structured errors, and each step's full log is saved to the file its line ends with.
14
- With --fix (or \`check fix\`), the project's fix, lint:fix and fmt or format scripts run instead, then the formatters its files call for (php-cs-fixer, \`just --fmt\`, go fmt, cargo fmt, ruff), and the files they changed are listed.`,EXITS=[[0,"every step passed"],[1,"one failed"],[2,"bad usage, no step is found or a step timed out"]],WATCH_DEBOUNCE_MS=200;function slotted(command,lock){return`slot ${lock===void 0?"":`--lock ${shellQuote(lock)} `}-- sh -c ${shellQuote(command)}`}async function plan(steps,settings){let planned=[];for(let{project,...step}of steps)planned.push({...step,dir:project.dir,label:project.name===void 0?step.name:`${project.name}/${step.name}`,placement:await place(project.dir,programOf(step.command),settings)});return planned}async function narrowed(steps,base){let cache=new Map,result=[];for(let step of steps){if(!cache.has(step.dir)){let paths=await changedPaths(step.dir,base);if(paths===void 0)fail("--changed needs a git repository");cache.set(step.dir,paths)}let{command,note}=await narrow(step,step.dir,cache.get(step.dir)??[]);result.push({...step,command,note})}return result}function launch(step){return step.placement===void 0?step.command:shellIn(step.placement,step.command)}function summaryLine(outcomes){let colors=paint(process3.stdout),failed=outcomes.filter((outcome)=>!outcome.ok).length,passed=outcomes.length-failed;return[colors.green(`${passed} passed`),...failed===0?[]:[colors.red(`${failed} failed`)],colors.dim(formatDuration(outcomes.reduce((sum,outcome)=>sum+outcome.ms,0)))].join(colors.dim(" \xB7 "))}async function runOnce(config,held){let{cwd,steps,slotting,lock,timeoutMs,parallel,failFast,retries,json,ndjson=!1,quiet}=config,directory=await logDirectory(cwd),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),outcomes=[],heading=json||quiet?"":header("check",`${basename4(cwd)} \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process3.stdout);if(heading!=="")console.log(heading);let execute=async(step,signals)=>{let down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step),lock):launch(step),logFile=join6(directory,`${step.label.replaceAll("/","-")}.log`),outcome,attempts=0;for(;;)if(attempts+=1,logFile=attempts===1?join6(directory,`${step.label.replaceAll("/","-")}.log`):join6(directory,`${step.label.replaceAll("/","-")}-try${attempts}.log`),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile),outcome.ok||down!==void 0||outcome.timedOut===!0||signals.signal!==void 0||attempts>retries)break;return{step,logFile,outcome,attempts}},report=({step,logFile,outcome,attempts})=>{let retryNote=attempts>1?`attempt ${attempts}/${retries+1}`:void 0,notes=[step.note,retryNote,step.placement===void 0?void 0:`in ${step.placement.service}`].filter((each)=>each!==void 0),described=notes.length===0?step.command:`${step.command} (${notes.join(", ")})`,entry=outcomeJson(step.label,step.command,logFile,outcome,step.placement?.service,step.dir);if(!json&&!(quiet&&outcome.ok))printOutcome(step.label,width,described,logFile,outcome,step.dir,entry.failed);outcomes.push(entry)};if(parallel){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});let aborted=!1,runs=steps.map(async(step)=>{let result=await execute(step,shared);if(failFast&&!result.outcome.ok&&!aborted){aborted=!0;for(let child of children)child.kill("SIGTERM")}return result});for(let run of runs)report(await run)}else for(let step of steps){let result=await execute(step,held);if(report(result),held.signal!==void 0||failFast&&!result.outcome.ok)break}let ran=outcomes.map(({name,ok})=>({name,ok})),kept=(await lastResults(cwd)??[]).filter(({name})=>!ran.some((each)=>each.name===name));if(await writeFile3(join6(directory,RESULTS_FILE),JSON.stringify([...kept,...ran]),{mode:384}),json)if(ndjson)console.log(JSON.stringify(outcomes));else printJson(outcomes);else if(heading!==""||quiet&&!outcomes.every((outcome)=>outcome.ok))console.log(summaryLine(outcomes));if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(outcomes.some((outcome)=>outcome.timedOut===!0))return 2;return outcomes.every((outcome)=>outcome.ok)?0:1}function shouldIgnoreWatchPath(filename){if(filename===null)return!1;let ignored=ignoredFolders([".git","var","tmp"]);return filename.split("/").some((part)=>part.startsWith(".git")||ignored.has(part))}async function watchAndRun(config,dirs){let held=holdSignals(),watchers=[],runConfig=config.json?{...config,ndjson:!0}:config,activeChild,stopWatch,timer,running=!1,pending=!1;held.forward({kill:(signal)=>{activeChild?.kill(signal),stopWatch?.()}});let stepSignals={get signal(){return held.signal},forward:(child)=>{activeChild=child},release:held.release},trigger=async()=>{if(running){pending=!0;return}running=!0;try{await runOnce(runConfig,stepSignals)}finally{activeChild=void 0,running=!1}if(pending&&held.signal===void 0)pending=!1,trigger()};try{if(await trigger(),held.signal!==void 0)return exitCodeOf(null,held.signal);if(!config.json)console.log(paint(process3.stdout).dim("watching for changes (Ctrl-C to stop)..."));await new Promise((resolveDone)=>{if(stopWatch=()=>{if(timer!==void 0)clearTimeout(timer);resolveDone()},held.signal!==void 0){stopWatch();return}for(let dir of new Set(dirs))watchers.push(watch(dir,{recursive:!0},(_event,filename)=>{if(held.signal!==void 0||shouldIgnoreWatchPath(filename))return;if(timer!==void 0)clearTimeout(timer);timer=setTimeout(()=>{if(held.signal===void 0)trigger()},WATCH_DEBOUNCE_MS)}))})}finally{for(let watcher of watchers)watcher.close();held.release()}return held.signal===void 0?0:exitCodeOf(null,held.signal)}async function check(args,cwd=process3.cwd()){let effectiveArgs=args[0]==="fix"&&!existsSync4(resolve3(cwd,"fix"))?["--fix",...args.slice(1)]:args,separator=effectiveArgs.indexOf("--"),ownFlags=separator===-1?effectiveArgs:effectiveArgs.slice(0,separator);if(ownFlags.includes("--slot")&&ownFlags.includes("--no-slot"))fail("--slot and --no-slot exclude each other");if(ownFlags.includes("--parallel")&&ownFlags.includes("--no-parallel"))fail("--parallel and --no-parallel exclude each other");let parsed=parse(effectiveArgs,usage,options,{allowNegative:!0,exits:EXITS,positionals:["[path...]"],replaces:"chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail, and with --fix each fixer and formatter run by hand",examples:["check",["check packages/kit --only lint,test","one workspace, two steps"],["check --changed --base main -x","narrowed to branch diff, fail fast"],["check --in app","every step inside the app service"],["check --fix --changed","fixers on changed files only"]]}),settings=placeSettings(parsed.values),rc=await loadCheckConfig(cwd);if(parsed.values.fix===!0){if(parsed.values.slot===!1)fail("--no-slot does not apply to --fix");if(parsed.values.parallel===!1)fail("--no-parallel does not apply to --fix");for(let flag of["failed","slot","parallel","fail-fast","watch"])if(parsed.values[flag]===!0)fail(`--${flag} does not apply to --fix`);if(parsed.values.retry!==void 0||parsed.values.lock!==void 0)fail("--retry and --lock do not apply to --fix");return runFixers(parsed.values,cwd,parsed.positionals,rc)}let timeoutRaw=parsed.values.timeout??rc?.timeout,timeoutMs=timeoutRaw===void 0?void 0:duration(timeoutRaw,"timeout",0),retries=parsed.values.retry===void 0?0:wholeNumber(parsed.values.retry,"--retry",0,0),lock=parsed.values.lock??rc?.lock,hasSlot=Bun.which("slot",{PATH:process3.env.PATH??""})!==null;if(lock!==void 0&&!hasSlot)fail("--lock needs the slot bin: bun install -g @kaynooo/cli-wait");if(parsed.values.slot===!0&&!hasSlot)console.error("slot bin not found, running unqueued: bun install -g @kaynooo/cli-wait");let slotting=parsed.values.slot!==!1&&hasSlot,targets=parsed.positionals,projects=await discoverProjects(cwd,targets),found=projects.flatMap((project)=>project.steps.map((step)=>({...step,project,label:project.name===void 0?step.name:`${project.name}/${step.name}`})));if(found.length===0)fail(`no ${STEP_NAMES.join(", ")} step in package.json, composer.json, deno.json, Justfile, Makefile, Taskfile, mise, pyproject.toml, Go, Rust, Python or PHP configs, nor in a subfolder`);let only=parsed.values.only??(rc?.only!==void 0&&rc.only.length>0?rc.only.join(","):void 0),wanted=pick(found,only);if(parsed.values.failed===!0){let failed=await lastFailed(cwd);if(failed===void 0||failed.length===0)fail("no failed step in the last run of this folder");if(wanted=wanted.filter((step)=>failed.includes(step.label)),wanted.length===0)fail(`none of the steps picked failed in the last run, which failed ${failed.join(", ")}`)}let planned=await plan(wanted,settings),base=parsed.values.base??rc?.base,steps=parsed.values.changed===!0?await narrowed(planned,base):planned,json=parsed.values.json===!0;if(parsed.values.list===!0){if(json)printJson(steps.map(({label,command,source,placement})=>({name:label,command,source,...placement===void 0?{}:{in:placement.service}})));else console.log(table(steps.map((step)=>[step.label,step.command,step.source,step.placement?.service??"host"])));return 0}let config={cwd,steps,slotting,lock,timeoutMs,parallel:parsed.values.parallel??rc?.parallel===!0,failFast:parsed.values["fail-fast"]===!0||rc?.failFast===!0,retries,json,quiet:parsed.values.quiet===!0};if(parsed.values.watch===!0)return watchAndRun(config,projects.map((project)=>project.dir));let held=holdSignals();try{return await runOnce(config,held)}finally{held.release()}}process4.exitCode=await runMain({name:"check",version,run:async(args)=>check(args)});
20
+ With --fix (or \`check fix\`), the project's fix, lint:fix and fmt or format scripts run instead, then the formatters its files call for (php-cs-fixer, \`just --fmt\`, go fmt, cargo fmt, ruff), and the files they changed are listed.`,EXITS=[[0,"every step passed"],[1,"one failed"],[2,"bad usage, no step is found or a step timed out"]],WATCH_DEBOUNCE_MS=200;async function plan(steps,settings){let planned=[];for(let{project,...step}of steps)planned.push({...step,dir:project.dir,label:project.name===void 0?step.name:`${project.name}/${step.name}`,placement:await place(project.dir,programOf(step.command),settings)});return planned}async function narrowed(steps,base){let cache=new Map,result=[];for(let step of steps){if(!cache.has(step.dir)){let paths=await changedPaths(step.dir,base);if(paths===void 0)fail("--changed needs a git repository");cache.set(step.dir,paths)}let{command,note}=await narrow(step,step.dir,cache.get(step.dir)??[]);result.push({...step,command,note})}return result}async function withCoverage(steps){let result=[];for(let step of steps){let adapted=await withCoverageCommand(step,step.dir),note=[step.note,adapted.note].filter((each)=>each!==void 0).join(", ");result.push({...step,command:adapted.command,...note===""?{}:{note}})}return result}function summaryLine(outcomes){let colors=paint(process5.stdout),failed=outcomes.filter((outcome)=>!outcome.ok).length,passed=outcomes.length-failed;return[colors.green(`${passed} passed`),...failed===0?[]:[colors.red(`${failed} failed`)],colors.dim(formatDuration(outcomes.reduce((sum,outcome)=>sum+outcome.ms,0)))].join(colors.dim(" \xB7 "))}async function runOnce(config,held){let{cwd,steps,slotting,lock,timeoutMs,parallel,failFast,retries,json,ndjson=!1,quiet}=config,directory=await logDirectory(cwd),stack=new Stack,width=Math.max(...steps.map((step)=>step.label.length)),outcomes=[],heading=json||quiet?"":header("check",`${basename6(cwd)} \xB7 ${steps.length} ${steps.length===1?"step":"steps"}`,process5.stdout);if(heading!=="")console.log(heading);let execute=async(step,signals)=>{let down=step.placement===void 0?void 0:await stack.problem(step.placement),command=slotting?slotted(launch(step),lock):launch(step),logFile=join8(directory,`${step.label.replaceAll("/","-")}.log`),outcome,attempts=0;for(;;)if(attempts+=1,logFile=attempts===1?join8(directory,`${step.label.replaceAll("/","-")}.log`):join8(directory,`${step.label.replaceAll("/","-")}-try${attempts}.log`),outcome=down===void 0?await runStep(command,step.dir,logFile,{...timeoutMs===void 0?{}:{timeoutMs},held:signals}):await refusedStep(down,logFile),outcome.ok||down!==void 0||outcome.timedOut===!0||signals.signal!==void 0||attempts>retries)break;return{step,logFile,outcome,attempts}},report=({step,logFile,outcome,attempts})=>{let retryNote=attempts>1?`attempt ${attempts}/${retries+1}`:void 0,notes=[step.note,retryNote,step.placement===void 0?void 0:`in ${step.placement.service}`].filter((each)=>each!==void 0),described=notes.length===0?step.command:`${step.command} (${notes.join(", ")})`,entry=outcomeJson(step.label,step.command,logFile,outcome,step.placement?.service,step.dir);if(!json&&!(quiet&&outcome.ok))printOutcome(step.label,width,described,logFile,outcome,step.dir,entry.failed);outcomes.push(entry)};if(parallel){let children=new Set,shared={get signal(){return held.signal},forward:(child)=>children.add(child),release:held.release};held.forward({kill:(signal)=>{for(let child of children)child.kill(signal)}});let aborted=!1,runs=steps.map(async(step)=>{let result=await execute(step,shared);if(failFast&&!result.outcome.ok&&!aborted){aborted=!0;for(let child of children)child.kill("SIGTERM")}return result});for(let run of runs)report(await run)}else for(let step of steps){let result=await execute(step,held);if(report(result),held.signal!==void 0||failFast&&!result.outcome.ok)break}if(await saveResults(cwd,directory,outcomes.map(({name,ok})=>({name,ok}))),json)if(ndjson)console.log(JSON.stringify(outcomes));else printJson(outcomes);else if(heading!==""||quiet&&!outcomes.every((outcome)=>outcome.ok))console.log(summaryLine(outcomes));if(held.signal!==void 0)return exitCodeOf(null,held.signal);if(outcomes.some((outcome)=>outcome.timedOut===!0))return 2;return outcomes.every((outcome)=>outcome.ok)?0:1}function shouldIgnoreWatchPath(filename){if(filename===null)return!1;let ignored=ignoredFolders([".git","var","tmp"]);return filename.split("/").some((part)=>part.startsWith(".git")||ignored.has(part))}async function watchAndRun(config,dirs){let held=holdSignals(),watchers=[],runConfig=config.json?{...config,ndjson:!0}:config,activeChild,stopWatch,timer,running=!1,pending=!1;held.forward({kill:(signal)=>{activeChild?.kill(signal),stopWatch?.()}});let stepSignals={get signal(){return held.signal},forward:(child)=>{activeChild=child},release:held.release},trigger=async()=>{if(running){pending=!0;return}running=!0;try{await runOnce(runConfig,stepSignals)}finally{activeChild=void 0,running=!1}if(pending&&held.signal===void 0)pending=!1,trigger()};try{if(await trigger(),held.signal!==void 0)return exitCodeOf(null,held.signal);if(!config.json)console.log(paint(process5.stdout).dim("watching for changes (Ctrl-C to stop)..."));await new Promise((resolveDone)=>{if(stopWatch=()=>{if(timer!==void 0)clearTimeout(timer);resolveDone()},held.signal!==void 0){stopWatch();return}for(let dir of new Set(dirs))watchers.push(watch(dir,{recursive:!0},(_event,filename)=>{if(held.signal!==void 0||shouldIgnoreWatchPath(filename))return;if(timer!==void 0)clearTimeout(timer);timer=setTimeout(()=>{if(held.signal===void 0)trigger()},WATCH_DEBOUNCE_MS)}))})}finally{for(let watcher of watchers)watcher.close();held.release()}return held.signal===void 0?0:exitCodeOf(null,held.signal)}async function check(args,cwd=process5.cwd()){let effectiveArgs=args[0]==="fix"&&!existsSync4(resolve3(cwd,"fix"))?["--fix",...args.slice(1)]:args,separator=effectiveArgs.indexOf("--"),ownFlags=separator===-1?effectiveArgs:effectiveArgs.slice(0,separator);if(ownFlags.includes("--slot")&&ownFlags.includes("--no-slot"))fail("--slot and --no-slot exclude each other");if(ownFlags.includes("--parallel")&&ownFlags.includes("--no-parallel"))fail("--parallel and --no-parallel exclude each other");let parsed=parse(effectiveArgs,usage,options,{allowNegative:!0,exits:EXITS,positionals:["[path...]"],replaces:"chaining docker compose exec <service> bun run check | tail, lint and test by hand, or bun run check && bun run lint && bun run test read through tail, and with --fix each fixer and formatter run by hand",examples:["check",["check packages/kit --only lint,test","one workspace, two steps"],["check --changed --base main -x","narrowed to branch diff, fail fast"],["check --only test --flaky 5","run tests 5 times to spot flakes"],["check --coverage 80","run tests with coverage and list files below 80%"],["check --in app","every step inside the app service"],["check --fix --changed","fixers on changed files only"]]}),settings=placeSettings(parsed.values),rc=await loadCheckConfig(cwd);if(parsed.values.fix===!0){if(parsed.values.slot===!1)fail("--no-slot does not apply to --fix");if(parsed.values.parallel===!1)fail("--no-parallel does not apply to --fix");for(let flag of["failed","slot","parallel","fail-fast","watch"])if(parsed.values[flag]===!0)fail(`--${flag} does not apply to --fix`);if(parsed.values.retry!==void 0||parsed.values.lock!==void 0)fail("--retry and --lock do not apply to --fix");if(parsed.values.flaky!==void 0)fail("--flaky does not apply to --fix");if(parsed.values.coverage!==void 0)fail("--coverage does not apply to --fix");return runFixers(parsed.values,cwd,parsed.positionals,rc)}let timeoutRaw=parsed.values.timeout??rc?.timeout,timeoutMs=timeoutRaw===void 0?void 0:duration(timeoutRaw,"timeout",0),retries=parsed.values.retry===void 0?0:wholeNumber(parsed.values.retry,"--retry",0,0),flakyRuns=parsed.values.flaky===void 0?void 0:wholeNumber(parsed.values.flaky,"flaky",0,2),coverageThreshold=parsed.values.coverage===void 0?void 0:parseThreshold(parsed.values.coverage),lock=parsed.values.lock??rc?.lock,hasSlot=Bun.which("slot",{PATH:process5.env.PATH??""})!==null;if(lock!==void 0&&!hasSlot)fail("--lock needs the slot bin: bun install -g @kaynooo/cli-wait");if(parsed.values.slot===!0&&!hasSlot)console.error("slot bin not found, running unqueued: bun install -g @kaynooo/cli-wait");let slotting=parsed.values.slot!==!1&&hasSlot,targets=parsed.positionals,projects=await discoverProjects(cwd,targets),found=projects.flatMap((project)=>project.steps.map((step)=>({...step,project,label:project.name===void 0?step.name:`${project.name}/${step.name}`})));if(found.length===0)fail(`no ${STEP_NAMES.join(", ")} step in package.json, composer.json, deno.json, Justfile, Makefile, Taskfile, mise, pyproject.toml, Go, Rust, Python or PHP configs, nor in a subfolder`);let rcOnly=rc?.only!==void 0&&rc.only.length>0?rc.only.join(","):void 0,only=parsed.values.only??(coverageThreshold!==void 0?"test":rcOnly),wanted=pick(found,only);if(parsed.values.failed===!0){let failed=await lastFailed(cwd);if(failed===void 0||failed.length===0)fail("no failed step in the last run of this folder");if(wanted=wanted.filter((step)=>failed.includes(step.label)),wanted.length===0)fail(`none of the steps picked failed in the last run, which failed ${failed.join(", ")}`)}let planned=await plan(wanted,settings),base=parsed.values.base??rc?.base,narrowedSteps=parsed.values.changed===!0?await narrowed(planned,base):planned,steps=coverageThreshold===void 0?narrowedSteps:await withCoverage(narrowedSteps),json=parsed.values.json===!0;if(parsed.values.list===!0){if(json)printJson(steps.map(({label,command,source,placement})=>({name:label,command,source,...placement===void 0?{}:{in:placement.service}})));else console.log(table(steps.map((step)=>[step.label,step.command,step.source,step.placement?.service??"host"])));return 0}let parallel=parsed.values.parallel??rc?.parallel===!0,quiet=parsed.values.quiet===!0;if(flakyRuns!==void 0){let held=holdSignals();try{return await runFlaky({cwd,steps,runs:flakyRuns,slotting,lock,timeoutMs,parallel,json,quiet},held)}finally{held.release()}}if(coverageThreshold!==void 0){let held=holdSignals();try{return await runCoverage({cwd,steps,threshold:coverageThreshold,slotting,lock,timeoutMs,parallel,json,quiet},held)}finally{held.release()}}let config={cwd,steps,slotting,lock,timeoutMs,parallel,failFast:parsed.values["fail-fast"]===!0||rc?.failFast===!0,retries,json,quiet};if(parsed.values.watch===!0)return watchAndRun(config,projects.map((project)=>project.dir));let held=holdSignals();try{return await runOnce(config,held)}finally{held.release()}}process6.exitCode=await runMain({name:"check",version,run:async(args)=>check(args)});
package/dist/j-cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/bin/sh
2
2
  // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
- import{outputMode,isInteractive,readUserConfig,paint,warn,role,closest,table,printJson,jsonOption,fail,OUTPUT_OPTIONS,parse,ignoredFolders,cacheFolder}from"./chunk-7d3myeb5.js";import{runMain,shellQuote,captureOutput,findComposeDir,readServices,place,argvIn,Stack,placeOptions,placeSettings,version,folders,justFlags,readPackageManifest,readComposerManifest,readDenoManifest,readJustManifest,readMakefileManifest,readTaskfileManifest,readMiseManifest,readPyprojectManifest}from"./chunk-ak7f4g3t.js";import{stopJob,visible,CTRL_KEY,styled,parseKeys,createState,withRows,appendRows,highlighted,press,chosen,SYNC_START,SYNC_END,overwrite,input2}from"./chunk-mhj3d5hy.js";import process7 from"process";import{resolve as resolvePath}from"path";import process6 from"process";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import process3 from"process";import{openSync}from"fs";import process2 from"process";import tty from"tty";import process from"process";var PREVIEW_BYTES=65536,PREVIEW_LINES=200,PREVIEW_TIMEOUT_MS=3000,PLACEHOLDER=/\{([1-9]\d*)?\}/g;function previewCommand(template,line,hidden=[]){return template.replace(PLACEHOLDER,(_,field)=>shellQuote(field===void 0?line:hidden[Number(field)-1]??""))}function previewLines(output){let lines=output.split(`
3
+ import{outputMode,isInteractive,readUserConfig,paint,warn,role,closest,table,printJson,jsonOption,fail,OUTPUT_OPTIONS,parse,ignoredFolders,cacheFolder}from"./chunk-qtqywtwc.js";import{runMain,shellQuote,captureOutput,findComposeDir,readServices,place,argvIn,Stack,placeOptions,placeSettings,version,folders,justFlags,readPackageManifest,readComposerManifest,readDenoManifest,readJustManifest,readMakefileManifest,readTaskfileManifest,readMiseManifest,readPyprojectManifest}from"./chunk-nkztmk15.js";import{stopJob,visible,CTRL_KEY,styled,parseKeys,createState,withRows,appendRows,highlighted,press,chosen,SYNC_START,SYNC_END,overwrite,input2}from"./chunk-ctrqm3zy.js";import process7 from"process";import{resolve as resolvePath}from"path";import process6 from"process";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import process3 from"process";import{openSync}from"fs";import process2 from"process";import tty from"tty";import process from"process";var PREVIEW_BYTES=65536,PREVIEW_LINES=200,PREVIEW_TIMEOUT_MS=3000,PLACEHOLDER=/\{([1-9]\d*)?\}/g;function previewCommand(template,line,hidden=[]){return template.replace(PLACEHOLDER,(_,field)=>shellQuote(field===void 0?line:hidden[Number(field)-1]??""))}function previewLines(output){let lines=output.split(`
4
4
  `);if(lines.at(-1)==="")lines.pop();return lines.slice(0,PREVIEW_LINES)}async function runPreview(template,line,signal,hidden=[]){let proc=Bun.spawn(["sh","-c",`exec 2>&1
5
5
  ${previewCommand(template,line,hidden)}`],{stdin:"ignore",stdout:"pipe",stderr:"ignore",detached:!0}),stop=()=>{try{process.kill(-proc.pid,"SIGKILL")}catch{proc.kill()}},timer=setTimeout(stop,PREVIEW_TIMEOUT_MS),chunks=[],size=0;signal.addEventListener("abort",stop);try{for await(let chunk of proc.stdout)if(chunks.push(chunk),size+=chunk.length,size>=PREVIEW_BYTES){stop();break}}finally{clearTimeout(timer),signal.removeEventListener("abort",stop)}return signal.aborted?[]:previewLines(Buffer.concat(chunks).subarray(0,PREVIEW_BYTES).toString())}var MIN_HEIGHT=4,PREVIEW_MIN_COLUMNS=80,PREVIEW_MIN_ROWS=10,PREVIEW_SHARE=0.4,PREVIEW_RIGHT_SHARE=0.5,RESET="\x1B[0m",SEPARATOR=" \u2502 ",HEIGHT=/^(\d+)(%?)$/;function parseHeight(text){let found=HEIGHT.exec(text);if(found===null||Number(found[1])<1)return;return found[2]==="%"?{percent:Math.min(100,Number(found[1]))}:{lines:Number(found[1])}}function layoutFor(size,height,previewing,position="right",share){let wanted="lines"in height?height.lines:Math.round(size.rows*height.percent/100),rows=Math.min(size.rows,Math.max(MIN_HEIGHT,wanted));if(!previewing||position==="hidden")return{height:rows,listHeight:rows,listWidth:size.columns,previewWidth:0,previewHeight:0};if(position==="down"){let previewHeight=rows>=PREVIEW_MIN_ROWS?Math.round(rows*(share??PREVIEW_SHARE)):0;return{height:rows,listHeight:rows-previewHeight,listWidth:size.columns,previewWidth:0,previewHeight}}let split=size.columns>=PREVIEW_MIN_COLUMNS,rightShare=share??PREVIEW_RIGHT_SHARE,listWidth=split?Math.max(10,Math.floor(size.columns*(1-rightShare))):size.columns;return{height:rows,listHeight:rows,listWidth,previewWidth:split?Math.max(0,size.columns-listWidth-SEPARATOR.length):0,previewHeight:0}}function fit(text,width,plain,mark=plain,marked=new Set,styles){let room=Bun.stringWidth(text)>width?width-1:width,out="",used=0,at=0;for(let char of text){let size=Bun.stringWidth(char);if(used+size>room)break;let style=marked.has(at)?"":styles?.[at]??"";out+=style===""?(marked.has(at)?mark:plain)(char):`${style}${char}${RESET}`,used+=size,at+=char.length}if(room<width)out+=plain("\u2026"),used+=1;return{text:out,width:used}}var identity=(text)=>text;function fitStyled(line,width,plain=identity){let{text,styles}=styled(line);return fit(text,width,plain,plain,new Set,styles)}function queryShown(state,layout){return visible({text:state.query,caret:state.caret},Math.max(1,layout.listWidth-Bun.stringWidth(state.prompt)))}function caretCell(state,layout){let shown=queryShown(state,layout);return{column:Math.min(layout.listWidth,Bun.stringWidth(state.prompt)+shown.column+1),char:shown.at??" "}}function helpLines(state,layout,theme){let lines=["type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move","left, right, ctrl-a, ctrl-e move in the query, ctrl or alt with left or right by a word","ctrl-w or ctrl-backspace erase a word, ctrl-u back to the start, ctrl-k to the end, del ahead","ctrl-y puts back what they erased, ctrl-z suspends to the shell",`enter picks${state.multi?", tab marks":""}, esc or ctrl-c cancels`,...state.expect.length>0?[`${state.expect.join(", ")} end the pick as this command asks`]:[]],title="keys, any key closes this help";return[{text:theme.accent("keys, any key closes this help"),width:30},...lines.map((line)=>fit(` ${line}`,layout.listWidth,theme.label))]}function listLines(state,layout,theme){if(state.help)return helpLines(state,layout,theme);let header=state.header===""?[]:state.header.split(`
6
6
  `).map((line)=>fitStyled(line,layout.listWidth,theme.label)),rows=Math.max(1,layout.listHeight-2-header.length),prefixWidth=state.multi?4:2,top=Math.max(0,Math.min(state.cursor-Math.floor(rows/2),state.matches.length-rows)),marks=(state.marked.size>0?` (${state.marked.size} marked)`:"")+(state.status===""?"":` ${state.status}`),promptWidth=Bun.stringWidth(state.prompt),shown=queryShown(state,layout),text=`${shown.before}${shown.at??""}${shown.after}`,query={text,width:Bun.stringWidth(text)},place=state.matches.length>rows?` (${state.cursor+1} of ${state.matches.length})`:"",count=fit(` ${state.matches.length}/${state.items.length}${place}${marks} ctrl-/ keys`,layout.listWidth,theme.label),lines=[{text:theme.accent(state.prompt)+query.text,width:promptWidth+query.width},count,...header];if(state.matches.length===0)lines.push(fit(" no match",layout.listWidth,theme.label));for(let[offset,match]of state.matches.slice(top,top+rows).entries()){let current=top+offset===state.cursor,pointer=current?theme.accent("\u276F"):" ",mark=state.multi?`${state.marked.has(match.index)?theme.id("\u25CF"):" "} `:"",text=fit(state.items[match.index],layout.listWidth-prefixWidth,current?theme.value:identity,theme.match??theme.accent,new Set(match.positions),state.styles[match.index]);lines.push({text:`${pointer} ${mark}${text.text}`,width:prefixWidth+text.width})}return lines}function render(state,layout,theme,preview=[]){let left=listLines(state,layout,theme);return Array.from({length:layout.height},(_,row)=>{if(row>=layout.listHeight)return row===layout.listHeight?theme.label("\u2500".repeat(layout.listWidth)):fitStyled(preview[row-layout.listHeight-1]??"",layout.listWidth).text;let list=left[row]??{text:"",width:0};if(layout.previewWidth===0)return list.text;return`${list.text}${" ".repeat(Math.max(0,layout.listWidth-list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row]??"",layout.previewWidth).text}`})}var PREVIEW_DELAY_MS=120,ESCAPE_WAIT_MS=30,OPEN={ctrl:"open"},HIDE_CURSOR="\x1B[?25l",SHOW_CURSOR="\x1B[?25h",REVERSE="\x1B[7m",REVERSE_END="\x1B[27m",PASTE_ON="\x1B[?2004h",PASTE_OFF="\x1B[?2004l",MOUSE_ON="\x1B[?1000h\x1B[?1006h",MOUSE_OFF="\x1B[?1006l\x1B[?1000l",CLEAR_BELOW="\r\x1B[J",SIGNALS=["SIGINT","SIGTERM","SIGHUP"];function up(lines){return lines>0?`\x1B[${lines}A`:""}function openTerminal(){let mode;try{mode=new tty.ReadStream(openSync("/dev/tty","r"))}catch{return fail("no terminal to read keys from (/dev/tty)")}let keys=Bun.file("/dev/tty").stream().getReader(),out=process2.stderr,resize;async function read(onChunk){let decoder=new TextDecoder;try{for(let chunk=await keys.read();!chunk.done;chunk=await keys.read())onChunk(decoder.decode(chunk.value,{stream:!0}))}catch{onChunk("\x03")}}return{get columns(){return out.columns||80},get rows(){return out.rows||24},theme:{accent:role("accent",out),label:role("label",out),value:role("value",out),id:role("id",out),match:(text)=>paint(out).underline(role("accent",out)(text))},write:(text)=>void out.write(text),listen(onChunk,onResize){resize=onResize,mode.setRawMode(!0),out.on("resize",onResize),read(onChunk)},suspend(){mode.setRawMode(!1),stopJob(),mode.setRawMode(!0)},close(){if(resize!==void 0)out.off("resize",resize);try{mode.setRawMode(!1)}finally{mode.destroy(),keys.cancel()}}}}async function select(rows,settings,terminal=openTerminal()){let{theme}=terminal,state=createState(rows,settings),preview=[],reserved=0,previewTimer,previewing=new AbortController,shownLine,finish,restored=!1,escape,showPreview=settings.preview!==void 0&&settings.previewPosition!=="hidden";function draw(clear=!1){if(restored)return;let layout=layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,showPreview,settings.previewPosition,settings.previewShare),frame=SYNC_START+HIDE_CURSOR;if(reserved!==layout.height||clear)frame+=CLEAR_BELOW+`
7
7
  `.repeat(layout.height-1)+up(layout.height-1),reserved=layout.height;let caret=caretCell(state,layout);frame+=`\r${overwrite(render(state,layout,theme,preview),terminal.columns)}${up(layout.height-1)}\r\x1B[${caret.column}G${REVERSE}${caret.char}${REVERSE_END}\r${SYNC_END}`,terminal.write(frame)}function pageSize(){let headerLines=state.header===""?0:state.header.split(`
8
8
  `).length;return Math.max(1,layoutFor({columns:terminal.columns,rows:terminal.rows},settings.height,showPreview,settings.previewPosition,settings.previewShare).listHeight-2-headerLines)}function refreshPreview(){let at=highlighted(state);if(!showPreview||settings.preview===void 0||at===shownLine)return;if(shownLine=at,clearTimeout(previewTimer),previewing.abort(),previewing=new AbortController,at===void 0){preview=[];return}let{signal}=previewing,template=settings.preview,row=state.rows[at];async function show(){let shown=typeof template==="string"?await runPreview(template,row.cells.join(" "),signal,row.hidden):await previewOf(template,row.hidden,signal);if(!signal.aborted)preview=shown,draw()}previewTimer=setTimeout(()=>void show(),PREVIEW_DELAY_MS)}function restore(){if(restored)return;restored=!0,clearTimeout(previewTimer),clearTimeout(escape),previewing.abort(),terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.close()}function suspend(){if(terminal.suspend===void 0)return;terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`),terminal.suspend(),terminal.write(`${PASTE_ON}${MOUSE_ON}`),draw(!0)}let stop=()=>{state={...state,done:"cancel"},finish?.()},paste={active:!1},{reload}=settings,pending=[],busy=!1,draining=!1;async function reloadRows(){if(reload===void 0)return;busy=!0,state={...state,status:"reloading"},draw();try{let next=await reload.run();state={...withRows(state,next.rows,next.header),status:""},shownLine=void 0}catch(error){state={...state,status:`reload failed: ${error instanceof Error?error.message:String(error)}`}}finally{busy=!1}}async function drain(){if(draining)return;draining=!0;try{for(let key=pending.shift();key!==void 0&&state.done===void 0;key=pending.shift())if(key===OPEN||typeof key==="object"&&"ctrl"in key&&key.ctrl===reload?.key)await reloadRows();else if(key==="suspend")suspend();else state=press({...state,page:pageSize()},key)}finally{draining=!1}if(state.done!==void 0){finish?.();return}refreshPreview(),draw()}function onChunk(chunk){if(escape!==void 0)clearTimeout(escape),escape=void 0,chunk=`\x1B${chunk}`;else if(chunk==="\x1B"){escape=setTimeout(()=>{escape=void 0,takeKeys("\x1B")},ESCAPE_WAIT_MS);return}takeKeys(chunk)}function takeKeys(chunk){let keys=parseKeys(chunk,paste,[...settings.expect??[],...reload?.key===void 0?[]:[reload.key]]);if(busy&&keys.includes("cancel")){stop();return}pending.push(...keys),drain()}let ended=new Promise((resolve)=>{finish=resolve});process2.once("exit",restore);for(let signal of SIGNALS)process2.once(signal,stop);async function consumeStream(source){state={...state,status:"loading"},draw();try{for await(let batch of source){if(restored||state.done!==void 0)return;if(batch.length===0)continue;state=appendRows(state,batch),refreshPreview(),draw()}}finally{if(!restored&&state.done===void 0)state={...state,status:""},draw()}}try{if(terminal.write(`${PASTE_ON}${MOUSE_ON}`),terminal.listen(onChunk,()=>draw(!0)),refreshPreview(),draw(!0),settings.stream!==void 0)consumeStream(settings.stream);if(reload?.onOpen===!0)pending.push(OPEN),drain();await ended}finally{for(let signal of SIGNALS)process2.off(signal,stop);process2.off("exit",restore),restore()}return state.done==="accept"?{rows:chosen(state),key:state.key,query:state.query}:void 0}async function previewOf(preview,hidden,signal){try{return previewLines(await preview(hidden,signal))}catch(error){return[error instanceof Error?error.message:String(error)]}}var REMEMBERED=20;function table2(rows){let widths=rows[0]?.cells.map((_,index)=>Math.max(...rows.map((row)=>Bun.stringWidth(row.cells[index]))))??[];return rows.map((row)=>[...row.hidden,...row.cells.map((cell,index)=>index===row.cells.length-1?cell.trimEnd():`${cell}${" ".repeat(widths[index]+1-Bun.stringWidth(cell))}`)].join("\t"))}async function pick(rows,options){let height=parseHeight(options.height??"100%"),keys=[...options.expect??[],...options.reload?.key===void 0?[]:[options.reload.key]];if(height===void 0)throw Error(`pick: the height is lines or a percentage, not ${options.height}`);for(let key of keys)if(!CTRL_KEY.test(key))throw Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);let found=await select(rows,{multi:!1,prompt:options.prompt,query:"",height,preview:options.preview,previewPosition:"down",header:options.header,expect:options.expect,searched:options.searched,reload:options.reload});return found===void 0?void 0:{key:found.key,hidden:found.rows[0]?.hidden??[],query:found.query}}function heightFor(count){return String(Math.max(15,Math.ceil((count+4)/0.6)))}function historyFile(name){return join(cacheFolder(),name,"history.json")}function history(name){try{let file=historyFile(name);return existsSync(file)?JSON.parse(readFileSync(file,"utf-8")):{}}catch{return{}}}function runs(name){return history(name)[process3.cwd()]??[]}function record(name,run){let all=history(name),file=historyFile(name);all[process3.cwd()]=[run,...(all[process3.cwd()]??[]).filter((earlier)=>earlier.id!==run.id)].slice(0,REMEMBERED),mkdirSync(dirname(file),{recursive:!0}),writeFileSync(file,JSON.stringify(all))}function byRecency(items,previous,idOf){let rankMap=new Map(previous.map((run,index)=>[run.id,index]));return[...items.filter((item)=>rankMap.has(idOf(item))).sort((a,b)=>rankMap.get(idOf(a))-rankMap.get(idOf(b))),...items.filter((item)=>!rankMap.has(idOf(item)))]}function word(arg){if(typeof arg==="string")return`=${arg}`;return"given"in arg?`+${arg.given}`:`?${arg.ask}`}function emit(mode,typed,recorded,command){let words=command.map(word);console.log([mode,typed,recorded,...words].join(`
9
- `))}function list(rows){console.log(JSON.stringify(rows))}function splitLast(args,ownOptions){let all={...ownOptions,...OUTPUT_OPTIONS,help:{type:"boolean",short:"h"}},flagType=new Map;for(let[name,option]of Object.entries(all)){let kind=option.type==="string"?"string":"boolean";if(flagType.set(`--${name}`,kind),option.short!==void 0)flagType.set(`-${option.short}`,kind);for(let alias of option.aliases??[])flagType.set(`--${alias}`,kind)}let keyOf=(word)=>{let eq=word.indexOf("=");return eq===-1?word:word.slice(0,eq)},takesValue=(word)=>!word.includes("=")&&flagType.get(word)==="string",isKnown=(word)=>flagType.has(keyOf(word));for(let i=0;i<args.length;i++){let word=args[i];if(word==="--")return;if(word==="-"){let own=args.slice(0,i),rest=[];for(let k=i+1;k<args.length;k++){let next=args[k];if(next==="--"){rest=args.slice(k+1);break}if(isKnown(next)){if(own.push(next),takesValue(next)&&k+1<args.length)own.push(args[++k])}else{rest=args.slice(k);break}}return{own,rest}}if(word.startsWith("-")){if(takesValue(word))i++;continue}return}return}import process4 from"process";import{join as join2}from"path";var QUALIFIED=/^([a-z]+):(?!:)(.+)$/;function build(base,items){return items.map((item)=>({...base,doc:null,parameters:[],...item}))}function just(dir,here){let found=readJustManifest(dir,here);if(found===void 0)return[];return build({kind:"just",tag:"just",runner:["just"],separated:!1,dir},found.recipes)}function make(dir){let found=readMakefileManifest(dir);if(found===void 0)return[];return build({kind:"make",tag:"make",runner:["make"],separated:!1,dir},found.targets)}function packageScripts(dir,here){let found=readPackageManifest(dir,here);if(found===void 0)return[];return build({kind:"package",tag:found.tool,runner:[found.tool,"run"],separated:found.tool==="npm",dir:found.dir},found.scripts.map(({name,body})=>({name,body})))}function composer(dir,here){let found=readComposerManifest(dir,here);if(found===void 0)return[];return build({kind:"composer",tag:"composer",runner:["composer","run"],separated:!0,dir:found.dir},found.scripts)}function deno(dir,here){let found=readDenoManifest(dir,here);if(found===void 0)return[];return build({kind:"deno",tag:"deno",runner:["deno","task"],separated:!1,dir:found.dir},found.tasks)}function taskfile(dir,here){let found=readTaskfileManifest(dir,here);if(found===void 0)return[];return build({kind:"task",tag:"task",runner:["task"],separated:!0,dir:found.dir},found.tasks)}function mise(dir,here){let items=readMiseManifest(dir,here);if(items.length===0)return[];return build({kind:"mise",tag:"mise",runner:["mise","run"],separated:!1,dir},items)}function pyproject(dir,here){let found=readPyprojectManifest(dir,here);if(found===void 0)return[];return[...build({kind:"poe",tag:"poe",runner:found.uv?["uv","run","poe"]:["poe"],separated:!1,dir:found.dir},found.poe),...build({kind:"uv",tag:"uv",runner:["uv","run"],separated:!1,dir:found.dir},found.scripts)]}var READERS=[just,make,packageScripts,composer,deno,taskfile,mise,pyproject],READER_OF={just,make,package:packageScripts,composer,deno,task:taskfile,mise,poe:pyproject,uv:pyproject},MANIFEST_OF=new Map([[just,"justfile"],[make,"Makefile"],[packageScripts,"package.json"],[composer,"composer.json"],[deno,"deno.json"],[taskfile,"Taskfile.yml"],[mise,"mise.toml"],[pyproject,"pyproject.toml"]]);function guarded(reader,dir,here,isWarned=!1){try{return reader(dir,here)}catch(error){if(isWarned)warn(`j: skipped ${join2(dir,MANIFEST_OF.get(reader)??"a manifest")}, it does not parse (${error instanceof Error?error.message:String(error)})`);return[]}}function everything(cwd="."){let here=READERS.flatMap((reader)=>guarded(reader,cwd,!0,!0)),below=folders(cwd).flatMap((dir)=>READERS.flatMap((reader)=>guarded(reader,cwd==="."?dir:join2(cwd,dir),!1,!0))),seen=new Set;return[...here,...below].filter((entry)=>{let id=`${entry.kind} ${entry.dir} ${entry.name}`,fresh=!seen.has(id);return seen.add(id),fresh})}function readKind(kind,dir){return guarded(READER_OF[kind],dir,dir===".").filter((entry)=>entry.kind===kind)}function key(entry){return entry.dir==="."?entry.name:`${entry.dir}/${entry.name}`}function id(entry){return`${entry.tag}:${key(entry)}`}function resolve(entries,named){let qualified=QUALIFIED.exec(named),tagged=qualified&&entries.some((entry)=>entry.tag===qualified[1])?qualified:void 0,pool=tagged?entries.filter((entry)=>entry.tag===tagged[1]):entries,rest=tagged?tagged[2]:named,exact=pool.filter((entry)=>key(entry)===rest);return exact.length>0?exact:pool.filter((entry)=>entry.name===rest)}function shortest(entries,entry){let found=resolve(entries,key(entry));return found.length===1&&found[0]===entry?key(entry):id(entry)}function signature(entry){return entry.parameters.map((parameter)=>parameter.default===null&&parameter.kind==="singular"?`<${parameter.name}>`:`[${parameter.name}]`).join(" ")}var TINTS={just:"yellow",make:"blue",package:"magenta",composer:"cyan",deno:"green",task:"cyan",mise:"red",poe:"green",uv:"green"};function labelled(entries){return new Set(entries.map((entry)=>entry.tag)).size>1}function row(entry,labels,signed){let colors=paint(process4.stderr),keyed=entry.dir==="."?entry.name:`${colors.dim(`${entry.dir}/`)}${entry.name}`;return{hidden:[entry.kind,entry.dir,entry.name,id(entry)],cells:[...labels?[colors[TINTS[entry.kind]](entry.tag)]:[],keyed,...signed?[colors.cyan(signature(entry))]:[],colors.dim(entry.doc??"")]}}async function pickJob(entries,narrowed=!1){let labels=labelled(entries),signed=entries.some((entry)=>signature(entry)!==""),picked=await pick(entries.map((entry)=>row(entry,labels,signed)),{prompt:`${[...new Set(entries.map((entry)=>entry.tag))].join("/")}> `,searched:labels?2:1,...narrowed?{height:heightFor(entries.length)}:{},preview:`${process4.execPath} ${process4.argv[1]} --show {1} {2} {3}`});return entries.find((candidate)=>id(candidate)===picked?.hidden[3])}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"fs";import{dirname as dirname2,join as join3,relative,resolve as resolve2}from"path";import process5 from"process";var usage="j sf [--service <name>] [command] [args...]\nj sf -\n\nPicks a Symfony console command on a terminal and runs it, asking for each required argument; without a terminal (a script, a pipe, an agent) it lists the commands, the form to use there.\nThe console is the nearest `bin/console` up to the repository root, then those of the child folders (keyed `api/cache:clear`), run in the auto-detected or configured PHP compose service when there is one (or on the host with `--host`), else with local php.\n`j sf -` runs the last command again with its arguments, `j sf <command> [args...]` runs without the picker, a name the list does not hold going to the console as is.",EXITS=[["the code of the console","a command it ran"],[0,"it listed the commands"],[1,"no bin/console here, or it listed no command"],[2,"a usage error"]],sfOptions={service:{type:"string",short:"s",aliases:["in"],conflicts:["host"],description:"compose service running PHP (overrides auto-detection and config.jsonc#sf.service)"},host:{type:"boolean",conflicts:["service"],description:"run on the host with local php even when a compose service mounts the folder"},list:{type:"boolean",short:"l",description:"list the commands without opening the picker"},json:jsonOption("[{ name, command, dir, description, signature, arguments, options }]")},MARKUP=/<(info|comment|question|error)>(.*?)<\/\1>/gs,TAGS={info:"green",comment:"yellow",question:"cyan",error:"red"},LINKS=/<\/?href[^>]*>/g,NAME_PARTS=/[-_]/,PHP_PROFILE=/\b(?:php|frankenphp)\b/i,PHPMYADMIN=/phpmyadmin/i;function marked(text,stream=process5.stdout){let colors=paint(stream);return text.replace(MARKUP,(_,tag,inner)=>colors[TAGS[tag]](inner)).replace(LINKS,"")}function argumentsOf(command){return Array.isArray(command.definition.arguments)?[]:Object.values(command.definition.arguments)}function optionsOf(command){return Array.isArray(command.definition.options)?[]:Object.values(command.definition.options)}function fromDir(dir,command){return dir==="."?command:["env","-C",dir,...command]}function up2(dir){let dirs=[];for(let current=dir;;current=join3(current,"..")){dirs.push(current);let absolute=resolve2(current);if(existsSync2(join3(current,".git"))||dirname2(absolute)===absolute)return dirs}}function children(dir="."){let ignored=ignoredFolders();return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function phpService(candidates,configured){let list=candidates.map((item)=>typeof item==="string"?{name:item,profile:item.toLowerCase()}:item);if(configured!==void 0&&configured!==""){let exact=list.find((item)=>item.name===configured);if(exact!==void 0)return exact.name}return list.find((item)=>item.name==="php")?.name??list.find((item)=>item.name.split(NAME_PARTS).includes("php"))?.name??list.find((item)=>!PHPMYADMIN.test(item.profile)&&PHP_PROFILE.test(item.profile))?.name}function configuredService(){let value=readUserConfig("sf").service;return typeof value==="string"&&value!==""?value:void 0}function mountsDir(service,absDir){return service.mounts.some((mount)=>{let inside=relative(mount.source,absDir);return!inside.startsWith("..")&&!inside.startsWith("/")})}async function consoleAt(dir,settings={}){let absDir=resolve2(dir),placement;if(settings.service!==void 0)placement=await place(absDir,"php",settings);else if(settings.host!==!0){let composeDir=findComposeDir(absDir),mounting=((composeDir===void 0?void 0:await readServices(composeDir))??[]).filter((candidate)=>mountsDir(candidate,absDir)),php=mounting.length===0?void 0:phpService(mounting,configuredService());if(php!==void 0)placement=Bun.which("docker",{PATH:process5.env.PATH??""})===null?await place(absDir,"php"):await place(absDir,"php",{service:php})}if(placement!==void 0){let relCompose=relative(process5.cwd(),placement.composeDir)||".",exec=argvIn(placement,["bin/console"]);return{dir,run:fromDir(relCompose,exec),list:{argv:exec,cwd:placement.composeDir,env:process5.env}}}return{dir,run:fromDir(dir,["php","bin/console"]),list:{argv:["php","bin/console"],cwd:absDir,env:process5.env}}}function hasConsole(dir="."){return up2(dir).some((candidate)=>existsSync2(join3(candidate,"bin/console")))||children(dir).some((child)=>existsSync2(join3(dir,child,"bin/console")))}async function consoles(settings={}){let here=up2(".").find((dir)=>existsSync2(join3(dir,"bin/console"))),dirs=[...here===void 0?[]:[here],...children().filter((dir)=>existsSync2(join3(dir,"bin/console")))];return Promise.all([...new Set(dirs)].map(async(dir)=>consoleAt(dir,settings)))}function cached(dir){return join3(cacheFolder(),"sf",`${resolve2(dir).replaceAll("/","%")}.json`)}function fromCache(dir){try{return existsSync2(cached(dir))?JSON.parse(readFileSync2(cached(dir),"utf-8")):void 0}catch{return}}async function live(app){let commands;try{let ran=await captureOutput([...app.list.argv,"list","--format=json"],{cwd:app.list.cwd,env:app.list.env});if(ran.code!==0)return fromCache(app.dir)??[];commands=JSON.parse(ran.stdout).commands.filter((command)=>!command.hidden)}catch{return fromCache(app.dir)??[]}return mkdirSync2(dirname2(cached(app.dir)),{recursive:!0}),writeFileSync2(cached(app.dir),JSON.stringify(commands)),commands}async function entries(fresh,settings={}){let found=await consoles(settings),lists=await Promise.all(found.map(async(app)=>fresh?live(app):fromCache(app.dir)??live(app)));return found.flatMap((app,index)=>lists[index].map((command)=>({app,command})))}function key2(entry){return entry.app.dir==="."?entry.command.name:`${entry.app.dir}/${entry.command.name}`}function named(name,colors){let colon=name.lastIndexOf(":");return colon===-1?name:`${colors.dim(name.slice(0,colon+1))}${name.slice(colon+1)}`}function signature2(command){return argumentsOf(command).map((argument)=>`${argument.is_required?"<":"["}${argument.name}${argument.is_array?"...":""}${argument.is_required?">":"]"}`).join(" ")}function entryJson(entry){let{command}=entry;return{name:key2(entry),command:command.name,dir:entry.app.dir,description:command.description,signature:signature2(command),arguments:argumentsOf(command).map((argument)=>({name:argument.name,required:argument.is_required,array:argument.is_array,description:argument.description})),options:optionsOf(command).map((option)=>({name:option.name,shortcut:option.shortcut,acceptsValue:option.accept_value,description:option.description}))}}function rows(found){let colors=paint(process5.stderr);return byRecency(found,runs("sf"),key2).map((entry)=>({hidden:[entry.app.dir,entry.command.name],cells:[entry.app.dir==="."?named(entry.command.name,colors):`${colors.dim(`${entry.app.dir}/`)}${named(entry.command.name,colors)}`,colors.cyan(signature2(entry.command)),colors.dim(entry.command.description)]}))}function preview(dir,name){let command=(fromCache(dir)??[]).find((candidate)=>candidate.name===name);if(!command)return;let colors=paint(process5.stdout),lines=[colors.bold(command.description),"",colors.yellow("Usage:"),...command.usage.map((line)=>` ${line}`),...argumentsOf(command).length?["",colors.yellow("Arguments:"),...argumentsOf(command).map((argument)=>` ${colors.green(argument.name.padEnd(20))} ${argument.description}`)]:[],...optionsOf(command).length?["",colors.yellow("Options:"),...optionsOf(command).map((option)=>` ${colors.green(`--${option.name}${option.accept_value?"=":""}`.padEnd(20))} ${option.description}`)]:[],...command.help?["",colors.yellow("Help:"),command.help]:[]];console.log(marked(lines.join(`
10
- `),process5.stdout))}function takesNext(command,word){return(word.startsWith("--")?optionsOf(command).find((each)=>each.name===word.slice(2)):optionsOf(command).find((each)=>each.shortcut.split("|").includes(word)))?.accept_value===!0}function argumentCount(command,given){let count=0,options=!0,value=!1;for(let word of given){let isValue=value&&!word.startsWith("-");if(value=!1,isValue)continue;if(!options||!word.startsWith("-")||word==="-")count++;else if(word==="--")options=!1;else value=takesNext(command,word)}return count}function commandFor(entry,given){let prompts=argumentsOf(entry.command).filter((argument)=>argument.is_required).slice(argumentCount(entry.command,given));return[...entry.app.run,entry.command.name,...given.map((value)=>({given:value})),...prompts.map((argument)=>({ask:argument.name}))]}async function answered(command,ask){let argv=[],given=[];for(let word of command){if(typeof word==="string"){argv.push(word);continue}let value="given"in word?word.given:await ask(word.ask);if(value===void 0)return;argv.push(value),given.push(value)}return{argv,given}}async function execute(emitting,typed,recorded,command){if(emitting)return emit("run",typed,recorded,command),0;if(!isInteractive()&&command.some((word)=>typeof word==="object"&&("ask"in word)))fail("a required argument is missing and there is no terminal to ask for it",1);let done=await answered(command,async(name)=>input2(`${name}:`,{history:`sf ${recorded||typed} ${name}`,hint:`pass ${name} as an argument after \`j sf ${recorded||typed}\``}));if(done===void 0)return 1;if(recorded!=="")record("sf",{id:recorded,args:done.given});let[argv,cwd]=done.argv[0]==="env"&&done.argv[1]==="-C"&&done.argv[2]!==void 0?[done.argv.slice(3),done.argv[2]]:[done.argv,void 0];return Bun.spawn(argv,{...cwd===void 0?{}:{cwd},stdio:["inherit","inherit","inherit"]}).exited}function listing(found){let sorted=byRecency(found,runs("sf"),key2),labels=sorted.map((entry)=>[key2(entry),signature2(entry.command)].filter(Boolean).join(" ")),width=Math.max(...labels.map((label)=>label.length));return sorted.map((entry,index)=>`${labels[index].padEnd(width)} ${entry.command.description}`.trimEnd()).join(`
9
+ `))}function list(rows){console.log(JSON.stringify(rows))}function splitLast(args,ownOptions){let all={...ownOptions,...OUTPUT_OPTIONS,help:{type:"boolean",short:"h"}},flagType=new Map;for(let[name,option]of Object.entries(all)){let kind=option.type==="string"?"string":"boolean";if(flagType.set(`--${name}`,kind),option.short!==void 0)flagType.set(`-${option.short}`,kind);for(let alias of option.aliases??[])flagType.set(`--${alias}`,kind)}let keyOf=(word)=>{let eq=word.indexOf("=");return eq===-1?word:word.slice(0,eq)},takesValue=(word)=>!word.includes("=")&&flagType.get(word)==="string",isKnown=(word)=>flagType.has(keyOf(word));for(let i=0;i<args.length;i++){let word=args[i];if(word==="--")return;if(word==="-"){let own=args.slice(0,i),rest=[];for(let k=i+1;k<args.length;k++){let next=args[k];if(next==="--"){rest=args.slice(k+1);break}if(isKnown(next)){if(own.push(next),takesValue(next)&&k+1<args.length)own.push(args[++k])}else{rest=args.slice(k);break}}return{own,rest}}if(word.startsWith("-")){if(takesValue(word))i++;continue}return}return}import process4 from"process";import{join as join2}from"path";var QUALIFIED=/^([a-z]+):(?!:)(.+)$/;function build(base,items){return items.map((item)=>({...base,doc:null,parameters:[],...item}))}function just(dir,here){let found=readJustManifest(dir,here);if(found===void 0)return[];return build({kind:"just",tag:"just",runner:["just"],separated:!1,dir},found.recipes)}function make(dir){let found=readMakefileManifest(dir);if(found===void 0)return[];return build({kind:"make",tag:"make",runner:["make"],separated:!1,dir},found.targets)}function packageScripts(dir,here){let found=readPackageManifest(dir,here);if(found===void 0)return[];return build({kind:"package",tag:found.tool,runner:[found.tool,"run"],separated:found.tool==="npm",dir:found.dir},found.scripts.map(({name,body})=>({name,body})))}function composer(dir,here){let found=readComposerManifest(dir,here);if(found===void 0)return[];return build({kind:"composer",tag:"composer",runner:["composer","run"],separated:!0,dir:found.dir},found.scripts)}function deno(dir,here){let found=readDenoManifest(dir,here);if(found===void 0)return[];return build({kind:"deno",tag:"deno",runner:["deno","task"],separated:!1,dir:found.dir},found.tasks)}function taskfile(dir,here){let found=readTaskfileManifest(dir,here);if(found===void 0)return[];return build({kind:"task",tag:"task",runner:["task"],separated:!0,dir:found.dir},found.tasks)}function mise(dir,here){let items=readMiseManifest(dir,here);if(items.length===0)return[];return build({kind:"mise",tag:"mise",runner:["mise","run"],separated:!1,dir},items)}function pyproject(dir,here){let found=readPyprojectManifest(dir,here);if(found===void 0)return[];return[...build({kind:"poe",tag:"poe",runner:found.uv?["uv","run","poe"]:["poe"],separated:!1,dir:found.dir},found.poe),...build({kind:"uv",tag:"uv",runner:["uv","run"],separated:!1,dir:found.dir},found.scripts)]}var READERS=[just,make,packageScripts,composer,deno,taskfile,mise,pyproject],READER_OF={just,make,package:packageScripts,composer,deno,task:taskfile,mise,poe:pyproject,uv:pyproject},MANIFEST_OF=new Map([[just,"justfile"],[make,"Makefile"],[packageScripts,"package.json"],[composer,"composer.json"],[deno,"deno.json"],[taskfile,"Taskfile.yml"],[mise,"mise.toml"],[pyproject,"pyproject.toml"]]);function guarded(reader,dir,here,isWarned=!1){try{return reader(dir,here)}catch(error){if(isWarned)warn(`j: skipped ${join2(dir,MANIFEST_OF.get(reader)??"a manifest")}, it does not parse (${error instanceof Error?error.message:String(error)})`);return[]}}function everything(cwd="."){let here=READERS.flatMap((reader)=>guarded(reader,cwd,!0,!0)),below=folders(cwd).flatMap((dir)=>READERS.flatMap((reader)=>guarded(reader,cwd==="."?dir:join2(cwd,dir),!1,!0))),seen=new Set;return[...here,...below].filter((entry)=>{let id=`${entry.kind} ${entry.dir} ${entry.name}`,fresh=!seen.has(id);return seen.add(id),fresh})}function readKind(kind,dir){return guarded(READER_OF[kind],dir,dir===".").filter((entry)=>entry.kind===kind)}function key(entry){return entry.dir==="."?entry.name:`${entry.dir}/${entry.name}`}function id(entry){return`${entry.tag}:${key(entry)}`}function resolve(entries,named){let qualified=QUALIFIED.exec(named),tagged=qualified&&entries.some((entry)=>entry.tag===qualified[1])?qualified:void 0,pool=tagged?entries.filter((entry)=>entry.tag===tagged[1]):entries,rest=tagged?tagged[2]:named,exact=pool.filter((entry)=>key(entry)===rest);return exact.length>0?exact:pool.filter((entry)=>entry.name===rest)}function shortest(entries,entry){let found=resolve(entries,key(entry));return found.length===1&&found[0]===entry?key(entry):id(entry)}function signature(entry){return entry.parameters.map((parameter)=>parameter.default===null&&parameter.kind==="singular"?`<${parameter.name}>`:`[${parameter.name}]`).join(" ")}var TINTS={just:"yellow",make:"blue",package:"magenta",composer:"cyan",deno:"green",task:"cyan",mise:"red",poe:"green",uv:"green"};function labelled(entries){return new Set(entries.map((entry)=>entry.tag)).size>1}function row(entry,labels,signed){let colors=paint(process4.stderr),keyed=entry.dir==="."?entry.name:`${colors.dim(`${entry.dir}/`)}${entry.name}`;return{hidden:[entry.kind,entry.dir,entry.name,id(entry)],cells:[...labels?[colors[TINTS[entry.kind]](entry.tag)]:[],keyed,...signed?[colors.cyan(signature(entry))]:[],colors.dim(entry.doc??"")]}}async function pickJob(entries,narrowed=!1){let labels=labelled(entries),signed=entries.some((entry)=>signature(entry)!==""),picked=await pick(entries.map((entry)=>row(entry,labels,signed)),{prompt:`${[...new Set(entries.map((entry)=>entry.tag))].join("/")}> `,searched:labels?2:1,...narrowed?{height:heightFor(entries.length)}:{},preview:`${process4.execPath} ${process4.argv[1]} --show {1} {2} {3}`});return entries.find((candidate)=>id(candidate)===picked?.hidden[3])}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"fs";import{dirname as dirname2,join as join3,relative,resolve as resolve2}from"path";import process5 from"process";var usage="j sf [--service <name>] [command] [args...]\nj sf -\n\nPicks a Symfony console command on a terminal and runs it, asking for each required argument; without a terminal (a script, a pipe, an agent) it lists the commands, the form to use there.\nThe console is the nearest `bin/console` up to the repository root, then those of the child folders (keyed `api/cache:clear`), run in the auto-detected or configured PHP compose service when there is one (or on the host with `--host`), else with local php.\n`j sf -` runs the last command again with its arguments, `j sf <command> [args...]` runs without the picker, a name the list does not hold going to the console as is.",EXITS=[["the code of the console","a command it ran"],[0,"it listed the commands"],[1,"no bin/console here, or it listed no command"],[2,"a usage error"]],sfOptions={service:{type:"string",short:"s",aliases:["in"],conflicts:["host"],description:"compose service running PHP (overrides auto-detection and config.jsonc#sf.service)"},host:{type:"boolean",conflicts:["service"],description:"run on the host with local php even when a compose service mounts the folder"},list:{type:"boolean",short:"l",description:"list the commands without opening the picker"},json:jsonOption("[{ name, command, dir, description, signature, arguments, options }]")},MARKUP=/<(info|comment|question|error)>(.*?)<\/\1>/gs,TAGS={info:"green",comment:"yellow",question:"cyan",error:"red"},LINKS=/<\/?href[^>]*>/g,NAME_PARTS=/[-_]/,PHP_PROFILE=/\b(?:php|frankenphp)\b/i,PHPMYADMIN=/phpmyadmin/i;function marked(text,stream=process5.stdout){let colors=paint(stream);return text.replace(MARKUP,(_,tag,inner)=>colors[TAGS[tag]](inner)).replace(LINKS,"")}function argumentsOf(command){return Array.isArray(command.definition.arguments)?[]:Object.values(command.definition.arguments)}function optionsOf(command){return Array.isArray(command.definition.options)?[]:Object.values(command.definition.options)}function fromDir(dir,command){return dir==="."?command:["env","-C",dir,...command]}function up2(dir){let dirs=[];for(let current=dir;;current=join3(current,"..")){dirs.push(current);let absolute=resolve2(current);if(existsSync2(join3(current,".git"))||dirname2(absolute)===absolute)return dirs}}function children(dir="."){let ignored=ignoredFolders();return readdirSync(dir,{withFileTypes:!0}).filter((child)=>child.isDirectory()&&!child.name.startsWith(".")&&!ignored.has(child.name)).map((child)=>child.name).toSorted()}function phpService(candidates,configured){let list=candidates.map((item)=>typeof item==="string"?{name:item,profile:item.toLowerCase()}:item);if(configured!==void 0&&configured!==""){let exact=list.find((item)=>item.name===configured);if(exact!==void 0)return exact.name}return list.find((item)=>item.name==="php")?.name??list.find((item)=>item.name.split(NAME_PARTS).includes("php"))?.name??list.find((item)=>!PHPMYADMIN.test(item.profile)&&PHP_PROFILE.test(item.profile))?.name}function configuredService(){let value=readUserConfig("sf").service;return typeof value==="string"&&value!==""?value:void 0}function mountsDir(service,absDir){return service.mounts.some((mount)=>{let inside=relative(mount.source,absDir);return!inside.startsWith("..")&&!inside.startsWith("/")})}async function consoleAt(dir,settings={}){let absDir=resolve2(dir),placement;if(settings.service!==void 0)placement=await place(absDir,"php",settings);else if(settings.host!==!0){let composeDir=findComposeDir(absDir),mounting=((composeDir===void 0?void 0:await readServices(composeDir))??[]).filter((candidate)=>mountsDir(candidate,absDir)),php=mounting.length===0?void 0:phpService(mounting,configuredService());if(php!==void 0)placement=Bun.which("docker",{PATH:process5.env.PATH??""})===null?await place(absDir,"php"):await place(absDir,"php",{service:php})}if(placement!==void 0){let relCompose=relative(process5.cwd(),placement.composeDir)||".",exec=argvIn(placement,["bin/console"]);return{dir,run:fromDir(relCompose,exec),list:{argv:exec,cwd:placement.composeDir,env:process5.env}}}return{dir,run:fromDir(dir,["php","bin/console"]),list:{argv:["php","bin/console"],cwd:absDir,env:process5.env}}}function hasConsole(dir="."){return up2(dir).some((candidate)=>existsSync2(join3(candidate,"bin/console")))||children(dir).some((child)=>existsSync2(join3(dir,child,"bin/console")))}async function consoles(settings={}){let here=up2(".").find((dir)=>existsSync2(join3(dir,"bin/console"))),dirs=[...here===void 0?[]:[here],...children().filter((dir)=>existsSync2(join3(dir,"bin/console")))];return Promise.all([...new Set(dirs)].map(async(dir)=>consoleAt(dir,settings)))}function cached(dir){return join3(cacheFolder(),"sf",`${resolve2(dir).replaceAll("/","%")}.json`)}function fromCache(dir){try{return existsSync2(cached(dir))?JSON.parse(readFileSync2(cached(dir),"utf-8")):void 0}catch{return}}async function live(app){let commands;try{let ran=await captureOutput([...app.list.argv,"list","--format=json"],{cwd:app.list.cwd,env:app.list.env});if(ran.code!==0)return fromCache(app.dir)??[];commands=JSON.parse(ran.stdout).commands.filter((command)=>!command.hidden)}catch{return fromCache(app.dir)??[]}return mkdirSync2(dirname2(cached(app.dir)),{recursive:!0}),writeFileSync2(cached(app.dir),JSON.stringify(commands)),commands}async function entries(fresh,settings={}){let found=await consoles(settings),lists=await Promise.all(found.map(async(app)=>fresh?live(app):fromCache(app.dir)??live(app)));return found.flatMap((app,index)=>lists[index].map((command)=>({app,command})))}function key2(entry){return entry.app.dir==="."?entry.command.name:`${entry.app.dir}/${entry.command.name}`}function named(name,colors){let colon=name.lastIndexOf(":");return colon===-1?name:`${colors.dim(name.slice(0,colon+1))}${name.slice(colon+1)}`}function signature2(command){return argumentsOf(command).map((argument)=>`${argument.is_required?"<":"["}${argument.name}${argument.is_array?"...":""}${argument.is_required?">":"]"}`).join(" ")}function entryJson(entry){let{command}=entry;return{name:key2(entry),command:command.name,dir:entry.app.dir,description:command.description,signature:signature2(command),arguments:argumentsOf(command).map((argument)=>({name:argument.name,required:argument.is_required,array:argument.is_array,description:argument.description})),options:optionsOf(command).map((option)=>({name:option.name,shortcut:option.shortcut,acceptsValue:option.accept_value,description:option.description}))}}function rows(found){let colors=paint(process5.stderr);return byRecency(found,runs("sf"),key2).map((entry)=>({hidden:[entry.app.dir,entry.command.name],cells:[entry.app.dir==="."?named(entry.command.name,colors):`${colors.dim(`${entry.app.dir}/`)}${named(entry.command.name,colors)}`,colors.cyan(signature2(entry.command)),colors.dim(entry.command.description)]}))}function optionLabel(option){let long=`${option.name}${option.accept_value?"=":""}`;return option.shortcut?`${option.shortcut.replaceAll("|",", ")}, ${long}`:` ${long}`}function preview(dir,name){let command=(fromCache(dir)??[]).find((candidate)=>candidate.name===name);if(!command)return;let colors=paint(process5.stdout),lines=[colors.bold(command.description),"",colors.yellow("Usage:"),...command.usage.map((line)=>` ${line}`),...argumentsOf(command).length?["",colors.yellow("Arguments:"),...argumentsOf(command).map((argument)=>` ${colors.green(argument.name.padEnd(20))} ${argument.description}`)]:[],...optionsOf(command).length?["",colors.yellow("Options:"),...optionsOf(command).map((option)=>` ${colors.green(optionLabel(option).padEnd(24))} ${option.description}`)]:[],...command.help?["",colors.yellow("Help:"),command.help]:[]];console.log(marked(lines.join(`
10
+ `),process5.stdout))}function takesNext(command,word){return(word.startsWith("--")?optionsOf(command).find((each)=>each.name===word):optionsOf(command).find((each)=>each.shortcut.split("|").includes(word)))?.accept_value===!0}function argumentCount(command,given){let count=0,options=!0,value=!1;for(let word of given){let isValue=value&&!word.startsWith("-");if(value=!1,isValue)continue;if(!options||!word.startsWith("-")||word==="-")count++;else if(word==="--")options=!1;else value=takesNext(command,word)}return count}function commandFor(entry,given){let prompts=argumentsOf(entry.command).filter((argument)=>argument.is_required).slice(argumentCount(entry.command,given));return[...entry.app.run,entry.command.name,...given.map((value)=>({given:value})),...prompts.map((argument)=>({ask:argument.name}))]}async function answered(command,ask){let argv=[],given=[];for(let word of command){if(typeof word==="string"){argv.push(word);continue}let value="given"in word?word.given:await ask(word.ask);if(value===void 0)return;argv.push(value),given.push(value)}return{argv,given}}async function execute(emitting,typed,recorded,command){if(emitting)return emit("run",typed,recorded,command),0;if(!isInteractive()&&command.some((word)=>typeof word==="object"&&("ask"in word)))fail("a required argument is missing and there is no terminal to ask for it",1);let done=await answered(command,async(name)=>input2(`${name}:`,{history:`sf ${recorded||typed} ${name}`,hint:`pass ${name} as an argument after \`j sf ${recorded||typed}\``}));if(done===void 0)return 1;if(recorded!=="")record("sf",{id:recorded,args:done.given});let[argv,cwd]=done.argv[0]==="env"&&done.argv[1]==="-C"&&done.argv[2]!==void 0?[done.argv.slice(3),done.argv[2]]:[done.argv,void 0];return Bun.spawn(argv,{...cwd===void 0?{}:{cwd},stdio:["inherit","inherit","inherit"]}).exited}function listing(found){let sorted=byRecency(found,runs("sf"),key2),labels=sorted.map((entry)=>[key2(entry),signature2(entry.command)].filter(Boolean).join(" ")),width=Math.max(...labels.map((label)=>label.length));return sorted.map((entry,index)=>`${labels[index].padEnd(width)} ${entry.command.description}`.trimEnd()).join(`
11
11
  `)}async function hidden(flag,rest,termList){if(flag==="--show")return preview(rest[0]??".",rest[1]??""),0;if(flag==="--record")return record("sf",{id:rest[0]??"",args:rest.slice(1)}),0;if(flag==="--rows")return console.log(table2(rows(await entries(!0))).join(`
12
12
  `)),0;if(!termList&&flag!=="--names")return;let refreshed=termList&&(await consoles()).some((found)=>fromCache(found.dir)!==void 0),found=await entries(!1);if(flag==="--names")return console.log(found.map((entry)=>`${key2(entry)} ${entry.command.description}`).join(`
13
13
  `)),0;if(refreshed)Bun.spawn([process5.execPath,process5.argv[1],"sf","--rows"],{stdio:["ignore","ignore","ignore"]}).unref();return list(byRecency(found,runs("sf"),key2).map((entry)=>({label:[key2(entry),signature2(entry.command)].filter(Boolean).join(" "),hint:entry.command.description,typed:key2(entry),preview:["--show",entry.app.dir,entry.command.name]}))),0}async function sf(args){let[flag=""]=args,termList=args.length===1&&flag==="--list"&&outputMode(process5.stdout)==="pipe",flagged=await hidden(flag,args.slice(1),termList);if(flagged!==void 0)return flagged;let emitting=flag==="--emit",words=emitting?args.slice(1):args,last=splitLast(words,sfOptions),parsed=parse(last?last.own:words,usage,sfOptions,{positionals:["[command]"],trailing:!0,exits:EXITS,replaces:"bin/console typed in the php container, with the command names and arguments looked up by hand",examples:["j sf",["j sf cache:clear","run it without the picker"],["j sf -s app cache:clear","target a custom PHP service"],["j sf -s app --json","list commands as JSON from a custom service"],["j sf --host cache:clear","run with local php instead of compose"],["j sf -","the last command again, with its arguments"]]}),command=last?void 0:parsed.positionals[0],given=last?last.rest:parsed.rest??[],settings={service:parsed.values.service,host:parsed.values.host},json=parsed.values.json===!0,listOnly=parsed.values.list===!0;if(json&&command===void 0&&!last){let found=await entries(!1,settings);return printJson(byRecency(found,runs("sf"),key2).map(entryJson)),0}let refreshed=command===void 0&&!last&&!listOnly&&(await consoles(settings)).some((found)=>fromCache(found.dir)!==void 0),found=await entries(!1,settings);if(last){let previous=runs("sf")[0],entry=previous&&found.find((candidate)=>key2(candidate)===previous.id);if(entry===void 0)fail(previous?`${previous.id} is gone`:"nothing run here yet",1);return execute(emitting,key2(entry),key2(entry),commandFor(entry,[...previous.args,...given]))}if(command!==void 0){let entry=found.find((candidate)=>key2(candidate)===command)??found.find((candidate)=>candidate.command.name===command);if(entry!==void 0)return execute(emitting,key2(entry),key2(entry),commandFor(entry,given));let[first]=await consoles(settings);if(first===void 0)fail("no bin/console here",1);return execute(emitting,command,"",[...first.run,command,...given.map((value)=>({given:value}))])}if(found.length===0)fail("no bin/console here, or it listed no command",1);if(listOnly||!isInteractive()){if(emitting)fail("the picker needs a terminal",1);return console.log(listing(found)),0}let picked=await pick(rows(found),{prompt:"sf> ",searched:1,preview:`${process5.execPath} ${process5.argv[1]} sf --show {1} {2}`,reload:refreshed?{onOpen:!0,run:async()=>({rows:rows(await entries(!0,settings))})}:void 0}),entry=picked&&(await entries(!1,settings)).find((candidate)=>candidate.app.dir===picked.hidden[0]&&candidate.command.name===picked.hidden[1]);return entry===void 0?1:execute(emitting,key2(entry),key2(entry),commandFor(entry,[]))}var usage2="j [name] [args...] [--in <service> | --host] [--list] [--json]\nj sf [--service <name>] [command] [args...]\nj -\n\nWithout a name, picks a recipe, script or task of this folder, its parents and its child folders and runs it, the ones run last first; without a terminal it lists them instead.\n`j -` runs the last one again with the same arguments, `j <name> [args...]` runs without the picker, the words after the name filling the parameters in order.\n`j sf [command] [args...]` (or `j sf:<command>`) picks or runs a Symfony `bin/console` command in the PHP compose service or local php.\nThe sources are a Justfile, a Makefile, package.json and composer.json scripts, deno tasks, a Taskfile, mise tasks, a pyproject and Symfony `bin/console`; a name several share offers them, unless qualified by its runner (`just:check`, `sf:cache:clear`).\nA script runs in the compose service that bind-mounts its folder, a Justfile, Makefile, Taskfile or mise task on the host, as its recipes drive the stack; `--in` and `--host` override either.",EXITS2=[["its own","the code of the command it ran"],[1,"there is nothing to run here or nothing by that name"]],options={...placeOptions,list:{type:"boolean",short:"l",description:"list the jobs without opening the picker"},json:jsonOption("[{ id, key, runner, dir, name, doc, parameters }]")};function preview2(kind,dir,name){let entry=readKind(kind,dir).find((candidate)=>candidate.name===name);if(entry===void 0)return;let colors=paint(process6.stdout);if(console.log(`${colors.dim(`$ ${dir==="."?"":`env -C ${dir} `}`)}${colors.bold([...entry.runner,entry.name].join(" "))}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-check",
3
3
  "type": "module",
4
- "version": "0.27.0",
4
+ "version": "0.28.2",
5
5
  "description": "check and j: run a repo's check, typecheck, lint, format check and test steps or, with --fix, its fixers, and pick/run recipes, scripts, tasks and Symfony console commands.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -37,6 +37,6 @@
37
37
  "j": "$npm_execpath src/j-cli.ts"
38
38
  },
39
39
  "devDependencies": {
40
- "@kaynooo/cli-kit": "0.53.0"
40
+ "@kaynooo/cli-kit": "0.54.2"
41
41
  }
42
42
  }
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{input2}from"./chunk-mhj3d5hy.js";import"./chunk-7d3myeb5.js";export{input2 as input};