@visulima/vis 1.0.0-alpha.10 → 1.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CHANGELOG.md +185 -42
  2. package/LICENSE.md +586 -0
  3. package/README.md +26 -4
  4. package/dist/config/index.d.ts +1739 -0
  5. package/dist/config/index.js +1 -0
  6. package/dist/generate/index.d.ts +1 -1
  7. package/dist/packem_chunks/applyDefaults.js +2 -0
  8. package/dist/packem_chunks/bin.js +232 -60
  9. package/dist/packem_chunks/doctor-probe.js +2 -0
  10. package/dist/packem_chunks/fix.js +11 -53
  11. package/dist/packem_chunks/handler.js +1 -1
  12. package/dist/packem_chunks/handler10.js +2 -1
  13. package/dist/packem_chunks/handler11.js +1 -1
  14. package/dist/packem_chunks/handler12.js +5 -2
  15. package/dist/packem_chunks/handler13.js +1 -1
  16. package/dist/packem_chunks/handler14.js +18 -5
  17. package/dist/packem_chunks/handler15.js +20 -1
  18. package/dist/packem_chunks/handler16.js +1 -20
  19. package/dist/packem_chunks/handler17.js +1 -1
  20. package/dist/packem_chunks/handler18.js +1 -1
  21. package/dist/packem_chunks/handler19.js +1 -1
  22. package/dist/packem_chunks/handler2.js +2 -1
  23. package/dist/packem_chunks/handler20.js +5 -1
  24. package/dist/packem_chunks/handler21.js +1 -1
  25. package/dist/packem_chunks/handler22.js +1 -5
  26. package/dist/packem_chunks/handler23.js +5 -1
  27. package/dist/packem_chunks/handler24.js +1 -1
  28. package/dist/packem_chunks/handler25.js +3 -5
  29. package/dist/packem_chunks/handler26.js +1 -1
  30. package/dist/packem_chunks/handler27.js +1 -3
  31. package/dist/packem_chunks/handler28.js +7 -1
  32. package/dist/packem_chunks/handler29.js +22 -6
  33. package/dist/packem_chunks/handler3.js +4 -2
  34. package/dist/packem_chunks/handler30.js +3 -23
  35. package/dist/packem_chunks/handler31.js +1 -3
  36. package/dist/packem_chunks/handler32.js +2 -2
  37. package/dist/packem_chunks/handler33.js +24 -23
  38. package/dist/packem_chunks/handler34.js +2 -2
  39. package/dist/packem_chunks/handler35.js +3 -19
  40. package/dist/packem_chunks/handler36.js +22 -428
  41. package/dist/packem_chunks/handler37.js +428 -22
  42. package/dist/packem_chunks/handler38.js +20 -20
  43. package/dist/packem_chunks/handler39.js +21 -21
  44. package/dist/packem_chunks/handler4.js +2 -4
  45. package/dist/packem_chunks/handler40.js +22 -3
  46. package/dist/packem_chunks/handler41.js +6 -10
  47. package/dist/packem_chunks/handler42.js +5 -153
  48. package/dist/packem_chunks/handler43.js +10 -42
  49. package/dist/packem_chunks/handler44.js +153 -3
  50. package/dist/packem_chunks/handler45.js +25 -27
  51. package/dist/packem_chunks/handler46.js +3 -0
  52. package/dist/packem_chunks/handler47.js +27 -0
  53. package/dist/packem_chunks/handler48.js +42 -0
  54. package/dist/packem_chunks/handler5.js +8 -2
  55. package/dist/packem_chunks/handler6.js +1 -13
  56. package/dist/packem_chunks/handler7.js +1 -8
  57. package/dist/packem_chunks/handler8.js +1 -1
  58. package/dist/packem_chunks/handler9.js +1 -1
  59. package/dist/packem_chunks/heal-accept.js +10 -0
  60. package/dist/packem_chunks/heal.js +14 -0
  61. package/dist/packem_chunks/index.js +3 -3
  62. package/dist/packem_chunks/tar.js +3 -0
  63. package/dist/packem_shared/ai-analysis-hm8d2W7z.js +67 -0
  64. package/dist/packem_shared/{ai-cache-Bynt6Y9x.js → ai-cache-DoiF80AR.js} +1 -1
  65. package/dist/packem_shared/ai-fix-nn4zOE95.js +43 -0
  66. package/dist/packem_shared/cache-directory-CwHlJhgx.js +1 -0
  67. package/dist/packem_shared/dependency-scan-COr5n63B.js +2 -0
  68. package/dist/packem_shared/{docker-BcfqH4Av.js → docker-D6OGr5_S.js} +1 -1
  69. package/dist/packem_shared/{failure-log-DqYen0LC.js → failure-log-iUVLf6ts.js} +1 -1
  70. package/dist/packem_shared/flakiness-D9wf0t56.js +1 -0
  71. package/dist/packem_shared/giget-CcEy_Elm.js +2 -0
  72. package/dist/packem_shared/index-DH-5hsrC.js +1 -0
  73. package/dist/packem_shared/otel-DxDUPJJH.js +6 -0
  74. package/dist/packem_shared/otelPlugin-CQq6poq8.js +1 -0
  75. package/dist/packem_shared/registry-CkubDdiY.js +2 -0
  76. package/dist/packem_shared/run-summary-utils-BfBvjzhY.js +1 -0
  77. package/dist/packem_shared/{runtime-check-CGHal8SO.js → runtime-check-BXZ43CBW.js} +1 -1
  78. package/dist/packem_shared/{selectors-CfH9ZY08.js → selectors-BylODRiM.js} +1 -1
  79. package/dist/packem_shared/toolchain-BgBOUHII.js +5 -0
  80. package/dist/packem_shared/typosquats-CcZl99B1.js +1 -0
  81. package/dist/packem_shared/verify-Baj5mFJ7.js +1 -0
  82. package/dist/packem_shared/vis-update-app-D1jl0UZZ.js +1 -0
  83. package/index.js +54 -53
  84. package/package.json +34 -26
  85. package/schemas/project.schema.json +739 -299
  86. package/schemas/vis-config.schema.json +3383 -278
  87. package/skills/vis/SKILL.md +96 -0
  88. package/templates/buildkite-ci/.buildkite/pipeline.yml.tera +85 -0
  89. package/templates/buildkite-ci/template.yml +20 -0
  90. package/dist/errors/index.d.ts +0 -26
  91. package/dist/errors/index.js +0 -1
  92. package/dist/packem_chunks/config.js +0 -2
  93. package/dist/packem_shared/VisConfigCycleError-CAYNC7d-.js +0 -1
  94. package/dist/packem_shared/VisConfigError-B5LP1zRf.js +0 -1
  95. package/dist/packem_shared/VisConfigLoadError-CeqBSd2Z.js +0 -2
  96. package/dist/packem_shared/VisConfigNotFoundError-DZ9KC527.js +0 -5
  97. package/dist/packem_shared/VisUpdateApp-D-L4_-Iu.js +0 -1
  98. package/dist/packem_shared/_commonjsHelpers-D6W6KoPK.js +0 -1
  99. package/dist/packem_shared/ai-analysis-CGuy7dfE.js +0 -67
  100. package/dist/packem_shared/cache-directory-D72ZEag2.js +0 -1
  101. package/dist/packem_shared/catalog-BVPerCwG.js +0 -12
  102. package/dist/packem_shared/dependency-scan-Du0tBu64.js +0 -2
  103. package/dist/packem_shared/flakiness-DSIHZGBT.js +0 -1
  104. package/dist/packem_shared/run-summary-utils-C24Aaf9E.js +0 -1
  105. package/dist/packem_shared/target-merge-DNa-6eWu.js +0 -1
  106. package/dist/packem_shared/toolchain-DQfTQY8E.js +0 -5
  107. package/dist/packem_shared/typosquats-DOR8izpX.js +0 -1
@@ -0,0 +1,42 @@
1
+ var $r=Object.defineProperty;var T=(r,e)=>$r(r,"name",{value:e,configurable:!0});import{createRequire as Tr}from"node:module";import{runConcurrently as et,TerminalBuffer as Wt,readLastRunSummary as Cr,enforceProjectConstraints as xr,expandTokensInString as Ir,parsePartition as Mr,TaskScheduler as Er,createTaskGraph as Rr,reverseTaskGraph as jr,generateRunSummary as Tt,writeChromeTrace as Or,CompositeLifeCycle as St,defaultTaskRunner as Ct,createLogReporter as Pr,writeRunSummary as Fr}from"@visulima/task-runner";import{an as _r,p as xt,aj as Ut,aK as Ar,ai as Lr,k as Dr,y as Hr,aL as Br,aM as Nr,s as Ve,aN as Gr}from"./bin.js";import{E as qr,a as Wr}from"../packem_shared/cache-directory-CwHlJhgx.js";import{join as Ce,basename as Vr,dirname as zr,resolve as Yt,relative as Yr}from"@visulima/path";import{F as Kr}from"../packem_shared/failure-log-iUVLf6ts.js";import{f as Qr,l as Xr,c as Zr,a as Jr,b as eo}from"../packem_shared/flakiness-D9wf0t56.js";import{r as to}from"../packem_shared/toolchain-BgBOUHII.js";import{i as ro,c as oo,b as so}from"../packem_shared/registry-CkubDdiY.js";import{p as no,r as io,f as ao}from"../packem_shared/selectors-BylODRiM.js";import{Box as h,Text as n,StaticRender as It,renderToString as re,ScrollView as Kt,Spinner as uo,useApp as ho,useWindowSize as fo,useInput as Mt,Dialog as po,render as mo}from"@visulima/tui";import N,{useSyncExternalStore as go,useState as Et,useRef as Ee,useCallback as ze,useEffect as Ye,useMemo as Rt}from"react";import{jsxs as d,jsx as c}from"react/jsx-runtime";import{T as Qt,C as tt,D as De,E as Xt}from"../packem_shared/symbols-CQmER5MT.js";import{duration as Zt}from"@visulima/humanizer";const Sr=Tr(import.meta.url),Me=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Le=T(r=>{if(typeof Me<"u"&&Me.versions&&Me.versions.node){const[e,t]=Me.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return Me.getBuiltinModule(r)}return Sr(r)},"__cjs_getBuiltinModule"),{existsSync:Vt,statSync:zt,watch:Ur}=Le("node:fs"),{createInterface:co,emitKeypressEvents:lo}=Le("node:readline"),{appendFile:rt}=Le("node:fs/promises"),{platform:wo,homedir:ot}=Le("node:os");var ko=Object.defineProperty,He=T((r,e)=>ko(r,"name",{value:e,configurable:!0}),"s$2");const vo={bun:["bun.lock","bun.lockb"],npm:["package-lock.json"],pnpm:["pnpm-lock.yaml"],yarn:["yarn.lock"]},yo={bun:["node_modules/.bun-tag"],npm:["node_modules/.package-lock.json"],pnpm:["node_modules/.modules.yaml","node_modules/.pnpm/lock.yaml"],yarn:["node_modules/.yarn-integrity","node_modules/.yarn-state.yml",".yarn/install-state.gz"]},bo={ci:{bun:"bun install --frozen-lockfile",npm:"npm ci",pnpm:"pnpm install --frozen-lockfile",yarn:"yarn install --immutable"},tty:{bun:"bun install",npm:"npm install",pnpm:"pnpm install",yarn:"yarn install"}},$o=1e3,To=He(r=>{for(const[e,t]of Object.entries(vo))for(const s of t)if(Vt(Ce(r,s)))return{lockfileFile:s,manager:e}},"detectPackageManager"),So=He((r,e)=>{let t;for(const s of yo[e]){const o=Ce(r,s);if(!Vt(o))continue;const{mtimeMs:a}=zt(o);(!t||a>t.mtimeMs)&&(t={mtimeMs:a,path:s})}return t},"findFreshestMarker"),Co=He((r,e={})=>{const t=To(r);if(!t)return{checked:!1};const{lockfileFile:s,manager:o}=t,a=zt(Ce(r,s)).mtimeMs,l=So(r,o),u=bo[e.inCi?"ci":"tty"][o],f={installMarkerMtimeMs:l?.mtimeMs,lockfileMtimeMs:a,lockfilePath:s,marker:l?.path,packageManager:o};return l?a>l.mtimeMs+$o?{checked:!0,detail:f,failure:"stale-install",message:`${s} is newer than node_modules (${l.path}) — run \`${u}\` to sync.`}:{checked:!0,detail:f}:{checked:!0,detail:f,failure:"missing-install",message:`lockfile detected but node_modules looks uninitialised — run \`${u}\` before \`vis run\`.`}},"checkLockfileFreshness"),xo=He((r,e,t,s={})=>{if(s.skip)return{checked:!1,shouldContinue:!0};const o=Co(r,{inCi:e});if(!o.failure)return{...o,shouldContinue:!0};const a=`preflight: ${o.message??"lockfile drift detected"}`;return e&&!s.ciAsWarning?{...o,formattedMessage:a,shouldContinue:!1}:(t.warn(a),{...o,formattedMessage:a,shouldContinue:!0})},"runLockfilePreflight");var Io=Object.defineProperty,Jt=T((r,e)=>Io(r,"name",{value:e,configurable:!0}),"p$5");const Mo=Jt(r=>r.split(",").map(e=>e.trim()).filter(e=>e!==""),"splitPatterns"),Eo=Jt((r,e,t)=>{const s=new Set,o=[];if(r===void 0||r.trim()==="")return{skipTaskIds:s,unmatchedPatterns:o};const a=[...t],l=new Set(a),u=new Map;for(const f of a){const p=f.lastIndexOf(":");if(p===-1)continue;const i=f.slice(p+1),S=u.get(i);S===void 0?u.set(i,[f]):S.push(f)}for(const f of Mo(r)){if(f.startsWith("~:"))throw new Error(`--skip-cache does not support the closest-project selector "~:" (received "${f}"). Use \`pkg:target\`, \`:target\`, or \`#tag:target\`.`);if(l.has(f)){s.add(f);continue}const p=no(f);if(!p){o.push(f);continue}let i=!1;if(p.kind==="all"){const S=u.get(p.target)??[];for(const b of S)s.add(b),i=!0}else if(p.kind==="project"){const S=p.projects?.[0];if(S!==void 0){const b=`${S}:${p.target}`;l.has(b)&&(s.add(b),i=!0)}}else if(p.kind==="tag"){const S=p.tag;if(S!==void 0){const b=u.get(p.target)??[];for(const E of b){const A=E.slice(0,E.lastIndexOf(":"));e.projects[A]?.tags?.includes(S)===!0&&(s.add(E),i=!0)}}}i||o.push(f)}return{skipTaskIds:s,unmatchedPatterns:o}},"resolveSkipCachePatterns");var Ro=Object.defineProperty,st=T((r,e)=>Ro(r,"name",{value:e,configurable:!0}),"a$2");const jo=/\$(?:\{([A-Z_]\w*)(:-[^}]*)?\}|([A-Z_]\w*))/gi,Oo=new Set(["0","!","#","$","*","-","?","@","_"]),Po=st(r=>{const e=new Map;for(const t of r.matchAll(jo)){const s=t[1],o=t[3],a=t[2],l=s??o;if(l===void 0||Oo.has(l))continue;const u=a!==void 0,f=e.get(l);f===void 0?e.set(l,u):f&&!u&&e.set(l,!1)}return[...e.entries()].map(([t,s])=>({hasDefault:s,name:t}))},"extractEnvReferences"),Fo=st(r=>{const{command:e,processEnv:t,taskEnv:s,taskId:o}=r,a=Po(e);if(a.length===0)return;const l=[];for(const{hasDefault:u,name:f}of a){if(u)continue;const p=s[f],i=t[f];p===void 0&&i===void 0&&l.push(f)}if(l.length!==0)return{missing:l.toSorted(),taskId:o}},"checkStrictEnv"),_o=st(r=>{const e=r.missing.map(t=>`$${t}`).join(", ");return`Strict env: ${r.taskId} references unset variable${r.missing.length===1?"":"s"} ${e}. Set ${r.missing.length===1?"it":"them"} in the task env, an envFile, or the parent shell — or opt out with options.strictEnv: false.`},"formatStrictEnvError");var Ao=Object.defineProperty,we=T((r,e)=>Ao(r,"name",{value:e,configurable:!0}),"i$2");const jt=we(r=>{const e=new Set;for(const t of Object.values(r.projects))for(const s of Object.keys(t.targets??{}))e.add(s);return[...e].sort()},"collectAvailableTargets"),Lo=we(r=>{const e=new Map;for(const t of r.values())for(const[s,o]of Object.entries(t))for(const a of o.aliases??[])e.has(a)||e.set(a,s);return e},"buildAliasMap"),Do=we((r,e)=>e.get(r)??r,"resolveTargetAlias"),Ho=we((r,e)=>{if(r.length===0)return e.length;if(e.length===0)return r.length;const t=[];for(let s=0;s<=e.length;s++)t[s]=[s];for(let s=0;s<=r.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let o=1;o<=r.length;o++){const a=e[s-1]===r[o-1]?0:1;t[s][o]=Math.min(t[s-1][o]+1,t[s][o-1]+1,t[s-1][o-1]+a)}return t[e.length][r.length]},"levenshtein"),Bo=we((r,e,t=3)=>er(r,e,1,t)[0],"suggestTarget"),er=we((r,e,t=3,s=3)=>{const o=[];for(const a of e){const l=Ho(r.toLowerCase(),a.toLowerCase());l<=s&&o.push({distance:l,name:a})}return o.sort((a,l)=>a.distance-l.distance||a.name.localeCompare(l.name)),o.slice(0,t).map(a=>a.name)},"suggestTargets"),No=we(r=>r.length===0?" (no targets found)":r.map(e=>` - ${e}`).join(`
2
+ `),"formatTargetList"),Go=we(async r=>{if(r.length===0||!process.stdin.isTTY||!process.stdout.isTTY)return;const e=co({input:process.stdin,output:process.stdout});try{process.stdout.write(`Available targets:
3
+ `);for(const[o,a]of r.entries())process.stdout.write(` ${String(o+1).padStart(2," ")}. ${a}
4
+ `);process.stdout.write(`
5
+ `);const t=(await new Promise(o=>{e.question("Select a target (number or name, blank to cancel): ",o)})).trim();if(t.length===0)return;const s=Number.parseInt(t,10);return Number.isFinite(s)&&s>=1&&s<=r.length?r[s-1]:r.includes(t)?t:Bo(t,r)}finally{e.close()}},"promptTargetInteractively");var qo=Object.defineProperty,nt=T((r,e)=>qo(r,"name",{value:e,configurable:!0}),"i$1");const Wo=nt(r=>Array.isArray(r)?`[${r.join(",")}]`:typeof r=="object"&&r!==null?JSON.stringify(r):String(r),"formatValue"),Uo=nt((r,e,t)=>e==="_"?`${r}${Array.isArray(t)?t.join(" "):String(t)}`:`${r}--${e}=${Wo(t)}`,"formatFlags"),it=nt((r,e,t)=>{const s=new Set(new Set(t.map(b=>b.target.target))),o=new Set(new Set(t.map(b=>b.target.project))),a=e.filter(b=>s.has(b)),l=r.filter(b=>o.has(b)),u=t.length-l.length*a.length,f=a.length===1?"target":"targets",p=a.join(", "),i=l.length===1?`project ${l[0]}`:`${l.length} projects`;let S=`${f} ${p} for ${i}`;return u>0&&(S+=` and ${u} ${u===1?"task":"tasks"} ${u===1?"it depends":"they depend"} on`),S},"formatTargetsAndProjects");var Vo=Object.defineProperty,zo=T((r,e)=>Vo(r,"name",{value:e,configurable:!0}),"c$4");const Yo={error:"red",info:"white",success:"green"},Xe=zo(({children:r,title:e,variant:t})=>{const s=Yo[t];return d(h,{flexDirection:"column",children:[d(h,{gap:1,children:[c(n,{bold:!0,inverse:!0,children:" VIS "}),c(n,{bold:!0,color:s,children:"•"}),c(n,{children:e})]}),r]})},"Header");var Ko=Object.defineProperty,Qo=T((r,e)=>Ko(r,"name",{value:e,configurable:!0}),"s$1");const tr=Qo(({cached:r,failed:e,failedIds:t,projectNames:s,skippedIds:o,succeeded:a,targets:l,tasks:u,took:f})=>{const p=it(s,l,u);if(e===0&&(!o||o.length===0)){const i=r>0?` (${r} read from cache)`:"";return c(It,{children:T(()=>c(Xe,{title:`Successfully ran ${p}`,variant:"success",children:d(h,{flexDirection:"column",paddingLeft:2,children:[d(n,{children:[c(n,{color:"green",children:Qt})," ",a+r," ","tasks completed",i?c(n,{dimColor:!0,children:i}):null]}),d(n,{dimColor:!0,children:[" ","Took",f]})]})}),"children")})}return c(It,{children:T(()=>c(Xe,{title:`Ran ${p}`,variant:"error",children:d(h,{flexDirection:"column",paddingLeft:2,children:[o&&o.length>0&&d(h,{flexDirection:"column",children:[d(n,{dimColor:!0,children:[o.length," ","task",o.length===1?"":"s"," ","skipped (dependency failed or --bail)"]}),o.map(i=>d(n,{dimColor:!0,children:[" - ",i]},i)),c(n,{})]}),e>0&&d(h,{flexDirection:"column",children:[d(n,{children:[c(n,{color:"red",children:String(e)})," ","task",e===1?"":"s"," ","failed:"]}),t.map(i=>d(n,{children:[" ",c(n,{color:"red",children:tt})," ",i]},i)),c(n,{})]}),d(n,{dimColor:!0,children:[" ","Took",f]})]})}),"children")})},"CommandSummary");var Xo=Object.defineProperty,Ke=T((r,e)=>Xo(r,"name",{value:e,configurable:!0}),"u$2");class Ae{static{T(this,"TaskStore")}static{Ke(this,"TaskStore")}#e;#r=new Set;#o=new Map;constructor(e){this.#e={autoExitCountdown:null,cached:0,completed:0,done:!1,endTime:null,failed:0,filterActive:!1,filterText:"",focusedPanel:"tasks",interactiveMode:!1,outputs:new Map,pinnedTaskIds:[null,null],rerunRequested:!1,retryTaskId:null,rows:e.map(t=>({status:"pending",taskId:t.id})),selectedIndex:0,startTime:Date.now(),statusFilter:"all",succeeded:0,viewMode:"list"}}getSnapshot=Ke(()=>this.#e,"getSnapshot");subscribe=Ke(e=>(this.#r.add(e),()=>{this.#r.delete(e)}),"subscribe");startTasks(e){const t=[...this.#e.rows];for(const s of e){const o=t.findIndex(a=>a.taskId===s.id);o!==-1&&(t[o]={...t[o],elapsed:0,status:"running"},this.#o.set(s.id,process.hrtime()))}this.#t({...this.#e,rows:t})}endTasks(e){const t=[...this.#e.rows];let{cached:s,completed:o,failed:a,succeeded:l}=this.#e;const u=new Map(this.#e.outputs);for(const p of e){const i=t.findIndex(S=>S.taskId===p.task.id);switch(i!==-1&&(t[i]={...t[i],duration:p.startTime&&p.endTime?p.endTime-p.startTime:void 0,status:p.status}),o++,p.status){case"failure":{a++;break}case"local-cache":case"local-cache-kept-existing":case"remote-cache":{s++;break}case"success":{l++;break}}p.terminalOutput&&!u.has(p.task.id)&&u.set(p.task.id,p.terminalOutput),this.#o.delete(p.task.id)}let{selectedIndex:f}=this.#e;if(a>this.#e.failed){const p=t.findIndex(i=>i.status==="failure");p!==-1&&(f=p)}this.#t({...this.#e,cached:s,completed:o,failed:a,outputs:u,rows:t,selectedIndex:f,succeeded:l})}static#s=256*1024;addOutput(e,t){if(!t.trim())return;let s=(this.#e.outputs.get(e)??"")+t;s.length>Ae.#s&&(s=s.slice(-Ae.#s)),this.#e.outputs.set(e,s),this.#t({...this.#e})}setOutput(e,t){this.#e.outputs.set(e,t),this.#t({...this.#e})}markDone(){this.#t({...this.#e,done:!0,endTime:Date.now()})}tick(){if(this.#o.size===0)return;let e=!1;const t=[...this.#e.rows];for(let s=0;s<t.length;s++){const o=t[s];if(o.status==="running"){const a=this.#o.get(o.taskId);if(a){const l=process.hrtime(a),u=l[0]*1e3+l[1]/1e6;t[s]={...o,elapsed:u},e=!0}}}e&&this.#t({...this.#e,rows:t})}setSelectedIndex(e){e!==this.#e.selectedIndex&&this.#t({...this.#e,selectedIndex:e})}setFocusedPanel(e){e!==this.#e.focusedPanel&&this.#t({...this.#e,focusedPanel:e})}setFilter(e){this.#t({...this.#e,filterText:e,selectedIndex:0})}setFilterActive(e){e!==this.#e.filterActive&&this.#t({...this.#e,filterActive:e,filterText:e?this.#e.filterText:"",selectedIndex:0})}pinTask(e,t){const s=[...this.#e.pinnedTaskIds];s[e]=t,this.#t({...this.#e,pinnedTaskIds:s})}clearPins(){this.#t({...this.#e,pinnedTaskIds:[null,null]})}requestRetry(e){const t=[...this.#e.rows],s=t.findIndex(u=>u.taskId===e);let{completed:o,failed:a,succeeded:l}=this.#e;if(s!==-1){const u=t[s].status;u==="failure"?(a=Math.max(0,a-1),o=Math.max(0,o-1)):u==="success"&&(l=Math.max(0,l-1),o=Math.max(0,o-1)),t[s]={...t[s],elapsed:0,status:"running"},this.#o.set(e,process.hrtime())}this.#t({...this.#e,completed:o,done:!1,endTime:null,failed:a,interactiveMode:!1,retryTaskId:e,rows:t,succeeded:l})}acknowledgeRetry(){const e=this.#e.retryTaskId;return e&&this.#t({...this.#e,retryTaskId:null}),e}setInteractiveMode(e){e!==this.#e.interactiveMode&&this.#t({...this.#e,interactiveMode:e})}setViewMode(e){e!==this.#e.viewMode&&this.#t({...this.#e,viewMode:e})}setStatusFilter(e){this.#t({...this.#e,selectedIndex:0,statusFilter:e})}requestRerun(){this.#o.clear(),this.#t({...this.#e,autoExitCountdown:null,cached:0,completed:0,done:!1,endTime:null,failed:0,interactiveMode:!1,outputs:new Map,rerunRequested:!0,rows:this.#e.rows.map(e=>({status:"pending",taskId:e.taskId})),startTime:Date.now(),succeeded:0,viewMode:"list"})}acknowledgeRerun(){this.#e.rerunRequested&&this.#t({...this.#e,rerunRequested:!1})}#t(e){this.#e=e;for(const t of this.#r)try{t()}catch{}}}var Zo=Object.defineProperty,ue=T((r,e)=>Zo(r,"name",{value:e,configurable:!0}),"t$1");const rr={delimiter:" ",language:{d:ue(()=>" d","d"),future:"in %s",h:ue(()=>" h","h"),m:ue(()=>" m","m"),mo:ue(()=>" mo","mo"),ms:ue(()=>" ms","ms"),past:"%s ago",s:ue(()=>" s","s"),w:ue(()=>" w","w"),y:ue(()=>" y","y")},largest:2,round:!0,spacer:"",units:["h","m","s","ms"]};ue(r=>{const e=r[0]*1e3+r[1]/1e6;return Zt(e,rr)},"formatHrtime");const ve=ue(r=>Zt(r,rr),"formatMs");var Jo=Object.defineProperty,je=T((r,e)=>Jo(r,"name",{value:e,configurable:!0}),"n$3");const Te=je(r=>r==="local-cache"||r==="local-cache-kept-existing"||r==="remote-cache","isCacheStatus"),Oe=je(r=>{switch(r){case"failure":return{color:"red",icon:tt};case"local-cache":case"local-cache-kept-existing":case"remote-cache":case"success":return{color:"green",icon:Qt};case"skipped":return{color:"gray",icon:De};default:return{color:"gray",icon:"?"}}},"getStatusInfo"),or=je(r=>{const{color:e,icon:t}=Oe(r);return re(N.createElement(n,{color:e},t),{columns:10}).trim()},"getStatusIcon"),es=je(r=>{const{color:e,icon:t}=Oe(r);switch(r){case"local-cache":case"local-cache-kept-existing":case"remote-cache":return re(N.createElement(n,null,N.createElement(n,{color:e},t)," ",N.createElement(n,{color:"cyan"},"[cache]")),{columns:30}).trim();case"skipped":return re(N.createElement(n,null,N.createElement(n,{dimColor:!0},t)," ",N.createElement(n,{dimColor:!0},"[skipped]")),{columns:30}).trim();default:return re(N.createElement(n,{color:e},t),{columns:10}).trim()}},"getStatusPrefix"),ts=je((r,e,t)=>{const s=t.trim();if(!s)return;const o=`
6
+ `;if(process.env.GITHUB_ACTIONS==="true")process.stdout.write(`::group::${or(e)} ${r}${o}`),process.stdout.write(s+o),process.stdout.write(`::endgroup::${o}`);else{const a=process.stdout.columns||80,l=re(N.createElement(n,{dimColor:!0},De.repeat(a)),{columns:a}).trim(),u=es(e),f=re(N.createElement(n,{bold:!0},r),{columns:a}).trim();process.stdout.write(`${l}${o}`),process.stdout.write(`${u} ${f}${o}`),process.stdout.write(s+o),process.stdout.write(`${l}${o}`)}},"logCommandOutputCI");var rs=Object.defineProperty,sr=T((r,e)=>rs(r,"name",{value:e,configurable:!0}),"c$3");const os=sr(r=>r==="running"?{color:"white",icon:"•"}:r==="pending"?{color:"gray",icon:"·"}:Oe(r),"getDisplayInfo"),Ot=sr(({duration:r,focused:e,interactiveMode:t,output:s,scrollRef:o,showFullscreenHint:a,status:l,taskId:u})=>{const f=l??"pending",{icon:p}=os(f),i=e?"bold":"single",S=f==="failure"?"red":f==="success"||Te(f)?e?"green":"gray":f==="running"?e?"white":"cyan":e?"white":"gray",b=u?`${p} ${u}`:void 0,E=r===void 0?void 0:ve(r),A=u?t?"Esc cancel | Enter send":e&&f==="running"&&a?"⏎ FULLSCREEN i INPUT":e&&f==="running"?"i INPUT":e&&a?"<enter> full screen":e?void 0:"<tab> or <enter> to focus":void 0;if(!u)return d(h,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",paddingX:2,paddingY:1,children:[c(n,{dimColor:!0,children:"Select a task to view output"}),c(n,{dimColor:!0,children:"Press Enter or 1/2 to pin"})]});const R=s?s.split(`
7
+ `).map(y=>y.replace(/\r$/,"")):[];return!s&&(f==="running"||f==="pending")?c(h,{borderBottomTitle:A,borderColor:S,borderStyle:i,borderTopRightTitle:E,borderTopTitle:b,flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:c(h,{alignItems:"center",flexGrow:1,justifyContent:"center",children:c(n,{dimColor:!0,children:"Waiting for task output..."})})}):d(h,{borderBottomTitle:A,borderColor:t?"yellow":S,borderStyle:i,borderTopRightTitle:E,borderTopTitle:b,flexDirection:"column",flexGrow:1,children:[c(h,{flexGrow:1,flexShrink:1,paddingY:1,children:c(Kt,{flexGrow:1,followOutput:!0,paddingX:2,ref:o,scrollbar:!0,scrollbarColor:"gray",scrollbarStyle:"block",children:R.map((y,j)=>c(n,{children:y},String(j)))})}),t&&c(h,{flexShrink:0,justifyContent:"center",paddingX:1,children:c(n,{bold:!0,color:"yellow",children:"INTERACTIVE — keystrokes forwarded to task — Esc to exit"})})]})},"OutputPanel");var ss=Object.defineProperty,Be=T((r,e)=>ss(r,"name",{value:e,configurable:!0}),"x$1");const nr=6,ir=8,ar=10,ns=Be(r=>r==="running"||r==="pending"?Xt:r==="local-cache"||r==="local-cache-kept-existing"?"Local":r==="remote-cache"?"Remote":De,"getCacheLabel"),Pt=Be((r,e)=>e[0]===r?"[1]":e[1]===r?"[2]":"","getPinLabel"),Ft=Be(({compact:r,isSelected:e,pinLabel:t,row:s})=>{const{status:o,taskId:a}=s,l=e?">":" ";let u;if(o==="running")u=d(n,{bold:!0,color:"white",children:[" ",c(uo,{type:"dots"})," "]});else if(o==="pending")u=c(n,{bold:!0,color:"gray",children:" · "});else{const{color:p,icon:i}=Oe(o);u=d(n,{bold:!0,color:p,children:[" ",i," "]})}let f=Xt;return o!=="running"&&o!=="pending"?f=s.duration===void 0?De:ve(s.duration):o==="running"&&s.elapsed!==void 0&&(f=ve(s.elapsed)),d(h,{children:[c(n,{children:l}),c(h,{width:nr,children:u}),d(h,{flexGrow:1,children:[c(n,{bold:e,inverse:e,children:a}),t?c(n,{dimColor:!0,children:` ${t}`}):null]}),!r&&c(h,{justifyContent:"flex-end",width:ir,children:c(n,{dimColor:!Te(o),children:ns(o)})}),!r&&c(h,{justifyContent:"flex-end",width:ar,children:c(n,{dimColor:o==="pending",children:f})})]})},"TaskListRow"),_t=Be(({compact:r,filterActive:e,filterText:t,focused:s,headerStatus:o,parallelSlots:a=3,pinnedTaskIds:l,rows:u,scrollRef:f,selectedIndex:p,title:i})=>{const S=o==="error"?"red":o==="success"?"green":s?"white":"gray",b=u[p]?.taskId,E=u.filter(y=>y.status==="running"),A=E.length>0||u.some(y=>y.status==="pending"),R=[];if(A)for(let y=0;y<a;y++){const j=E[y];j?R.push(c(Ft,{compact:r,isSelected:j.taskId===b,pinLabel:Pt(j.taskId,l),row:j},`par-${j.taskId}`)):R.push(d(h,{children:[c(n,{children:" "}),c(h,{width:nr,children:c(n,{bold:!0,color:"gray",children:" · "})}),c(n,{dimColor:!0,children:"Waiting for task..."})]},`par-empty-${String(y)}`))}return d(h,{borderColor:S,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[d(h,{flexShrink:0,gap:1,paddingX:1,children:[c(n,{bold:!0,inverse:!0,children:" VIS "}),c(n,{children:i}),!r&&d(h,{flexGrow:1,gap:0,justifyContent:"flex-end",children:[c(h,{justifyContent:"flex-end",width:ir,children:c(n,{dimColor:!0,children:"Cache"})}),c(h,{justifyContent:"flex-end",width:ar,children:c(n,{dimColor:!0,children:"Duration"})})]})]}),c(Kt,{flexGrow:1,flexShrink:1,paddingLeft:1,paddingY:1,ref:f,scrollbar:!0,scrollbarColor:"gray",scrollbarStyle:"block",children:u.map(y=>c(Ft,{compact:r,isSelected:y.taskId===b,pinLabel:Pt(y.taskId,l),row:y},y.taskId))}),A&&c(h,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",borderTop:!0,flexDirection:"column",flexShrink:0,paddingLeft:1,paddingY:1,children:R}),e&&d(h,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",borderTop:!0,flexShrink:0,paddingX:1,children:[c(n,{bold:!0,color:"white",children:"/ "}),c(n,{children:t}),c(n,{inverse:!0,children:" "})]})]})},"TaskListPanel");var is=Object.defineProperty,as=T((r,e)=>is(r,"name",{value:e,configurable:!0}),"y$2");const At=40,Lt=10,Dt=100,cs=as(({autoExitSeconds:r,parallelSlots:e,projectNames:t,stdinRegistry:s,store:o,targets:a,tasks:l})=>{const{exit:u}=ho(),{columns:f,rows:p}=fo(),i=go(o.subscribe,o.getSnapshot),[S,b]=Et(!1),E=Ee(null),A=Ee(null),R=Ee(null),[y,j]=Et(!1),O=Ee({list:0,splitList:0,splitOutput:0}),Q=ze(()=>{i.viewMode==="list"?O.current.list=A.current?.getScrollOffset()??0:i.viewMode==="split"&&(O.current.splitList=A.current?.getScrollOffset()??0,O.current.splitOutput=R.current?.getScrollOffset()??0)},[i.viewMode]),F=ze(k=>{setTimeout(()=>{if(k==="list"){const m=O.current.list;A.current?.scrollTo(m)}else if(k==="split"){const m=O.current.splitList;m>0?A.current?.scrollTo(m):A.current?.scrollTo(Math.max(0,o.getSnapshot().selectedIndex-2)),R.current?.scrollTo(O.current.splitOutput)}},0)},[o]),w=Ee(!1);Ye(()=>{i.done&&!w.current&&(w.current=!0,r>0&&j(!0)),!i.done&&w.current&&(w.current=!1,j(!1))},[i.done,r]);const x=Rt(()=>{let k=i.rows;if(i.statusFilter!=="all"&&(k=k.filter(m=>i.statusFilter==="failed"?m.status==="failure":i.statusFilter==="running"?m.status==="running"||m.status==="pending":i.statusFilter==="passed"?m.status==="success"||Te(m.status):!0)),i.filterText){const m=i.filterText.toLowerCase();k=k.filter(C=>C.taskId.toLowerCase().includes(m))}return k},[i.rows,i.filterText,i.statusFilter]),P=Rt(()=>i.rows.filter(k=>k.status==="running").length,[i.rows]),G=(x[i.selectedIndex]??null)?.taskId??null,$=i.pinnedTaskIds[0]??G,H=$?i.rows.find(k=>k.taskId===$):null,ie=$?i.outputs.get($)??"":"",L=it(t,a,l),q=i.done?`Completed ${L} (${ve((i.endTime??Date.now())-i.startTime)})`:`Running ${L}...`,ae=i.done?i.failed>0?"error":"success":"running",J=ze(k=>{A.current?.scrollTo(Math.max(0,k-2))},[]);if(Ye(()=>{i.interactiveMode&&H?.status!=="running"&&o.setInteractiveMode(!1)},[i.interactiveMode,H?.status,o]),Ye(()=>{if(!$)return;let k=f;i.viewMode==="split"&&f>=Dt?k=f-Math.floor(f*.4)-2:(i.viewMode==="split"||i.viewMode==="fullscreen")&&(k=f-2);const m=Math.max(1,p-4);s.get($)?.resize?.(k,m)},[f,p,i.viewMode,$]),Mt((k,m)=>{if(m.escape){o.setInteractiveMode(!1);return}if(!$)return;const C=s.get($);if(!C){o.setInteractiveMode(!1);return}if(m.return)C.write("\r");else if(m.upArrow)C.write("\x1B[A");else if(m.downArrow)C.write("\x1B[B");else if(m.rightArrow)C.write("\x1B[C");else if(m.leftArrow)C.write("\x1B[D");else if(m.backspace)C.write("");else if(m.delete)C.write("\x1B[3~");else if(m.tab)C.write(" ");else if(m.home)C.write("\x1B[H");else if(m.end)C.write("\x1B[F");else if(m.pageUp)C.write("\x1B[5~");else if(m.pageDown)C.write("\x1B[6~");else if(m.ctrl&&k){const ee=k.toUpperCase().codePointAt(0);ee!==void 0&&ee>=65&&ee<=90&&C.write(String.fromCodePoint(ee-64))}else k&&C.write(k)},{isActive:i.interactiveMode}),Mt((k,m)=>{if(k==="c"&&m.ctrl){u();return}if(!y){if(S){m.escape||k==="?"?b(!1):k==="q"?(b(!1),j(!0)):m.downArrow||k==="j"?E.current?.scrollBy(1):m.upArrow||k==="k"?E.current?.scrollBy(-1):m.pageDown?E.current?.scrollBy(5):m.pageUp?E.current?.scrollBy(-5):m.home?E.current?.scrollToTop():m.end&&E.current?.scrollToBottom();return}if(k==="?"){b(!0);return}if(k==="q"){j(!0);return}if(k==="r"&&i.done){o.requestRerun();return}if(k==="R"&&i.done){const C=x[i.selectedIndex];C?.status==="failure"&&o.requestRetry(C.taskId);return}if(k==="F"&&!i.filterActive){const C=["all","failed","running","passed"],ee=C.indexOf(i.statusFilter);o.setStatusFilter(C[(ee+1)%C.length]);return}if(i.filterActive){if(m.escape){o.setFilterActive(!1);return}if(m.return){o.setFilterActive(!1);return}if(m.backspace){o.setFilter(i.filterText.slice(0,-1));return}if(k&&!m.ctrl&&!m.meta){o.setFilter(i.filterText+k);return}return}if(k==="i"&&H?.status==="running"&&(i.viewMode==="fullscreen"||i.viewMode==="split"&&i.focusedPanel==="output")){o.setInteractiveMode(!0);return}if(i.viewMode==="fullscreen"){if(m.escape){o.setViewMode("split"),F("split");return}if(m.downArrow||k==="j"){R.current?.scrollBy(1);return}if(m.upArrow||k==="k"){R.current?.scrollBy(-1);return}if(m.pageDown||m.ctrl&&k==="d"){R.current?.scrollBy(12);return}if(m.pageUp||m.ctrl&&k==="u"){R.current?.scrollBy(-12);return}if(m.home){R.current?.scrollToTop();return}if(m.end){R.current?.scrollToBottom();return}return}if(i.viewMode==="split"){if(m.tab){const C=i.focusedPanel==="tasks"?"output":"tasks";o.setFocusedPanel(C);return}if(i.focusedPanel==="output"){if(m.escape){o.setFocusedPanel("tasks");return}if(m.return){Q(),o.setViewMode("fullscreen");return}if(m.downArrow||k==="j"){R.current?.scrollBy(1);return}if(m.upArrow||k==="k"){R.current?.scrollBy(-1);return}if(m.pageDown||m.ctrl&&k==="d"){R.current?.scrollBy(12);return}if(m.pageUp||m.ctrl&&k==="u"){R.current?.scrollBy(-12);return}if(m.home){R.current?.scrollToTop();return}if(m.end){R.current?.scrollToBottom();return}return}if(m.escape){o.setViewMode("list"),F("list");return}if(m.return){o.setFocusedPanel("output");return}}if(i.viewMode==="list"||i.viewMode==="split"&&i.focusedPanel==="tasks"){if(m.downArrow||k==="j"){const C=Math.min(i.selectedIndex+1,Math.max(0,x.length-1));o.setSelectedIndex(C),J(C);return}if(m.upArrow||k==="k"){const C=Math.max(i.selectedIndex-1,0);o.setSelectedIndex(C),J(C);return}if(m.return&&i.viewMode==="list"){Q(),O.current.splitList=0,O.current.splitOutput=0,o.setViewMode("split"),o.setFocusedPanel("output"),F("split");return}if(k==="/"){o.setFilterActive(!0);return}if(k==="1"&&G){o.pinTask(0,G);return}if(k==="2"&&G){o.pinTask(1,G);return}if(k==="0"){o.clearPins();return}m.escape&&i.filterText&&o.setFilter("")}}},{isActive:!i.interactiveMode}),f<At||p<Lt)return c(h,{alignItems:"center",height:p,justifyContent:"center",width:f,children:d(n,{color:"yellow",children:["Terminal too small (",f,"x",p,"). Minimum:"," ",At,"x",Lt]})});const B=d(h,{gap:1,children:[i.succeeded>0&&d(n,{bold:!0,color:"green",children:["✓"," ",i.succeeded]}),i.failed>0&&d(n,{bold:!0,color:"red",children:["✗"," ",i.failed]}),P>0&&d(n,{color:"cyan",children:["◷"," ",P]}),d(n,{dimColor:!0,children:[i.rows.length," ","total"]}),i.statusFilter!=="all"&&d(n,{color:"yellow",children:["[",i.statusFilter,"]"]})]});let he;if(i.viewMode==="fullscreen")he=[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"Esc"}),c(n,{dimColor:!0,children:"BACK"})]},"esc"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"↑↓"}),c(n,{dimColor:!0,children:"SCROLL"})]},"scroll"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"^u ^d"}),c(n,{dimColor:!0,children:"PAGE"})]},"page"),...H?.status==="running"?[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"i"}),c(n,{dimColor:!0,children:"INPUT"})]},"i")]:[],d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"q"}),c(n,{dimColor:!0,children:"QUIT"})]},"q")];else if(i.done){const k=x[i.selectedIndex]?.status==="failure";he=[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"q"}),c(n,{dimColor:!0,children:"QUIT"})]},"q"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"r"}),c(n,{dimColor:!0,children:"RERUN"})]},"r"),...k?[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"R"}),c(n,{dimColor:!0,children:"RETRY"})]},"R")]:[],d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"?"}),c(n,{dimColor:!0,children:"HELP"})]},"?"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"↑↓"}),c(n,{dimColor:!0,children:"NAV"})]},"nav"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"F"}),c(n,{dimColor:!0,children:"FILTER"})]},"F"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"⏎"}),c(n,{dimColor:!0,children:i.viewMode==="list"?"OUTPUT":"FULLSCREEN"})]},"enter")]}else i.viewMode==="split"&&i.focusedPanel==="output"?he=[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"q"}),c(n,{dimColor:!0,children:"QUIT"})]},"q"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"Esc"}),c(n,{dimColor:!0,children:"BACK"})]},"esc"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"↑↓"}),c(n,{dimColor:!0,children:"SCROLL"})]},"scroll"),...H?.status==="running"?[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"i"}),c(n,{dimColor:!0,children:"INPUT"})]},"i")]:[],d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"⏎"}),c(n,{dimColor:!0,children:"FULLSCREEN"})]},"enter"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"Tab"}),c(n,{dimColor:!0,children:"PANEL"})]},"tab"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"?"}),c(n,{dimColor:!0,children:"HELP"})]},"?")]:he=[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"q"}),c(n,{dimColor:!0,children:"QUIT"})]},"q"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"?"}),c(n,{dimColor:!0,children:"HELP"})]},"?"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"↑↓"}),c(n,{dimColor:!0,children:"NAV"})]},"nav"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"/"}),c(n,{dimColor:!0,children:"FILTER"})]},"/"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"F"}),c(n,{dimColor:!0,children:"STATUS"})]},"F"),d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"⏎"}),c(n,{dimColor:!0,children:i.viewMode==="list"?"OUTPUT":"FULLSCREEN"})]},"enter"),...i.viewMode==="split"?[d(h,{gap:1,children:[c(n,{bold:!0,color:"white",children:"Tab"}),c(n,{dimColor:!0,children:"PANEL"})]},"tab")]:[]];const ce=d(h,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",flexShrink:0,justifyContent:"space-between",children:[c(h,{flexGrow:1,flexWrap:"wrap",gap:2,paddingX:1,children:he}),c(h,{flexShrink:0,paddingX:1,children:B})]}),D=d(po,{backgroundColor:"#1e1e1e",footer:d(n,{dimColor:!0,children:[c(n,{bold:!0,color:"white",children:"↑↓"})," ","scroll"," ",c(n,{bold:!0,color:"white",children:"?"}),"/",c(n,{bold:!0,color:"white",children:"Esc"})," ","close"]}),scrollRef:E,title:"KEYBOARD SHORTCUTS",visible:S,width:52,children:[d(h,{flexDirection:"column",marginBottom:1,children:[d(h,{marginBottom:1,children:[c(n,{dimColor:!0,children:"── "}),c(n,{bold:!0,color:"white",children:"NAVIGATION"})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","↑","/k"]}),c(n,{dimColor:!0,children:" Move up"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","↓","/j"]}),c(n,{dimColor:!0,children:" Move down"})]})]}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","Tab"]}),c(n,{dimColor:!0,children:" Switch panel (split)"})]}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","Esc"]}),c(n,{dimColor:!0,children:" Back / close"})]}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","Enter"]}),c(n,{dimColor:!0,children:" Show output / fullscreen"})]})]}),d(h,{flexDirection:"column",marginBottom:1,children:[d(h,{marginBottom:1,children:[c(n,{dimColor:!0,children:"── "}),c(n,{bold:!0,color:"white",children:"VIEWS"})]}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","Enter"]}),d(n,{dimColor:!0,children:[" ","List"," ","→"," ","Split"," ","→"," ","Fullscreen"]})]}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","Esc"]}),d(n,{dimColor:!0,children:[" ","Fullscreen"," ","→"," ","Split"," ","→"," ","List"]})]})]}),d(h,{flexDirection:"column",marginBottom:1,children:[d(h,{marginBottom:1,children:[c(n,{dimColor:!0,children:"── "}),c(n,{bold:!0,color:"white",children:"ACTIONS"})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","/"]}),c(n,{dimColor:!0,children:" Filter by text"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","F"]}),c(n,{dimColor:!0,children:" Filter by status"})]})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","1"]}),c(n,{dimColor:!0,children:"/"}),c(n,{bold:!0,color:"white",children:"2"}),c(n,{dimColor:!0,children:" Pin to output pane"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","0"]}),c(n,{dimColor:!0,children:" Clear pins"})]})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","r"]}),c(n,{dimColor:!0,children:" Rerun all (done)"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","R"]}),c(n,{dimColor:!0,children:" Retry failed task"})]})]}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","i"]}),c(n,{dimColor:!0,children:" Interactive input (running task)"})]})]}),d(h,{flexDirection:"column",marginBottom:1,children:[d(h,{marginBottom:1,children:[c(n,{dimColor:!0,children:"── "}),c(n,{bold:!0,color:"white",children:"SCROLLING"}),c(n,{dimColor:!0,children:" (output panel)"})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","↑","/k"]}),c(n,{dimColor:!0,children:" Scroll up"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","↓","/j"]}),c(n,{dimColor:!0,children:" Scroll down"})]})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","^u"]}),c(n,{dimColor:!0,children:" Page up"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","^d"]}),c(n,{dimColor:!0,children:" Page down"})]})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","Home"]}),c(n,{dimColor:!0,children:" Top"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","End"]}),c(n,{dimColor:!0,children:" Bottom"})]})]})]}),d(h,{flexDirection:"column",children:[d(h,{marginBottom:1,children:[c(n,{dimColor:!0,children:"── "}),c(n,{bold:!0,color:"white",children:"GENERAL"})]}),d(h,{children:[c(h,{width:24,children:d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","q"]}),c(n,{dimColor:!0,children:" Quit"})]})}),d(n,{children:[d(n,{bold:!0,color:"white",children:[" ","?"]}),c(n,{dimColor:!0,children:" Toggle help"})]})]})]})]}),U=c(_r,{autoExitSeconds:r>0?r:3,onCancel:T(()=>{j(!1)},"onCancel"),visible:y});if(i.viewMode==="fullscreen")return d(h,{flexDirection:"column",height:p,width:f,children:[c(h,{flexGrow:1,children:c(Ot,{duration:H?.duration??H?.elapsed,focused:!0,interactiveMode:i.interactiveMode,output:ie,scrollRef:R,status:H?.status,taskId:$})}),ce,U,D]});if(i.viewMode==="split"){const k=f>=Dt,m=c(_t,{compact:!0,filterActive:i.filterActive,filterText:i.filterText,focused:i.focusedPanel==="tasks",headerStatus:ae,parallelSlots:e,pinnedTaskIds:i.pinnedTaskIds,rows:x,scrollRef:A,selectedIndex:i.selectedIndex,title:q}),C=c(Ot,{duration:H?.duration??H?.elapsed,focused:i.focusedPanel==="output",interactiveMode:i.interactiveMode,output:ie,scrollRef:R,showFullscreenHint:!0,status:H?.status,taskId:$});if(k){const fe=Math.floor(f*.4);return d(h,{flexDirection:"column",height:p,width:f,children:[d(h,{flexDirection:"row",flexGrow:1,children:[c(h,{width:fe,children:m}),c(h,{flexGrow:1,children:C})]}),ce,U,D]})}const ee=Math.floor(p*.45);return d(h,{flexDirection:"column",height:p,width:f,children:[c(h,{height:ee,children:m}),c(h,{flexGrow:1,children:C}),ce,U,D]})}return d(h,{flexDirection:"column",height:p,width:f,children:[c(h,{flexGrow:1,children:c(_t,{filterActive:i.filterActive,filterText:i.filterText,focused:!0,headerStatus:ae,parallelSlots:e,pinnedTaskIds:i.pinnedTaskIds,rows:x,scrollRef:A,selectedIndex:i.selectedIndex,title:q})}),ce,U,D]})},"VisTaskRunnerApp");var ls=Object.defineProperty,$e=T((r,e)=>ls(r,"name",{value:e,configurable:!0}),"n$2");const ds=$e(r=>{const{args:e,autoExit:t=!1,outputStyle:s="normal",projectNames:o,stdinRegistry:a,tasks:l}=r,u=new Ae(l),f=typeof e.parallel=="number"?e.parallel:3,p=t===!0?3:typeof t=="number"?t:0;let i,S;const b=new Promise(F=>{S=F});let E;const A=$e(()=>{E&&(clearInterval(E),E=void 0)},"cleanup"),R=$e(()=>{if(a){for(const F of a.values())F.kill?.();a.clear()}},"killAllPtyProcesses"),y=$e(()=>{A(),Q(),R(),process.stdout.write("\x1B[?1049l\x1B[?25h"),i?.cleanup(),process.exit(1)},"onSignal"),j=$e(()=>{const F=u.getSnapshot(),w=ve(Date.now()-F.startTime),x=F.rows.filter($=>$.status==="failure").map($=>$.taskId),P=process.stdout.columns||80;process.stdout.write(`
8
+ `);for(const $ of F.rows){const{status:H,taskId:ie}=$,L=Oe(H);let q="";switch(H){case"local-cache":case"local-cache-kept-existing":{q=" [local cache]";break}case"remote-cache":{q=" [remote cache]";break}case"skipped":{q=" [skipped]";break}}const ae=re(N.createElement(n,null," ",N.createElement(n,{color:L.color},L.icon),` vis run ${ie}`,q?N.createElement(n,{dimColor:!0},` ${q}`):null),{columns:P});process.stdout.write(`${ae}
9
+ `)}process.stdout.write(`
10
+ `);const G=re(N.createElement(tr,{cached:F.cached,failed:F.failed,failedIds:x,projectNames:o,succeeded:F.succeeded,targets:e.targets,tasks:l,took:w}),{columns:P});if(process.stdout.write(`${G}
11
+ `),x.length>0&&s!=="quiet")for(const $ of x){const H=F.outputs.get($);if(H?.trim()){const ie=re(N.createElement(n,null,`
12
+ `,N.createElement(n,{bold:!0,color:"red"},` ${tt} vis run ${$}`)),{columns:P});process.stdout.write(`${ie}
13
+
14
+ `);const L=H.trim().split(`
15
+ `).map(q=>` ${q}`).join(`
16
+ `);process.stdout.write(`${L}
17
+ `)}}},"printExitSummary");let O;const Q=$e(()=>{O&&(clearInterval(O),O=void 0)},"clearKeepAlive");return{lifeCycle:{endCommand(){A(),u.markDone(),O||(O=setInterval(()=>{},1e3)),process.stdin.isTTY&&typeof process.stdin.setRawMode=="function"&&(process.stdin.setRawMode(!0),process.stdin.ref(),process.stdin.resume())},endTasks(F){u.endTasks(F)},printTaskTerminalOutput(F,w,x){u.getSnapshot().outputs.has(F.id)||u.addOutput(F.id,x)},startCommand(){process.on("SIGINT",y),process.on("SIGTERM",y),O||(O=setInterval(()=>{},1e3)),process.stdin.isTTY&&typeof process.stdin.setRawMode=="function"&&(process.stdin.setRawMode(!0),process.stdin.ref(),process.stdin.resume()),i=mo(N.createElement(cs,{autoExitSeconds:p,parallelSlots:f,projectNames:o,stdinRegistry:a??new Map,store:u,targets:e.targets,tasks:l}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}),i.waitUntilExit().then(()=>{Q(),R(),process.removeListener("SIGINT",y),process.removeListener("SIGTERM",y),j(),S()}).catch(()=>{Q(),R(),process.removeListener("SIGINT",y),process.removeListener("SIGTERM",y),S()})},startTasks(F){u.startTasks(F),E||(E=setInterval(()=>{u.tick()},100))}},renderIsDone:b,store:u}},"createDynamicOutputRenderer");var us=Object.defineProperty,at=T((r,e)=>us(r,"name",{value:e,configurable:!0}),"l$1");const hs=at(r=>r==="quiet"?"quiet":"normal","parseOutputStyle"),fs=at((r,e)=>{const t=r.overrides.visOptions;return t?.outputStyle==="normal"||t?.outputStyle==="quiet"?t.outputStyle:e},"resolveTaskOutputStyle");class ps{static{T(this,"StaticOutputLifeCycle")}static{at(this,"StaticOutputLifeCycle")}#e;#r;#o;#s=[];#t=[];#n=new Map;#i;#a;#c=0;constructor(e){this.#e=e.projectNames,this.#r=e.args.targets,this.#o=e.tasks,this.#i=e.logReporter,this.#a=e.outputStyle??"normal"}startCommand(){this.#c=Date.now();const e=process.stdout.columns||80,t=`Running ${it(this.#e,this.#r,this.#o)}`,s=re(N.createElement(Xe,{title:t,variant:"info"}),{columns:e});process.stdout.write(s);const o=this.#o[0],a=o?.overrides?Object.entries(o.overrides).filter(([l])=>l!=="command"):[];if(a.length>0){process.stdout.write(`
18
+ With additional flags:
19
+ `);for(const[l,u]of a)process.stdout.write(`${Uo(" ",l,u)}
20
+ `)}process.stdout.write(`
21
+ `)}startTasks(e){const t=process.stdout.columns||80;for(const s of e){const o=re(N.createElement(n,null,N.createElement(n,{dimColor:!0},">"),` ${s.id}`),{columns:t});process.stdout.write(`${o}
22
+ `)}}endTasks(e){const t=process.stdout.columns||80;for(const s of e){this.#n.set(s.task.id,s),s.status==="failure"?this.#s.push(s):Te(s.status)&&this.#t.push(s);const o=or(s.status),a=s.startTime&&s.endTime?` (${ve(s.endTime-s.startTime)})`:"",l=Te(s.status)?" [cache]":"",u=re(N.createElement(n,null,o,` ${s.task.id}`,l?N.createElement(n,{color:"cyan"},l):null,a?N.createElement(n,{dimColor:!0},a):null),{columns:t});process.stdout.write(`${u}
23
+ `)}}printTaskTerminalOutput(e,t,s){if(!(fs(e,this.#a)==="quiet"&&(t==="success"||Te(t)))){if(this.#i){this.#i.printTaskTerminalOutput(e,t,s);return}ts(e.id,t,s)}}endCommand(){const e=ve(Date.now()-this.#c),t=this.#o.filter(a=>!this.#n.has(a.id)).map(a=>a.id);process.stdout.write(`
24
+ `);const s=process.stdout.columns||80,o=re(N.createElement(tr,{cached:this.#t.length,failed:this.#s.length,failedIds:this.#s.map(a=>a.task.id),projectNames:this.#e,skippedIds:t.length>0?t:void 0,succeeded:this.#n.size-this.#s.length-this.#t.length,targets:this.#r,tasks:this.#o,took:e}),{columns:s});process.stdout.write(`${o}
25
+ `)}}var ms=Object.defineProperty,Y=T((r,e)=>ms(r,"name",{value:e,configurable:!0}),"r$1");function Re(r,e={},t){for(const s in r){const o=r[s],a=t?`${t}:${s}`:s;typeof o=="object"&&o!==null?Re(o,e,a):typeof o=="function"&&(e[a]=o)}return e}T(Re,"c$2");Y(Re,"flatHooks");function gs(...r){const e={};for(const t of r){const s=Re(t);for(const o in s)e[o]?e[o].push(s[o]):e[o]=[s[o]]}for(const t in e)if(e[t].length>1){const s=e[t];e[t]=(...o)=>cr(s,a=>a(...o))}else e[t]=e[t][0];return e}T(gs,"v$1");Y(gs,"mergeHooks");function cr(r,e){return r.reduce((t,s)=>t.then(()=>e(s)),Promise.resolve())}T(cr,"d");Y(cr,"serial");const lr=(()=>{if(console.createTask)return console.createTask;const r={run:Y(e=>e(),"run")};return()=>r})();function Ne(r,e,t,s){for(let o=t;o<r.length;o+=1)try{const a=s?s.run(()=>r[o](...e)):r[o](...e);if(a&&typeof a.then=="function")return Promise.resolve(a).then(()=>Ne(r,e,o+1,s))}catch(a){return Promise.reject(a)}}T(Ne,"k$1");Y(Ne,"callHooks");function dr(r,e,t){if(r.length>0)return Ne(r,e,0,lr(t))}T(dr,"y$1");Y(dr,"serialTaskCaller");function ur(r,e,t){if(r.length>0){const s=lr(t);return Promise.all(r.map(o=>s.run(()=>o(...e))))}}T(ur,"m");Y(ur,"parallelTaskCaller");function ws(r,e){return r.reduce((t,s)=>t.then(()=>s(...e||[])),Promise.resolve())}T(ws,"x");Y(ws,"serialCaller");function ks(r,e){return Promise.all(r.map(t=>t(...e||[])))}T(ks,"P");Y(ks,"parallelCaller");function _e(r,e){for(const t of[...r])t(e)}T(_e,"a$1");Y(_e,"callEachWith");var vs=class{static{T(this,"p")}static{Y(this,"Hookable")}_hooks;_before;_after;_deprecatedHooks;_deprecatedMessages;constructor(){this._hooks={},this._before=void 0,this._after=void 0,this._deprecatedMessages=void 0,this._deprecatedHooks={},this.hook=this.hook.bind(this),this.callHook=this.callHook.bind(this),this.callHookWith=this.callHookWith.bind(this)}hook(e,t,s={}){if(!e||typeof t!="function")return()=>{};const o=e;let a;for(;this._deprecatedHooks[e];)a=this._deprecatedHooks[e],e=a.to;if(a&&!s.allowDeprecated){let l=a.message;l||(l=`${o} hook has been deprecated`+(a.to?`, please use ${a.to}`:"")),this._deprecatedMessages||(this._deprecatedMessages=new Set),this._deprecatedMessages.has(l)||(console.warn(l),this._deprecatedMessages.add(l))}if(!t.name)try{Object.defineProperty(t,"name",{get:Y(()=>"_"+e.replace(/\W+/g,"_")+"_hook_cb","get"),configurable:!0})}catch{}return this._hooks[e]=this._hooks[e]||[],this._hooks[e].push(t),()=>{t&&(this.removeHook(e,t),t=void 0)}}hookOnce(e,t){let s,o=Y((...a)=>(typeof s=="function"&&s(),s=void 0,o=void 0,t(...a)),"_function");return s=this.hook(e,o),s}removeHook(e,t){const s=this._hooks[e];if(s){const o=s.indexOf(t);o!==-1&&s.splice(o,1),s.length===0&&(this._hooks[e]=void 0)}}clearHook(e){this._hooks[e]=void 0}deprecateHook(e,t){this._deprecatedHooks[e]=typeof t=="string"?{to:t}:t;const s=this._hooks[e]||[];this._hooks[e]=void 0;for(const o of s)this.hook(e,o)}deprecateHooks(e){for(const t in e)this.deprecateHook(t,e[t])}addHooks(e){const t=Re(e),s=Object.keys(t).map(o=>this.hook(o,t[o]));return()=>{for(const o of s)o();s.length=0}}removeHooks(e){const t=Re(e);for(const s in t)this.removeHook(s,t[s])}removeAllHooks(){this._hooks={}}callHook(e,...t){return this.callHookWith(dr,e,t)}callHookParallel(e,...t){return this.callHookWith(ur,e,t)}callHookWith(e,t,s){const o=this._before||this._after?{name:t,args:s,context:{}}:void 0;this._before&&_e(this._before,o);const a=e(this._hooks[t]?[...this._hooks[t]]:[],s,t);return a instanceof Promise?a.finally(()=>{this._after&&o&&_e(this._after,o)}):(this._after&&o&&_e(this._after,o),a)}beforeEach(e){return this._before=this._before||[],this._before.push(e),()=>{if(this._before!==void 0){const t=this._before.indexOf(e);t!==-1&&this._before.splice(t,1)}}}afterEach(e){return this._after=this._after||[],this._after.push(e),()=>{if(this._after!==void 0){const t=this._after.indexOf(e);t!==-1&&this._after.splice(t,1)}}}};function hr(){return new vs}T(hr,"w$1");Y(hr,"createHooks");(class{static{Y(this,"HookableCore")}_hooks;constructor(){this._hooks={}}hook(r,e){return!r||typeof e!="function"?()=>{}:(this._hooks[r]=this._hooks[r]||[],this._hooks[r].push(e),()=>{e&&(this.removeHook(r,e),e=void 0)})}removeHook(r,e){const t=this._hooks[r];if(t){const s=t.indexOf(e);s!==-1&&t.splice(s,1),t.length===0&&(this._hooks[r]=void 0)}}callHook(r,...e){const t=this._hooks[r];if(!(!t||t.length===0))return Ne(t,e,0)}});const Ht=typeof window<"u";function ys(r,e={}){const t={inspect:Ht,group:Ht,filter:Y(()=>!0,"filter"),...e},s=t.filter,o=typeof s=="string"?i=>i.startsWith(s):s,a=t.tag?`[${t.tag}] `:"",l=Y(i=>a+i.name+"".padEnd(i._id,"\0"),"logPrefix"),u={},f=r.beforeEach(i=>{o!==void 0&&!o(i.name)||(u[i.name]=u[i.name]||0,i._id=u[i.name]++,console.time(l(i)))}),p=r.afterEach(i=>{o!==void 0&&!o(i.name)||(t.group&&console.groupCollapsed(i.name),t.inspect?console.timeLog(l(i),i.args):console.timeEnd(l(i)),t.group&&console.groupEnd(),u[i.name]--)});return{close:Y(()=>{f(),p()},"close")}}T(ys,"W");Y(ys,"createDebugger");var bs=Object.defineProperty,Ge=T((r,e)=>bs(r,"name",{value:e,configurable:!0}),"t");const $s=Ge(()=>hr(),"createVisHooks"),Ts=Ge(async(r,e)=>{if(!(!e||e.length===0))for(const t of e){if(t.hooks)for(const[s,o]of Object.entries(t.hooks)){const a=Array.isArray(o)?o:[o];for(const l of a)r.hook(s,l)}t.setup&&await t.setup(r)}},"registerPlugins");class Ss{static{T(this,"HookableLifeCycle")}static{Ge(this,"HookableLifeCycle")}#e;#r;#o=new Map;constructor(e,t){this.#e=e,this.#r=t}startTasks(e){for(const t of e)this.#o.set(t.id,t),this.#s("task:before",t)}endTasks(e){for(const t of e)this.#o.delete(t.task.id),this.#s("task:after",t.task,t),t.status==="failure"?this.#s("task:failure",t.task,t):Cs(t.status)&&this.#s("task:cacheHit",t.task,t)}printCacheMiss(e,t){this.#s("task:cacheMiss",e,t)}onTaskStdout(e,t){this.#s("task:stdout",e,t)}onTaskStderr(e,t){this.#s("task:stderr",e,t)}#s(e,...t){Promise.resolve(this.#e.callHook(e,...t)).catch(s=>{if(this.#r)try{this.#r(e,s)}catch{}})}}const Cs=Ge(r=>r==="local-cache"||r==="local-cache-kept-existing"||r==="remote-cache","isCacheStatus");var xs=Object.defineProperty,qe=T((r,e)=>xs(r,"name",{value:e,configurable:!0}),"o$1");const Is=qe(async r=>{if(process.env.VIS_NO_SHELL_HISTORY||wo()==="win32")return;const e=process.env.SHELL;if(!e)return;const t=Vr(e);try{if(t==="zsh"){await Ms(r);return}if(t==="bash"){await Es(r);return}t==="fish"&&await Rs(r)}catch{}},"appendToShellHistory"),Ms=qe(async r=>{const e=process.env.HISTFILE??Ce(process.env.ZDOTDIR??ot(),".zsh_history"),t=`: ${Math.floor(Date.now()/1e3)}:0;${r}
26
+ `;await rt(e,t)},"writeZshHistory"),Es=qe(async r=>{const e=process.env.HISTFILE??Ce(ot(),".bash_history");await rt(e,`${r}
27
+ `)},"writeBashHistory"),Rs=qe(async r=>{const e=Ce(ot(),".local","share","fish","fish_history"),t=`- cmd: ${r.replaceAll("\\","\\\\").replaceAll(`
28
+ `,String.raw`\n`)}
29
+ when: ${Math.floor(Date.now()/1e3)}
30
+ `;await rt(e,t)},"writeFishHistory");var js=Object.defineProperty,Qe=T((r,e)=>js(r,"name",{value:e,configurable:!0}),"e");const Os=Qe(r=>{const{killGracePeriodMs:e=5e3,onTimeout:t,sendSignal:s,timeoutMs:o}=r;if(o<=0)return{cancel:Qe(()=>{},"cancel")};const a=Math.max(e,0);let l;const u=setTimeout(()=>{t?.(),s("SIGTERM"),a>0&&(l=setTimeout(()=>{s("SIGKILL")},a))},o);return{cancel:Qe(()=>{clearTimeout(u),l&&clearTimeout(l)},"cancel")}},"scheduleTimeoutKill");var Ps=Object.defineProperty,Se=T((r,e)=>Ps(r,"name",{value:e,configurable:!0}),"l");const Fs=[/node_modules(?:\/|$)/,/\.git(?:\/|$)/,/\.vis(?:\/|$)/,/\.task-runner(?:\/|$)/],Bt=Se((r,e)=>{const t=new Set,s=new Set;for(const[,l]of r){const u=l.task.hashDetails?.nodes;if(u)for(const f of Object.keys(u))t.add(f),s.add(zr(Yt(e,f)))}const o=[...s].sort(),a=[];for(const l of o)a.some(u=>l===u||l.startsWith(`${u}/`))||a.push(l);return{directories:a,files:t}},"collectTrackedWatchTargets"),_s=Se((r,e,t)=>{const s=new Set;for(const o of r){const a=Yt(e,o);for(const l of t)if(a===l||a.startsWith(`${l}/`)){const u=Yr(l,a);u.length>0&&s.add(u)}}return o=>{const a=o.replaceAll("\\","/");return s.has(a)}},"createTrackedFileFilter"),As=Se(r=>{const e=r.replaceAll("\\","/");return Fs.some(t=>t.test(e))},"shouldIgnore"),Nt=Se(r=>{const{debounceMs:e=150,filter:t,onChange:s,paths:o}=r,a=[];let l=new Set,u;const f=Se(()=>{u=void 0;const p=[...l];l=new Set,p.length!==0&&Promise.resolve(s(p)).catch(i=>{xt.error("[vis watch] onChange handler failed:",i)})},"flush");for(const p of o)try{const i=Ur(p,{recursive:!0},(S,b)=>{b&&(As(b)||t&&!t(b)||(l.add(b),u&&clearTimeout(u),u=setTimeout(f,e)))});a.push(i)}catch(i){xt.warn(`[vis watch] unable to watch ${p}: ${i.message}`)}return{close:Se(()=>{u&&clearTimeout(u);for(const p of a)try{p.close()}catch{}},"close")}},"startWatcher");var Ls=Object.defineProperty,Ds=T((r,e)=>Ls(r,"name",{value:e,configurable:!0}),"n");const Hs=Ds((r,e)=>{const t=e?.trim();if(!t)return{filter:void 0,tasks:[...r]};const s=t.toLowerCase();return{filter:t,tasks:r.filter(o=>o.target.project.toLowerCase().includes(s))}},"applyProjectFilter");var Bs=Object.defineProperty,me=T((r,e)=>Bs(r,"name",{value:e,configurable:!0}),"a");const Ns=[""," Watch keybinds:"," r, Enter rerun"," a rerun all (clear filter)"," p filter by project name"," q, Ctrl+C quit"," h, ? show this help",""].join(`
31
+ `),Gs=me(r=>{r.write(`${Ns}
32
+ `)},"writeHelp"),qs=me(async(r,e)=>{e.write("filter projects (empty to cancel) > ");const t=r,s=t.isRaw===!0;if(s)try{t.setRawMode?.(!1)}catch{}return await new Promise(o=>{let a="";const l=me(u=>{a+=typeof u=="string"?u:u.toString("utf8");const f=a.indexOf(`
33
+ `);if(f===-1)return;const p=a.slice(0,f).replace(/\r$/,"").trim();if(r.off("data",l),s)try{t.setRawMode?.(!0)}catch{}o(p.length>0?p:void 0)},"onData");r.on("data",l)})},"defaultPromptFilter"),Ws=me(r=>{const{handlers:e}=r,t=r.input??process.stdin,s=r.output??process.stdout,o=r.promptFilter??qs;if(!t||t.isTTY===!1)return{close:me(()=>{},"close")};lo(t);const a=t.isRaw===!0;try{t.setRawMode?.(!0)}catch{return{close:me(()=>{},"close")}}typeof t.resume=="function"&&t.resume();let l=!1;const u=me(async i=>{if(i.ctrl===!0&&i.name==="c"){await e.onQuit();return}if(!l)switch(i.name){case"?":case"h":{await e.onHelp();break}case"a":{await e.onClearFilter();break}case"p":{l=!0;try{const S=await o(t,s);S===void 0?s.write(`filter cancelled.
34
+ `):await e.onFilter(S)}finally{l=!1}break}case"q":{await e.onQuit();break}case"r":{await e.onRerun();break}case"return":{await e.onRerun();break}}},"dispatch"),f=me((i,S)=>{u(S).catch(b=>{s.write(`[vis watch] keybind handler failed: ${b.message}
35
+ `)})},"onKeypress"),p=t;return p.on("keypress",f),{close:me(()=>{if(p.off("keypress",f),!a)try{t.setRawMode?.(!1)}catch{}const i=t;if(typeof i.pause=="function")try{i.pause()}catch{}},"close")}},"installKeybinds");var Us=Object.defineProperty,Ze=T((r,e)=>Us(r,"name",{value:e,configurable:!0}),"u");const Vs=Ze(r=>{const e=r.overrides.visOptions;return e&&typeof e=="object"?e:void 0},"getVisOptions"),zs=Ze(async r=>{const{initialTasks:e,probe:t,registeredEntries:s,taskGraph:o,visVersion:a}=r,l=new Map,u=new Map,f=new Map;for(const w of s)if(ro(w.pid)){if(w.visVersion!==a){u.set(w.id,w);continue}l.set(w.id,w)}if(t){const w=[...l.values()],x=await Promise.all(w.map(async P=>{try{return[P.id,await t(P)]}catch{return[P.id,!1]}}));for(const[P,G]of x)if(!G){const $=l.get(P);l.delete(P),$&&f.set(P,$)}}const p=new Set(e.map(w=>w.id)),i=new Set,S=[],b=[],E=new Set;for(const w of Object.values(o.dependencies))for(const x of w)E.add(x);for(const[w,x]of Object.entries(o.tasks)){if(!Vs(x)?.service)continue;if(l.has(w)){i.add(w),b.push(l.get(w));continue}if(p.has(w)||!E.has(w))continue;const P=u.get(w),G=f.get(w);let $;P?$=`Service ${w} is registered with vis ${P.visVersion}, but this invocation is vis ${a}. Restart with \`vis service restart ${w}\` to pick up the new version.`:G?$=`Service ${w} is registered (PID ${String(G.pid)}) but failed its readiness probe — the wrapper process is alive but the underlying server is not responding. Run \`vis service restart ${w}\` to recover.`:$=`Target depends on the service ${w}, which is not running. Run \`vis service start ${w}\` first, or invoke \`${w}\` directly.`,S.push({message:$,targetId:w})}if(i.size===0)return{diagnostics:S,initialTasks:e,satisfiedServices:b,serviceEnvByTaskId:new Map,taskGraph:o};const A=new Map,R=Ze(w=>{const x=new Set,P=[...o.dependencies[w]??[]],G=new Set;for(;P.length>0;){const $=P.pop();if(!G.has($)){G.add($),i.has($)&&x.add($);for(const H of o.dependencies[$]??[])G.has(H)||P.push(H)}}return[...x].sort()},"collectTransitiveServices");for(const w of Object.keys(o.dependencies)){if(i.has(w))continue;const x=R(w);if(x.length===0)continue;const P={};for(const G of x){const $=l.get(G);$&&Object.assign(P,$.env)}Object.keys(P).length>0&&A.set(w,P)}const y={};for(const[w,x]of Object.entries(o.tasks))i.has(w)||(y[w]=x);const j={};for(const[w,x]of Object.entries(o.dependencies))i.has(w)||(j[w]=x.filter(P=>!i.has(P)));const O=new Map;for(const w of Object.keys(y))O.set(w,0);for(const w of Object.values(j))for(const x of w)O.has(x)&&O.set(x,(O.get(x)??0)+1);const Q=[];for(const w of o.roots)!i.has(w)&&y[w]&&Q.push(w);for(const[w,x]of O)x===0&&!Q.includes(w)&&y[w]&&Q.push(w);const F=e.filter(w=>!i.has(w.id));return{diagnostics:S,initialTasks:F,satisfiedServices:b,serviceEnvByTaskId:A,taskGraph:{dependencies:j,roots:Q,tasks:y}}},"applyServiceRegistry");var Ys=Object.defineProperty,M=T((r,e)=>Ys(r,"name",{value:e,configurable:!0}),"o");const ct="VIS_AFFECTED_FILES",Ks=2e3,fr=M((r,e,t)=>t||!e?r:e.startsWith("/")?e:`${r}/${e}`,"resolveCwd"),Gt=M(async(r,e,t,s)=>{const o=r.map(a=>{const l=a.overrides.command;if(!l)return;const u=a.overrides.visOptions,f=fr(e,a.projectRoot,!!u?.runFromWorkspaceRoot),p=u?.envFile?Ut(f,u.envFile):{},i=t&&(u?.affectedFiles==="env"||u?.affectedFiles==="both")?{[ct]:t.join(`
36
+ `)}:{};return{command:l,cwd:f,env:{INIT_CWD:s,...p,...i},name:a.id}}).filter(a=>a!==void 0);o.length!==0&&await et(o,{killOthers:["failure"]})},"runPersistentTasks"),Je=256*1024;class Qs{static{T(this,"Ze")}static{M(this,"OutputRingBuffer")}#e;#r="";#o=!1;constructor(e){this.#e=e}append(e){this.#r+=e,this.#r.length>this.#e&&(this.#r=this.#r.slice(-this.#e),this.#o=!0)}toString(){return this.#o?`[...output truncated, showing last ${Math.round(this.#e/1024)}KB...]
37
+ ${this.#r}`:this.#r}}const pr=M(r=>{const e=r.overrides.visOptions;if(e&&typeof e=="object")return e},"getTaskOptions"),lt=M(r=>`'${r.replaceAll("'",String.raw`'\''`)}'`,"singleQuoteEscape"),Xs=M((r,e,t)=>{if(!e||e.length===0||t===!1||t===void 0)return r;if(t==="args"||t==="both"){const s=e.map(o=>lt(o)).join(" ");return`${r} ${s}`}return r},"buildAffectedFilesArgs"),mr="visForwardedArgs",Zs=M((r,e)=>{const t=e.overrides[mr];if(!Array.isArray(t)||t.length===0)return r;const s=t.map(o=>lt(o)).join(" ");return`${r} ${s}`},"appendForwardedArgs"),Js=M(async(r,e,t)=>{if(!e)return t();const s=r.get(e)??Promise.resolve();let o;const a=new Promise(u=>{o=u}),l=s.then(()=>a);r.set(e,l),await s;try{return await t()}finally{o(),r.get(e)===l&&r.delete(e)}},"withMutex"),en=M(r=>{let e=Math.max(0,Math.floor(r));return{claim(t){const s=Math.max(0,Math.min(t,e));return e-=s,s},get remaining(){return e}}},"createRetryBudget"),tn=M((r,e,t)=>{const s=`${e}\0${typeof t=="string"?t:String(t)}`,o=r.get(s);if(o)return o;const a=Ut(e,t);return r.set(s,a),a},"loadEnvFileCached"),qt=M(r=>{const e=new Map;return async(t,s)=>{const{affectedFiles:o,currentOs:a,initCwd:l,lifeCycle:u,mutexPool:f,onOutput:p,onOutputReplace:i,retryBudget:S,serviceEnvByTaskId:b,stdinRegistry:E,strictEnv:A,workspaceRoot:R}=r,y=pr(t),j=fr(R,s.cwd??t.projectRoot,y?.runFromWorkspaceRoot===!0),O=t.overrides.command;if(!O)return{code:0,terminalOutput:`No command configured for ${t.target.project}:${t.target.target}`};const Q=Zs(O,t),F=Xs(Q,o,y?.affectedFiles),w=Ar(y,a),x=w?`${w} -c ${lt(F)}`:F,P=y?.envFile?tn(e,j,y.envFile):void 0,G={};o&&o.length>0&&(y?.affectedFiles==="env"||y?.affectedFiles==="both")&&(G[ct]=o.join(`
38
+ `));const $=b?.get(t.id),H={INIT_CWD:l,...P,...$,...s.env,...G};if(y?.strictEnv??A??!1){const D=Fo({command:F,processEnv:process.env,taskEnv:H,taskId:t.id});if(D){const U=_o(D);return u?.onTaskStderr?.(t,U),{code:1,terminalOutput:U}}}const ie=y?.pty===!0,L=!!E,q=L||ie;q&&(t.cache=!1);const ae=q?void 0:new Qs(Je),J=q?new Wt(Je):void 0;let B;const he=M(D=>{if(D.kind==="started"&&(B=D.kill,D.write&&E&&E.set(t.id,{kill:D.kill,resize:D.resize,write:D.write})),(D.kind==="stdout"||D.kind==="stderr")&&D.text!==void 0)if(D.kind==="stdout"?u?.onTaskStdout?.(t,D.text):u?.onTaskStderr?.(t,D.text),J)J.write(D.text),L&&i?.(t.id,J.toString());else{const U=`${D.text}
39
+ `;ae.append(U),p?.(t.id,U)}D.kind==="close"&&E&&E.delete(t.id)},"onEvent"),ce=M(async()=>{const D=y?.retryCount??0,U=y?.retryDelay,k=S?S.claim(D):D,m=typeof y?.timeout=="number"&&y.timeout>0?y.timeout:0,C=typeof y?.killGracePeriodMs=="number"&&y.killGracePeriodMs>=0?y.killGracePeriodMs:5e3;let ee=!1;const fe=Os({killGracePeriodMs:C,onTimeout:M(()=>{ee=!0},"onTimeout"),sendSignal:M(We=>{B?.(We)},"sendSignal"),timeoutMs:m});let xe;try{xe=await et([{command:x,cwd:j,env:H,name:t.id,...q?{ptySize:{cols:process.stdout.columns??80,rows:process.stdout.rows??24},stdin:"pty"}:{}}],{killOthers:["failure"],onEvent:he,...k>0?{restart:{delay:U??"exponential",tries:k}}:{}})}finally{fe.cancel()}const ye=xe.closeEvents[0],Pe=J?J.toString():ae.toString();return ee?{code:124,terminalOutput:`${Pe}
40
+ [timeout] Task "${t.id}" exceeded ${m}ms budget.
41
+ `}:{code:ye?.exitCode??1,terminalOutput:Pe}},"runOnce");return f?Js(f,y?.mutex,ce):ce()}},"createConcurrentExecutor"),rn=M(r=>{if(!r||r.trim().length===0)return;const e=Number.parseFloat(r);return!Number.isFinite(e)||e<=0?{invalid:r}:{value:Math.floor(e)}},"parseEnvConcurrency"),on=M(async(r,e)=>{const t=await Cr(r);if(!t){e.warn("No previous run recorded yet. Run a task at least once to populate .task-runner/last-summary.json.");return}const s=(t.duration/1e3).toFixed(2);if(e.info(""),e.info(`Last run — ${t.startTime} (${s}s)`),e.info(""),e.info(` Total: ${String(t.stats.total)}`),e.info(` Succeeded: ${String(t.stats.succeeded)}`),e.info(` Cached: ${String(t.stats.cached)}`),e.info(` Failed: ${String(t.stats.failed)}`),e.info(` Skipped: ${String(t.stats.skipped)}`),e.info(""),t.stats.failed>0){const a=t.tasks.filter(l=>l.exitCode!==void 0&&l.exitCode!==0);e.info("Failed tasks:");for(const l of a){const u=l.duration??0;e.info(` × ${l.taskId} (exit ${String(l.exitCode??-1)}, ${u}ms)`)}e.info("")}const o=[...t.tasks].filter(a=>typeof a.duration=="number").sort((a,l)=>(l.duration??0)-(a.duration??0)).slice(0,5);if(o.length>0){e.info("Slowest tasks:");for(const a of o)e.info(` ${a.taskId.padEnd(40)} ${String(a.duration??0).padStart(6)}ms [${a.cacheStatus}]`);e.info("")}},"renderLastRunSummary"),sn=M(r=>{if(!(r===void 0||r==="")){if(r!=="read"&&r!=="write"&&r!=="readwrite")throw new Error(`--cache-mode must be one of: read, write, readwrite (received "${r}")`);return r}},"parseCacheMode"),nn=M(r=>{if(!(r===void 0||r==="")){if(r!=="http"&&r!=="reapi")throw new Error(`--cache-backend must be one of: http, reapi (received "${r}")`);return r}},"parseCacheBackend"),Sn=M(async({argument:r,logger:e,options:t,runtime:s,visConfig:o,workspaceRoot:a})=>{if(!a)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const l=a;if(t.lastDetails===!0){await on(l,e);return}const u=process.cwd(),f=await Lr(l),{config:p,packageJsons:i,projectOptions:S,workspace:b}=Dr(l,o,f),E=Hr(l,b,i);let A=r[0];if(!A){const g=jt(b);if(process.stdout.isTTY&&process.stdin.isTTY){const v=await Go(g);if(!v){e.info("No target selected.");return}A=v,await Is(`vis run ${v}`)}else{e.info("Available targets:"),e.info(""),e.info(No(g)),e.info(""),e.info("Usage: vis run <target>");return}}if(p.constraints&&!t.skipConstraints){const g=xr(E,p.constraints);if(g.length>0){for(const v of g)e.error(`[${v.rule}] ${v.message}`);throw new Error(`${g.length} project constraint violation(s) found. Use --skip-constraints to bypass.`)}}if(t.affected){const g=[A];t.parallel!==void 0&&g.push(`--parallel=${String(t.parallel)}`),t.cache||g.push("--no-cache"),t.query&&g.push(`--query=${String(t.query)}`),t.reverse&&g.push("--reverse"),typeof t.runnerTags=="string"&&t.runnerTags!==""&&g.push(`--runner-tags=${t.runnerTags}`),await s.runCommand("affected",{argv:g});return}const R=await io(A,b,process.cwd(),l),y=Lo(S),j=Do(R.target,y);j!==R.target&&e.debug?.(`Resolved alias "${R.target}" → "${j}"`);let O=R.projects;const Q=r.slice(1).map(String);if(t.projects){const g=new Set(t.projects.split(",").map(v=>v.trim()));if(O=O.filter(v=>g.has(v)),O.length===0)throw new Error(`No matching projects found for: ${String(t.projects)}`)}if(t.query&&(O=ao(O,b,t.query),O.length===0)){e.info(`Query "${String(t.query)}" matched no projects.`);return}const F=Br(),w=process.env[ct],x=w?w.split(`
42
+ `).filter(Boolean):void 0,P=(typeof t.runnerTags=="string"?t.runnerTags:process.env.VIS_RUNNER_TAGS)??void 0,G=P?new Set(P.split(",").map(g=>g.trim()).filter(Boolean)):void 0,$=[],H=new Map;for(const g of O){const v=S.get(g)?.[j];if(!v)continue;const I=v.options;if(!I?.internal){if(!Nr(I,!!Ve)){e.debug?.(`Skipping ${g}:${j} — runInCI filter`);continue}if(!Gr(I,G)){e.debug?.(`Skipping ${g}:${j} — runner-tags filter`);continue}$.push(g),H.set(g,v)}}if($.length===0){const g=jt(b),v=Object.entries(b.projects).filter(([,I])=>I.targets?.[j]!==void 0).map(([I])=>I);if(e.error(`No projects have the "${j}" target.`),v.length>0){e.info(""),e.info(`Target "${j}" exists in these projects but was filtered out:`);for(const I of v.slice(0,5))e.info(` - ${I}`);v.length>5&&e.info(` …and ${v.length-5} more`)}else{const I=er(j,g,3);I.length>0&&(e.info(""),e.info(I.length===1?`Did you mean "${I[0]}"?`:`Did you mean one of: ${I.map(V=>`"${V}"`).join(", ")}?`)),e.info(""),e.info("Run `vis run` without arguments to see all available targets.")}return}const ie=t.pty===!0;let L=$.map(g=>{const v=b.projects[g],I=H.get(g),V={project:g,target:j},W=`${g}:${j}`,pe=ie?{...I.options,pty:I.options?.pty??!0}:I.options,oe=I.command?Ir(I.command,{affectedFiles:x,projectRoot:v?.root}):I.command;return{cache:I.cache,id:W,outputs:I.outputs??[],overrides:{command:oe,...Q.length>0?{[mr]:Q}:{},...pe?{visOptions:pe}:{}},parallelism:I.parallelism,projectRoot:v?.root,target:V}});const q=[],ae=[];for(const g of L)pr(g)?.persistent?(g.cache=!1,q.push(g)):ae.push(g);L=ae;const J=Mr(t.partition);if(J&&(L=Er.partitionTasks(L,J),e.info(`Partition ${J.index}/${J.total}: running ${L.length} task(s)`),L.length===0)){e.info("No tasks assigned to this partition.");return}let B=Rr(L,{projectGraph:E,targetDefaults:p.targetDefaults,workspace:b});for(const[g,v]of Object.entries(B.tasks)){if(v.overrides.visOptions!==void 0)continue;const I=v.target.project,V=v.target.target,W=S.get(I)?.[V];W?.options&&(v.overrides={...v.overrides,visOptions:W.options},B.tasks[g]=v)}if(typeof t.skipCache=="string"&&t.skipCache.trim()!=="")if(t.cache){const g=Eo(t.skipCache,b,Object.keys(B.tasks));for(const v of g.skipTaskIds){const I=B.tasks[v];I!==void 0&&(I.cache=!1)}g.unmatchedPatterns.length>0&&e.warn(`--skip-cache: no tasks matched ${g.unmatchedPatterns.map(v=>`"${v}"`).join(", ")}`),g.skipTaskIds.size>0&&e.debug?.(`--skip-cache: bypassing cache for ${String(g.skipTaskIds.size)} task(s)`)}else e.debug?.("--skip-cache ignored: --no-cache already disables caching for the whole run");await to(l,p.toolchain,{error:M(g=>{e.error(g)},"error"),info:M(g=>{e.info(g)},"info"),warn:M(g=>{e.warn(g)},"warn")},!!t.skipToolchain);const he=t.preflight!==!1&&p.preflight?.lockfile!==!1,ce=xo(l,Ve,{warn:M(g=>{e.warn(g)},"warn")},{skip:!he});if(!ce.shouldContinue)throw new Error(`${ce.formattedMessage??"preflight: lockfile drift detected"} (pass --no-preflight to bypass)`);const D=await oo(l),U=await zs({initialTasks:L,probe:t.dryRun?void 0:async g=>{try{return await so(g.config,{timeoutMs:Ks}),!0}catch{return!1}},registeredEntries:D,taskGraph:B,visVersion:process.env.VIS_VERSION??"0.0.0"});if(U.diagnostics.length>0){for(const g of U.diagnostics)e.error(g.message);throw new Error(`${U.diagnostics.length} service dependency error(s) — start the missing services or invoke them directly.`)}L=U.initialTasks,B=U.taskGraph;const{serviceEnvByTaskId:k}=U;if(U.satisfiedServices.length>0){const g=U.satisfiedServices.map(v=>v.id).join(", ");e.debug?.(`Auto-attached to running services: ${g}`)}if(t.reverse&&(B=jr(B),e.debug?.(`Reversed task graph: ${String(B.roots.length)} new root(s) (originally leaves)`)),t.dryRun){const g=Object.keys(B.tasks).length,v=B.roots.length;e.info(`Execution plan (${String(g)} task(s), ${String(v)} root(s)):`),e.info("");const I=new Set,V=M((W,pe)=>{if(I.has(W))return;I.add(W);for(const ke of B.dependencies[W]??[])V(ke,pe+1);const oe=B.tasks[W],se=" ".repeat(pe+1);e.info(`${se}${W}${oe?.cache===!1?" (no-cache)":""}`)},"walkPlan");for(const W of B.roots)V(W,0);for(const W of Object.keys(B.tasks))V(W,0);q.length>0&&(e.info(""),e.info(` + ${String(q.length)} persistent task(s) (run after graph completes)`)),e.info("");return}const m=Date.now(),C=$s(),ee=M((g,v)=>{const I=v instanceof Error?v.message:String(v);e.warn(`Plugin error in ${g}: ${I}`)},"onHookError");await Ts(C,p.plugins);const fe=typeof t.profile=="string"?t.profile:void 0,xe=M(async g=>{if(!fe)return;const v=Tt(g,B,m),I=fe.startsWith("/")?fe:`${l}/${fe}`;await Or(v,I),e.info(`Profile written to ${fe}`)},"maybeWriteProfile"),ye=p.taskRunnerOptions??{},Pe=qr(l,t.cacheDir,ye.cacheDirectory,p.sharedWorktreeCache),We=Wr(Pe,l,p.branchScopedCache),be=rn(process.env.VIS_RUN_CONCURRENCY_LIMIT);be&&"invalid"in be&&e.warn(`VIS_RUN_CONCURRENCY_LIMIT=${be.invalid} is not a positive number; falling back to default concurrency.`);const gr=be&&"value"in be?be.value:void 0,wr=t.parallel??gr??3,dt=t.strictEnv??p.strictEnv??!1,Fe={dryRun:t.dryRun??!1,parallel:wr,skipNxCache:!t.cache,summarize:t.summarize??!1,...ye,cacheDirectory:We};if(ye.remoteCache){const g=sn(t.cacheMode),v=nn(t.cacheBackend);(g||v)&&(Fe.remoteCache={...ye.remoteCache,...g?{mode:g}:{},...v?{backend:v}:{}})}else(t.cacheMode||t.cacheBackend)&&e.warn("[vis run] --cache-mode and --cache-backend require a `remoteCache` block in vis.config.ts; ignoring.");const kr=process.stdout.isTTY&&!Ve,vr=p.tui?.autoExit??!1,ut={args:{parallel:Fe.parallel,targets:[j]},autoExit:vr,projectNames:$,tasks:L},ht=typeof t.retryBudget=="number"?t.retryBudget:void 0,ft=ht===void 0?void 0:en(ht),pt=new Ss(C,ee),mt=new Kr(l),gt=hs(typeof t.outputStyle=="string"?t.outputStyle.toLowerCase():void 0);if(await C.callHook("run:before",{tasks:L,workspaceRoot:l}),kr){const g=new Map,v=ds({...ut,outputStyle:gt,stdinRegistry:g}),{lifeCycle:I,store:V}=v,W=new St([I,pt,mt]),pe=qt({affectedFiles:x,currentOs:F,initCwd:u,lifeCycle:W,mutexPool:new Map,onOutput:M((_,z)=>{V.addOutput(_,z)},"onOutput"),onOutputReplace:M((_,z)=>{V.setOutput(_,z)},"onOutputReplace"),retryBudget:ft,serviceEnvByTaskId:k,stdinRegistry:g,strictEnv:dt,workspaceRoot:l});let oe="rerun",se=null,ke=new Map;for(;oe!=="quit";){if(oe==="rerun")ke=await Ct(L,Fe,{lifeCycle:W,projectGraph:E,taskExecutor:pe,taskGraph:B,workspaceRoot:l});else if(oe==="retry"&&se){const _=L.find(Z=>Z.id===se),z=_?.overrides.command;if(_&&z){const Z=_.projectRoot??l,ge=Z.startsWith("/")?Z:`${l}/${Z}`;W.startTasks?.([_]);const ne=new Wt(Je),le=(await et([{command:z,cwd:ge,name:_.id,ptySize:{cols:process.stdout.columns??80,rows:process.stdout.rows??24},stdin:"pty"}],{onEvent:M(K=>{K.kind==="started"&&K.write&&g.set(_.id,{kill:K.kill,resize:K.resize,write:K.write}),(K.kind==="stdout"||K.kind==="stderr")&&K.text&&(ne.write(K.text),V.setOutput(_.id,ne.toString())),K.kind==="close"&&g.delete(_.id)},"onEvent")})).closeEvents[0];W.endTasks?.([{code:le?.exitCode??1,status:le?.exitCode===0?"success":"failure",task:_,terminalOutput:V.getSnapshot().outputs.get(_.id)}])}else _&&W.endTasks?.([{code:1,status:"failure",task:_,terminalOutput:`No command configured for ${_.id}`}]);se=null,V.markDone()}oe=await new Promise(_=>{const z=V.subscribe(()=>{const Z=V.getSnapshot();Z.rerunRequested&&(V.acknowledgeRerun(),z(),_("rerun")),Z.retryTaskId&&(se=V.acknowledgeRetry(),z(),_("retry"))});v.renderIsDone.then(()=>{z(),_("quit")}).catch(()=>{z(),_("quit")})})}await v.renderIsDone,await C.callHook("run:after",ke),await xe(ke),q.length>0&&!t.failFast&&await Gt(q,l,x,u)}else{const g=new Map,v=typeof t.log=="string"?t.log.toLowerCase():"",I=v==="labeled"||v==="grouped"||v==="interleaved"?v:void 0,V=I?Pr(I):void 0,W=new St([new ps({...ut,logReporter:V,outputStyle:gt}),pt,mt]),pe=qt({affectedFiles:x,currentOs:F,initCwd:u,lifeCycle:W,mutexPool:g,retryBudget:ft,serviceEnvByTaskId:k,strictEnv:dt,workspaceRoot:l}),oe=M(async()=>{const _=Date.now(),z=await Ct(L,Fe,{lifeCycle:W,projectGraph:E,taskExecutor:pe,taskGraph:B,workspaceRoot:l}),Z=Date.now()-_;if(t.summarize){const de=Tt(z,B,m);await Fr(de,l)}let ge=!1;for(const[,de]of z)de.status==="failure"&&(ge=!0);const ne=Qr(z,Z),le=Xr(l),K=Zr(l,Z,le);return e.info(""),e.info(` ${ne}${K?` ${K}`:""}`),{hasFailure:ge,results:z,runHistory:le}},"runOnce"),se=await oe();await C.callHook("run:after",se.results),await xe(se.results);const{hasFailure:ke}=se;if(t.watch){const _=$.map(X=>{const te=b.projects[X]?.root;if(te)return te.startsWith("/")?te:`${l}/${te}`}).filter(X=>X!==void 0),z=L;let Z;const ge=M(X=>{const te=Hs(z,X);return Z=te.filter,L=te.tasks,te.tasks.length},"applyFilter");let ne=!1,le=se.results;const K=M(()=>{const X=Bt(le,l);if(X.directories.length>0&&X.files.size>0){const te=_s(X.files,l,X.directories);return{handle:Nt({filter:te,onChange:wt,paths:X.directories}),mode:"tracked"}}return{handle:Nt({onChange:wt,paths:_}),mode:"roots"}},"buildHandle");let de;const wt=M(async X=>{if(!ne){ne=!0;try{e.info(`Change detected in ${X.length} file(s), rerunning…`),le=(await oe()).results,de?.close(),de=K().handle}finally{ne=!1}}},"onChangeHandler"),kt=K();de=kt.handle;const yr=kt.mode==="tracked"?`Watching ${String(Bt(le,l).files.size)} tracked file(s)`:`Watching ${String(_.length)} project root(s)`;e.info(`${yr} — edit a file to rerun, press h for keybinds, q to quit.`);const Ue=M(async()=>{if(!ne){ne=!0;try{if(L.length===0){e.info("No tasks match the active filter — press a to clear it.");return}le=(await oe()).results,de?.close(),de=K().handle}finally{ne=!1}}},"triggerRerun");await new Promise(X=>{let te=!1,vt;const yt=M(()=>{bt()},"onSigint"),bt=M(()=>{te||(te=!0,vt?.close(),process.off("SIGINT",yt),de?.close(),X())},"exit");process.on("SIGINT",yt),vt=Ws({handlers:{onClearFilter:M(async()=>{const Ie=ge(void 0);e.info(`Filter cleared — running ${String(Ie)} task(s).`),await Ue()},"onClearFilter"),onFilter:M(async Ie=>{const br=Z,$t=ge(Ie);if($t===0){e.info(`Filter "${Ie}" matched no projects — keeping previous filter.`),ge(br);return}e.info(`Filter "${Ie}" matched ${String($t)} task(s).`),await Ue()},"onFilter"),onHelp:M(()=>{Gs(process.stdout)},"onHelp"),onQuit:M(()=>{bt()},"onQuit"),onRerun:Ue}})});return}if(ke){if(t.flaky!==!1){const _=Jr(l,{minRuns:2},se.runHistory);if(_.length>0){e.info(""),e.info("Flaky tasks (based on historical runs):"),e.info("");for(const z of eo(_))e.info(` ${z}`);e.info("")}}throw new Error("Some tasks failed.")}q.length>0&&!t.failFast&&await Gt(q,l,x,u)}},"execute");export{en as createRetryBudget,Sn as default};
@@ -1,2 +1,8 @@
1
- var d=Object.defineProperty;var l=(s,t)=>d(s,"name",{value:t,configurable:!0});import{createRequire as f}from"node:module";import{c as y,p as e,I as w,T as h}from"./bin.js";const m=f(import.meta.url),c=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,g=l(s=>{if(typeof c<"u"&&c.versions&&c.versions.node){const[t,r]=c.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return c.getBuiltinModule(s)}return m(s)},"__cjs_getBuiltinModule"),{spawnSync:v}=g("node:child_process");var b=Object.defineProperty,_=l((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");const $=_(async({options:s,visConfig:t,workspaceRoot:r})=>{const p=r??process.cwd(),a=y(p);if(a.name==="pnpm"&&!s.scan){e.info("Delegating to pnpm approve-builds...");const i=["approve-builds"];s.all&&i.push("--all");const o=v("pnpm",i,{cwd:p,stdio:"inherit"});if(o.error)throw new Error(`Failed to run pnpm approve-builds: ${o.error.message}`);if(o.status!==0&&o.status!==null&&(e.error(`pnpm approve-builds exited with code ${o.status}`),process.exitCode=o.status),!s.syncNative){e.notice(""),e.notice("Tip: vis.config.ts security.allowBuilds may now be out of sync with pnpm-workspace.yaml."),e.notice("Run 'vis check --security-config' to compare, or copy the new entries into vis.config.ts.");return}}else{const i=t?.security?.allowBuilds??{},o=w(p,i);if(o.length===0)e.success("No unapproved build scripts found.");else{e.warn(`Found ${o.length} package${o.length===1?"":"s"} with unapproved build scripts:
2
- `);for(const n of o)e.info(` ${n}`);e.notice(""),e.notice("To approve these packages, add them to vis.config.ts:"),e.notice(""),e.notice(" security: {"),e.notice(" allowBuilds: {");for(const n of o){const u=n.split(" (")[0];e.notice(` "${u}": true,`)}e.notice(" },"),e.notice(" },"),a.name==="pnpm"&&(e.notice(""),e.notice("Or run 'pnpm approve-builds' to update pnpm-workspace.yaml directly."))}}if(s.syncNative){const i=t?.security?.allowBuilds??{};if(Object.keys(i).length===0)e.warn("No security.allowBuilds configured in vis.config.ts. Nothing to sync.");else{const o=h(a.name,p,i);e.info("");for(const n of o)e.success(n)}}},"execute");export{$ as default};
1
+ var I=Object.defineProperty;var T=(c,r)=>I(c,"name",{value:r,configurable:!0});import{findPackageManagerSync as H}from"@visulima/package";import{render as j,renderToString as J,Text as y}from"@visulima/tui";import{A as V,O as W,W as Z,p as f,u as q,g as G,M as m,V as K,S as Q,B as X,c as b,v as _,j as ee,s as te}from"./bin.js";import a from"react";import{H as re,e as oe,Z as ne}from"../packem_shared/ai-analysis-hm8d2W7z.js";import{U as se,B as ie,T as M}from"../packem_shared/vis-update-app-D1jl0UZZ.js";var ae=Object.defineProperty,ce=T((c,r)=>ae(c,"name",{value:r,configurable:!0}),"$");const ye=ce(async({argument:c,logger:r,options:e,visConfig:i,workspaceRoot:C})=>{if(!C)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const d=C;if(e.securityConfig){const t=V(d);if(W(i??{},t.name),e.sync&&t.name==="pnpm"){const o=Z(i??{});if(o.length>0){f.info(`
2
+ Settings that would sync to pnpm-workspace.yaml:`);for(const x of o)f.success(` ${x}`)}else f.info("No security settings to sync.")}else e.sync&&t.name!=="pnpm"&&(f.info(`--sync is only available for pnpm projects. Your project uses ${t.name}.`),f.info("vis enforces security settings at the vis layer for non-pnpm projects."));if(!e.security&&!c?.length)return}const{packageManager:N}=H(d),U=q(d),l=i?.update??{},v=G(d,N,{dev:e.dev,prod:e.prod});if(v.size===0){r.info("No catalogs found.");return}const w=e.target??l.target??"latest";if(!["latest","minor","patch"].includes(w))throw new Error(`Invalid target "${w}". Use: latest, minor, or patch.`);const A={exclude:[...m(e.exclude),...m(l.exclude)],ignore:m(l.ignore),include:[...m(e.include),...m(l.include),...c],includeLocked:!!e.includeLocked,includePrerelease:e.prerelease||l.prerelease||!1,security:!e.noSecurity,target:w};let E=0;for(const t of v.values())E+=t.size;const h=!!process.stdout.isTTY&&!te;let u;const B=h?(t,o)=>{u?u.rerender(a.createElement(M,{current:t,total:o})):u=j(a.createElement(M,{current:t,total:o}),{interactive:!0,patchConsole:!1})}:(t,o)=>{r.info(`Checking ${String(t)}/${String(o)} dependencies...`)};h||r.info(`Checking ${String(E)} catalog dependencies against npm registry...
3
+ `);const O=K(i?.security?.socket),{failed:$,outdated:s}=await Q(v,A,U,B,d,O,i?.security?.socket?.acceptedRisks);if(u&&(u.clear(),u.unmount()),$.length>0&&r.warn(`Failed to fetch: ${$.join(", ")}`),s.length===0){r.info("All catalog dependencies are up to date.");return}const k=e.format??l.format??"table",P=re(e.aiType??"impact"),p=e.ai?await oe(s,r,i?.ai,P):void 0;if(h&&k==="table"){const t=new se(s,p??null),o=i?.tui?.autoExit??!1,x=o===!0?3:typeof o=="number"?o:0;await j(a.createElement(ie,{autoExitSeconds:x,isDryRun:!0,store:t}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit();const z=process.stdout.columns||80;process.stdout.write(`
4
+ `);for(const n of s){const L=n.vulnerabilities?.length||n.socketReport&&n.socketReport.alerts.length>0,S=!!n.acceptedRisk,Y=L?S?"✓":"⚠":"✓",D=S?"gray":n.updateType==="major"?"red":n.updateType==="minor"?"yellow":"green",g=n.socketReport?.score.overall,F=g===void 0?"":` [${String(Math.round(g*100))}%]`,R=g===void 0?void 0:X(g);process.stdout.write(`${J(a.createElement(y,null," ",a.createElement(y,{color:D},Y),` ${n.packageName} ${n.currentRange} → ${n.newRange}`,a.createElement(y,{dimColor:!0},` ${n.updateType}`),R?a.createElement(y,{color:R},F):null),{columns:z})}
5
+ `)}process.stdout.write(`
6
+ `),r.info(b(s))}else if(k==="json"){const t={failed:$,outdated:s};p&&(t.aiAnalysis=p),process.stdout.write(`${JSON.stringify(t,void 0,2)}
7
+ `)}else k==="minimal"?process.stdout.write(`${_(s)}
8
+ `):(ee(s,r),r.info(b(s)),p&&(r.info(""),r.info(ne(p))));e.exitCode&&s.length>0&&(process.exitCode=1)},"execute");export{ye as default};
@@ -1,13 +1 @@
1
- var F=Object.defineProperty;var C=(e,r)=>F(e,"name",{value:r,configurable:!0});import{createRequire as q}from"node:module";import{isAccessibleSync as v}from"@visulima/fs";import{formatBytes as g}from"@visulima/humanizer";import{join as L}from"@visulima/path";import{Cache as M,parseCacheSize as K,readLastRunSummary as T,getLastRunSummaryPath as Q}from"@visulima/task-runner";import{B as G,J as D}from"../packem_shared/ai-cache-Bynt6Y9x.js";import{_ as V,E as N}from"../packem_shared/cache-directory-D72ZEag2.js";import{p as n,H as X,a as E}from"./bin.js";import{r as J,f as I,a as Z,d as ee}from"../packem_shared/run-summary-utils-C24Aaf9E.js";const U=q(import.meta.url),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,b=C(e=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[r,t]=k.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return k.getBuiltinModule(e)}return U(e)},"__cjs_getBuiltinModule"),{readdir:j,stat:A,realpath:z,rm:O}=b("node:fs/promises"),{createInterface:Y}=b("node:readline");var te=Object.defineProperty,h=C((e,r)=>te(e,"name",{value:r,configurable:!0}),"f");const W=h(async e=>{let r=0;try{const t=await j(e,{withFileTypes:!0});for(const o of t){const s=L(e,o.name);if(o.isDirectory())r+=await W(s);else if(o.isFile()){const a=await A(s);r+=a.size}}}catch{}return r},"sumDirectorySize"),w=h(async e=>{const r=[];let t;try{t=await j(e)}catch{return[]}for(const o of t){if(o.startsWith("."))continue;const s=L(e,o);try{const a=await A(s);if(!a.isDirectory())continue;const c=await W(s);r.push({hash:o,mtimeMs:a.mtimeMs,path:s,sizeBytes:c})}catch{}}return r.sort((o,s)=>s.mtimeMs-o.mtimeMs),r},"collectCacheEntries"),se=h((e,r=Date.now())=>{const t=Math.floor((r-e)/1e3);return t<60?`${String(t)}s`:t<3600?`${String(Math.floor(t/60))}m`:t<86400?`${String(Math.floor(t/3600))}h`:`${String(Math.floor(t/86400))}d`},"formatAge"),re=h(e=>new Promise(r=>{const t=Y({input:process.stdin,output:process.stderr});t.question(`${e} (y/N) `,o=>{t.close();const s=o.trim().toLowerCase();r(s==="y"||s==="yes")})}),"confirmPrompt"),oe=h(async(e,r,t)=>{if(!v(e)){if(r==="json"){process.stdout.write(`${JSON.stringify({directory:e,entries:[],totalBytes:0,totalCount:0},void 0,2)}
2
- `);return}n.info(`No cache directory found at ${e}`);return}const o=await w(e);if(o.length===0){if(r==="json"){process.stdout.write(`${JSON.stringify({directory:e,entries:[],totalBytes:0,totalCount:0},void 0,2)}
3
- `);return}n.info(`Cache directory is empty: ${e}`);return}const s=o.reduce((i,d)=>i+d.sizeBytes,0);if(r==="json"){const i=Date.now();process.stdout.write(`${JSON.stringify({directory:e,entries:o.map(d=>({ageMs:i-d.mtimeMs,hash:d.hash,mtimeIso:new Date(d.mtimeMs).toISOString(),sizeBytes:d.sizeBytes})),totalBytes:s,totalCount:o.length},void 0,2)}
4
- `);return}n.info(`Cache directory: ${e}`),n.info(`Entries: ${String(o.length)} (${g(s,{decimals:1,space:!1})})`),t.info("");const a=Date.now(),c=o.map(i=>({age:se(i.mtimeMs,a),hash:i.hash.slice(0,12),size:g(i.sizeBytes,{decimals:1,space:!1})})),u=Math.max(4,...c.map(i=>i.hash.length)),f=Math.max(4,...c.map(i=>i.size.length)),l=Math.max(3,...c.map(i=>i.age.length));t.info(` ${"hash".padEnd(u)} ${"size".padEnd(f)} ${"age".padEnd(l)}`),t.info(` ${"-".repeat(u)} ${"-".repeat(f)} ${"-".repeat(l)}`);for(const i of c)t.info(` ${i.hash.padEnd(u)} ${i.size.padEnd(f)} ${i.age.padEnd(l)}`)},"runList"),ae=h(()=>{try{const e=G();e>0&&n.info(`Cleared ${String(e)} cached AI response${e===1?"":"s"}.`)}catch(e){n.warn(`Failed to clear AI response cache: ${e instanceof Error?e.message:String(e)}`)}},"clearAiCacheSafe"),ne=h(()=>{try{const e=X();e>0&&n.info(`Cleared ${String(e)} cached Socket.dev report${e===1?"":"s"}.`)}catch(e){n.warn(`Failed to clear Socket.dev cache: ${e instanceof Error?e.message:String(e)}`)}},"clearSocketCacheSafe"),ie=h(async(e,r,t)=>{if(!v(e)){n.info(`No cache directory to clean at ${e}`);return}if(t.dryRun){const s=await w(e),a=s.reduce((c,u)=>c+u.sizeBytes,0);n.info(`Would remove ${String(s.length)} cache entr${s.length===1?"y":"ies"} (${g(a,{decimals:1,space:!1})}) from ${e}`);return}const o=V(e,r);try{const s=await z(e),a=await z(r);if(s===a){n.error("Refusing to delete the workspace root. The cache directory resolved to the same path as the workspace."),process.exitCode=1;return}}catch{}if(!o&&!t.force){if(n.warn(`Cache directory is outside the workspace root: ${e}`),n.warn("This will recursively delete the entire directory, including anything stored there by other tools."),!process.stdin.isTTY){n.error("Refusing to clean an out-of-workspace cache without --force (stdin is not a TTY)."),process.exitCode=1;return}if(!await re(" Continue?")){n.info("Aborted.");return}}o?await new M({cacheDirectory:e,workspaceRoot:r}).clear():await O(e,{force:!0,recursive:!0}),n.success(`Cleared cache: ${e}`)},"runClean"),ce=h(async(e,r,t)=>{if(!v(e)){n.info(`No cache directory to prune at ${e}`);return}if(t.maxCacheAgeDays!==void 0&&(!Number.isFinite(t.maxCacheAgeDays)||t.maxCacheAgeDays<0)){n.error(`Invalid --max-age-days value: expected a finite number >= 0, got ${String(t.maxCacheAgeDays)}`),process.exitCode=1;return}if(t.keepLast!==void 0&&(!Number.isFinite(t.keepLast)||t.keepLast<0||!Number.isInteger(t.keepLast))){n.error(`Invalid --keep-last value: expected a non-negative integer, got ${String(t.keepLast)}`),process.exitCode=1;return}if(t.maxCacheSize!==void 0){let i;try{i=K(t.maxCacheSize)}catch(d){n.error(`Invalid --max-size value: ${d instanceof Error?d.message:String(d)}`),process.exitCode=1;return}if(!Number.isFinite(i)||i<=0){n.error(`Invalid --max-size value: expected a positive size, got "${t.maxCacheSize}" (${String(i)} bytes)`),process.exitCode=1;return}}const o=t.maxCacheAgeDays===void 0?void 0:t.maxCacheAgeDays*24*60*60*1e3,s=await w(e),a=s.reduce((i,d)=>i+d.sizeBytes,0);if(t.keepLast!==void 0&&s.length>t.keepLast){const i=s.slice(t.keepLast);await Promise.all(i.map(d=>O(d.path,{force:!0,recursive:!0})))}await new M({cacheDirectory:e,maxCacheAge:o,maxCacheSize:t.maxCacheSize,workspaceRoot:r}).removeOldEntries();const c=await w(e),u=c.reduce((i,d)=>i+d.sizeBytes,0),f=s.length-c.length,l=a-u;if(f<=0){n.info("Nothing to prune — all entries are within the configured limits.");return}n.success(`Pruned ${String(f)} entr${f===1?"y":"ies"}, freed ${g(l,{decimals:1,space:!1})}.`)},"runPrune"),R=16,P=h(e=>e.length>R?`${e.slice(0,R)}…`:e,"truncateHash"),x=h((e,r,t)=>{const o=Object.entries(r??{});if(o.length!==0){t.info(` ${e}:`),o.sort(([s],[a])=>s.localeCompare(a));for(const[s,a]of o)t.info(` ${s.padEnd(40)} ${P(a)}`)}},"renderHashDetailsBucket"),ue=h(async(e,r,t)=>{const{format:o,runId:s,workspaceRoot:a}=r,c=s===void 0?await T(a):await J(a,s);if(!c){if(o==="json"){process.stdout.write(`${JSON.stringify({error:"no-summary",runId:s??null,taskId:e},void 0,2)}
5
- `),process.exitCode=1;return}s===void 0?n.error("No previous run summary found. Run a task first to populate `.task-runner/last-summary.json`."):n.error(`Run summary "${s}" not found in .task-runner/runs/.`),process.exitCode=1;return}const u=I(c,e);if(!u){if(o==="json"){process.stdout.write(`${JSON.stringify({error:"task-not-in-summary",runId:c.id,taskId:e},void 0,2)}
6
- `),process.exitCode=1;return}n.error(`Task "${e}" was not part of run ${c.id}.`),n.info(`Tasks in this run: ${c.tasks.map(d=>d.taskId).join(", ")||"(none)"}`),process.exitCode=1;return}const f=await Z(a,c.id),l=f?I(f,e):void 0,i=ee(u.hashDetails,l?.hashDetails);if(o==="json"){process.stdout.write(`${JSON.stringify({diff:i,previousRunId:f?.id??null,previousTask:l?{cacheStatus:l.cacheStatus,hash:l.hash??null,hashDetails:l.hashDetails??null}:null,runId:c.id,task:{cacheStatus:u.cacheStatus,hash:u.hash??null,hashDetails:u.hashDetails??null,taskId:u.taskId}},void 0,2)}
7
- `);return}if(n.info(`Why ${e}? (run ${c.id})`),t.info(""),t.info(` status: ${u.cacheStatus}`),t.info(` hash: ${u.hash??"(none)"}`),l?t.info(` prev: ${l.hash??"(none)"} [run ${f?.id??"?"}]`):t.info(" prev: (no prior run found)"),t.info(""),!l){n.info("No previous run to diff against — first time this task was recorded.");return}if(!i.commandChanged&&i.nodes.added.length===0&&i.nodes.changed.length===0&&i.nodes.removed.length===0&&i.runtime.added.length===0&&i.runtime.changed.length===0&&i.runtime.removed.length===0&&i.implicitDeps.added.length===0&&i.implicitDeps.changed.length===0&&i.implicitDeps.removed.length===0){n.success("No hash inputs changed since the previous run.");return}t.info("Hash inputs that changed since the previous run:"),t.info(""),i.commandChanged&&t.info(" command: changed");for(const d of["nodes","runtime","implicitDeps"]){const m=i[d];if(!(m.added.length===0&&m.changed.length===0&&m.removed.length===0)){t.info(` ${d}:`);for(const $ of m.added)t.info(` + ${$}`);for(const $ of m.changed)t.info(` ~ ${$}`);for(const $ of m.removed)t.info(` - ${$}`)}}t.info(""),n.info(`Last summary file: ${Q(a)}`)},"runWhy"),de=h(async(e,r,t)=>{const{format:o,runId:s,workspaceRoot:a}=r,c=s===void 0?await T(a):await J(a,s);if(!c){if(o==="json"){process.stdout.write(`${JSON.stringify({error:"no-summary",runId:s??null,taskId:e},void 0,2)}
8
- `),process.exitCode=1;return}s===void 0?n.error("No previous run summary found. Run a task first to populate `.task-runner/last-summary.json`."):n.error(`Run summary "${s}" not found in .task-runner/runs/.`),process.exitCode=1;return}const u=I(c,e);if(!u){if(o==="json"){process.stdout.write(`${JSON.stringify({error:"task-not-in-summary",runId:c.id,taskId:e},void 0,2)}
9
- `),process.exitCode=1;return}n.error(`Task "${e}" was not part of run ${c.id}.`),process.exitCode=1;return}if(o==="json"){process.stdout.write(`${JSON.stringify({cacheStatus:u.cacheStatus,hash:u.hash??null,hashDetails:u.hashDetails??null,runId:c.id,taskId:u.taskId},void 0,2)}
10
- `);return}n.info(`Hash for ${e} (run ${c.id})`),t.info(""),t.info(` status: ${u.cacheStatus}`),t.info(` hash: ${u.hash??"(none)"}`),u.hashDetails?(t.info(""),t.info(` command: ${P(u.hashDetails.command)}`),x("nodes",u.hashDetails.nodes,t),x("runtime",u.hashDetails.runtime,t),x("implicitDeps",u.hashDetails.implicitDeps,t)):(t.info(""),n.info("No hash details recorded for this task."))},"runHash"),he=h(async(e,r)=>{if(!v(e)){if(r==="json"){process.stdout.write(`${JSON.stringify({directory:e,exists:!1,totalBytes:0,totalCount:0})}
11
- `);return}n.info(`No cache directory at ${e}`);return}const t=await w(e),o=t.reduce((s,a)=>s+a.sizeBytes,0);if(r==="json"){process.stdout.write(`${JSON.stringify({directory:e,exists:!0,totalBytes:o,totalCount:t.length})}
12
- `);return}n.info(`Cache directory: ${e}`),n.info(`Entries: ${String(t.length)}`),n.info(`Total size: ${g(o,{decimals:1,space:!1})}`)},"runSize"),_=h(e=>e==="task"||e==="ai"||e==="socket"||e==="all"?e:(e&&e.length>0&&n.warn(`Unknown --type value '${e}'; falling back to 'all'.`),"all"),"parseCacheTarget"),p=h((e,r)=>e==="all"||e===r,"includesTarget"),y=h(e=>e===void 0?null:new Date(e).toISOString(),"isoOrNull"),B=h((e,r)=>{n.info(`${e}:`),n.info(` Entries: ${String(r.entries)}`),n.info(` Total size: ${g(r.totalSizeBytes,{decimals:1,space:!1})}`),n.info(` Oldest: ${r.oldestEntry?new Date(r.oldestEntry).toISOString():"N/A"}`),n.info(` Newest: ${r.newestEntry?new Date(r.newestEntry).toISOString():"N/A"}`)},"printAuxStatsBlock"),le=h(e=>e==="worktree"||e==="shared"||e==="all"?e:(e&&e.length>0&&n.warn(`Unknown --scope value '${e}'; falling back to 'shared'.`),"shared"),"parseScope"),S=h((e,r,t)=>{const o=e??process.cwd(),s=t??{},a=s.taskRunnerOptions??{},c=le(r.scope),u=r.cacheDir,f=N(o,u,a.cacheDirectory,!1),l=N(o,u,a.cacheDirectory,s.sharedWorktreeCache);let i,d;switch(c){case"all":{i=l,d=l===f?[l]:[l,f];break}case"worktree":{i=f,d=[f];break}default:i=l,d=[l]}return{cacheDirectories:d,cacheDirectory:i,scope:c,sharedWorktreeCache:s.sharedWorktreeCache,workspaceRoot:o}},"resolveCacheDirectoryFromContext"),Ce=h(async({logger:e,options:r,visConfig:t,workspaceRoot:o})=>{const{cacheDirectories:s}=S(o,r,t),a=r.format??"table";for(const c of s)s.length>1&&n.info(`# ${c}`),await oe(c,a,e)},"cacheListExecute"),xe=h(async({options:e,visConfig:r,workspaceRoot:t})=>{const o=_(e.type),s=!!e.dryRun;if(p(o,"task")){const{cacheDirectory:a,workspaceRoot:c}=S(t,e,r);await ie(a,c,{dryRun:s,force:!!e.force})}if(p(o,"ai"))if(s){const a=D();n.info(`Would clear ${String(a.entries)} cached AI response${a.entries===1?"":"s"}.`)}else ae();if(p(o,"socket"))if(s){const a=E();n.info(`Would clear ${String(a.entries)} cached Socket.dev report${a.entries===1?"":"s"}.`)}else ne()},"cacheCleanExecute"),De=h(async({options:e,visConfig:r,workspaceRoot:t})=>{const{cacheDirectories:o,workspaceRoot:s}=S(t,e,r);for(const a of o)o.length>1&&n.info(`# ${a}`),await ce(a,s,{keepLast:typeof e.keepLast=="number"?e.keepLast:void 0,maxCacheAgeDays:typeof e.maxAgeDays=="number"?e.maxAgeDays:void 0,maxCacheSize:e.maxSize})},"cachePruneExecute"),H=h(e=>e??process.cwd(),"resolveWorkspaceRoot"),Ee=h(async({argument:e,logger:r,options:t,workspaceRoot:o})=>{const s=e[0];if(!s){n.error("No task ID specified. Usage: vis cache why <project>:<target>"),process.exitCode=1;return}await ue(s,{format:t.format??"table",runId:t.run,workspaceRoot:H(o)},r)},"cacheWhyExecute"),Ie=h(async({argument:e,logger:r,options:t,workspaceRoot:o})=>{const s=e[0];if(!s){n.error("No task ID specified. Usage: vis cache hash <project>:<target>"),process.exitCode=1;return}await de(s,{format:t.format??"table",runId:t.run,workspaceRoot:H(o)},r)},"cacheHashExecute"),ze=h(async({options:e,visConfig:r,workspaceRoot:t})=>{const o=_(e.type);if((e.format??"table")==="json"){const s={};if(p(o,"task")){const{cacheDirectories:a}=S(t,e,r);s.task=await Promise.all(a.map(async c=>{const u=v(c),f=u?await w(c):[],l=f.reduce((i,d)=>i+d.sizeBytes,0);return{directory:c,entries:f.length,exists:u,newestEntry:y(f[0]?.mtimeMs),oldestEntry:y(f.at(-1)?.mtimeMs),totalBytes:l}}))}if(p(o,"ai")){const a=D();s.ai={entries:a.entries,newestEntry:y(a.newestEntry),oldestEntry:y(a.oldestEntry),totalBytes:a.totalSizeBytes}}if(p(o,"socket")){const a=E();s.socket={entries:a.entries,newestEntry:y(a.newestEntry),oldestEntry:y(a.oldestEntry),totalBytes:a.totalSizeBytes}}process.stdout.write(`${JSON.stringify(s,void 0,2)}
13
- `);return}if(p(o,"task")){const{cacheDirectories:s}=S(t,e,r);for(const a of s)s.length>1&&n.info(`# ${a}`),await he(a,"table")}p(o,"ai")&&B("AI response cache",D()),p(o,"socket")&&B("Socket.dev report cache",E())},"cacheSizeExecute");export{xe as cacheCleanExecute,Ie as cacheHashExecute,Ce as cacheListExecute,De as cachePruneExecute,ze as cacheSizeExecute,Ee as cacheWhyExecute,ae as clearAiCacheSafe,ne as clearSocketCacheSafe,w as collectCacheEntries,se as formatAge,ie as runClean,de as runHash,oe as runList,ce as runPrune,he as runSize,ue as runWhy};
1
+ var h=Object.defineProperty;var g=(r,n)=>h(r,"name",{value:n,configurable:!0});import{r as m}from"../packem_shared/toolchain-BgBOUHII.js";var C=Object.defineProperty,a=g((r,n)=>C(r,"name",{value:n,configurable:!0}),"a");const u=a(()=>process.env.GITHUB_BASE_REF?{base:`origin/${process.env.GITHUB_BASE_REF}`,head:process.env.GITHUB_SHA??"HEAD"}:process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME?{base:`origin/${process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`,head:process.env.CI_COMMIT_SHA??"HEAD"}:process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH?{base:`origin/${process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH}`,head:process.env.BUILDKITE_COMMIT??"HEAD"}:process.env.CIRCLE_BRANCH&&process.env.CIRCLE_SHA1?{base:"origin/main",head:process.env.CIRCLE_SHA1}:{base:"origin/main",head:"HEAD"},"detectCiRefs"),A=a(async({argument:r,logger:n,options:e,runtime:s,visConfig:f,workspaceRoot:t})=>{const p=r[0];if(!p)throw new Error("Missing targets. Usage: vis ci <target>[,<target>…]");const l=p.split(",").map(o=>o.trim()).filter(Boolean);if(l.length===0)throw new Error("Missing targets. Usage: vis ci <target>[,<target>…]");if(!t)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const{base:_,head:d}=u(),c=e.base??_,E=e.head??d;e.skipToolchain||n.info("▸ Toolchain pre-flight"),await m(t,f?.toolchain,{error:a(o=>{n.error(o)},"error"),info:a(o=>{n.info(o)},"info"),warn:a(o=>{n.warn(o)},"warn")},!!e.skipToolchain),e.install===!1?n.info("▸ Skipping install (--no-install)"):(n.info("▸ Installing dependencies"),await s.runCommand("install",{argv:["--frozen-lockfile"]}));for(const o of l){n.info(`▸ Running affected ${o} (base=${c}, head=${E})`);const i=[o,`--base=${c}`,`--head=${E}`,`--upstream=${String(e.upstream??"none")}`,`--downstream=${String(e.downstream??"deep")}`];e.parallel!==void 0&&i.push(`--parallel=${String(e.parallel)}`),e.partition&&i.push(`--partition=${String(e.partition)}`),e.query&&i.push(`--query=${String(e.query)}`),await s.runCommand("affected",{argv:i})}n.info("▸ CI pipeline complete")},"execute");export{A as default};
@@ -1,8 +1 @@
1
- var I=Object.defineProperty;var S=(c,o)=>I(c,"name",{value:o,configurable:!0});import{findPackageManagerSync as J}from"@visulima/package";import{render as b,renderToString as V,Text as y}from"@visulima/tui";import{c as W,O as Z,W as q,p as f,V as G,B as H,d as K}from"./bin.js";import a from"react";import{z as Q,e as X,Z as _}from"../packem_shared/ai-analysis-CGuy7dfE.js";import{U as ee,B as te,f as j}from"../packem_shared/VisUpdateApp-D-L4_-Iu.js";import{o as oe,a as re,N as m,w as ne,v as N,O as se,T as ie}from"../packem_shared/catalog-BVPerCwG.js";var ae=Object.defineProperty,ce=S((c,o)=>ae(c,"name",{value:o,configurable:!0}),"$");const we=ce(async({argument:c,logger:o,options:e,visConfig:i,workspaceRoot:C})=>{if(!C)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const d=C;if(e.securityConfig){const t=W(d);if(Z(i??{},t.name),e.sync&&t.name==="pnpm"){const r=q(i??{});if(r.length>0){f.info(`
2
- Settings that would sync to pnpm-workspace.yaml:`);for(const x of r)f.success(` ${x}`)}else f.info("No security settings to sync.")}else e.sync&&t.name!=="pnpm"&&(f.info(`--sync is only available for pnpm projects. Your project uses ${t.name}.`),f.info("vis enforces security settings at the vis layer for non-pnpm projects."));if(!e.security&&!c?.length)return}const{packageManager:O}=J(d),U=oe(d),l=i?.update??{},w=re(d,O,{dev:e.dev,prod:e.prod});if(w.size===0){o.info("No catalogs found.");return}const v=e.target??l.target??"latest";if(!["latest","minor","patch"].includes(v))throw new Error(`Invalid target "${v}". Use: latest, minor, or patch.`);const z={exclude:[...m(e.exclude),...m(l.exclude)],ignore:m(l.ignore),include:[...m(e.include),...m(l.include),...c],includeLocked:!!e.includeLocked,includePrerelease:e.prerelease||l.prerelease||!1,security:!e.noSecurity,target:v};let E=0;for(const t of w.values())E+=t.size;const h=!!process.stdout.isTTY&&!K;let u;const B=h?(t,r)=>{u?u.rerender(a.createElement(j,{current:t,total:r})):u=b(a.createElement(j,{current:t,total:r}),{interactive:!0,patchConsole:!1})}:(t,r)=>{o.info(`Checking ${String(t)}/${String(r)} dependencies...`)};h||o.info(`Checking ${String(E)} catalog dependencies against npm registry...
3
- `);const M=G(i?.security?.socket),{failed:$,outdated:s}=await ne(w,z,U,B,d,M,i?.security?.socket?.acceptedRisks);if(u&&(u.clear(),u.unmount()),$.length>0&&o.warn(`Failed to fetch: ${$.join(", ")}`),s.length===0){o.info("All catalog dependencies are up to date.");return}const k=e.format??l.format??"table",P=Q(e.aiType??"impact"),p=e.ai?await X(s,o,i?.ai,P):void 0;if(h&&k==="table"){const t=new ee(s,p??null),r=i?.tui?.autoExit??!1,x=r===!0?3:typeof r=="number"?r:0;await b(a.createElement(te,{autoExitSeconds:x,isDryRun:!0,store:t}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit();const L=process.stdout.columns||80;process.stdout.write(`
4
- `);for(const n of s){const Y=n.vulnerabilities?.length||n.socketReport&&n.socketReport.alerts.length>0,T=!!n.acceptedRisk,A=Y?T?"✓":"⚠":"✓",D=T?"gray":n.updateType==="major"?"red":n.updateType==="minor"?"yellow":"green",g=n.socketReport?.score.overall,F=g===void 0?"":` [${String(Math.round(g*100))}%]`,R=g===void 0?void 0:H(g);process.stdout.write(`${V(a.createElement(y,null," ",a.createElement(y,{color:D},A),` ${n.packageName} ${n.currentRange} → ${n.newRange}`,a.createElement(y,{dimColor:!0},` ${n.updateType}`),R?a.createElement(y,{color:R},F):null),{columns:L})}
5
- `)}process.stdout.write(`
6
- `),o.info(N(s))}else if(k==="json"){const t={failed:$,outdated:s};p&&(t.aiAnalysis=p),process.stdout.write(`${JSON.stringify(t,void 0,2)}
7
- `)}else k==="minimal"?process.stdout.write(`${se(s)}
8
- `):(ie(s,o),o.info(N(s)),p&&(o.info(""),o.info(_(p))));e.exitCode&&s.length>0&&(process.exitCode=1)},"execute");export{we as default};
1
+ var a=Object.defineProperty;var d=(s,o)=>a(s,"name",{value:o,configurable:!0});import{createRequire as p}from"node:module";import{isAccessibleSync as k}from"@visulima/fs";import{join as m}from"@visulima/path";import{cleanWorkspace as b}from"#native";import{p as c}from"./bin.js";import{f as R}from"../packem_shared/utils-DrNg0XTR.js";const g=p(import.meta.url),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,h=d(s=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[o,n]=f.versions.node.split(".").map(Number);if(o>22||o===22&&n>=3||o===20&&n>=16)return f.getBuiltinModule(s)}return g(s)},"__cjs_getBuiltinModule"),{readdirSync:v,lstatSync:y,unlinkSync:_}=h("node:fs");var $=Object.defineProperty,u=d((s,o)=>$(s,"name",{value:o,configurable:!0}),"f");const j=u(s=>{const o=[],n=[s];for(;n.length>0;){const t=n.pop();let i;try{i=v(t)}catch{continue}for(const r of i){const e=m(t,r);try{const l=y(e);if(l.isSymbolicLink()||!l.isDirectory())continue}catch{continue}r==="node_modules"?o.push(e):r!==".git"&&r!==".hg"&&n.push(e)}}return o},"findNodeModulesDirectories"),S=["pnpm-lock.yaml","package-lock.json","npm-shrinkwrap.json","yarn.lock","bun.lock","bun.lockb"],x=u((s,o,n)=>{let t=0,i=!1;for(const r of S){const e=m(s,r);if(k(e)){if(o){n.info(` ${e}`),t++;continue}try{_(e),c.success(`Removed ${e}`),t++}catch(l){c.error(`${e}: ${R(l)}`),i=!0}}}return{hadError:i,removed:t}},"removeLockfiles"),D=u(async({logger:s,options:o,workspaceRoot:n})=>{const t=n??process.cwd(),i=o.lockfile||!1;if(o.dryRun){const e=j(t);if(e.length>0){c.info("Would remove:");for(const l of e)s.info(` ${l}`)}else c.info("No node_modules directories found.");i&&x(t,!0,s);return}const r=b(t,i);for(const e of r.removed)c.success(`Removed ${e}`);for(const e of r.lockfilesRemoved)c.success(`Removed ${e}`);for(const e of r.errors)c.error(e);r.removed.length===0&&r.lockfilesRemoved.length===0?c.info("No node_modules directories found."):c.info(`Cleaned ${r.removed.length} node_modules director${r.removed.length===1?"y":"ies"}`),r.errors.length>0&&(process.exitCode=1)},"execute");export{D as default};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var f=(r,n)=>m(r,"name",{value:n,configurable:!0});import{r as u}from"../packem_shared/toolchain-DQfTQY8E.js";var _=Object.defineProperty,a=f((r,n)=>_(r,"name",{value:n,configurable:!0}),"n");const C=a(()=>process.env.GITHUB_BASE_REF?{base:`origin/${process.env.GITHUB_BASE_REF}`,head:process.env.GITHUB_SHA??"HEAD"}:process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME?{base:`origin/${process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`,head:process.env.CI_COMMIT_SHA??"HEAD"}:process.env.CIRCLE_BRANCH&&process.env.CIRCLE_SHA1?{base:"origin/main",head:process.env.CIRCLE_SHA1}:{base:"origin/main",head:"HEAD"},"detectCiRefs"),w=a(async({argument:r,logger:n,options:e,runtime:t,visConfig:d,workspaceRoot:s})=>{const l=r[0];if(!l)throw new Error("Missing targets. Usage: vis ci <target>[,<target>…]");const p=l.split(",").map(o=>o.trim()).filter(Boolean);if(p.length===0)throw new Error("Missing targets. Usage: vis ci <target>[,<target>…]");if(!s)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const{base:E,head:h}=C(),c=e.base??E,g=e.head??h;e.skipToolchain||n.info("▸ Toolchain pre-flight"),await u(s,d?.toolchain,{error:a(o=>{n.error(o)},"error"),info:a(o=>{n.info(o)},"info"),warn:a(o=>{n.warn(o)},"warn")},!!e.skipToolchain),e.install===!1?n.info("▸ Skipping install (--no-install)"):(n.info("▸ Installing dependencies"),await t.runCommand("install",{argv:["--frozen-lockfile"]}));for(const o of p){n.info(`▸ Running affected ${o} (base=${c}, head=${g})`);const i=[o,`--base=${c}`,`--head=${g}`,`--upstream=${String(e.upstream??"none")}`,`--downstream=${String(e.downstream??"deep")}`];e.parallel!==void 0&&i.push(`--parallel=${String(e.parallel)}`),e.partition&&i.push(`--partition=${String(e.partition)}`),e.query&&i.push(`--query=${String(e.query)}`),await t.runCommand("affected",{argv:i})}n.info("▸ CI pipeline complete")},"execute");export{w as default};
1
+ var i=Object.defineProperty;var n=(e,o)=>i(e,"name",{value:o,configurable:!0});import{m as l,d as p}from"./bin.js";var f=Object.defineProperty,d=n((e,o)=>f(e,"name",{value:o,configurable:!0}),"n");const m=d(async({logger:e,options:o,visConfig:a,workspaceRoot:r})=>{const c=r??process.cwd(),t=l(c,{configBackend:a?.install?.backend,configCorepack:a?.install?.corepack}),s=p(t,o.check||!1,c,e);s!==0&&(process.exitCode=s)},"execute");export{m as default};
@@ -1 +1 @@
1
- var a=Object.defineProperty;var d=(s,o)=>a(s,"name",{value:o,configurable:!0});import{createRequire as p}from"node:module";import{isAccessibleSync as k}from"@visulima/fs";import{join as m}from"@visulima/path";import{cleanWorkspace as b}from"#native";import{p as c}from"./bin.js";import{f as R}from"../packem_shared/utils-DrNg0XTR.js";const g=p(import.meta.url),f=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,h=d(s=>{if(typeof f<"u"&&f.versions&&f.versions.node){const[o,n]=f.versions.node.split(".").map(Number);if(o>22||o===22&&n>=3||o===20&&n>=16)return f.getBuiltinModule(s)}return g(s)},"__cjs_getBuiltinModule"),{readdirSync:v,lstatSync:y,unlinkSync:_}=h("node:fs");var $=Object.defineProperty,u=d((s,o)=>$(s,"name",{value:o,configurable:!0}),"f");const j=u(s=>{const o=[],n=[s];for(;n.length>0;){const t=n.pop();let i;try{i=v(t)}catch{continue}for(const r of i){const e=m(t,r);try{const l=y(e);if(l.isSymbolicLink()||!l.isDirectory())continue}catch{continue}r==="node_modules"?o.push(e):r!==".git"&&r!==".hg"&&n.push(e)}}return o},"findNodeModulesDirectories"),S=["pnpm-lock.yaml","package-lock.json","npm-shrinkwrap.json","yarn.lock","bun.lock","bun.lockb"],x=u((s,o,n)=>{let t=0,i=!1;for(const r of S){const e=m(s,r);if(k(e)){if(o){n.info(` ${e}`),t++;continue}try{_(e),c.success(`Removed ${e}`),t++}catch(l){c.error(`${e}: ${R(l)}`),i=!0}}}return{hadError:i,removed:t}},"removeLockfiles"),D=u(async({logger:s,options:o,workspaceRoot:n})=>{const t=n??process.cwd(),i=o.lockfile||!1;if(o.dryRun){const e=j(t);if(e.length>0){c.info("Would remove:");for(const l of e)s.info(` ${l}`)}else c.info("No node_modules directories found.");i&&x(t,!0,s);return}const r=b(t,i);for(const e of r.removed)c.success(`Removed ${e}`);for(const e of r.lockfilesRemoved)c.success(`Removed ${e}`);for(const e of r.errors)c.error(e);r.removed.length===0&&r.lockfilesRemoved.length===0?c.info("No node_modules directories found."):c.info(`Cleaned ${r.removed.length} node_modules director${r.removed.length===1?"y":"ies"}`),r.errors.length>0&&(process.exitCode=1)},"execute");export{D as default};
1
+ var d=Object.defineProperty;var i=(a,s)=>d(a,"name",{value:s,configurable:!0});import{m as f,e as m}from"./bin.js";var u=Object.defineProperty,v=i((a,s)=>u(a,"name",{value:s,configurable:!0}),"n");const x=v(async({argument:a,logger:s,options:e,visConfig:r,workspaceRoot:t})=>{const o=a;if(!o||o.length===0)throw new Error("No package specified. Usage: vis dlx <package[@version]> [args...]");const[g,...l]=o,c=t??process.cwd(),p=f(c,{configBackend:r?.install?.backend,configCorepack:r?.install?.corepack}),k=e.package?Array.isArray(e.package)?e.package:[e.package]:[],n=m(p,{additionalPackages:k,args:l,package:g,shellMode:e.shellMode||!1,silent:e.silent||!1},c,s);n!==0&&(process.exitCode=n)},"execute");export{x as default};
@@ -0,0 +1,10 @@
1
+ var H=Object.defineProperty;var k=(e,t)=>H(e,"name",{value:t,configurable:!0});import{createRequire as U}from"node:module";import{resolve as O,relative as F}from"@visulima/path";import{d as D,P as K,R as S,I as j,p as V}from"./heal.js";import{A as q,G as Y,p as a}from"./bin.js";const P=U(import.meta.url),T=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,A=k(e=>{if(typeof T<"u"&&T.versions&&T.versions.node){const[t,o]=T.versions.node.split(".").map(Number);if(t>22||t===22&&o>=3||t===20&&o>=16)return T.getBuiltinModule(e)}return P(e)},"__cjs_getBuiltinModule"),{readFile:B}=A("node:fs/promises"),{createInterface:M}=A("node:readline");var J=Object.defineProperty,I=k((e,t)=>J(e,"name",{value:t,configurable:!0}),"o");const W=I(()=>!!process.stdout.isTTY&&process.env.CI!=="true","isInteractive"),z=I(e=>new Promise(t=>{const o=M({input:process.stdin,output:process.stderr});o.question(`${e} (Y/n) `,i=>{o.close();const s=i.trim().toLowerCase();t(s===""||s==="y"||s==="yes")})}),"defaultPrompt"),X=I((e,t)=>{const o=q(t),i=Y(o,{exact:!1,filter:[],global:!1,optional:!1,packages:[e],peer:!1,saveDev:!1,workspace:!1,workspaceRoot:!1},t,console);return Promise.resolve({exitCode:i})},"defaultRunInstall"),y=I(e=>`pnpm add ${e}`,"installCommandFor"),Q=I(e=>e==="@gitbeaker/rest"?import("@gitbeaker/rest"):import("@octokit/rest"),"defaultImport"),L=I(async(e,t={})=>{const o=t.interactive??W(),i=t.prompt??z,s=t.runInstall??X,l=t.importImpl??Q,d=t.workspaceRoot??process.cwd();try{return await l(e)}catch(n){const{code:u}=n;if(u!=="ERR_MODULE_NOT_FOUND"&&u!=="MODULE_NOT_FOUND")throw n}if(!o)throw new Error(`${e} is not installed. \`vis ai heal accept\` needs it to talk to the host. Install it in your repo first:
2
+ ${y(e)}`);if(!await i(`${e} isn't installed. Install it now?`))throw new Error(`${e} install declined. Re-run \`vis ai heal accept\` after installing manually:
3
+ ${y(e)}`);const r=await s(e,d);if(r.exitCode!==0)throw new Error(`Install of ${e} failed (exit ${String(r.exitCode)}). Install manually and retry:
4
+ ${y(e)}`);return await l(e)},"loadOptionalSdk");var Z=Object.defineProperty,C=k((e,t)=>Z(e,"name",{value:t,configurable:!0}),"s");const ee=C(e=>{const t=e.indexOf("/");if(t<=0||t===e.length-1)throw new Error(`Expected GITHUB_REPOSITORY in "owner/repo" form, got: ${e}`);return{owner:e.slice(0,t),repo:e.slice(t+1)}},"splitGithubRepo"),te=C(async(e,t)=>{if(t.githubClient)return t.githubClient;const o=(await(t.loadSdk??L)("@octokit/rest")).Octokit;if(!o)throw new TypeError("Loaded `@octokit/rest` but no `Octokit` export was found. Reinstall the package or pin to a supported major.");return new o({auth:e})},"loadGithubClient"),oe=C(async(e,t,o)=>{if(o.gitlabClient)return o.gitlabClient;const i=(await(o.loadSdk??L)("@gitbeaker/rest")).Gitlab;if(!i)throw new TypeError("Loaded `@gitbeaker/rest` but no `Gitlab` export was found. Reinstall the package or pin to a supported major.");return new i({host:t,token:e})},"loadGitlabClient"),re=C(e=>e.replace(/\/api\/v\d+\/?$/,""),"apiBaseToHost"),ie=C(async e=>{const{branch:t,ciContext:o,files:i,message:s,workspaceRoot:l}=e,d=e.readFile??(w=>B(w,"utf8"));if(!o.repo)throw new Error("Cannot commit on GitHub: GITHUB_REPOSITORY (owner/repo) is not set.");if(!o.token)throw new Error("Cannot commit on GitHub: GITHUB_TOKEN is not set. Grant the workflow `contents: write` and pass the token through.");const{owner:r,repo:n}=ee(o.repo),u=await te(o.token,e),p=(await u.rest.git.getRef({owner:r,ref:`heads/${t}`,repo:n})).data.object.sha,h=(await u.rest.git.getCommit({commit_sha:p,owner:r,repo:n})).data.tree.sha,m=await Promise.all(i.map(async w=>{const E=O(l,w),v=await d(E),_=await u.rest.git.createBlob({content:Buffer.from(v,"utf8").toString("base64"),encoding:"base64",owner:r,repo:n});return{mode:"100644",path:w,sha:_.data.sha,type:"blob"}})),f=await u.rest.git.createTree({base_tree:h,owner:r,repo:n,tree:m}),b=await u.rest.git.createCommit({message:s,owner:r,parents:[p],repo:n,tree:f.data.sha});return await u.rest.git.updateRef({owner:r,ref:`heads/${t}`,repo:n,sha:b.data.sha}),{sha:b.data.sha,url:b.data.html_url}},"commitToGithub"),ae=C(async e=>{const{branch:t,ciContext:o,files:i,message:s,workspaceRoot:l}=e,d=e.readFile??(m=>B(m,"utf8"));if(!o.repo)throw new Error("Cannot commit on GitLab: CI_PROJECT_ID / CI_PROJECT_PATH is not set.");if(!o.token)throw new Error("Cannot commit on GitLab: no token. CI_JOB_TOKEN cannot push commits — set GITLAB_TOKEN to a PAT/project-token with `api` scope.");if(!o.apiBaseUrl)throw new Error("Cannot commit on GitLab: CI_API_V4_URL is not set.");const r=re(o.apiBaseUrl),n=await oe(o.token,r,e),u=await Promise.all(i.map(async m=>{const f=O(l,m);return{action:"update",content:await d(f),filePath:m}})),p=await n.Commits.create(o.repo,t,s,u),h=p.id??p.sha;if(!h)throw new Error("GitLab Commits.create returned no commit ID — cannot reference the new commit.");return{sha:h,url:p.web_url??p.webUrl}},"commitToGitlab"),ne=C(async e=>{if(e.files.length===0)throw new Error("Cannot commit: no files to include.");if(e.ciContext.provider==="github-actions")return await ie(e);if(e.ciContext.provider==="gitlab-ci")return await ae(e);throw new Error(`Cannot commit: unsupported CI provider \`${e.ciContext.provider}\`. Run \`vis ai heal accept\` from a recognised CI environment.`)},"commitFiles");var se=Object.defineProperty,g=k((e,t)=>se(e,"name",{value:t,configurable:!0}),"u");const G="/vis heal accept",ce=g(async e=>{if(!e)return;let t;try{t=await B(e,"utf8")}catch{return}const o=JSON.parse(t),i=o.comment?.body??"",s=o.comment?.user?.login??"",l=o.pull_request?.head?.repo?.full_name,d=o.pull_request?.base?.repo?.full_name??o.repository?.full_name,r=l!==void 0&&d!==void 0&&l!==d;return{actor:s,body:i,headRef:o.pull_request?.head?.ref,isFork:r}},"loadGithubTrigger"),le=g(e=>{const t=e.VIS_HEAL_TRIGGER_BODY,o=e.VIS_HEAL_TRIGGER_ACTOR;if(!(!t||!o))return{actor:o,body:t,headRef:e.VIS_HEAL_HEAD_REF,isFork:!1}},"loadGitlabTrigger"),de=g(e=>{const t=e.BUILDKITE_UNBLOCKER_EMAIL??e.BUILDKITE_UNBLOCKER;if(t)return{actor:t,body:G,headRef:e.BUILDKITE_BRANCH,isFork:!1}},"loadBuildkiteTrigger"),ue=g(async(e,t)=>{if(e.provider==="github-actions")return await ce(t.GITHUB_EVENT_PATH);if(e.provider==="gitlab-ci")return le(t);if(e.provider==="buildkite")return de(t)},"loadTrigger"),pe=g((e,t)=>{const o=t.BUILDKITE_REPO;if(!o)return;const i=/(?:^|@|\/\/)github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(o);if(i&&t.GITHUB_TOKEN)return{apiBaseUrl:void 0,buildId:void 0,buildNumber:void 0,prNumber:e.prNumber,provider:"github-actions",repo:`${i[1]}/${i[2]}`,sha:e.sha,token:t.GITHUB_TOKEN};const s=/\/\/([^/]*gitlab[^/]*)\/([^/]+)\/(.+?)(?:\.git)?\/?$/i.exec(o),l=s?null:/@([^/:]*gitlab[^/:]*):([^/]+)\/(.+?)(?:\.git)?\/?$/i.exec(o),d=s??l;if(d&&t.GITLAB_TOKEN){const r=d[1];return{apiBaseUrl:t.CI_API_V4_URL??`https://${r}/api/v4`,buildId:void 0,buildNumber:void 0,prNumber:e.prNumber,provider:"gitlab-ci",repo:`${d[2]}/${d[3]}`,sha:e.sha,token:t.GITLAB_TOKEN}}},"deriveBuildkiteCommitContext"),me=g(async e=>{const t=e.fetchImpl??globalThis.fetch,o=`${(e.apiBaseUrl??"https://api.github.com").replace(/\/+$/,"")}/repos/${e.repo}/pulls/${String(e.prNumber)}`;try{const i=await t(o,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e.token}`,"X-GitHub-Api-Version":"2022-11-28"}});return i.ok?(await i.json()).head?.ref:void 0}catch{return}},"fetchGithubHeadRef"),fe=g((e,t,o,i)=>{const s=t.map(l=>`- \`${l}\``).join(`
5
+ `);return["## vis ai heal — committed","",`Accepted by @${i}.`,"",`Failing task: \`${o}\``,e.url?`Commit: [\`${e.sha.slice(0,7)}\`](${e.url})`:`Commit: \`${e.sha.slice(0,7)}\``,"","### Files changed",s,"","_Re-run the failing job to confirm the fix landed._"].join(`
6
+ `)},"summariseDetail"),he=g(async(e,t={})=>{const{logger:o,visConfig:i,workspaceRoot:s}=e,l=s??process.cwd(),d=t.env??process.env,r=await(t.detectCi??(()=>D(d)))();if(r.provider==="unknown"){a.error("`vis ai heal accept` must run inside a recognised CI provider (GitHub Actions, GitLab CI, or Buildkite)."),process.exitCode=1;return}const n=await ue(r,d);if(!n){const c=r.provider==="github-actions"?"No issue_comment payload found. Trigger this command from a workflow listening for `issue_comment.created`.":r.provider==="gitlab-ci"?"No GitLab trigger payload found. Set VIS_HEAL_TRIGGER_BODY, VIS_HEAL_TRIGGER_ACTOR, and VIS_HEAL_HEAD_REF in the bridge that re-emits note hooks as pipeline runs.":"No Buildkite unblock signal found. Wire this command to run after a manually-unblocked block step so BUILDKITE_UNBLOCKER_EMAIL is set.";a.error(c),process.exitCode=1;return}if(r.provider!=="buildkite"&&!n.body.includes(G)){a.notice(`Trigger comment does not contain \`${G}\`; nothing to do.`);return}const u=i?.ai?.heal?.allowedActors??[];if(u.length===0){a.error("`ai.heal.allowedActors` is empty. Configure the allow-list in `vis.config.*` before enabling auto-commit."),process.exitCode=1;return}if(!n.actor||!u.includes(n.actor)){const c=r.provider==="buildkite"?"Buildkite entries are emails (BUILDKITE_UNBLOCKER_EMAIL) or Buildkite usernames (BUILDKITE_UNBLOCKER), not the upstream GitHub/GitLab username.":r.provider==="gitlab-ci"?"GitLab entries are platform usernames (without the leading `@`).":"GitHub entries are platform usernames (without the leading `@`).";a.error(`Actor \`${n.actor||"(unknown)"}\` is not in \`ai.heal.allowedActors\`. Refusing to commit. ${c}`),process.exitCode=1;return}if(n.isFork){a.error("Refusing to accept: the change is from a forked repository. The CI token does not have write access to the fork."),process.exitCode=1;return}let p=n.headRef;if(!p&&r.provider==="github-actions"&&r.prNumber!==void 0&&r.repo&&r.token&&(p=await me({fetchImpl:t.fetchImpl,prNumber:r.prNumber,repo:r.repo,token:r.token})),!p){a.error("Could not resolve the PR / MR head branch. Ensure the trigger payload includes head.ref or set VIS_HEAL_HEAD_REF."),process.exitCode=1;return}a.info(`Accepting fix on \`${p}\` for actor \`${n.actor}\`.`);const h=await K(l,e.options.run);if(h.outcome==="no-failed-task"){a.error("No failed tasks found in the run summary. The accept command should run on the same workspace as the original failure."),process.exitCode=1;return}if(h.outcome==="missing-metadata"){a.error(`Failed task ${h.failedTask.taskId} is missing project/target metadata; cannot validate the fix.`),process.exitCode=1;return}if(h.outcome==="no-failure-context"){a.error(`No failure log or run summary found for ${h.failedTask.taskId}.`),process.exitCode=1;return}const m=h,f=await S(e,m);if(f.outcome==="no-proposal"){a.error("AI fix proposal failed; cannot commit."),process.exitCode=1;return}if(f.outcome==="cannot-fix"){a.warn(`AI declined to fix: ${f.detail??"(no reason)"}. Nothing to commit.`),process.exitCode=1;return}if(f.outcome==="empty-patches"){a.warn("AI returned an empty patch set. Nothing to commit."),process.exitCode=1;return}if(f.outcome==="no-patches-applied"){a.error("Patches could not be applied to the workspace. Refusing to commit."),process.exitCode=1;return}a.info(`Re-running ${m.failedTask.taskId} to validate the fix before committing...`);const b=await j(e,m,{validate:t.validate});if(b.exitCode!==0){a.error(`Validation failed (exit ${String(b.exitCode)}). Refusing to commit.`),b.stderr.trim().length>0&&(o.info("--- validation stderr (tail) ---"),o.info(b.stderr.split(`
7
+ `).slice(-20).join(`
8
+ `))),process.exitCode=1;return}a.success("Validation passed. Committing.");const w=(f.applyResults??[]).filter(c=>c.status==="applied").map(c=>{const $=c.absolutePath??c.patch.file,x=F(l,$);return x===""||x.startsWith("..")?c.patch.file:x});if(w.length===0){a.error("No applied files to commit. Aborting."),process.exitCode=1;return}const E=[`fix: vis ai heal accepted by @${n.actor}`,"",`Failing task: ${m.failedTask.taskId}`,f.proposal?.explanation?`
9
+ ${f.proposal.explanation}`:"","","Auto-committed by `vis ai heal accept`."].join(`
10
+ `);let v=r;if(r.provider==="buildkite"){const c=pe(r,d);if(!c){a.error("Cannot determine the upstream VCS to commit to. Buildkite jobs need GITHUB_TOKEN or GITLAB_TOKEN set (matching the host parsed from BUILDKITE_REPO) for `vis ai heal accept` to land the commit."),process.exitCode=1;return}v=c}let _;try{_=await ne({branch:p,ciContext:v,files:w,message:E,workspaceRoot:l,...t.commitOverrides})}catch(c){a.error(`Commit failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1;return}a.success(`Committed as ${_.sha.slice(0,7)}${_.url?` — ${_.url}`:""}.`);const N=fe(_,w,m.failedTask.taskId,n.actor),R=await(t.postComment??(async(c,$)=>V({body:c,context:$})))(N,r);!R.posted&&R.method!=="skipped"&&a.warn(`Commit landed but the confirmation comment failed: ${R.error??"unknown"}`)},"acceptHeal"),Ie=g(async e=>{await he(e)},"aiHealAccept");export{G as TRIGGER_PHRASE,Ie as aiHealAccept,pe as deriveBuildkiteCommitContextForTesting,me as fetchGithubHeadRefForTesting,de as loadBuildkiteTriggerForTesting,ce as loadGithubTriggerForTesting,le as loadGitlabTriggerForTesting,he as runHealAcceptForTesting,fe as summariseDetailForTesting};
@@ -0,0 +1,14 @@
1
+ var U=Object.defineProperty;var I=(t,e)=>U(t,"name",{value:e,configurable:!0});import{createRequire as A}from"node:module";import{bold as O,dim as v,red as G,green as j,yellow as F}from"@visulima/colorize";import{relative as D}from"@visulima/path";import{readLastRunSummary as K}from"@visulima/task-runner";import{r as H,a as M,b as V,c as J}from"../packem_shared/ai-fix-nn4zOE95.js";import{p as u}from"./bin.js";import{r as z}from"../packem_shared/run-summary-utils-BfBvjzhY.js";const L=A(import.meta.url),b=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,T=I(t=>{if(typeof b<"u"&&b.versions&&b.versions.node){const[e,o]=b.versions.node.split(".").map(Number);if(e>22||e===22&&o>=3||e===20&&o>=16)return b.getBuiltinModule(t)}return L(t)},"__cjs_getBuiltinModule"),{spawn:k}=T("node:child_process"),{readFile:q}=T("node:fs/promises");var Q=Object.defineProperty,g=I((t,e)=>Q(t,"name",{value:e,configurable:!0}),"i");const W=g(t=>{if(!t)return;const e=/^refs\/pull\/(\d+)\//.exec(t);return e?Number.parseInt(e[1],10):void 0},"parsePrNumberFromGithubRef"),Y=g(async t=>{if(!t)return{prNumber:void 0,sha:void 0};try{const e=await q(t,"utf8"),o=JSON.parse(e),r=o.pull_request?.number??o.issue?.number??o.number,i=o.pull_request?.head?.sha;return{prNumber:r,sha:i}}catch{return{prNumber:void 0,sha:void 0}}},"readPrNumberFromGithubEvent"),Z=g(async t=>{const e=W(t.GITHUB_REF),{prNumber:o,sha:r}=e===void 0?await Y(t.GITHUB_EVENT_PATH):{prNumber:e,sha:void 0};return{apiBaseUrl:void 0,buildId:void 0,buildNumber:void 0,prNumber:e??o,provider:"github-actions",repo:t.GITHUB_REPOSITORY,sha:r??t.GITHUB_SHA,token:t.GITHUB_TOKEN}},"detectGithubActions"),X=g(t=>{const e=t.CI_MERGE_REQUEST_IID,o=e!==void 0&&e!==""?Number.parseInt(e,10):void 0,r=t.CI_API_V4_URL,i=t.GITLAB_TOKEN??t.CI_TOKEN;return{apiBaseUrl:r,buildId:void 0,buildNumber:void 0,prNumber:Number.isFinite(o)?o:void 0,provider:"gitlab-ci",repo:t.CI_PROJECT_ID??t.CI_PROJECT_PATH,sha:t.CI_COMMIT_SHA,token:i}},"detectGitlabCi"),ee=g(t=>{const e=t.BUILDKITE_PULL_REQUEST,o=e!==void 0&&e!==""&&e!=="false"?Number.parseInt(e,10):void 0,r=t.BUILDKITE_BUILD_NUMBER,i=r!==void 0&&r!==""?Number.parseInt(r,10):void 0,n=t.BUILDKITE_ORGANIZATION_SLUG,a=t.BUILDKITE_PIPELINE_SLUG,s=n!==void 0&&n!==""&&a!==void 0&&a!==""?`${n}/${a}`:void 0;return{apiBaseUrl:(t.BUILDKITE_API_BASE_URL??"https://api.buildkite.com").replace(/\/+$/,""),buildId:t.BUILDKITE_BUILD_ID,buildNumber:Number.isFinite(i)?i:void 0,prNumber:Number.isFinite(o)?o:void 0,provider:"buildkite",repo:s,sha:t.BUILDKITE_COMMIT,token:t.BUILDKITE_API_TOKEN}},"detectBuildkite"),te=g(async(t=process.env)=>t.GITHUB_ACTIONS==="true"?await Z(t):t.GITLAB_CI==="true"?X(t):t.BUILDKITE==="true"?ee(t):{apiBaseUrl:void 0,buildId:void 0,buildNumber:void 0,prNumber:void 0,provider:"unknown",repo:void 0,sha:void 0,token:void 0},"detectCiContext");var oe=Object.defineProperty,h=I((t,e)=>oe(t,"name",{value:e,configurable:!0}),"p");const re=h((t,e,o,r)=>new Promise(i=>{const n=["pr","comment",String(e),"--body-file","-"];r&&n.push("--repo",r);const a=k(t,n,{stdio:["pipe","ignore","pipe"]});let s="";a.stderr?.setEncoding("utf8"),a.stderr?.on("data",d=>{s+=d}),a.once("error",()=>{i({exitCode:127,stderr:s})}),a.once("close",d=>{i({exitCode:d??-1,stderr:s})}),a.stdin?.on("error",()=>{}),a.stdin?.end(o)}),"runGhComment"),ie=h(async(t,e,o,r,i)=>{const n=`https://api.github.com/repos/${e}/issues/${String(o)}/comments`;try{const a=await t(n,{body:JSON.stringify({body:r}),headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"},method:"POST"});if(!a.ok){const s=await a.text().catch(()=>"");return{error:`GitHub REST returned ${String(a.status)}: ${s.slice(0,500)}`,ok:!1}}return{ok:!0}}catch(a){return{error:a instanceof Error?a.message:String(a),ok:!1}}},"postViaGithubRest"),ne=h(async(t,e,o,r,i,n)=>{const a=encodeURIComponent(o),s=`${e.replace(/\/+$/,"")}/projects/${a}/merge_requests/${String(r)}/notes`;try{const d=await t(s,{body:JSON.stringify({body:i}),headers:{"Content-Type":"application/json","PRIVATE-TOKEN":n},method:"POST"});if(!d.ok){const p=await d.text().catch(()=>"");return{error:`GitLab REST returned ${String(d.status)}: ${p.slice(0,500)}`,ok:!1}}return{ok:!0}}catch(d){return{error:d instanceof Error?d.message:String(d),ok:!1}}},"postViaGitlabRest"),ae=h((t,e,o,r)=>new Promise(i=>{const n=k(t,["annotate","--style",o,"--context",r],{stdio:["pipe","ignore","pipe"]});let a="";n.stderr?.setEncoding("utf8"),n.stderr?.on("data",s=>{a+=s}),n.once("error",()=>{i({exitCode:127,stderr:a})}),n.once("close",s=>{i({exitCode:s??-1,stderr:a})}),n.stdin?.on("error",()=>{}),n.stdin?.end(e)}),"runBuildkiteAnnotate"),se=h(async(t,e,o,r,i,n,a,s)=>{const[d,p]=o.split("/",2);if(!d||!p)return{error:`Buildkite repo identifier \`${o}\` is not in {org}/{pipeline} form.`,ok:!1};const m=`${e}/v2/organizations/${encodeURIComponent(d)}/pipelines/${encodeURIComponent(p)}/builds/${String(r)}/annotations`;try{const c=await t(m,{body:JSON.stringify({body:i,context:a,style:n}),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},method:"POST"});if(!c.ok){const l=await c.text().catch(()=>"");return{error:`Buildkite REST returned ${String(c.status)}: ${l.slice(0,500)}`,ok:!1}}return{ok:!0}}catch(c){return{error:c instanceof Error?c.message:String(c),ok:!1}}},"postViaBuildkiteRest"),de=h(async(t,e,o,r)=>{const i=e.buildId?`vis-ai-heal-${e.buildId}`:"vis-ai-heal",n="info",a=await ae(o,t,n,i);if(a.exitCode===0)return{method:"buildkite-cli",posted:!0};if(!e.apiBaseUrl||!e.repo||e.buildNumber===void 0||!e.token){const d=[];return e.repo||d.push("BUILDKITE_ORGANIZATION_SLUG / BUILDKITE_PIPELINE_SLUG"),e.buildNumber===void 0&&d.push("BUILDKITE_BUILD_NUMBER"),e.token||d.push("BUILDKITE_API_TOKEN (with `write_build_annotations` scope)"),{error:`buildkite-agent annotate exited ${String(a.exitCode)} (${a.stderr.trim().slice(0,200)}); cannot fall back to REST without ${d.join(", ")}`,method:"buildkite-cli",posted:!1}}const s=await se(r,e.apiBaseUrl,e.repo,e.buildNumber,t,n,i,e.token);return s.ok?{method:"rest",posted:!0}:{error:`buildkite-agent annotate exited ${String(a.exitCode)}; REST fallback also failed: ${s.error??"unknown"}`,method:"rest",posted:!1}},"postBuildkiteAnnotation"),pe=h(async(t,e,o,r)=>{if(e.prNumber===void 0)return{method:"skipped",posted:!1};const i=await re(o,e.prNumber,t,e.repo);if(i.exitCode===0)return{method:"gh-cli",posted:!0};if(!e.repo||!e.token)return{error:`gh exited ${String(i.exitCode)} (${i.stderr.trim().slice(0,200)}); cannot fall back to REST without GITHUB_REPOSITORY + GITHUB_TOKEN`,method:"gh-cli",posted:!1};const n=await ie(r,e.repo,e.prNumber,t,e.token);return n.ok?{method:"rest",posted:!0}:{error:`gh exited ${String(i.exitCode)}; REST fallback also failed: ${n.error??"unknown"}`,method:"rest",posted:!1}},"postGithubComment"),ce=h(async(t,e,o)=>{if(e.prNumber===void 0)return{method:"skipped",posted:!1};if(!e.apiBaseUrl||!e.repo)return{error:"GitLab CI context is missing CI_API_V4_URL or CI_PROJECT_ID; cannot post note.",method:"rest",posted:!1};if(!e.token)return{error:"GitLab CI context has no token. CI_JOB_TOKEN cannot post MR notes — set GITLAB_TOKEN to a personal/project access token with `api` scope.",method:"rest",posted:!1};const r=await ne(o,e.apiBaseUrl,e.repo,e.prNumber,t,e.token);return r.ok?{method:"rest",posted:!0}:{error:r.error,method:"rest",posted:!1}},"postGitlabComment"),ue=h(async t=>{const{body:e,buildkiteAgentBin:o="buildkite-agent",context:r,fetchImpl:i=globalThis.fetch,ghBin:n="gh"}=t;return r.provider==="github-actions"?await pe(e,r,n,i):r.provider==="gitlab-ci"?await ce(e,r,i):r.provider==="buildkite"?await de(e,r,o,i):{method:"skipped",posted:!1}},"postPrComment");var le=Object.defineProperty,f=I((t,e)=>le(t,"name",{value:e,configurable:!0}),"l");const C=f(t=>{let e=0,o=0;for(const r of t)r.status==="applied"?e+=1:o+=1;return{applied:e,failed:o}},"summarizeApply"),_=f((t,e,o)=>{const r=H(t,e,o),i=D(t,r);return i===""||i.startsWith("..")?r:i},"formatDisplayPath"),fe=f((t,e,o,r)=>new Promise(i=>{const n=process.argv[1];if(!n){i({exitCode:-1,stderr:"Cannot locate vis bin (process.argv[1] missing).",stdout:""});return}const a=[n,"run",o,"--projects",e,"--no-cache","--summarize","--fail-fast"],s=k(process.execPath,a,{cwd:t,env:{...process.env,NO_COLOR:"1"},stdio:["ignore","pipe","pipe"]});let d="",p="";const m=setTimeout(()=>{s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),2e3).unref()},r);s.stdout?.setEncoding("utf8"),s.stdout?.on("data",c=>{d+=c}),s.stderr?.setEncoding("utf8"),s.stderr?.on("data",c=>{p+=c}),s.once("error",c=>{clearTimeout(m),i({exitCode:-1,stderr:c.message,stdout:d})}),s.once("close",c=>{clearTimeout(m),i({exitCode:c??-1,stderr:p,stdout:d})})}),"validateFixByRerun"),me=6e4,y=f(t=>{let e=0;const o=t.match(/`{3,}/g);if(o)for(const r of o)e=Math.max(e,r.length);return"`".repeat(Math.max(3,e+1))},"pickFence"),$=f((t,e,o)=>{if(t.patches.length===0)return"_No patches proposed._";const r=[];for(const[i,n]of t.patches.entries()){const a=_(e,o,n.file),s=[`**[${String(i+1)}] \`${a}\`**`];n.reason&&s.push(`_${n.reason}_`);const d=y(`${n.oldString}
2
+ ${n.newString}`);s.push(`${d}diff`);for(const p of n.oldString.split(`
3
+ `))s.push(`- ${p}`);for(const p of n.newString.split(`
4
+ `))s.push(`+ ${p}`);s.push(d),r.push(s.join(`
5
+ `))}return r.join(`
6
+
7
+ `)},"renderProposalDiff"),x=f((t,e,o,r)=>{const i=["## vis ai heal — proposed fix","",`Failing task: \`${e.taskId}\` (provider: \`${t.provider}\`, confidence: \`${t.confidence}\`)`];r&&i.push(`Run anchored at \`${r.slice(0,7)}\`.`),i.push(""),i.push("### Root cause"),i.push(t.explanation||"_(no explanation)_"),i.push("");const n=["### Proposed patch",$(t,o,e.cwd),""],a=["### Validation",`Re-ran \`${e.taskId}\` after applying the patch on the CI runner — task **passed**.`,"","### Apply locally","```sh",`vis ai fix ${e.taskId} --apply`,"```","","---","","_Auto-generated by `vis ai heal`. Auto-commit is on the roadmap; for now the patch lives in this comment and is yours to accept or reject._"],s=[...i,...n,...a].join(`
8
+ `);if(Buffer.byteLength(s,"utf8")<=me)return s;const d=["### Proposed patch",`_Patch set is too large for a comment (${String(t.patches.length)} files). Run \`vis ai fix ${e.taskId} --apply\` locally to inspect and apply it._`,""];return[...i,...d,...a].join(`
9
+ `)},"renderCommentBody"),he=f((t,e,o)=>{const r=[O(`Proposal (${t.provider}, confidence: ${t.confidence})`),t.explanation||v("<no explanation>")];for(const[i,n]of t.patches.entries()){r.push(""),r.push(`[${String(i+1)}] ${_(e,o,n.file)}`),n.reason&&r.push(v(` reason: ${n.reason}`));for(const a of n.oldString.split(`
10
+ `))r.push(G(` - ${a}`));for(const a of n.newString.split(`
11
+ `))r.push(j(` + ${a}`))}return r.join(`
12
+ `)},"renderProposalForLog"),ge=f(async(t,e)=>{const o=e===void 0?await K(t):await z(t,e);if(o){for(const r of o.tasks)if(r.exitCode!==void 0&&r.exitCode!==0)return{project:r.target?.project,runId:o.id,target:r.target?.target,taskId:r.taskId}}},"findFirstFailedTask"),Ie=1800*1e3,w=f(async(t,e)=>{const o=await ge(t,e);if(!o)return{outcome:"no-failed-task"};if(!o.project||!o.target)return{failedTask:o,outcome:"missing-metadata"};const r=await M(t,o.taskId,{runId:o.runId});return r?{failedTask:{project:o.project,runId:o.runId,target:o.target,taskId:o.taskId},failureContext:r,outcome:"ready"}:{failedTask:{project:o.project,runId:o.runId,target:o.target,taskId:o.taskId},outcome:"no-failure-context"}},"findHealCandidate"),N=f(async(t,e)=>{const{logger:o,options:r,visConfig:i,workspaceRoot:n}=t,a=n??process.cwd(),s=r.dryRun===!0,d=i?.ai,p=await V(e.failureContext,o,{cache:r.noCache!==!0,config:d});if(!p)return{outcome:"no-proposal"};if(p.cannotFix)return{detail:p.cannotFix,outcome:"cannot-fix",proposal:p};if(p.patches.length===0)return{outcome:"empty-patches",proposal:p};if(s)return{outcome:"dry-run",proposal:p};const m=await J(a,e.failureContext.cwd,p);return C(m).applied===0?{applyResults:m,outcome:"no-patches-applied",proposal:p}:{applyResults:m,outcome:"applied",proposal:p}},"proposeAndApply"),E=f(async(t,e,o={})=>{const r=t.workspaceRoot??process.cwd(),i=t.options.validationTimeout===void 0?Ie:t.options.validationTimeout*1e3;return await(o.validate??((n,a)=>fe(r,n,a,i)))(e.failedTask.project,e.failedTask.target)},"validateAppliedFix"),S=f(async(t,e,o,r={})=>{const i=await(r.detectCi??te)(),n=i.provider==="gitlab-ci"?"MR":i.provider==="buildkite"?"annotation":"PR";if(i.provider==="unknown")return{ciContext:i,outcome:"no-ci",surface:n};const a=x(e,o,t,i.sha),s=await(r.postComment??(async(d,p)=>ue({body:d,context:p})))(a,i);return s.posted?{ciContext:i,method:s.method,outcome:"posted",surface:n}:s.method==="skipped"?{ciContext:i,outcome:"no-pr",surface:n}:{ciContext:i,error:s.error,method:s.method,outcome:"post-failed",surface:n}},"postHealComment"),R=f(async(t,e={})=>{const{logger:o,workspaceRoot:r}=t,i=r??process.cwd(),n=await w(i,t.options.run);if(n.outcome==="no-failed-task"){u.info("No failed tasks found in the latest run summary. Nothing to heal.");return}if(n.outcome==="missing-metadata"){u.error(`Failed task ${n.failedTask.taskId} is missing project/target metadata in the run summary; cannot validate a fix.`),process.exitCode=1;return}if(n.outcome==="no-failure-context"){u.error(`No failure log or run summary found for ${n.failedTask.taskId}.`),process.exitCode=1;return}const a={failedTask:n.failedTask,failureContext:n.failureContext};u.info(`Healing ${a.failedTask.taskId} (run ${a.failedTask.runId??"unknown"})`),a.failureContext.terminalOutputCaptured||u.warn(`No captured terminal output for ${a.failedTask.taskId}; the AI proposal will be weaker without it.`);const s=await N(t,a);if(s.outcome==="no-proposal"){u.error("AI fix proposal failed or no provider available."),process.exitCode=1;return}if(s.outcome==="cannot-fix"){u.warn(`AI declined to fix: ${s.detail??"(no reason)"}`);return}if(s.outcome==="empty-patches"){u.warn("AI returned an empty patch set.");return}const d=s.proposal;if(o.info(he(d,i,a.failureContext.cwd)),s.outcome==="dry-run"){u.info("Dry run: skipping apply, validation, and PR comment.");return}const p=s.applyResults??[],m=C(p);if(u.info(`Applied ${String(m.applied)}/${String(p.length)} patches.`),s.outcome==="no-patches-applied"){u.error("No patches could be applied (all failed validation)."),process.exitCode=1;return}u.info(`Re-running ${a.failedTask.taskId} to validate the fix...`);const c=await E(t,a,{validate:e.validate});if(c.exitCode!==0){u.error(`Validation failed (exit ${String(c.exitCode)}). Patch is not posted.`),c.stderr.trim().length>0&&(o.info(F("--- validation stderr (tail) ---")),o.info(c.stderr.split(`
13
+ `).slice(-20).join(`
14
+ `))),process.exitCode=1;return}u.success("Validation passed.");const l=await S(i,d,a.failureContext,{detectCi:e.detectCi,postComment:e.postComment});if(l.outcome==="no-ci"){u.notice("Not running in a recognised CI provider; skipping PR comment. Patch was applied + validated locally.");return}if(l.outcome==="posted"){const P=l.surface==="annotation"?`build #${String(l.ciContext.buildNumber??"?")}`:`${l.surface} #${String(l.ciContext.prNumber)}`;u.success(`Posted fix proposal to ${P} via ${l.method??"unknown"}.`);return}if(l.outcome==="no-pr"){u.notice(`No ${l.surface} number detected (push-event run); skipping comment.`);return}const B=l.surface==="annotation"?"annotation":`${l.surface} comment`;u.error(`Failed to post ${B}: ${l.error??"unknown error"}`)},"heal"),be=f(async t=>{await R(t)},"aiHeal"),we=Object.defineProperty({__proto__:null,aiHeal:be,findHealCandidate:w,pickFenceForTesting:y,postHealComment:S,proposeAndApply:N,renderCommentBodyForTesting:x,renderProposalDiffForTesting:$,runHealForTesting:R,validateAppliedFix:E},Symbol.toStringTag,{value:"Module"});export{E as I,w as P,N as R,te as d,we as h,ue as p};
@@ -1,7 +1,7 @@
1
- var H=Object.defineProperty;var v=(e,t)=>H(e,"name",{value:t,configurable:!0});import{walkSync as J,readFileSync as k}from"@visulima/fs";import{readYamlSync as X}from"@visulima/fs/yaml";import{relative as M,join as R}from"@visulima/path";import{parse as Z}from"yaml";import{constantCase as ee,trainCase as te,snakeCase as ne,pascalCase as re,kebabCase as ie,camelCase as se}from"@visulima/string/case";var ae=Object.defineProperty,d=v((e,t)=>ae(e,"name",{value:t,configurable:!0}),"e");const h=d(e=>e==null?"":typeof e=="string"?e:String(e),"stringify"),S={camel_case:d(e=>se(h(e)),"camel_case"),kebab_case:d(e=>ie(h(e)),"kebab_case"),lower_case:d(e=>h(e).toLowerCase(),"lower_case"),pascal_case:d(e=>re(h(e)),"pascal_case"),path_join:d((e,...t)=>{const r=[h(e),...t.map(h)];return R(...r)},"path_join"),path_relative:d((e,t)=>M(h(t),h(e)),"path_relative"),snake_case:d(e=>ne(h(e)),"snake_case"),upper_case:d(e=>h(e).toUpperCase(),"upper_case"),upper_kebab_case:d(e=>te(h(e)),"upper_kebab_case"),upper_snake_case:d(e=>ee(h(e)),"upper_snake_case")};d(e=>Object.hasOwn(S,e),"isKnownFilter");const I=d((e,t,r=[])=>{const n=S[e];if(!n)throw new Error(`Unknown filter "${e}". Known filters: ${Object.keys(S).sort().join(", ")}.`);return n(t,...r)},"applyFilter");var oe=Object.defineProperty,N=v((e,t)=>oe(e,"name",{value:t,configurable:!0}),"d$1");const L=N(e=>{const t=[];let r=0,n=0,i,s=-1;for(const a of e){if(s+=1,i){a===i&&(i=void 0);continue}if(a==='"'||a==="'"){i=a;continue}a==="("?r+=1:a===")"?r-=1:a===","&&r===0&&(t.push(e.slice(n,s)),n=s+1)}return t.push(e.slice(n)),t},"splitCommaOutsideQuotes"),le=N(e=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1)},"stripQuotes");var ce=Object.defineProperty,$=v((e,t)=>ce(e,"name",{value:t,configurable:!0}),"i$1");const fe=/\[([^\]]+)\]/g,ue=$(e=>{const t=e.trim(),r=t.indexOf("(");if(r===-1)return{args:[],name:t};if(!t.endsWith(")"))throw new Error(`Filter call "${e}" missing closing ")"`);const n=t.slice(0,r).trim(),i=t.slice(r+1,-1).trim();return i===""?{args:[],name:n}:{args:L(i).map(s=>{const a=s.trim();return le(a)??a}),name:n}},"parseFilterCall"),pe=$(e=>{const t=e.split("|").map(n=>n.trim()),r=t[0]??"";if(!r)throw new Error(`Empty variable name in expression "${e}"`);return{filters:t.slice(1).map(ue),name:r}},"parsePipe"),me=$(e=>e==null?"":typeof e=="string"?e:String(e),"stringify"),de=$((e,t)=>{const r=e.replaceAll(fe,(n,i)=>{const{filters:s,name:a}=pe(i);if(!Object.hasOwn(t,a))throw new Error(`Variable "${a}" used in filename "${e}" but not defined`);let o=t[a];for(const l of s)o=I(l.name,o,l.args);return me(o)});return q(r)},"interpolateFilename"),q=$(e=>e.split("/").map(t=>t.endsWith(".tera")||t.endsWith(".twig")?t.slice(0,-5):t).join("/"),"stripTeraSuffix"),he=$(e=>e.endsWith(".raw")?e.slice(0,-4):e,"stripRawSuffix"),ye=$(e=>{const t=e.split("/");return(t.at(-1)??"").startsWith("_")?!0:t.slice(0,-1).includes("partials")},"isPartialPath");var ge=Object.defineProperty,be=v((e,t)=>ge(e,"name",{value:t,configurable:!0}),"i");const we=be((e,t)=>{if(!e.startsWith(`---
1
+ var z=Object.defineProperty;var v=(e,t)=>z(e,"name",{value:t,configurable:!0});import{walkSync as H,readFileSync as k}from"@visulima/fs";import{readYamlSync as X}from"@visulima/fs/yaml";import{relative as M,join as N}from"@visulima/path";import{p as Z,ao as ee}from"./bin.js";import{constantCase as te,trainCase as ne,snakeCase as re,pascalCase as ie,kebabCase as se,camelCase as ae}from"@visulima/string/case";var oe=Object.defineProperty,d=v((e,t)=>oe(e,"name",{value:t,configurable:!0}),"e");const h=d(e=>e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):JSON.stringify(e),"stringify"),S={camel_case:d(e=>ae(h(e)),"camel_case"),kebab_case:d(e=>se(h(e)),"kebab_case"),lower_case:d(e=>h(e).toLowerCase(),"lower_case"),pascal_case:d(e=>ie(h(e)),"pascal_case"),path_join:d((e,...t)=>{const r=[h(e),...t.map(n=>h(n))];return N(...r)},"path_join"),path_relative:d((e,t)=>M(h(t),h(e)),"path_relative"),snake_case:d(e=>re(h(e)),"snake_case"),upper_case:d(e=>h(e).toUpperCase(),"upper_case"),upper_kebab_case:d(e=>ne(h(e)),"upper_kebab_case"),upper_snake_case:d(e=>te(h(e)),"upper_snake_case")};d(e=>Object.hasOwn(S,e),"isKnownFilter");const R=d((e,t,r=[])=>{const n=S[e];if(!n)throw new Error(`Unknown filter "${e}". Known filters: ${Object.keys(S).sort().join(", ")}.`);return n(t,...r)},"applyFilter");var le=Object.defineProperty,I=v((e,t)=>le(e,"name",{value:t,configurable:!0}),"d$1");const L=I(e=>{const t=[];let r=0,n=0,i,s=-1;for(const a of e){if(s+=1,i){a===i&&(i=void 0);continue}if(a==='"'||a==="'"){i=a;continue}a==="("?r+=1:a===")"?r-=1:a===","&&r===0&&(t.push(e.slice(n,s)),n=s+1)}return t.push(e.slice(n)),t},"splitCommaOutsideQuotes"),ce=I(e=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1)},"stripQuotes");var fe=Object.defineProperty,$=v((e,t)=>fe(e,"name",{value:t,configurable:!0}),"s$1");const ue=/\[([^\]]+)\]/g,pe=$(e=>{const t=e.trim(),r=t.indexOf("(");if(r===-1)return{args:[],name:t};if(!t.endsWith(")"))throw new Error(`Filter call "${e}" missing closing ")"`);const n=t.slice(0,r).trim(),i=t.slice(r+1,-1).trim();return i===""?{args:[],name:n}:{args:L(i).map(s=>{const a=s.trim();return ce(a)??a}),name:n}},"parseFilterCall"),me=$(e=>{const t=e.split("|").map(n=>n.trim()),r=t[0]??"";if(!r)throw new Error(`Empty variable name in expression "${e}"`);return{filters:t.slice(1).map(n=>pe(n)),name:r}},"parsePipe"),de=$(e=>e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):JSON.stringify(e),"stringify"),he=$((e,t)=>{const r=e.replaceAll(ue,(n,i)=>{const{filters:s,name:a}=me(i);if(!Object.hasOwn(t,a))throw new Error(`Variable "${a}" used in filename "${e}" but not defined`);let o=t[a];for(const l of s)o=R(l.name,o,l.args);return de(o)});return q(r)},"interpolateFilename"),q=$(e=>e.split("/").map(t=>t.endsWith(".tera")||t.endsWith(".twig")?t.slice(0,-5):t).join("/"),"stripTeraSuffix"),ye=$(e=>e.endsWith(".raw")?e.slice(0,-4):e,"stripRawSuffix"),ge=$(e=>{const t=e.split("/");return(t.at(-1)??"").startsWith("_")?!0:t.slice(0,-1).includes("partials")},"isPartialPath");var be=Object.defineProperty,we=v((e,t)=>be(e,"name",{value:t,configurable:!0}),"i");const ve=we((e,t)=>{if(!e.startsWith(`---
2
2
  `)&&!e.startsWith(`---\r
3
3
  `))return{body:e};const r=e.indexOf(`
4
4
  ---`,3);if(r===-1)return{body:e};let n=r+1+3;e[n]==="\r"&&(n+=1),e[n]===`
5
5
  `&&(n+=1);const i=e.startsWith(`---\r
6
- `)?5:4,s=e.slice(i,r).replaceAll("\r","");let a;try{a=t(s)}catch(o){const l=o instanceof Error?o.message:String(o);throw new Error(`Failed to parse frontmatter YAML: ${l}`)}if(a==null)return{body:e.slice(n)};if(typeof a!="object"||Array.isArray(a))throw new TypeError(`Frontmatter must be a YAML mapping, got ${Array.isArray(a)?"array":typeof a}`);return{body:e.slice(n),frontmatter:a}},"splitFrontmatter");var ve=Object.defineProperty,f=v((e,t)=>ve(e,"name",{value:t,configurable:!0}),"c");const $e=/\{\{-?(.+?)-?\}\}|\{%-?(.+?)-?%\}/gs,U=f(e=>{const t=[];let r=0,n=1;const i=f(s=>{for(const a of s)a===`
7
- `&&(n+=1)},"advanceLine");for(const s of e.matchAll($e)){const a=s.index??0;if(a>r){const c=e.slice(r,a);t.push({line:n,type:"text",value:c}),i(c)}const o=n,l=s[0];l.startsWith("{{")?t.push({line:o,type:"expr",value:(s[1]??"").trim()}):t.push({line:o,type:"stmt",value:(s[2]??"").trim()}),i(l),r=a+l.length}if(r<e.length){const s=e.slice(r);t.push({line:n,type:"text",value:s})}return t},"tokenize"),xe=new Set(["block","endblock","endfilter","endmacro","extends","filter","import","macro","set"]),G=f((e,t)=>{let r=0;const n=f((s,a)=>{throw new Error(`${t}:${s}: ${a}`)},"error"),i=f(s=>{const a=[];for(;r<e.length;){const o=e[r];if(o.type==="text"){a.push({type:"text",value:o.value}),r+=1;continue}if(o.type==="expr"){a.push({expression:o.value,line:o.line,type:"expr"}),r+=1;continue}const l=o.value.split(/\s+/)[0]??"";if(s.includes(l))return a;if(xe.has(l)&&n(o.line,`Tera feature "{% ${l} %}" is not supported. Supported: if/else/endif, for/endfor, include. Rewrite the template to avoid macros, set, extends, block, and import.`),l==="if"){r+=1;const c=o.value.slice(2).trim(),m=i(["else","endif"]);let u;r<e.length&&e[r].type==="stmt"&&e[r].value.split(/\s+/)[0]==="else"&&(r+=1,u=i(["endif"])),(r>=e.length||e[r].type!=="stmt"||e[r].value.split(/\s+/)[0]!=="endif")&&n(o.line,"Unterminated {% if %} — missing {% endif %}"),r+=1,a.push({alternate:u,condition:c,consequent:m,line:o.line,type:"if"});continue}if(l==="for"){r+=1;const c=o.value.slice(3).trim(),m=c.indexOf(" in ");m===-1&&n(o.line,"Malformed {% for %} — expected `for <name> in <collection>`");const u=c.slice(0,m).trim(),g=c.slice(m+4).trim();(!u||!g)&&n(o.line,"Malformed {% for %} — missing binding or collection");const p=i(["endfor"]);(r>=e.length||e[r].type!=="stmt"||e[r].value.split(/\s+/)[0]!=="endfor")&&n(o.line,"Unterminated {% for %} — missing {% endfor %}"),r+=1,a.push({binding:u,body:p,collection:g,line:o.line,type:"for"});continue}if(l==="include"){r+=1;const c=o.value.slice(7).trim(),m=Q(c);m===void 0&&n(o.line,"Malformed {% include %} — expected a quoted partial name"),a.push({line:o.line,name:m,type:"include"});continue}n(o.line,`Unknown tag "{% ${l} %}". Supported: if, for, include.`)}return a},"parseBlock");return i([])},"parse"),Q=f(e=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1)},"stripQuotes"),Ee=f(e=>e==null?"":typeof e=="boolean"||typeof e=="number"?String(e):typeof e=="string"?e:JSON.stringify(e),"stringify"),Oe=f(e=>e==null||e===!1||e===0||e===""?!1:Array.isArray(e)?e.length>0:!0,"isTruthy"),V=f((e,t,r,n,i=!0)=>{const s=e.split(".");if(i&&s.length>0&&!Object.hasOwn(t,s[0]))throw new Error(`${n}:${r}: Variable "${e}" is not defined`);let a=t;for(const o of s){if(a==null)return;if(typeof a!="object")throw new TypeError(`${n}:${r}: Cannot read "${o}" on non-object value`);a=a[o]}return a},"lookupVariable"),ke=f(e=>{const t=[];let r=0,n=0,i;for(let s=0;s<e.length;s+=1){const a=e[s];if(i){a===i&&(i=void 0);continue}if(a==='"'||a==="'"){i=a;continue}a==="("?r+=1:a===")"?r-=1:a==="|"&&r===0&&(t.push(e.slice(n,s)),n=s+1)}return t.push(e.slice(n)),t},"splitFilterPipe"),je=f(e=>{const t=e.trim(),r=t.indexOf("(");if(r===-1)return{args:[],name:t};if(!t.endsWith(")"))throw new Error(`Filter call "${e}" missing closing ")"`);const n=t.slice(0,r).trim(),i=t.slice(r+1,-1).trim();return i?{args:L(i).map(s=>s.trim()),name:n}:{args:[],name:n}},"parseFilterCall"),j=f((e,t,r,n,i=!0)=>{const s=e.trim();if(s==="true")return!0;if(s==="false")return!1;if(s==="null"||s==="none")return null;const a=Q(s);return a!==void 0?a:/^-?\d+(\.\d+)?$/.test(s)?Number(s):V(s,t,r,n,i)},"evaluatePrimary"),B=f((e,t,r,n,i=!0)=>{const s=ke(e),a=s[0].trim();let o=j(a,t,r,n,i);for(let l=1;l<s.length;l+=1){const c=s[l].trim(),{args:m,name:u}=je(c),g=m.map(p=>j(p,t,r,n,i));try{o=I(u,o,g)}catch(p){const w=p instanceof Error?p.message:String(p);throw new Error(`${n}:${r}: ${w}`)}}return o},"evaluateExpression"),D=f((e,t)=>{let r,n=0;for(let i=0;i<=e.length-t.length;i+=1){const s=e[i];if(r){s===r&&(r=void 0);continue}if(s==='"'||s==="'"){r=s;continue}if(s==="("){n+=1;continue}if(s===")"){n-=1;continue}if(n===0&&e.slice(i,i+t.length)===t)return i}return-1},"findOperatorOutsideQuotes"),A=f((e,t)=>{const r=[];let n=0,i=0;for(;i<=e.length-t.length;){const s=D(e.slice(i),t);if(s===-1)break;r.push(e.slice(n,i+s)),i+=s+t.length,n=i}return r.push(e.slice(n)),r},"splitLogical"),x=f((e,t,r,n)=>{const i=e.trim();if(i==="")return!1;if(i.startsWith("(")&&i.endsWith(")")&&Se(i)===i.length-1)return x(i.slice(1,-1),t,r,n);const s=A(i," or ");if(s.length>1)return s.some(o=>x(o,t,r,n));const a=A(i," and ");if(a.length>1)return a.every(o=>x(o,t,r,n));if(i.startsWith("not "))return!x(i.slice(4),t,r,n);for(const o of["==","!="]){const l=D(i,o);if(l!==-1){const c=j(i.slice(0,l),t,n,r,!1),m=j(i.slice(l+o.length),t,n,r,!1),u=c===m;return o==="=="?u:!u}}return Oe(B(i,t,n,r,!1))},"evaluateConditionExpression"),Se=f(e=>{if(e[0]!=="(")return-1;let t=0,r,n=-1;for(const i of e){if(n+=1,r){i===r&&(r=void 0);continue}if(i==='"'||i==="'"){r=i;continue}if(i==="(")t+=1;else if(i===")"&&(t-=1,t===0))return n}return-1},"matchingParen"),E=f((e,t)=>{let r="";for(const n of e){if(n.type==="text"){r+=n.value;continue}if(n.type==="expr"){r+=Ee(B(n.expression,t.scope,n.line,t.filename));continue}if(n.type==="if"){const i=x(n.condition,t.scope,t.filename,n.line)?n.consequent:n.alternate??[];r+=E(i,t);continue}if(n.type==="for"){const i=V(n.collection,t.scope,n.line,t.filename,!1);if(i==null)continue;if(!Array.isArray(i))throw new TypeError(`${t.filename}:${n.line}: {% for %} expected an array, got ${typeof i}`);for(const s of i){const a={...t.scope,[n.binding]:s};r+=E(n.body,{...t,scope:a})}continue}if(n.type==="include"){const i=t.partials?.get(n.name);if(!i)throw new Error(`${t.filename}:${n.line}: Partial "${n.name}" not found. Available: ${[...t.partials?.keys()??[]].join(", ")||"(none)"}`);const s=t.includeStack??new Set;if(s.has(n.name)){const a=[...s,n.name].join(" → ");throw new Error(`${t.filename}:${n.line}: Circular partial include detected: ${a}`)}s.add(n.name);try{r+=E(i,{...t,filename:`<partial:${n.name}>`,includeStack:s})}finally{s.delete(n.name)}}}return r},"renderNodes"),_e=f((e,t)=>G(U(e),t),"parseTemplate");f((e,t)=>E(e,t),"renderAst");const _=f((e,t)=>E(G(U(e),t.filename),t),"renderTemplate");var Ce=Object.defineProperty,y=v((e,t)=>Ce(e,"name",{value:t,configurable:!0}),"s");const P="template.yml",Te=".raw",We=new Set([".cjs",".css",".env",".gitattributes",".gitignore",".graphql",".html",".ini",".js",".json",".json5",".jsonc",".jsx",".lock",".md",".mdx",".mjs",".prettierrc",".raw",".rs",".scss",".sh",".sql",".svg",".tera",".toml",".ts",".tsx",".twig",".txt",".vue",".xml",".yaml",".yml"]),Ae=new Set(["Brewfile","CHANGELOG","CODEOWNERS","CONTRIBUTING","COPYING","Dockerfile","Gemfile","LICENCE","LICENSE","Makefile","NOTICE","Procfile","Rakefile","README","VERSION"]),Pe=y(e=>{const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),r=t===-1?e:e.slice(t+1),n=r.lastIndexOf(".");return n===-1||n===0?"":r.slice(n).toLowerCase()},"lastDot"),Y=y(e=>{const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)},"basename"),Fe=y(e=>{const t=Pe(e);if(t!=="")return We.has(t);const r=Y(e);return!!Ae.has(r)},"isLikelyText"),Me=y(e=>{const t={default:e.default,internal:e.internal,order:e.order,prompt:e.prompt,required:e.required};switch(e.type){case"array":return{...t,type:"array"};case"boolean":return{...t,default:typeof t.default=="boolean"?t.default:void 0,type:"boolean"};case"enum":return{...t,multiple:e.multiple,type:"enum",values:e.values??[]};case"number":return{...t,type:"number"};case"string":return{...t,type:"string"};default:throw new Error(`Unsupported variable type "${String(e.type)}"`)}},"yamlVariableToVariable"),Re=y(e=>e.replaceAll("\\","/").replace(/^\.\//,"").replaceAll(/\/+/g,"/"),"normalizeDestinationPath"),Ie=y((e,t,r)=>{const n=t.split("/").filter(Boolean);if(n.length===0)throw new Error("Empty destination path for value");let i=e;for(let s=0;s<n.length-1;s+=1){const a=n[s],o=i[a];if(o===void 0){const l={};i[a]=l,i=l}else if(typeof o=="object"&&!Buffer.isBuffer(o))i=o;else throw new TypeError(`Path conflict: "${n.slice(0,s+1).join("/")}" is both a file and a directory`)}i[n.at(-1)]=r},"flattenFiles"),F=y((e,t,r)=>{if(typeof e!="string")return Ne(e);const n=e.includes("{{")||e.includes("{%")?_(e,{filename:`${r}#frontmatter`,scope:t}):e;return x(n,t,`${r}#frontmatter`,1)},"evaluateGate"),Ne=y(e=>e==null||e===!1||e===0||e===""?!1:Array.isArray(e)?e.length>0:typeof e=="string"?e!=="false"&&e!=="0":!0,"truthyValue"),De=y((e,t)=>{const r=R(e,P),n=X(r);if(!n||typeof n!="object")throw new Error(`${r}: must contain a YAML mapping`);const i={};if(n.variables)for(const[l,c]of Object.entries(n.variables))i[l]=Me(c);const s=new Map,a=[];for(const l of J(e,{includeDirs:!1,includeSymlinks:!1})){if(l.path===r)continue;const c=M(e,l.path).replaceAll("\\","/");if(c===P)continue;if(ye(c)){const u=k(l.path),g=_e(u,c);for(const p of Le(c))s.has(p)&&s.get(p)!==g&&console.warn(`warn: partial name "${p}" is declared by multiple files — last one wins. Use distinct names or fully-qualified includes.`),s.set(p,g);continue}if(c.endsWith(Te)){const u=k(l.path);a.push({binary:null,isRaw:!0,rawText:u,relativePath:c});continue}if(Fe(c)){const u=k(l.path);a.push({binary:null,isRaw:!1,rawText:u,relativePath:c});continue}const m=k(l.path,{buffer:!0});a.push({binary:m,isRaw:!1,rawText:null,relativePath:c})}const o=y(l=>{const c={...l.builtins,...l.options},m={},u={};for(const p of a){const w=p.relativePath;let O,C,T=!1;if(p.binary)O=p.binary;else if(p.isRaw)O=p.rawText??"";else{const K=p.rawText??"",b=we(K,z=>Z(z));if(b.frontmatter){if(b.frontmatter.skip!==void 0&&F(b.frontmatter.skip,c,w)||b.frontmatter.if!==void 0&&!F(b.frontmatter.if,c,w))continue;typeof b.frontmatter.to=="string"&&(C=_(b.frontmatter.to,{filename:`${w}#frontmatter.to`,partials:s,scope:c})),b.frontmatter.force===!0&&(T=!0)}O=_(b.body,{filename:w,partials:s,scope:c})}const W=Re(C??de(he(w),c));Ie(m,W,O),T&&(u[W]={force:!0})}const g={files:m};return Object.keys(u).length>0&&(g.filesMeta=u),g},"produce");return{about:{description:n.description??`Moon-format template at ${e}`,name:n.title??t},destination:n.destination,options:i,produce:o}},"loadMoonTemplate"),Le=y(e=>{const t=q(e),r=new Set;r.add(t);const n=Y(t);if(r.add(n),n.startsWith("_")){r.add(n.replace(/^_+/,""));const i=t.slice(0,t.length-n.length);r.add(`${i}${n.replace(/^_+/,"")}`)}return[...r]},"partialKeys");export{De as loadMoonTemplate};
6
+ `)?5:4,s=e.slice(i,r).replaceAll("\r","");let a;try{a=t(s)}catch(o){const l=o instanceof Error?o.message:String(o);throw new Error(`Failed to parse frontmatter YAML: ${l}`,{cause:o})}if(a==null)return{body:e.slice(n)};if(typeof a!="object"||Array.isArray(a))throw new TypeError(`Frontmatter must be a YAML mapping, got ${Array.isArray(a)?"array":typeof a}`);return{body:e.slice(n),frontmatter:a}},"splitFrontmatter");var $e=Object.defineProperty,f=v((e,t)=>$e(e,"name",{value:t,configurable:!0}),"c");const xe=/\{\{-?(.+?)-?\}\}|\{%-?(.+?)-?%\}/gs,U=f(e=>{const t=[];let r=0,n=1;const i=f(s=>{for(const a of s)a===`
7
+ `&&(n+=1)},"advanceLine");for(const s of e.matchAll(xe)){const a=s.index??0;if(a>r){const c=e.slice(r,a);t.push({line:n,type:"text",value:c}),i(c)}const o=n,l=s[0];l.startsWith("{{")?t.push({line:o,type:"expr",value:(s[1]??"").trim()}):t.push({line:o,type:"stmt",value:(s[2]??"").trim()}),i(l),r=a+l.length}if(r<e.length){const s=e.slice(r);t.push({line:n,type:"text",value:s})}return t},"tokenize"),Ee=new Set(["block","endblock","endfilter","endmacro","extends","filter","import","macro","set"]),Q=f((e,t)=>{let r=0;const n=f((s,a)=>{throw new Error(`${t}:${s}: ${a}`)},"error"),i=f(s=>{const a=[];for(;r<e.length;){const o=e[r];if(o.type==="text"){a.push({type:"text",value:o.value}),r+=1;continue}if(o.type==="expr"){a.push({expression:o.value,line:o.line,type:"expr"}),r+=1;continue}const l=o.value.split(/\s+/)[0]??"";if(s.includes(l))return a;if(Ee.has(l)&&n(o.line,`Tera feature "{% ${l} %}" is not supported. Supported: if/else/endif, for/endfor, include. Rewrite the template to avoid macros, set, extends, block, and import.`),l==="if"){r+=1;const c=o.value.slice(2).trim(),m=i(["else","endif"]);let u;r<e.length&&e[r].type==="stmt"&&e[r].value.split(/\s+/)[0]==="else"&&(r+=1,u=i(["endif"])),(r>=e.length||e[r].type!=="stmt"||e[r].value.split(/\s+/)[0]!=="endif")&&n(o.line,"Unterminated {% if %} — missing {% endif %}"),r+=1,a.push({alternate:u,condition:c,consequent:m,line:o.line,type:"if"});continue}if(l==="for"){r+=1;const c=o.value.slice(3).trim(),m=c.indexOf(" in ");m===-1&&n(o.line,"Malformed {% for %} — expected `for <name> in <collection>`");const u=c.slice(0,m).trim(),g=c.slice(m+4).trim();(!u||!g)&&n(o.line,"Malformed {% for %} — missing binding or collection");const p=i(["endfor"]);(r>=e.length||e[r].type!=="stmt"||e[r].value.split(/\s+/)[0]!=="endfor")&&n(o.line,"Unterminated {% for %} — missing {% endfor %}"),r+=1,a.push({binding:u,body:p,collection:g,line:o.line,type:"for"});continue}if(l==="include"){r+=1;const c=o.value.slice(7).trim(),m=G(c);m===void 0&&n(o.line,"Malformed {% include %} — expected a quoted partial name"),a.push({line:o.line,name:m,type:"include"});continue}n(o.line,`Unknown tag "{% ${l} %}". Supported: if, for, include.`)}return a},"parseBlock");return i([])},"parse"),G=f(e=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1)},"stripQuotes"),Oe=f(e=>e==null?"":typeof e=="boolean"||typeof e=="number"?String(e):typeof e=="string"?e:JSON.stringify(e),"stringify"),ke=f(e=>e==null||e===!1||e===0||e===""?!1:Array.isArray(e)?e.length>0:!0,"isTruthy"),V=f((e,t,r,n,i=!0)=>{const s=e.split(".");if(i&&s.length>0&&!Object.hasOwn(t,s[0]))throw new Error(`${n}:${r}: Variable "${e}" is not defined`);let a=t;for(const o of s){if(a==null)return;if(typeof a!="object")throw new TypeError(`${n}:${r}: Cannot read "${o}" on non-object value`);a=a[o]}return a},"lookupVariable"),je=f(e=>{const t=[];let r=0,n=0,i;for(let s=0;s<e.length;s+=1){const a=e[s];if(i){a===i&&(i=void 0);continue}if(a==='"'||a==="'"){i=a;continue}a==="("?r+=1:a===")"?r-=1:a==="|"&&r===0&&(t.push(e.slice(n,s)),n=s+1)}return t.push(e.slice(n)),t},"splitFilterPipe"),Se=f(e=>{const t=e.trim(),r=t.indexOf("(");if(r===-1)return{args:[],name:t};if(!t.endsWith(")"))throw new Error(`Filter call "${e}" missing closing ")"`);const n=t.slice(0,r).trim(),i=t.slice(r+1,-1).trim();return i?{args:L(i).map(s=>s.trim()),name:n}:{args:[],name:n}},"parseFilterCall"),j=f((e,t,r,n,i=!0)=>{const s=e.trim();if(s==="true")return!0;if(s==="false")return!1;if(s==="null"||s==="none")return null;const a=G(s);return a!==void 0?a:/^-?\d+(?:\.\d+)?$/.test(s)?Number(s):V(s,t,r,n,i)},"evaluatePrimary"),B=f((e,t,r,n,i=!0)=>{const s=je(e),a=s[0].trim();let o=j(a,t,r,n,i);for(let l=1;l<s.length;l+=1){const c=s[l].trim(),{args:m,name:u}=Se(c),g=m.map(p=>j(p,t,r,n,i));try{o=R(u,o,g)}catch(p){const w=p instanceof Error?p.message:String(p);throw new Error(`${n}:${r}: ${w}`,{cause:p})}}return o},"evaluateExpression"),D=f((e,t)=>{let r,n=0;for(let i=0;i<=e.length-t.length;i+=1){const s=e[i];if(r){s===r&&(r=void 0);continue}if(s==='"'||s==="'"){r=s;continue}if(s==="("){n+=1;continue}if(s===")"){n-=1;continue}if(n===0&&e.slice(i,i+t.length)===t)return i}return-1},"findOperatorOutsideQuotes"),A=f((e,t)=>{const r=[];let n=0,i=0;for(;i<=e.length-t.length;){const s=D(e.slice(i),t);if(s===-1)break;r.push(e.slice(n,i+s)),i+=s+t.length,n=i}return r.push(e.slice(n)),r},"splitLogical"),x=f((e,t,r,n)=>{const i=e.trim();if(i==="")return!1;if(i.startsWith("(")&&i.endsWith(")")&&Ce(i)===i.length-1)return x(i.slice(1,-1),t,r,n);const s=A(i," or ");if(s.length>1)return s.some(o=>x(o,t,r,n));const a=A(i," and ");if(a.length>1)return a.every(o=>x(o,t,r,n));if(i.startsWith("not "))return!x(i.slice(4),t,r,n);for(const o of["==","!="]){const l=D(i,o);if(l!==-1){const c=j(i.slice(0,l),t,n,r,!1),m=j(i.slice(l+o.length),t,n,r,!1),u=c===m;return o==="=="?u:!u}}return ke(B(i,t,n,r,!1))},"evaluateConditionExpression"),Ce=f(e=>{if(e[0]!=="(")return-1;let t=0,r,n=-1;for(const i of e){if(n+=1,r){i===r&&(r=void 0);continue}if(i==='"'||i==="'"){r=i;continue}if(i==="(")t+=1;else if(i===")"&&(t-=1,t===0))return n}return-1},"matchingParen"),E=f((e,t)=>{let r="";for(const n of e){if(n.type==="text"){r+=n.value;continue}if(n.type==="expr"){r+=Oe(B(n.expression,t.scope,n.line,t.filename));continue}if(n.type==="if"){const i=x(n.condition,t.scope,t.filename,n.line)?n.consequent:n.alternate??[];r+=E(i,t);continue}if(n.type==="for"){const i=V(n.collection,t.scope,n.line,t.filename,!1);if(i==null)continue;if(!Array.isArray(i))throw new TypeError(`${t.filename}:${n.line}: {% for %} expected an array, got ${typeof i}`);for(const s of i){const a={...t.scope,[n.binding]:s};r+=E(n.body,{...t,scope:a})}continue}if(n.type==="include"){const i=t.partials?.get(n.name);if(!i)throw new Error(`${t.filename}:${n.line}: Partial "${n.name}" not found. Available: ${[...t.partials?.keys()??[]].join(", ")||"(none)"}`);const s=t.includeStack??new Set;if(s.has(n.name)){const a=[...s,n.name].join(" → ");throw new Error(`${t.filename}:${n.line}: Circular partial include detected: ${a}`)}s.add(n.name);try{r+=E(i,{...t,filename:`<partial:${n.name}>`,includeStack:s})}finally{s.delete(n.name)}}}return r},"renderNodes"),_e=f((e,t)=>Q(U(e),t),"parseTemplate");f((e,t)=>E(e,t),"renderAst");const C=f((e,t)=>E(Q(U(e),t.filename),t),"renderTemplate");var Te=Object.defineProperty,y=v((e,t)=>Te(e,"name",{value:t,configurable:!0}),"s");const P="template.yml",We=".raw",Ae=new Set([".cjs",".css",".env",".gitattributes",".gitignore",".graphql",".html",".ini",".js",".json",".json5",".jsonc",".jsx",".lock",".md",".mdx",".mjs",".prettierrc",".raw",".rs",".scss",".sh",".sql",".svg",".tera",".toml",".ts",".tsx",".twig",".txt",".vue",".xml",".yaml",".yml"]),Pe=new Set(["Brewfile","CHANGELOG","CODEOWNERS","CONTRIBUTING","COPYING","Dockerfile","Gemfile","LICENCE","LICENSE","Makefile","NOTICE","Procfile","Rakefile","README","VERSION"]),Fe=y(e=>{const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),r=t===-1?e:e.slice(t+1),n=r.lastIndexOf(".");return n===-1||n===0?"":r.slice(n).toLowerCase()},"lastDot"),Y=y(e=>{const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)},"basename"),Me=y(e=>{const t=Fe(e);if(t!=="")return Ae.has(t);const r=Y(e);return Pe.has(r)},"isLikelyText"),Ne=y(e=>{const t={default:e.default,internal:e.internal,order:e.order,prompt:e.prompt,required:e.required};switch(e.type){case"array":return{...t,type:"array"};case"boolean":return{...t,default:typeof t.default=="boolean"?t.default:void 0,type:"boolean"};case"enum":return{...t,multiple:e.multiple,type:"enum",values:e.values??[]};case"number":return{...t,type:"number"};case"string":return{...t,type:"string"};default:throw new Error(`Unsupported variable type "${String(e.type)}"`)}},"yamlVariableToVariable"),Re=y(e=>e.replaceAll("\\","/").replace(/^\.\//,"").replaceAll(/\/+/g,"/"),"normalizeDestinationPath"),Ie=y((e,t,r)=>{const n=t.split("/").filter(Boolean);if(n.length===0)throw new Error("Empty destination path for value");let i=e;for(let s=0;s<n.length-1;s+=1){const a=n[s],o=i[a];if(o===void 0){const l={};i[a]=l,i=l}else if(typeof o=="object"&&!Buffer.isBuffer(o))i=o;else throw new TypeError(`Path conflict: "${n.slice(0,s+1).join("/")}" is both a file and a directory`)}i[n.at(-1)]=r},"flattenFiles"),F=y((e,t,r)=>{if(typeof e!="string")return Le(e);const n=e.includes("{{")||e.includes("{%")?C(e,{filename:`${r}#frontmatter`,scope:t}):e;return x(n,t,`${r}#frontmatter`,1)},"evaluateGate"),Le=y(e=>e==null||e===!1||e===0||e===""?!1:Array.isArray(e)?e.length>0:typeof e=="string"?e!=="false"&&e!=="0":!0,"truthyValue"),Ye=y((e,t)=>{const r=N(e,P),n=X(r);if(!n||typeof n!="object")throw new Error(`${r}: must contain a YAML mapping`);const i={};if(n.variables)for(const[l,c]of Object.entries(n.variables))i[l]=Ne(c);const s=new Map,a=[];for(const l of H(e,{includeDirs:!1,includeSymlinks:!1})){if(l.path===r)continue;const c=M(e,l.path).replaceAll("\\","/");if(c===P)continue;if(ge(c)){const u=k(l.path),g=_e(u,c);for(const p of qe(c))s.has(p)&&s.get(p)!==g&&Z.warn(`partial name "${p}" is declared by multiple files — last one wins. Use distinct names or fully-qualified includes.`),s.set(p,g);continue}if(c.endsWith(We)){const u=k(l.path);a.push({binary:null,isRaw:!0,rawText:u,relativePath:c});continue}if(Me(c)){const u=k(l.path);a.push({binary:null,isRaw:!1,rawText:u,relativePath:c});continue}const m=k(l.path,{buffer:!0});a.push({binary:m,isRaw:!1,rawText:null,relativePath:c})}const o=y(l=>{const c={...l.builtins,...l.options},m={},u={};for(const p of a){const w=p.relativePath;let O,_,T=!1;if(p.binary)O=p.binary;else if(p.isRaw)O=p.rawText??"";else{const J=p.rawText??"",b=ve(J,K=>ee(K));if(b.frontmatter){if(b.frontmatter.skip!==void 0&&F(b.frontmatter.skip,c,w)||b.frontmatter.if!==void 0&&!F(b.frontmatter.if,c,w))continue;typeof b.frontmatter.to=="string"&&(_=C(b.frontmatter.to,{filename:`${w}#frontmatter.to`,partials:s,scope:c})),b.frontmatter.force===!0&&(T=!0)}O=C(b.body,{filename:w,partials:s,scope:c})}const W=Re(_??he(ye(w),c));Ie(m,W,O),T&&(u[W]={force:!0})}const g={files:m};return Object.keys(u).length>0&&(g.filesMeta=u),g},"produce");return{about:{description:n.description??`Moon-format template at ${e}`,name:n.title??t},destination:n.destination,options:i,produce:o}},"loadMoonTemplate"),qe=y(e=>{const t=q(e),r=Y(t),n=new Set([r,t]);if(r.startsWith("_")){n.add(r.replace(/^_+/,""));const i=t.slice(0,t.length-r.length);n.add(`${i}${r.replace(/^_+/,"")}`)}return[...n]},"partialKeys");export{Ye as loadMoonTemplate};