@kaynooo/cli-view 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/view.js +17 -12
- package/package.json +2 -2
- package/src/view.ts +19 -56
package/dist/view.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import process from"process";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 canPage(stream=process.stdout,env=process.env){return isHumanTerminal(stream,env)}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G.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)]}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 G,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G=/^[a-f0-9]+$/i;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"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});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}}var init_config=__esm(()=>{init_args()});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";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 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))}var FILE_CACHE;var init_user_config=__esm(()=>{FILE_CACHE=new Map});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";function toLinear(channel){let value=channel/255;return value<=0.04045?value/12.92:((value+0.055)/1.055)**2.4}function toOklab(hex){let[r,g,b]=[1,3,5].map((at)=>toLinear(Number.parseInt(hex.slice(at,at+2),16))),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b);return[0.2104542553*l+0.793617785*m-0.0040720468*s,1.9779984951*l-2.428592205*m+0.4505937099*s,0.0259040371*l+0.7827717662*m-0.808675766*s]}function fromOklab([lightness,a,b]){let l=(lightness+0.3963377774*a+0.2158037573*b)**3,m=(lightness-0.1055613458*a-0.0638541728*b)**3,s=(lightness-0.0894841775*a-1.291485548*b)**3;return`#${[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s].map((channel)=>fromLinear(channel).toString(16).padStart(2,"0")).join("")}`}function gradientAt(theme,ratio){if(theme.gradient===void 0)return;let key=theme.gradient.join(),ends=ENDS.get(key);if(ends===void 0)ends=[toOklab(theme.gradient[0]),toOklab(theme.gradient[1])],ENDS.set(key,ends);let at=Math.min(1,Math.max(0,ratio)),[from,to]=ends;return fromOklab(from.map((start,index)=>start+(to[index]-start)*at))}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))}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"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}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}}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 fromLinear=(value)=>Math.round(255*Math.min(1,Math.max(0,value<=0.0031308?value*12.92:1.055*value**0.4166666666666667-0.055))),ENDS,DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();ENDS=new Map;DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",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",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",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:"#",rule:"-",corner:"+",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,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process5 from"process";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 role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}function link(text,url,stream,env=process5.env){if(takesControlCodes(stream,env))return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;return text===url?text:`${text} (${url})`}var STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();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])))});function stripAnsi(text){return text.replace(ANSI,"")}function stripControls(text){return text.replace(CONTROLS,"")}function escapeControls(text){return text.replace(CONTROLS,(char)=>{let code=char.charCodeAt(0);if(code===127)return"^?";return code<128?`^${String.fromCharCode(code+64)}`:`M-^${String.fromCharCode(code-64)}`})}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 ANSI,CONTROLS,ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text=__esm(()=>{ANSI=/\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;CONTROLS=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;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}\\`});import process6 from"process";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 textWidth(text){return Bun.stringWidth(text)}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))}var UNITS;var init_format=__esm(()=>{init_mode();init_style();init_text();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]]});import process7 from"process";function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
3
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import process from"process";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 canPage(stream=process.stdout,env=process.env){return isHumanTerminal(stream,env)}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G.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)]}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 G,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G=/^[a-f0-9]+$/i;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"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});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}}var init_config=__esm(()=>{init_args()});var init_jsonc=()=>{};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";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 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))}var FILE_CACHE;var init_user_config=__esm(()=>{init_jsonc();FILE_CACHE=new Map});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";function toLinear(channel){let value=channel/255;return value<=0.04045?value/12.92:((value+0.055)/1.055)**2.4}function toOklab(hex){let[r,g,b]=[1,3,5].map((at)=>toLinear(Number.parseInt(hex.slice(at,at+2),16))),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b);return[0.2104542553*l+0.793617785*m-0.0040720468*s,1.9779984951*l-2.428592205*m+0.4505937099*s,0.0259040371*l+0.7827717662*m-0.808675766*s]}function fromOklab([lightness,a,b]){let l=(lightness+0.3963377774*a+0.2158037573*b)**3,m=(lightness-0.1055613458*a-0.0638541728*b)**3,s=(lightness-0.0894841775*a-1.291485548*b)**3;return`#${[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s].map((channel)=>fromLinear(channel).toString(16).padStart(2,"0")).join("")}`}function blend(gradient,ratio){let key=gradient.join(),ends=ENDS.get(key);if(ends===void 0)ends=[toOklab(gradient[0]),toOklab(gradient[1])],ENDS.set(key,ends);let at=Math.min(1,Math.max(0,ratio)),[from,to]=ends;return fromOklab(from.map((start,index)=>start+(to[index]-start)*at))}function gradientAt(theme,ratio){return theme.gradient===void 0?void 0:blend(theme.gradient,ratio)}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))}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"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),process4.stderr.write(`warning: theme ${message}
|
|
4
|
+
`)}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}}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 fromLinear=(value)=>Math.round(255*Math.min(1,Math.max(0,value<=0.0031308?value*12.92:1.055*value**0.4166666666666667-0.055))),ENDS,DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();ENDS=new Map;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,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process5 from"process";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 writeErr(text=""){process5.stderr.write(`${text}
|
|
5
|
+
`)}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}function link(text,url,stream,env=process5.env){if(takesControlCodes(stream,env))return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;return text===url?text:`${text} (${url})`}var STATUS_WORDS,STATUS_OF,GRAPHEMES;var init_style=__esm(()=>{init_colors();init_mode();init_theme();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]))),GRAPHEMES=new Intl.Segmenter});function stripAnsi(text){return text.replace(ANSI,"")}function stripControls(text){return text.replace(CONTROLS,"")}function escapeControls(text){return text.replace(CONTROLS,(char)=>{let code=char.charCodeAt(0);if(code===127)return"^?";return code<128?`^${String.fromCharCode(code+64)}`:`M-^${String.fromCharCode(code-64)}`})}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}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]}var ANSI,CONTROLS,ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text=__esm(()=>{ANSI=/\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;CONTROLS=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;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}\\`});import process6 from"process";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 textWidth(text){return Bun.stringWidth(text)}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))}var UNITS;var init_format=__esm(()=>{init_mode();init_style();init_text();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]]});import process7 from"process";function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
4
6
|
`),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(`
|
|
5
7
|
`)}`,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(`
|
|
6
8
|
`)}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(`
|
|
7
|
-
`)}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 description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
8
|
-
`),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:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}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]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}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]:wrapText(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 OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_AGENT_EXAMPLES=2,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});import process8 from"process";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}async function readInput(path,{noStdin="nothing is piped on stdin"}={}){if(path==="-"){if(process8.stdin.isTTY)fail(noStdin);return Bun.stdin.text()}let file=Bun.file(path);if(!await file.exists())fail(`no file ${path}`);return file.text()}var WHOLE;var init_input=__esm(()=>{init_args();WHOLE=/^\d+$/});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.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(process9.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,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(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.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)}`}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)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");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}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},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"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});import{existsSync as existsSync4}from"fs";import process17 from"process";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.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&&(resolve3(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}init_format();init_mode();init_style();init_theme();init_args();init_format();init_format();init_style();init_text();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join5}from"path";import process14 from"process";import process11 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process11.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process11.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
9
|
-
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return
|
|
10
|
-
`),0}init_args();var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
9
|
+
`)}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(`
|
|
10
|
+
`),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)}}}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]}`)}`)]}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 OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_AGENT_EXAMPLES=2,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();init_text();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});import process8 from"process";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}async function readInput(path,{noStdin="nothing is piped on stdin"}={}){if(path==="-"){if(process8.stdin.isTTY)fail(noStdin);return Bun.stdin.text()}let file=Bun.file(path);if(!await file.exists())fail(`no file ${path}`);return file.text()}var WHOLE;var init_input=__esm(()=>{init_args();WHOLE=/^\d+$/});import{AsyncLocalStorage}from"async_hooks";import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.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(process9.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(process9.stdout)?process9.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)}`}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)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,parseContext,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");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}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};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"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_process=()=>{};import process13 from"process";async function askpassClient(argv){let socketPath=process13.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process13.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
11
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process13.stdout.write(`${answer}
|
|
12
|
+
`),0}var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";var init_askpass=()=>{};var init_folders=__esm(()=>{init_user_config()});import process17 from"process";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.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&&(resolve3(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}init_format();init_mode();init_style();init_theme();init_args();init_format();init_style();init_format();init_process();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join5}from"path";import process14 from"process";init_args();var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
11
13
|
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'
|
|
12
14
|
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
13
15
|
set -l current (commandline -ct)
|
|
@@ -62,12 +64,15 @@ autoload -Uz add-zsh-hook
|
|
|
62
64
|
add-zsh-hook precmd __kaynooo_cli_register
|
|
63
65
|
typeset -gaU __kaynooo_cli_bins
|
|
64
66
|
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
65
|
-
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}init_mode();init_format();init_mode();import
|
|
67
|
+
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}init_mode();init_format();init_mode();import process11 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process11.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process11.pid}`,codes=[`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`,`\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process11.stderr,env=process11.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}init_style();init_text();init_theme();import{appendFileSync,mkdirSync as mkdirSync2,readFileSync as readFileSync4,renameSync,statSync as statSync3,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname3,join as join4}from"path";import process12 from"process";init_user_config();var CLI_FOLDER="kaynooo-cli";init_user_config();var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process12.env){return xdgFolder(env.XDG_STATE_HOME,join4(homedir3(),".local","state"))}function usagePath(env=process12.env){return join4(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process12.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,mode,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)},...mode===void 0?{}:{mode}}}function trimUsage(path,maxBytes){let info=statSync3(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync4(path,"utf8").split(`
|
|
66
68
|
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
67
69
|
`)}
|
|
68
|
-
`,temp=`${path}.${
|
|
69
|
-
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};function printError(prefix,message,hint,cause){
|
|
70
|
-
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){console.error(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv),printError);if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();heading.bin={name,version:()=>version??packageVersion()};try{code=await run(argv)}catch(error){meta=error instanceof HelpShown,code=reportThrown(name,error,redact,wantsJson(argv))}finally{heading.bin=void 0}if(notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}init_args();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]]);init_style();init_config();init_text();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();import{basename,dirname as dirname5,join as join6,relative,sep}from"path";var PARENT=`..${sep}`;var WORD_START=/[a-z_$]/i,WORD=/^[\w$-]+/,NUMBER=/^(?:0x[\da-f_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)/i,PREVIOUS_WORD=/[\w$]$/,AFTER_KEY=/^\s*:/,YAML_KEY=/^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/,SETTING_KEY=/^(\s*)([\w.-]+)(?=\s*[=:])/,SECTION=/^\s*\[.*\]\s*$/,WHITESPACE=/\s/,FLAG=/^--?[a-z][\w-]*/i,COMMAND_END=/[|&;(]\s*$/,PROMPT=/^\s*(?:[$>]\s*)?$/,DIGIT=/\d/,TRAILING_NEWLINE=/\n$/,LEADING_DOT=/^\./,TRIPLE_QUOTES=['"""',"'''"];function words(list){return new Set(list.split(" "))}var SLASHES={line:["//"],block:["/*","*/"]},HASH={line:["#"]},CONSTANTS="true false null undefined NaN Infinity",C_LIKE="if else for while do switch case default break continue return throw try catch finally new delete typeof instanceof in of void yield await async static public private protected readonly abstract extends implements super this",SCRIPT=`${C_LIKE} const let var function class import export from as type interface enum namespace declare satisfies keyof is get set ${CONSTANTS}`,LANGUAGES={script:{...SLASHES,quotes:"\"'`",keywords:words(SCRIPT)},json:{line:[],quotes:'"',keywords:words("true false null"),quotedKeys:!0},jsonc:{...SLASHES,quotes:'"',keywords:words("true false null"),quotedKeys:!0},python:{...HASH,quotes:`"'`,keywords:words("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self")},shell:{...HASH,commands:!0,quotes:"\"'`",keywords:words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not")},yaml:{...HASH,quotes:`"'`,keywords:words("true false null yes no"),key:YAML_KEY,quotedKeys:!0},toml:{...HASH,quotes:`"'`,keywords:words("true false"),key:SETTING_KEY,section:SECTION},ini:{line:["#",";"],quotes:`"'`,keywords:words("true false yes no on off"),key:SETTING_KEY,section:SECTION},css:{line:[],block:["/*","*/"],quotes:`"'`,keywords:words("important inherit initial unset auto none")},html:{line:[],block:["<!--","-->"],quotes:`"'`,keywords:words("")},sql:{line:["--"],block:["/*","*/"],quotes:"\"'`",caseInsensitive:!0,keywords:words("select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full on group by order having limit offset as distinct union all null is in like between case when then else end primary key foreign references default unique with returning true false")},rust:{...SLASHES,quotes:'"',keywords:words("fn let mut const static struct enum impl trait pub use mod crate self super if else match for while loop break continue return as in ref move async await dyn where type unsafe true false None Some Ok Err")},go:{...SLASHES,quotes:"\"'`",keywords:words("func var const type struct interface map chan package import if else for range switch case default break continue return go defer select fallthrough goto nil true false")},php:{...SLASHES,line:["//","#"],quotes:`"'`,keywords:words(`${C_LIKE} function class interface trait namespace use public private protected static final echo array fn match list isset empty require include require_once include_once true false null`)},java:{...SLASHES,quotes:`"'`,keywords:words(`${C_LIKE} class interface enum package import final void int long double float boolean char byte short true false null var record`)},c:{...SLASHES,quotes:`"'`,keywords:words(`${C_LIKE} struct union typedef enum const volatile extern sizeof void int long double float char short unsigned signed auto register inline static include define ifdef ifndef endif pragma true false NULL nullptr class template typename namespace using bool`)},ruby:{...HASH,quotes:`"'`,keywords:words("def end class module if elsif else unless while until for in do begin rescue ensure return yield self nil true false and or not require require_relative include extend attr_accessor attr_reader puts then case when")},lua:{line:["--"],quotes:`"'`,keywords:words("function end if then else elseif for while do repeat until return local break in and or not nil true false")},dockerfile:{...HASH,quotes:`"'`,caseInsensitive:!0,keywords:words("from run cmd label expose env add copy entrypoint volume user workdir arg onbuild stopsignal healthcheck shell as")},makefile:{...HASH,quotes:`"'`,keywords:words("ifeq ifneq ifdef ifndef else endif include define endef export")}},ALIASES={script:["ts","tsx","mts","cts","js","jsx","mjs","cjs","typescript","javascript","vue","svelte"],json:["json","jsonl","ndjson"],jsonc:["jsonc","json5"],python:["py","python"],shell:["sh","bash","zsh","fish","shell","console"],yaml:["yml","yaml"],toml:["toml"],ini:["ini","conf","cfg","properties","editorconfig"],css:["css","scss","less"],html:["html","htm","xml","svg"],sql:["sql"],rust:["rs","rust"],go:["go","golang"],php:["php"],java:["java","kt","kts","cs","swift","dart","scala"],c:["c","h","cpp","cc","hpp","cxx"],ruby:["rb","ruby"],lua:["lua"],dockerfile:["dockerfile","containerfile"],makefile:["makefile","mk","just","justfile"]},BY_NAME=new Map(Object.entries(ALIASES).flatMap(([name,aliases])=>aliases.map((alias)=>[alias,name]))),EXTENSION=/\.([^./]+)$/,BASENAME=/[^/]*$/;function languageOf(nameOrPath){let base=(BASENAME.exec(nameOrPath)?.[0]??"").toLowerCase(),extension=EXTENSION.exec(base)?.[1];return BY_NAME.get(extension??base)??BY_NAME.get(base.replace(LEADING_DOT,""))}function paintLines(text,paint){return text.split(`
|
|
70
|
+
`,temp=`${path}.${process12.pid}.tmp`;writeFileSync2(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process12.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync2(dirname3(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
71
|
+
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};var HINT_CODE=/`[^`\n]+`/g;function styleHint(text,accent){return text.replaceAll(HINT_CODE,(match)=>accent(match))}function printError(prefix,message,hint,cause){if(!takesControlCodes(process14.stderr)){let causeLine=cause===void 0?"":`
|
|
72
|
+
cause: ${cause}`,hintLine=hint===void 0?"":`
|
|
73
|
+
hint: ${hint}`;writeErr(`error: ${prefix}: ${message}${causeLine}${hintLine}`);return}let colors=paint(process14.stderr),{theme}=activeTheme(),mark=tinted(colors.bold,theme.colors.problem)(theme.glyphs.problem),muted=tinted(colors,theme.colors.label),warn=tinted(colors,theme.colors.warn),accent=tinted(colors,theme.colors.accent),causeLine=cause===void 0?"":`
|
|
74
|
+
${muted("cause")} ${cause}`,hintLine=hint===void 0?"":`
|
|
75
|
+
${warn("hint")} ${styleHint(hint,accent)}`;writeErr(`${mark} ${colors.bold(prefix)}${muted(":")} ${message}${causeLine}${hintLine}`)}function printJsonError(message,hint,cause,extra){writeErr(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}var LEVEL_VALUE_FLAGS=new Set(["--color","--completions"]);function wantsJson(argv,options){let json=!1;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--")break;if(arg==="--json"){json=!0;continue}if(arg==="--no-json"){json=!1;continue}if(LEVEL_VALUE_FLAGS.has(arg)){i++;continue}if(options!==void 0&&arg.startsWith("-")&&!arg.includes("=")){if(Object.entries(options).some(([name,{short,type}])=>type==="string"&&(arg===`--${name}`||arg===`-${short}`))&&argv[i+1]!==void 0&&!(argv[i+1]==="--json"&&Object.hasOwn(options,"json")))i++}}return json}async function maybeAskpass(argv){if(process14.env.KAYNOOO_ASKPASS_SOCKET===void 0)return;await Promise.resolve().then(() => init_askpass());return askpassClient(argv)}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await maybeAskpass(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv),printError);if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();if(heading.bin={name,version:()=>version??packageVersion()},await parseContext.run({},async()=>{try{code=await run(argv)}catch(error){let ctx=parseContext.getStore(),json=ctx?.json??wantsJson(argv,ctx?.options);meta=error instanceof HelpShown,code=reportThrown(name,error,redact,json)}finally{heading.bin=void 0}}),notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}init_args();init_process();init_style();init_config();init_text();init_folders();init_format();init_args();init_args();init_mode();init_process();init_style();init_text();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_args();import{existsSync as existsSync4}from"fs";var FILE_SPAN=/^(.+):(\d+)(?:-(\d*))?$/;function parseFileSpan(arg,exists=existsSync4){if(arg==="-"||exists(arg))return{raw:arg,path:arg};let match=FILE_SPAN.exec(arg);if(match===null)return{raw:arg,path:arg};let start=Number(match[2]),end;if(match[3]===void 0)end=start;else if(match[3]!=="")end=Number(match[3]);if(start<1||end!==void 0&&end<start)badUsage(`invalid line range in '${arg}'`);return{raw:arg,path:match[1],start,...end===void 0?{}:{end}}}init_style();init_text();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();init_process();import{basename,dirname as dirname5,join as join6,relative,sep}from"path";var PARENT=`..${sep}`;var WORD_START=/[a-z_$]/i,WORD=/^[\w$-]+/,NUMBER=/^(?:0x[\da-f_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)/i,PREVIOUS_WORD=/[\w$]$/,AFTER_KEY=/^\s*:/,YAML_KEY=/^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/,SETTING_KEY=/^(\s*)([\w.-]+)(?=\s*[=:])/,SECTION=/^\s*\[.*\]\s*$/,WHITESPACE=/\s/,FLAG=/^--?[a-z][\w-]*/i,COMMAND_END=/[|&;(]\s*$/,PROMPT=/^\s*(?:[$>]\s*)?$/,DIGIT=/\d/,TRAILING_NEWLINE=/\n$/,LEADING_DOT=/^\./,TRIPLE_QUOTES=['"""',"'''"];function words(list){return new Set(list.split(" "))}var SLASHES={line:["//"],block:["/*","*/"]},HASH={line:["#"]},CONSTANTS="true false null undefined NaN Infinity",C_LIKE="if else for while do switch case default break continue return throw try catch finally new delete typeof instanceof in of void yield await async static public private protected readonly abstract extends implements super this",SCRIPT=`${C_LIKE} const let var function class import export from as type interface enum namespace declare satisfies keyof is get set ${CONSTANTS}`,LANGUAGES={script:{...SLASHES,quotes:"\"'`",keywords:words(SCRIPT)},json:{line:[],quotes:'"',keywords:words("true false null"),quotedKeys:!0},jsonc:{...SLASHES,quotes:'"',keywords:words("true false null"),quotedKeys:!0},python:{...HASH,quotes:`"'`,keywords:words("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self")},shell:{...HASH,commands:!0,quotes:"\"'`",keywords:words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not")},yaml:{...HASH,quotes:`"'`,keywords:words("true false null yes no"),key:YAML_KEY,quotedKeys:!0},toml:{...HASH,quotes:`"'`,keywords:words("true false"),key:SETTING_KEY,section:SECTION},ini:{line:["#",";"],quotes:`"'`,keywords:words("true false yes no on off"),key:SETTING_KEY,section:SECTION},css:{line:[],block:["/*","*/"],quotes:`"'`,keywords:words("important inherit initial unset auto none")},html:{line:[],block:["<!--","-->"],quotes:`"'`,keywords:words("")},sql:{line:["--"],block:["/*","*/"],quotes:"\"'`",caseInsensitive:!0,keywords:words("select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full on group by order having limit offset as distinct union all null is in like between case when then else end primary key foreign references default unique with returning true false")},rust:{...SLASHES,quotes:'"',keywords:words("fn let mut const static struct enum impl trait pub use mod crate self super if else match for while loop break continue return as in ref move async await dyn where type unsafe true false None Some Ok Err")},go:{...SLASHES,quotes:"\"'`",keywords:words("func var const type struct interface map chan package import if else for range switch case default break continue return go defer select fallthrough goto nil true false")},php:{...SLASHES,line:["//","#"],quotes:`"'`,keywords:words(`${C_LIKE} function class interface trait namespace use public private protected static final echo array fn match list isset empty require include require_once include_once true false null`)},java:{...SLASHES,quotes:`"'`,keywords:words(`${C_LIKE} class interface enum package import final void int long double float boolean char byte short true false null var record`)},c:{...SLASHES,quotes:`"'`,keywords:words(`${C_LIKE} struct union typedef enum const volatile extern sizeof void int long double float char short unsigned signed auto register inline static include define ifdef ifndef endif pragma true false NULL nullptr class template typename namespace using bool`)},ruby:{...HASH,quotes:`"'`,keywords:words("def end class module if elsif else unless while until for in do begin rescue ensure return yield self nil true false and or not require require_relative include extend attr_accessor attr_reader puts then case when")},lua:{line:["--"],quotes:`"'`,keywords:words("function end if then else elseif for while do repeat until return local break in and or not nil true false")},dockerfile:{...HASH,quotes:`"'`,caseInsensitive:!0,keywords:words("from run cmd label expose env add copy entrypoint volume user workdir arg onbuild stopsignal healthcheck shell as")},makefile:{...HASH,quotes:`"'`,keywords:words("ifeq ifneq ifdef ifndef else endif include define endef export")}},ALIASES={script:["ts","tsx","mts","cts","js","jsx","mjs","cjs","typescript","javascript","vue","svelte"],json:["json","jsonl","ndjson"],jsonc:["jsonc","json5"],python:["py","python"],shell:["sh","bash","zsh","fish","shell","console"],yaml:["yml","yaml"],toml:["toml"],ini:["ini","conf","cfg","properties","editorconfig"],css:["css","scss","less"],html:["html","htm","xml","svg"],sql:["sql"],rust:["rs","rust"],go:["go","golang"],php:["php"],java:["java","kt","kts","cs","swift","dart","scala"],c:["c","h","cpp","cc","hpp","cxx"],ruby:["rb","ruby"],lua:["lua"],dockerfile:["dockerfile","containerfile"],makefile:["makefile","mk","just","justfile"]},BY_NAME=new Map(Object.entries(ALIASES).flatMap(([name,aliases])=>aliases.map((alias)=>[alias,name]))),EXTENSION=/\.([^./]+)$/,BASENAME=/[^/]*$/;function languageOf(nameOrPath){let base=(BASENAME.exec(nameOrPath)?.[0]??"").toLowerCase(),extension=EXTENSION.exec(base)?.[1];return BY_NAME.get(extension??base)??BY_NAME.get(base.replace(LEADING_DOT,""))}function paintLines(text,paint){return text.split(`
|
|
71
76
|
`).map((line)=>line===""?line:paint(line)).join(`
|
|
72
77
|
`)}function stringEnd(source,start,quote){let triple=TRIPLE_QUOTES.find((each)=>source.startsWith(each,start)),multiline=quote==="`"||triple!==void 0,closer=triple??quote,at=start+closer.length;while(at<source.length){let char=source.charAt(at);if(char==="\\")at+=2;else if(source.startsWith(closer,at))return at+closer.length;else if(char===`
|
|
73
78
|
`&&!multiline)return at;else at++}return source.length}function lineLead(line,language,theme){if(language.section?.test(line)===!0)return{done:theme.heading(line),rest:""};let match=language.key?.exec(line);if(match===null||match===void 0)return{done:"",rest:line};return{done:`${match[1]??""}${theme.accent(match[2]??"")}`,rest:line.slice(match[0].length)}}function highlight(source,name,theme){let language=LANGUAGES[name],text=source.replaceAll(`\r
|
|
@@ -127,12 +132,12 @@ ${theme.dim("\u2500".repeat(rule))}
|
|
|
127
132
|
`},th:(children,meta)=>(aligns.push(meta?.align==="right"?"right":"left"),`${children}${CELL}`),td:(children)=>`${children}${CELL}`,tr:(children)=>`${children}${ROW}`,table:(children)=>{let rows=children.split(ROW).filter((row)=>row!=="").map((row)=>row.split(CELL).slice(0,-1)),drawn=renderTable(rows,aligns,width,theme);return aligns=[],block(`${drawn}
|
|
128
133
|
|
|
129
134
|
`)}});return`${finish(trimmed(rendered.replaceAll(BLOCK,"")),width)}
|
|
130
|
-
`}import process16 from"process";function themeFor(stream=process16.stdout,env=process16.env){let colors=paint(stream,env),accent=role("accent",stream,env),path=role("path",stream,env);return{heading:(text)=>accent(colors.bold(text)),code:role("id",stream,env),path,id:role("id",stream,env),dim:role("label",stream,env),bold:colors.bold,italic:colors.italic,strike:colors.strikethrough,changed:colors.inverse,added:colors.green,removed:colors.red,accent,keyword:colors.magenta,string:colors.green,number:colors.yellow,link:(text,url)=>path(colors.underline(link(text,url,stream,env))),shade:(text,ratio)=>takesControlCodes(stream,env)?tinted(colors,gradientAt(activeTheme().theme,ratio)??activeTheme().theme.colors.accent,env)(text):text}}var DEFAULT_WIDTH=80,MARKDOWN_FILE=/\.(?:md|markdown|mdx)$/i,DIFF_FILE=/\.(?:diff|patch)$/i,
|
|
135
|
+
`}import process16 from"process";function themeFor(stream=process16.stdout,env=process16.env){let colors=paint(stream,env),accent=role("accent",stream,env),path=role("path",stream,env);return{heading:(text)=>accent(colors.bold(text)),code:role("id",stream,env),path,id:role("id",stream,env),dim:role("label",stream,env),bold:colors.bold,italic:colors.italic,strike:colors.strikethrough,changed:colors.inverse,added:colors.green,removed:colors.red,accent,keyword:colors.magenta,string:colors.green,number:colors.yellow,link:(text,url)=>path(colors.underline(link(text,url,stream,env))),shade:(text,ratio)=>takesControlCodes(stream,env)?tinted(colors,gradientAt(activeTheme().theme,ratio)??activeTheme().theme.colors.accent,env)(text):text}}var DEFAULT_WIDTH=80,MARKDOWN_FILE=/\.(?:md|markdown|mdx)$/i,DIFF_FILE=/\.(?:diff|patch)$/i,TRAILING_NEWLINE3=/\n$/,USAGE="view [options] [file...]: shows markdown files, source files, plain text files or git diffs in the colours of the other @kaynooo CLIs\n\nFiles (each optionally with a line range such as src/a.ts:10-50), or what is piped on stdin (or - for stdin). A source file is highlighted behind line numbers by its extension or --lang, a diff, a `git log -p` or a `git show` is recognised by its first line or a .diff or .patch name, .md/.mdx/.markdown files (and stdin by default) are markdown, and unknown or .txt/.log files are shown as plain text preserving line breaks; --diff and --markdown force one.\nLines wrap to the terminal width and a long output on a terminal goes through $PAGER, unless --no-pager. No colour with NO_COLOR, a pipe or --plain. Control characters of the text, escape sequences included, show as cat -v writes them (^[) in code, text and diffs and are dropped from markdown, --json too.",EXITS=[[0,"it showed the text"],[1,"there is nothing to show"],[2,"a usage error or a file that is missing"]],OPTIONS={diff:{type:"boolean",conflicts:["markdown","lang"],description:"show the text as a diff"},markdown:{type:"boolean",conflicts:["diff","lang"],description:"show the text as markdown"},lang:{type:"string",short:"l",conflicts:["diff","markdown"],description:"show the text as code in this language (ts, json, yaml, sh...)"},lines:{type:"boolean",description:"number the lines of code and text (on a terminal by default)",negative:"do not number the lines"},width:{type:"string",short:"w",description:"columns to wrap to, instead of the terminal's"},pager:{type:"boolean",description:"page a long output on a terminal",negative:"do not page long output"},json:jsonOption("{kind: code, diff, markdown or text, language, text} (or an array for multiple files), rendered without colour")};function sliceRange(text,start,end){if(start===void 0)return{text,startLine:1};let slice=text.replaceAll(`\r
|
|
131
136
|
`,`
|
|
132
137
|
`).replace(TRAILING_NEWLINE3,"").split(`
|
|
133
138
|
`).slice(start-1,end);return{text:slice.length===0?"":`${slice.join(`
|
|
134
139
|
`)}
|
|
135
|
-
`,startLine:start}}function columnsOf(variable){let columns=Number(variable);return Number.isInteger(columns)&&columns>=20?columns:DEFAULT_WIDTH}function pagerCommand(pager=process17.env.PAGER){return pager===void 0||pager.trim()===""||pager.trim()==="less"?["less","-FRX"]:["sh","-c",pager]}async function page(text){try{let pager=Bun.spawn(pagerCommand(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});try{pager.stdin.write(text),await pager.stdin.end()}catch{}await pager.exited}catch{process17.stdout.write(text)}}function detectKind(path,text,language,forced){if(forced.lang)return"code";if(forced.diff)return"diff";if(forced.markdown)return"markdown";if(MARKDOWN_FILE.test(path))return"markdown";if(DIFF_FILE.test(path)||looksLikeDiff(text))return"diff";if(language!==void 0)return"code";return path==="-"?"markdown":"text"}function renderKind(kind,text,language,theme,numbered,width,startLine){if(kind==="code")return renderCode(text,language,theme,numbered,startLine);if(kind==="text")return renderCode(text,void 0,theme,numbered,startLine);return kind==="diff"?renderDiff(text,theme):renderMarkdown(text,{theme,width})}async function main(args){let{values,positionals}=parse(args,USAGE,OPTIONS,{exits:EXITS,positionals:["[file...]"],allowNegative:!0,replaces:"cat, bat or less on a markdown or source file, delta on a diff",examples:["view README.md","view src/a.ts:10-40","view a.ts b.ts","git diff | view"]})
|
|
136
|
-
${item.
|
|
140
|
+
`,startLine:start}}function columnsOf(variable){let columns=Number(variable);return Number.isInteger(columns)&&columns>=20?columns:DEFAULT_WIDTH}function pagerCommand(pager=process17.env.PAGER){return pager===void 0||pager.trim()===""||pager.trim()==="less"?["less","-FRX"]:["sh","-c",pager]}async function page(text){try{let pager=Bun.spawn(pagerCommand(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});try{pager.stdin.write(text),await pager.stdin.end()}catch{}await pager.exited}catch{process17.stdout.write(text)}}function detectKind(path,text,language,forced){if(forced.lang)return"code";if(forced.diff)return"diff";if(forced.markdown)return"markdown";if(MARKDOWN_FILE.test(path))return"markdown";if(DIFF_FILE.test(path)||looksLikeDiff(text))return"diff";if(language!==void 0)return"code";return path==="-"?"markdown":"text"}function renderKind(kind,text,language,theme,numbered,width,startLine){if(kind==="code")return renderCode(text,language,theme,numbered,startLine);if(kind==="text")return renderCode(text,void 0,theme,numbered,startLine);return kind==="diff"?renderDiff(text,theme):renderMarkdown(text,{theme,width})}async function main(args){let{values,positionals}=parse(args,USAGE,OPTIONS,{exits:EXITS,positionals:["[file...]"],allowNegative:!0,replaces:"cat, bat or less on a markdown or source file, delta on a diff",examples:["view README.md","view src/a.ts:10-40","view a.ts b.ts","git diff | view"]}),forcedLanguage=values.lang===void 0?void 0:languageOf(values.lang);if(values.lang!==void 0&&forcedLanguage===void 0)badUsage(`unknown language ${values.lang}`);let specs=(positionals.length===0?["-"]:positionals).map((arg)=>parseFileSpan(arg)),human=isHumanTerminal(process17.stdout),width=wholeNumber(values.width,"width",human?process17.stdout.columns||DEFAULT_WIDTH:columnsOf(process17.env.COLUMNS),20),json=values.json===!0,theme=json?themeFor({isTTY:!1}):themeFor(process17.stdout),numbered=values.lines??(json?!1:human),forced={diff:values.diff===!0,markdown:values.markdown===!0,lang:values.lang!==void 0},rendered=[];for(let spec of specs){let raw=await readInput(spec.path,{noStdin:"give a file, or pipe the text on stdin"}),{text,startLine}=sliceRange(raw,spec.start,spec.end);if(text.trim()==="")fail("nothing to show",1);let language=forcedLanguage??(spec.path==="-"?void 0:languageOf(spec.path)),kind=detectKind(spec.path,text,language,forced),output=renderKind(kind,text,language,theme,numbered,width,startLine);rendered.push({spec,kind,language,text:json?stripAnsi(output):output})}if(json){if(rendered.length===1){let[only]=rendered;printJson({kind:only.kind,language:only.kind==="code"?only.language??null:null,text:only.text})}else printJson(rendered.map((item)=>({path:item.spec.raw,kind:item.kind,language:item.kind==="code"?item.language??null:null,text:item.text})));return 0}let output=rendered.length===1?rendered[0].text:rendered.map((item)=>`${theme.bold(theme.path(item.spec.raw))}
|
|
141
|
+
${item.text}`).join(`
|
|
137
142
|
`);if(canPage(process17.stdout)&&values.pager!==!1&&output.split(`
|
|
138
143
|
`).length>(process17.stdout.rows||24))await page(output);else process17.stdout.write(output);return 0}process17.exitCode=await runMain({name:"view",run:main});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-view",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.10.0",
|
|
5
5
|
"description": "view: markdown files and git diffs shown in the colours of the other @kaynooo CLIs, paged when long.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -36,6 +36,6 @@
|
|
|
36
36
|
"view": "$npm_execpath src/view.ts"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@kaynooo/cli-kit": "0.
|
|
39
|
+
"@kaynooo/cli-kit": "0.54.0"
|
|
40
40
|
}
|
|
41
41
|
}
|
package/src/view.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
2
|
|
|
3
|
-
import type { ExitRow } from '@kaynooo/cli-kit'
|
|
3
|
+
import type { ExitRow, FileSpan } from '@kaynooo/cli-kit'
|
|
4
4
|
import type { Name } from './code'
|
|
5
5
|
import type { Theme } from './theme'
|
|
6
|
-
import { existsSync } from 'node:fs'
|
|
7
6
|
import process from 'node:process'
|
|
8
|
-
import { badUsage, canPage, fail, isHumanTerminal, jsonOption, parse, printJson, readInput, runMain, stripAnsi, wholeNumber } from '@kaynooo/cli-kit'
|
|
7
|
+
import { badUsage, canPage, fail, isHumanTerminal, jsonOption, parse, parseFileSpan, printJson, readInput, runMain, stripAnsi, wholeNumber } from '@kaynooo/cli-kit'
|
|
9
8
|
import { languageOf, renderCode } from './code'
|
|
10
9
|
import { looksLikeDiff, renderDiff } from './diff'
|
|
11
10
|
import { renderMarkdown } from './markdown'
|
|
@@ -14,7 +13,6 @@ import { themeFor } from './theme'
|
|
|
14
13
|
const DEFAULT_WIDTH = 80
|
|
15
14
|
const MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i
|
|
16
15
|
const DIFF_FILE = /\.(?:diff|patch)$/i
|
|
17
|
-
const FILE_RANGE = /^(.+):(\d+)(?:-(\d*))?$/
|
|
18
16
|
const TRAILING_NEWLINE = /\n$/
|
|
19
17
|
|
|
20
18
|
const USAGE = `view [options] [file...]: shows markdown files, source files, plain text files or git diffs in the colours of the other @kaynooo CLIs
|
|
@@ -24,46 +22,15 @@ Lines wrap to the terminal width and a long output on a terminal goes through $P
|
|
|
24
22
|
const EXITS: ExitRow[] = [[0, 'it showed the text'], [1, 'there is nothing to show'], [2, 'a usage error or a file that is missing']]
|
|
25
23
|
|
|
26
24
|
const OPTIONS = {
|
|
27
|
-
diff: { type: 'boolean', description: 'show the text as a diff' },
|
|
28
|
-
markdown: { type: 'boolean', description: 'show the text as markdown' },
|
|
29
|
-
lang: { type: 'string', short: 'l', description: 'show the text as code in this language (ts, json, yaml, sh...)' },
|
|
30
|
-
lines: { type: 'boolean', description: 'number the lines of code and text (
|
|
25
|
+
diff: { type: 'boolean', conflicts: ['markdown', 'lang'], description: 'show the text as a diff' },
|
|
26
|
+
markdown: { type: 'boolean', conflicts: ['diff', 'lang'], description: 'show the text as markdown' },
|
|
27
|
+
lang: { type: 'string', short: 'l', conflicts: ['diff', 'markdown'], description: 'show the text as code in this language (ts, json, yaml, sh...)' },
|
|
28
|
+
lines: { type: 'boolean', description: 'number the lines of code and text (on a terminal by default)', negative: 'do not number the lines' },
|
|
31
29
|
width: { type: 'string', short: 'w', description: 'columns to wrap to, instead of the terminal\'s' },
|
|
32
|
-
pager: { type: 'boolean', description: 'page a long output on a terminal
|
|
30
|
+
pager: { type: 'boolean', description: 'page a long output on a terminal', negative: 'do not page long output' },
|
|
33
31
|
json: jsonOption('{kind: code, diff, markdown or text, language, text} (or an array for multiple files), rendered without colour'),
|
|
34
32
|
} as const
|
|
35
33
|
|
|
36
|
-
interface FileSpec {
|
|
37
|
-
raw: string
|
|
38
|
-
path: string
|
|
39
|
-
start?: number
|
|
40
|
-
end?: number
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// Parses `path:10-50`, `path:10`, or `path:10-`, leaving a literal path containing `:` intact when that file exists.
|
|
44
|
-
function parseSpec(raw: string): FileSpec {
|
|
45
|
-
if (raw === '-' || existsSync(raw))
|
|
46
|
-
return { raw, path: raw }
|
|
47
|
-
|
|
48
|
-
const match = FILE_RANGE.exec(raw)
|
|
49
|
-
|
|
50
|
-
if (match === null)
|
|
51
|
-
return { raw, path: raw }
|
|
52
|
-
|
|
53
|
-
const start = Number(match[2])
|
|
54
|
-
let end: number | undefined
|
|
55
|
-
|
|
56
|
-
if (match[3] === undefined)
|
|
57
|
-
end = start
|
|
58
|
-
else if (match[3] !== '')
|
|
59
|
-
end = Number(match[3])
|
|
60
|
-
|
|
61
|
-
if (start < 1 || (end !== undefined && end < start))
|
|
62
|
-
badUsage(`invalid line range in '${raw}'`)
|
|
63
|
-
|
|
64
|
-
return { raw, path: match[1]!, start, ...end === undefined ? {} : { end } }
|
|
65
|
-
}
|
|
66
|
-
|
|
67
34
|
function sliceRange(text: string, start: number | undefined, end: number | undefined): { text: string, startLine: number } {
|
|
68
35
|
if (start === undefined)
|
|
69
36
|
return { text, startLine: 1 }
|
|
@@ -142,22 +109,19 @@ function renderKind(kind: Kind, text: string, language: Name | undefined, theme:
|
|
|
142
109
|
|
|
143
110
|
async function main(args: string[]): Promise<number> {
|
|
144
111
|
const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ['[file...]'], allowNegative: true, replaces: 'cat, bat or less on a markdown or source file, delta on a diff', examples: ['view README.md', 'view src/a.ts:10-40', 'view a.ts b.ts', 'git diff | view'] })
|
|
145
|
-
|
|
146
|
-
if (values.diff === true && values.markdown === true)
|
|
147
|
-
badUsage('--diff and --markdown exclude each other')
|
|
148
|
-
|
|
149
112
|
const forcedLanguage = values.lang === undefined ? undefined : languageOf(values.lang)
|
|
150
113
|
|
|
151
114
|
if (values.lang !== undefined && forcedLanguage === undefined)
|
|
152
115
|
badUsage(`unknown language ${values.lang}`)
|
|
153
116
|
|
|
154
|
-
const specs = (positionals.length === 0 ? ['-'] : positionals).map(
|
|
117
|
+
const specs = (positionals.length === 0 ? ['-'] : positionals).map(arg => parseFileSpan(arg))
|
|
155
118
|
const human = isHumanTerminal(process.stdout)
|
|
156
119
|
const width = wholeNumber(values.width, 'width', human ? process.stdout.columns || DEFAULT_WIDTH : columnsOf(process.env.COLUMNS), 20)
|
|
157
|
-
const
|
|
158
|
-
const
|
|
120
|
+
const json = values.json === true
|
|
121
|
+
const theme = json ? themeFor({ isTTY: false }) : themeFor(process.stdout)
|
|
122
|
+
const numbered = values.lines ?? (json ? false : human)
|
|
159
123
|
const forced = { diff: values.diff === true, markdown: values.markdown === true, lang: values.lang !== undefined }
|
|
160
|
-
const rendered: { spec:
|
|
124
|
+
const rendered: { spec: FileSpan, kind: Kind, language: Name | undefined, text: string }[] = []
|
|
161
125
|
|
|
162
126
|
for (const spec of specs) {
|
|
163
127
|
const raw = await readInput(spec.path, { noStdin: 'give a file, or pipe the text on stdin' })
|
|
@@ -168,28 +132,27 @@ async function main(args: string[]): Promise<number> {
|
|
|
168
132
|
|
|
169
133
|
const language = forcedLanguage ?? (spec.path === '-' ? undefined : languageOf(spec.path))
|
|
170
134
|
const kind = detectKind(spec.path, text, language, forced)
|
|
171
|
-
const
|
|
172
|
-
const plain = stripAnsi(renderKind(kind, text, language, plainTheme, values.lines ?? false, width, startLine))
|
|
135
|
+
const output = renderKind(kind, text, language, theme, numbered, width, startLine)
|
|
173
136
|
|
|
174
|
-
rendered.push({ spec, kind, language,
|
|
137
|
+
rendered.push({ spec, kind, language, text: json ? stripAnsi(output) : output })
|
|
175
138
|
}
|
|
176
139
|
|
|
177
|
-
if (
|
|
140
|
+
if (json) {
|
|
178
141
|
if (rendered.length === 1) {
|
|
179
142
|
const [only] = rendered
|
|
180
143
|
|
|
181
|
-
printJson({ kind: only!.kind, language: only!.kind === 'code' ? only!.language ?? null : null, text: only!.
|
|
144
|
+
printJson({ kind: only!.kind, language: only!.kind === 'code' ? only!.language ?? null : null, text: only!.text })
|
|
182
145
|
}
|
|
183
146
|
else {
|
|
184
|
-
printJson(rendered.map(item => ({ path: item.spec.raw, kind: item.kind, language: item.kind === 'code' ? item.language ?? null : null, text: item.
|
|
147
|
+
printJson(rendered.map(item => ({ path: item.spec.raw, kind: item.kind, language: item.kind === 'code' ? item.language ?? null : null, text: item.text })))
|
|
185
148
|
}
|
|
186
149
|
|
|
187
150
|
return 0
|
|
188
151
|
}
|
|
189
152
|
|
|
190
153
|
const output = rendered.length === 1
|
|
191
|
-
? rendered[0]!.
|
|
192
|
-
: rendered.map(item => `${theme.bold(theme.path(item.spec.raw))}\n${item.
|
|
154
|
+
? rendered[0]!.text
|
|
155
|
+
: rendered.map(item => `${theme.bold(theme.path(item.spec.raw))}\n${item.text}`).join('\n')
|
|
193
156
|
|
|
194
157
|
if (canPage(process.stdout) && values.pager !== false && output.split('\n').length > (process.stdout.rows || 24))
|
|
195
158
|
await page(output)
|