epiq 1.8.5 → 1.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +4185 -2418
- package/dist/index.js +89 -85
- package/dist/mcp.js +80 -76
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,102 +1,106 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),u("Created project.json",null)}catch(o){return
|
|
4
|
-
`);return i===-1?"":s.slice(i+1)}finally{
|
|
5
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
2
|
+
import Wt from"chalk";import{render as qN}from"ink";import YN from"meow";import XN from"react";import oy from"chalk";import tv from"node:crypto";var Tn={Success:"success",Fail:"fail"},l=e=>({status:Tn.Fail,message:e,value:null}),u=(e,t)=>({status:Tn.Success,message:e,value:t}),a=e=>e.status==="fail",me=e=>e.status==="success";var cn="EPIQ_USER_NAME",Ts="EPIQ_USER_ID",Uc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",nv=26,Da=80,Ba=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),ws=e=>e.trim().length>0&&e.length<=Da,Pr=e=>e.trim().toLowerCase(),rv=e=>{let t=tv.createHash("sha256").update(`epiq:actor:${Pr(e)}`).digest(),n="";for(let r=0;r<nv;r++)n+=Uc[(t[r]??0)%Uc.length];return n},Lr=(e,t=process.env)=>{let n=(t[cn]??"").trim(),r=(t[Ts]??"").trim();return n?ws(n)?!r&&e.userId&&e.userName&&Pr(e.userName)===Pr(n)?u("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!Ba(r)?l(`${Ts} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?l(`${Ts} is the configured user's own id; using it under a different name would rename them on the board`):u("Resolved actor from environment",{userId:r||rv(n),userName:r?n:Pr(n)}):l(`${cn} must be 1-${Da} characters of text`):r?l(`${Ts} is set without ${cn}`):u("No actor override",null)},Fa=(e,t,n=process.env)=>{let r=e.trim();if(!ws(r))return l(`${t} must be 1-${Da} characters of text`);let o=(n[cn]??"").trim();return o&&Pr(o)!==Pr(r)?l(`${t} names ${r}, but ${cn} names ${o}`):(o||(n[cn]=r),u("Applied actor name argument",o||r))};import _v from"node:path";import{z as hn}from"zod";import Ro from"node:fs";import Vt from"node:path";import wn from"node:fs";import lt from"node:path";import yo from"node:fs";import{ulid as ov}from"ulid";import{z as Ms}from"zod";var sv="__epiq_state__",iv=Ms.object({projectId:Ms.string().min(1),stateBranch:Ms.string().min(1),createdAt:Ms.iso.datetime()}),Ps=()=>({projectId:ov(),stateBranch:sv,createdAt:new Date().toISOString()}),pt=e=>{let t=kr(e);if(!yo.existsSync(t))return l("Missing .epiq/project.json");try{let n=yo.readFileSync(t,"utf8"),r=JSON.parse(n),o=iv.safeParse(r);return o.success?u("Read project.json",o.data):l(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return l(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},vo=e=>{let t=pt(e);return a(t)?l(t.message):u("Read projectId",t.value.projectId)},Oa=({repoRoot:e,fileContents:t})=>{let n=or(e),r=kr(e);try{if(yo.mkdirSync(n,{recursive:!0}),yo.existsSync(r)){let o=pt(e);return a(o)?l(o.message):u("Project already initialized",null)}return yo.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),u("Created project.json",null)}catch(o){return l(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import av from"node:os";import lv from"node:path";var Pt=".epiq-global",un=()=>process.env.EPIQ_GLOBAL_DIR??lv.join(av.homedir(),Pt);var _a=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let d=e(...s).then(c=>(a(c)&&n.delete(i),c));n.set(i,d)}return n.get(i)});return o.clear=()=>n.clear(),o};import Lt from"fs";import Wa from"path";import dv from"util";var jc=500,Ga=4*1024*1024,Ua=16*1024,cv=50,ja=0,$c=()=>process.env.EPIQ_MCP==="true",uv=()=>{let e=process.cwd(),t=Ls(e);return a(t)?$c()?Wa.join(un(),"epiq-mcp.log"):void 0:Wa.join(t.value,rt,"log","epiq.log")},mv=(e,t)=>{let n=Lt.statSync(e).size;if(n<=t)return Lt.readFileSync(e,"utf8");let r=Lt.openSync(e,"r");try{let o=Buffer.alloc(t);Lt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
4
|
+
`);return i===-1?"":s.slice(i+1)}finally{Lt.closeSync(r)}};function pv(e){if(!Lt.existsSync(e))return;let t=Lt.statSync(e).size,n=mv(e,Ga).split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Ga&&n.length<=jc)return;let r=n.slice(-jc).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;
|
|
8
|
-
`;try{
|
|
9
|
-
`);c(n?{stdout:i,stderr:f,exitCode:124}:
|
|
10
|
-
`)))}),o.on("close",f=>{let g=f??1;if(n){c({stdout:i,stderr:
|
|
11
|
-
`)));return}c(u("Git command succeeded",{stdout:i,stderr:
|
|
12
|
-
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let v of e){let
|
|
7
|
+
`;Lt.writeFileSync(e,r,"utf8")}var fv=e=>{if(e.length<=Ua)return e;let t=e.length-Ua;return`${e.slice(0,Ua)} \u2026 [${t} more chars]`};function $a(e,t,n=!1){let r=uv();if(!r)return;let o=fv(dv.format(...t)),s=new Date,d=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
8
|
+
`;try{Lt.mkdirSync(Wa.dirname(r),{recursive:!0}),Lt.appendFileSync(r,d,"utf8"),ja++,(ja>=cv||Lt.statSync(r).size>Ga)&&(ja=0,pv(r))}catch{}}var Ha=()=>$c()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",z={info(...e){let t=Ha();(t==="info"||t==="debug")&&$a("[Info]",e,!1)},debug(...e){Ha()==="debug"&&$a("[Debug]",e,!0)},error(...e){let t=Ha();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;$a("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=z;import{spawn as Wc}from"node:child_process";import mn from"node:fs";import pn from"node:path";var pe={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>U({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>U({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>U({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>U({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>U({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return U({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>U({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>U({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>U({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>U({args:["worktree","prune"],cwd:e})};var Gt=e=>{let t=Se(e);if(a(t))return l("Unable to resolve epiq project root");let n=pt(t.value);return a(n)?l("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},ft="origin";var Va=1e4,gv=12e4,hv=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),yv=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&hv.has(t)?gv:Va},vv=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(pn.delimiter))if(t)for(let n of e){let r=pn.join(t,n);try{if(!mn.statSync(r).isFile())continue;return mn.accessSync(r,mn.constants.X_OK),r}catch{continue}}return"git"},Gc=vv(),Vc={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},zc=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!mn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(l(f));return}let o=Wc(Gc,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Vc}),s=!1,i="",d="",c=f=>{s||(s=!0,clearTimeout(p),r(f))},m=yv(e),p=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
9
|
+
`);c(n?{stdout:i,stderr:f,exitCode:124}:l(f))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{i+=f}),o.stderr.on("data",f=>{d+=f}),o.on("error",f=>{if(n){c({stdout:i,stderr:f.message,exitCode:1});return}c(l([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
10
|
+
`)))}),o.on("close",f=>{let g=f??1;if(n){c({stdout:i,stderr:d,exitCode:g});return}if(g!==0){c(l([`git ${e.join(" ")}`,d.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
11
|
+
`)));return}c(u("Git command succeeded",{stdout:i,stderr:d,exitCode:g}))})}),U=({args:e,cwd:t})=>zc({args:e,cwd:t,allowFail:!1}),He=({args:e,cwd:t})=>zc({args:e,cwd:t,allowFail:!0}),ks=(e,t)=>new Promise(n=>{if(e.length===0){n(u("No blobs to read",new Map));return}let r=Wc(Gc,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Vc}),o=[],s="",i=!1,d=m=>{i||(i=!0,clearTimeout(c),n(m))},c=setTimeout(()=>{r.kill("SIGTERM"),d(l(`git cat-file --batch timed out after ${Va}ms`))},Va);r.stdout.on("data",m=>o.push(m)),r.stderr.setEncoding("utf8"),r.stderr.on("data",m=>{s+=m}),r.on("error",m=>d(l(m.message))),r.on("close",m=>{if(m!==0){d(l(`git cat-file --batch exited ${m}${s?`
|
|
12
|
+
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let v of e){let I=p.indexOf(10,g);if(I===-1){d(l(`git cat-file --batch output ended before a header for ${v}`));return}let x=p.toString("utf8",g,I);g=I+1;let C=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(x);if(!C||!C[1]){d(l(`Unexpected git cat-file --batch header: "${x}"`));return}let A=Number(C[1]);f.set(v,p.toString("utf8",g,g+A)),g+=A+1}d(u("Read blobs",f))}),r.stdin.write(e.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`),r.stdin.end()}),
|
|
15
|
-
${r.message}`);let o=await
|
|
16
|
-
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},
|
|
17
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
18
|
-
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},
|
|
19
|
-
${o.message}`);let s=await
|
|
20
|
-
${s.message}`);let i=await
|
|
21
|
-
`+r.message);let o=
|
|
22
|
-
`+o.message):u("Ensured epiq storage",n)},
|
|
23
|
-
`,
|
|
24
|
-
|
|
14
|
+
`),r.stdin.end()}),Br=async({cwd:e,message:t,pathspec:n})=>{let r=await pe.commit({cwd:e,message:t,pathspec:n});if(a(r))return l(`Failed to create commit
|
|
15
|
+
${r.message}`);let o=await U({args:["rev-parse","HEAD"],cwd:e});return a(o)?l(`Commit created, but failed to read HEAD SHA
|
|
16
|
+
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},za=async e=>{let t=await U({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return l(t.message);let n=t.value.stdout.trim();return u("Resolved git dir",pn.isAbsolute(n)?n:pn.resolve(e,n))},bv=async e=>{let t=await za(e);if(a(t))return l(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(mn.existsSync(pn.join(n,s)))return u("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(mn.existsSync(pn.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},Ds=async e=>{let t=await bv(e);return a(t)?l(t.message):u("Checked for in-progress Git operation",t.value!==null)},fn=async({repoRoot:e})=>{let n=(await He({args:["remote","get-url",ft],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},bo=async({repoRoot:e,branch:t})=>{let n=await He({args:["ls-remote","--heads",ft,t],cwd:e});return n.exitCode!==0?l(n.stderr.trim()||`Unable to inspect remote branch ${ft}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},Bs=async({repoRoot:e,branch:t})=>{let n=await He({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?u("Local branch exists",!0):n.exitCode===1?u("Local branch missing",!1):l(n.stderr.trim()||`Unable to inspect branch ${t}`)},Dr=e=>{try{return mn.realpathSync.native(e)}catch{return pn.resolve(e)}},Kc=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return l(n.message);let r=Dr(t),o=n.value.stdout.split(`
|
|
17
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Dr).includes(r);return u("Checked worktree registration",o)},Ka=async e=>{let t=await He({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Fs=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?l(t.message):u("Resolved current branch",t.value.stdout.trim())},qc=async e=>{let t=await U({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?l(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},Yc=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Xc=async e=>{let t=await He({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?mn.existsSync(pn.join(n,"rebase-merge"))||mn.existsSync(pn.join(n,"rebase-apply")):!1},xv=3,Iv=120,Sv=e=>new Promise(t=>setTimeout(t,e)),Ev=async(e,t)=>{let n=await pe.rebaseOnto({cwd:e,ref:t});for(let r=1;r<xv;r+=1){if(!a(n)||await Xc(e))return n;await Sv(Iv),n=await pe.rebaseOnto({cwd:e,ref:t})}return n},Rv=async e=>{if(!await Xc(e))return u("No rebase to abort",!1);let t=await He({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?l(`Failed to abort the rebase in progress at ${e}
|
|
18
|
+
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},Hc=async e=>{let t=await He({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},xo=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),Cv=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Io=async({cwd:e,branch:t})=>{let n=await Rv(e);if(a(n))return l(n.message);let r=await Hc(e),o=await pe.fetch({cwd:e,remote:ft,branch:t});if(a(o))return Cv(o.message)?u("Remote branch missing, skipped pull",!1):l(`Failed to fetch ${t}
|
|
19
|
+
${o.message}`);let s=await Ev(e,`${ft}/${t}`);if(a(s))return l(`Failed during rebase
|
|
20
|
+
${s.message}`);let i=await Hc(e),d=r!==null&&i!==null&&r!==i;return u(d?"Pulled with rebase":"Already up to date",d)},Jc=async e=>{let t=await He({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?u("No upstream to compare against",!1):u("Compared against upstream",Number(t.stdout.trim())>0)},Qc=async e=>{let t=await He({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?l(t.stderr.trim()||"Unable to inspect the worktree for changes"):u("Inspected worktree for changes",t.stdout.trim().length>0)},Zc=async(e,t)=>{let n=await He({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?u("No staged changes",!1):n.exitCode===1?u("Has staged changes",!0):l(n.stderr.trim()||"Unable to inspect staged changes")};var eu=async e=>{let t=await Fs(e);return a(t)?l(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var ru="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ou=e=>lt.join(rt,gn,e),su=()=>lt.join(rt,Xa),iu=un,sr=()=>lt.join(iu(),"worktrees"),fe=({repoRoot:e})=>{let t=vo(e);return a(t)?l(t.message):u("Resolved state branch root",lt.join(sr(),t.value))},Nv=e=>lt.join(e,rt),tu=e=>lt.join(Nv(e),gn);var So=e=>{try{return wn.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return l(t instanceof Error?t.message:String(t))}},Eo=()=>{let e=iu(),t=sr(),n=!wn.existsSync(e)||!wn.existsSync(t),r=So(e);if(a(r))return l(`Ensure epiq home failed.
|
|
21
|
+
`+r.message);let o=So(t);return a(o)?l(`Ensure worktrees dir failed.
|
|
22
|
+
`+o.message):u("Ensured epiq storage",n)},au=e=>{wn.existsSync(e)&&(z.debug("[sync] remove path",e),wn.rmSync(e,{recursive:!0,force:!0}))};var Av=`*.jsonl merge=union
|
|
23
|
+
`,Tv=`*~pending*.jsonl
|
|
24
|
+
`,qa=()=>lt.join(rt,gn,".gitattributes"),Ya=()=>lt.join(rt,gn,".gitignore"),nu=(e,t)=>{try{wn.readFileSync(e,"utf8")!==t&&wn.writeFileSync(e,t)}catch{wn.writeFileSync(e,t)}},lu=(e,t)=>{for(let n of[tu(e),tu(t)]){let r=So(n);if(a(r))return l(r.message)}return nu(lt.join(t,qa()),Av),nu(lt.join(t,Ya()),Tv),u("Ensured state branch",void 0)},du=async e=>{let t=await U({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return l(`ensure state branch is storage only failed
|
|
25
25
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
26
|
-
`).filter(Boolean).filter(i=>i!==
|
|
27
|
-
${o.message}`);let s=await
|
|
28
|
-
`),u("Config written",null)}catch{return a(`Unable to write ~/${At}/config.json`)}},gt=e=>{let t=Cr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return iu(n)},ht=()=>{let e=za(),t=Ka();if(d(t))return a(`Unable to create ~/${At}`);if(!($e.readFile(e)!==null)){let x=iu(Cv);if(d(x))throw new Error(`Unable to create ~/${At}/config.json`)}let r=Cr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:l,autoSyncDebounceMs:c,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,g=Ir({userId:i,userName:s});if(d(g))return a(g.message);let v=g.value??{userId:i,userName:s};return!v.userName||!v.userId?a(`User name or ID not configured in ~/${At}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:v.userName,userId:v.userId,autoSync:l??!1,autoSyncIntervalMs:c??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as Av}from"react";var fo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},qa=new Set,Tv=()=>{for(let e of qa)e()},ie=()=>fo,au=()=>Av(e=>(qa.add(e),()=>{qa.delete(e)}),()=>fo),ze=e=>(fo={...fo,...e},Tv(),fo);import{spawn as wv}from"node:child_process";import Ya from"node:process";var Xa=e=>{let t=Ya.platform==="darwin"?"open":Ya.platform==="win32"?"cmd":"xdg-open",n=Ya.platform==="win32"?["/c","start","",e]:[e];wv(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as $h}from"node:fs/promises";import Hn from"chalk";import Cg from"string-width";import{decodeTime as du}from"ulid";var Ls=1440*60*1e3,go=(e,t=Date.now())=>e>t+Ls?t:e,Re=e=>go(du(e)),Rr=e=>{let t=Date.now()+Ls,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},ks=e=>{try{return u("Decoded date",new Date(Re(e)))}catch(t){return a("Decoding failed + "+t.message)}},Rn=e=>{if(!e?.id)return null;try{return du(e.id)}catch{return null}};var Ds="removed",Qe=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):a("Unable to find node in breadcrumb")},lu=["png","jpg","gif","webp"];var V={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Ja(e){return e.context===V.WORKSPACE}function P(e){return e.context===V.TICKET}function Nn(e){return e.context===V.TEXT}function ut(e){return e.context===V.FIELD}function ho(e){return e.context===V.FIELD_LIST}var Pt=e=>e.context===V.SWIMLANE,Nr=e=>e.context===V.BOARD,yo=e=>e.context===V.COMMENT;import{useSyncExternalStore as uE}from"react";var b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var cu=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",uu=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",mu=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",pu=(e,t)=>{if(uu(e,e.sequence))return S.MoveCursorLeftOfWord;if(mu(e,e.sequence))return S.MoveCursorRightOfWord;if(cu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.GetLastCommandFromHistory;case"down":return S.GetNextCommandFromHistory;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}},fu=(e,t)=>{if(uu(e,e.sequence))return S.MoveCursorLeftOfWord;if(mu(e,e.sequence))return S.MoveCursorRightOfWord;if(cu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.NavPreviousItem;case"down":return S.NavNextItem;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}};import gu from"string-width";function Bs(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Mv=/\u001B\[[0-9;]*m/,Qa="\x1B[0m",Pv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Za=(e,t)=>{if(t<=0)return"";if(gu(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(Mv.test(l)){o+=l,i=l!==Qa&&l!=="\x1B[m";continue}for(let c of Pv(l)){let m=gu(c);if(s+m>r)return`${o}...${i?Qa:""}`;o+=c,s+=m}}return`${o}...${i?Qa:""}`},Ie=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),hu=e=>e.charAt(0).toUpperCase()+e.slice(1);var yu=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},vu=(e,t)=>t?e.get(t)??[]:[];var bu=new WeakMap,Lv=e=>{let t=bu.get(e);return t||(t=yu(e),bu.set(e,t)),t};var xu=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return vu(Lv(e),r).filter(s=>Bs(r,s)>=n)};var kv={hint:"",hints:[],overlap:0,remainder:""},Iu=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return kv;let o=xu({wordList:r,inputToMatch:e,overlapThreshold:1});return Dv(t,o)},Dv=(e,t)=>{let n=t[0]??"",r=Bs(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,p=(l&&i?o:n)+(l&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as Ov}from"ulid";var vo=24n,Bv=vo*4n,Vt=(1n<<Bv)-1n,Fv=/^[0-9a-f]+$/;function Su(e){return!e||!Fv.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function yt(e,t=vo){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ze(e,t){if(!e&&!t)return yt(Vt/2n,vo);let n=e?Su(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?Su(t):u("Resolved upper bound",Vt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return a("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):yt(i,vo)}function Eu(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Vt*BigInt(r+1)/(t+1n),s=yt(o,vo);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var ed=(e,t)=>{let n=ae(e),r=Eu(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return a("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:Ov(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as Nb}from"ulid";var fe={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var _=e=>e.slice(-7).toUpperCase(),Fs=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?_(e).includes(n):!0};var ge={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:V.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:_(e)},context:V.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:V.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:V.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:V.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:_(e)},context:V.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:V.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:V.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var _v=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Os]=_v;var td=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...td(e,t),convergence:!0}),xo=e=>d(e)&&e.convergence===!0,gn=e=>{let t=e.filter(d);return{fatal:t.filter(n=>!xo(n)),skipped:t.filter(xo)}},hn=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Cu=e=>{let t=C.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Au(t);return d(n)?n:null},Ru=e=>{if(!rd())return null;for(let t of e){let n=Cu(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Cu(r);if(o)return o}return null},Uv=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},jv=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},nd=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return jv(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},$v=e=>{we(t=>({...t,eventLog:[...t.eventLog,e]}))},Hv=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?td("Invalid user ID format",e):u("Valid user",null)},ot=null,Wv=e=>{for(let[t,n]of e.nodeLog){let r=C.getNode(t);r&&C.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&we(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Ru([...e.virtualNodeIds])},Gv=(e,t)=>{let n=Hv(e);if(d(n))return n;let r=[...new Set(nd(e))];if(ot){for(let s of r){if(!t){let i=ot.nodeLog.get(s);i?i.push(e):ot.nodeLog.set(s,[e])}if(rd()){ot.virtualNodeIds.add(s);let i=h().nodes[s]?.parentNodeId;i&&ot.virtualNodeIds.add(i)}}return t||ot.appLog.push(e),null}t||(r.forEach(s=>Uv(s,e)),$v(e));let o=Ru(r);return o||null},bo=(e,t,n)=>C.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,Vv={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ge.workspace(t,n,r),s=Io(o);if(d(s))return td(s.message,e);let i=C.createNode(o);return d(i)?F(i.message??"Failed to initialize workspace",e):Ja(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=bo(t,void 0,e);if(o)return o;let s=C.createNode(ge.workspace(t,n,r));return d(s)?F(s.message??"Failed to add workspace",e):Ja(s.value)?u("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=C.createNode(ge.board(t,n,r,o));return d(i)?F(i.message??"Unable to create board",e):Nr(i.value)?u("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=C.createNode(ge.swimlane(t,n,r,o));return d(i)?F(i.message??"Unable to create swimlane",e):Pt(i.value)?u("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=C.createNode(ge.ticket(t,n,r,o));return d(i)?F(i.message??"Unable to create issue",e):P(i.value)?u("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=bo(t,r,e);if(i)return i;let l=C.createNode(ge.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(fe.DESCRIPTION)?"vertical":"horizontal"}));return d(l)?F(l.message??`Unable to create field: ${n}`,e):ut(l.value)?u("Added field",{action:e.action,result:l.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!C.getNode(t))return F(`Unable to locate node with id ${t}`,e);let o=C.renameNode(t,n);return d(o)?F(o.message??"Unable to edit title",e):u("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=C.tombstoneNode(t);return d(n)?F(n.message??"Unable to delete node",e):u("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=C.createTag({id:t,name:n});return d(r)?F(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=C.tombstoneTag(t);return d(n)?F(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=C.restoreTag(t,n);return d(r)?F(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=C.createContributor({id:t,name:n});return d(r)?F(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=C.renameContributor(t,n);return d(r)?F(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=C.tombstoneContributor(t);return d(n)?F(n.message??"Unable to remove contributor",e):u("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=C.restoreContributor(t,n);return d(r)?F(r.message??"Unable to restore contributor",e):u("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=C.tag(t,n);return d(r)?F(r.message??"Unable to tag issue",e):u("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=C.untag(t,n);return d(r)?F(r.message??"Unable to untag issue",e):u("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=C.assign(t,n);return d(r)?F(r.message??"Unable to assign issue",e):u("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=C.unassign(t,n);return d(r)?F(r.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?F(o.message??"Failed to move node",e):u("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=C.editValue(t,n);return d(r)?F(r.message??"Unable to edit description",e):u("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.getNode(t);if(!o)return F("Unable to locate issue",e);if(!P(o))return F("Can only close issues",e);let s=C.getNode(he);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=C.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?F(i.message??"Unable to close issue",e):u("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.getNode(t);if(!o)return F("Unable to locate issue",e);if(!P(o))return F("Can only reopen issues",e);let s=C.getNode(he);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!C.getNode(n))return F("Reopen parent no longer exists",e);let l=C.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?F(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=C.lockNode(t);return d(n)?F(n.message??"Unable to lock node",e):u("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=C.getNode(r);if(!s)return F(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let i=C.updateNode({...s,rank:o});if(d(i))return F(i.message??"Unable to rebalance child",e)}return u("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=C.createComment({id:t,issue:n,authorId:r,authorName:C.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?F(s.message??"Unable to add comment",e):u("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=C.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let s=C.editComment(t,r);return d(s)?F(s.message??"Unable to edit comment",e):u("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=C.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let o=C.deleteComment(t);return d(o)?F(o.message??"Unable to delete comment",e):u("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,l=C.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(l)?F(l.message??"Unable to add attachment",e):u("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=C.getAttachment(t);if(!r)return F("Unable to locate attachment",e);if(r.issue!==n)return F("Attachment does not belong to issue",e);let o=C.deleteAttachment(t);return d(o)?F(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=C.linkUserId({contributorId:t,userId:e.userId});return d(n)?F(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function An(e,t=!1){let n=Vv[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!vt()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&ot){if(ot.genesisApplied)return F("the workspace is already initialized",e);ot.genesisApplied=!0}let r;try{r=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(d(r))return r;let o=Gv(e,t);return o||r}var Lt=e=>{let t=Nu(()=>{let n=ot===null;n&&(ot={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>An(o));if(n&&ot){let o=Wv(ot);if(o)return e.map(()=>o)}return r}finally{n&&(ot=null)}});return d(t)?e.map(()=>a(t.message)):t.value};import hd from"node:path";import{decodeTime as fb,monotonicFactory as gb}from"ulid";import{z as Qn}from"zod";var od=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";import Ae from"node:fs";import Jn from"node:path";import{ulid as zv}from"ulid";var Us="~pending",sd=/~pending(-[0-9a-z]+)*$/i,wu=/-f(\d+)$/,Mu=e=>{let t=e.indexOf(".");return t===-1?`${e}${Us}`:e.slice(0,t)+Us+e.slice(t)},id=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},Pu=e=>{let[t,n]=id(e);return sd.test(t)?t.replace(sd,"")+n:null},Lu=e=>e.replace(sd,""),js=e=>e.endsWith(".jsonl")&&Pu(e)!==null,ku=e=>{let[t]=id(e),n=wu.exec(t);return n&&js(e)?Number(n[1]):null},Kv=e=>Mu(e).replace(Us,`${Us}-${zv().toLowerCase()}`),qv=(e,t)=>{let[n,r]=id(e);return`${n.replace(wu,"")}-f${t}${r}`},Du=(e,t)=>Jn.join(Mt(e),Mu(t)),Yv=(e,t)=>Math.max(0,Ae.statSync(e).size-(ku(t)??0)),Bu=e=>{let t=Mt(e);try{return Ae.existsSync(t)?Ae.readdirSync(t).filter(js).some(n=>Yv(Jn.join(t,n),n)>0):!1}catch{return!0}},Xv=3,Fu=(e,t)=>{for(let n=1;;n++){let r=Ae.openSync(e,"a"),o;try{Ae.writeSync(r,t),o=Ae.fstatSync(r).ino}finally{Ae.closeSync(r)}let s;try{s=Ae.statSync(e).ino}catch{s=null}if(s===o||n>=Xv)return}},Jv=e=>{let t;try{t=Ae.openSync(e,"r")}catch{return!0}try{let{size:n}=Ae.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ae.readSync(t,r,0,1,n-1),r[0]===10}finally{Ae.closeSync(t)}},_s=10,Tu=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(_s)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ae.appendFileSync(e,Buffer.concat([Buffer.from(Jv(e)?"":`
|
|
29
|
-
`),o,Buffer.from(o[o.length-1]===
|
|
30
|
-
`)]));let s=0;for(let i of o)i===
|
|
31
|
-
`).entries()){let m=c.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{i(
|
|
32
|
-
`),n&&(n.current=c);let f=hd.basename(i.value);return zu(t,f,c),ju(t,f),u("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return a(`Failed to persist event: ${s}`)}}function Zu(e,t,n){let r=yd(t,n);if(d(r))return a(r.message);let o={...e,id:r.value[0]},s=An(o);if(s.status!==En.Success)return s;let i=Ks({event:o,rootDir:t,edge:n,id:r.value});return d(i)?i:s}function B(e,t){if(e.length===0||!e[0])return a("No events provided");if(h().readOnly)return a(h().readOnlyReason??"Cannot change the board while time travelling");let n={},r=Ab(e[0],t,n);if(d(r))return r;let o=e.map(i=>Zu(i,t,n)),s=o.filter(d);return s.length>0?a("Materialize and persist failed: "+s.map(i=>i.message).join(", ")):u("Materialization succeeded",o.map(i=>i.value))}var Ab=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let r=C.getContributor(e.userId),o={id:Nb(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return u("Contributor name is current",void 0);let s=Zu(o,t,n);return d(s)?a(s.message):u("Contributor name recorded",void 0)};var er=e=>e.trim().toLocaleLowerCase(),vd=(e,t)=>er(e).includes(er(t));var Tb=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},wb=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},em=null,tm=new Map,Mb=()=>{let e=h().eventLog??[];if(e===em)return tm;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return em=e,tm=t,t},Pb=e=>{let{contributors:t}=h(),n=Mb().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},nm=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return vd(e.title??"",n);case"description":return vd(e.props.description??"",n);case"tag":return Tb(e).map(er).some(o=>o.includes(n));case"assignee":return wb(e).map(er).some(o=>o.includes(n));case"actor":return Pb(e).map(er).some(o=>o.includes(n));case"ref":return Fs(e.id,t.value);default:return!0}};var rm=(e,t)=>e.rank.localeCompare(t.rank),Lb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,om=(e,t)=>Object.values(e).filter(n=>Lb(n,t)).sort(rm),sm=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>nm(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(rm);return n};var im=e=>qs(ae(e),{at:"end"}),qs=(e,t={at:"end"})=>{let n=o=>d(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ze(void 0,void 0));let r=()=>n(Ze(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ze(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ze(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=am(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(Ze(i?.rank,s.rank))}case"after":{let o=am(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(Ze(s.rank,i?.rank))}}},ae=e=>{let t=h();if(!lm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return om(t.nodes,e)},am=(e,t)=>e.findIndex(n=>n.id===t),dm=(e,t,n={at:"end"})=>qs(ae(t).filter(r=>r.id!==e),n),Kt=(e,t,n,r,o)=>{let s=dm(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=ed(e,r);if(d(i))return i;let l=B([i.value],o);if(d(l))return l;let c=dm(t,e,n);return d(c)?c:c.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",c.value.rank)},Pn=(e,t,n)=>{let r=im(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=ed(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=im(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var O={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=q(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||O.navigate({contextNode:o,selectedIndex:q(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=q(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;O.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>cm(1),navigateToPreviousItem:()=>cm(-1),navigateToNextContainer:()=>um(1),navigateToPreviousContainer:()=>um(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},cm=e=>{let{selectedIndex:t,contextNode:n}=h(),r=q(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;O.navigate({selectedIndex:s,contextNode:n})},um=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=q(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let c=q(l.id),m=Math.max(0,c.length-1),p=Math.min(Math.max(0,r),m),f=c.length?p:-1;O.navigate({contextNode:l,selectedIndex:f})};var pm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),fm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},kb=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&ut(t)&&t.childRenderAxis==="vertical"},Ys=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=ae(r.id);return O.navigate({contextNode:r,selectedIndex:pm(t,o.length)}),!0},gm=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ys(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=ae(o.id).findIndex(l=>l.id===n.id);return i>=0?(O.navigate({contextNode:o,selectedIndex:i}),!0):gm(o.id)},mm=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),gm(n))return!0;n=t[n]?.parentNodeId}return!1},Db=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},hm=e=>{let{nodes:t,rootNodeId:n}=h();if(kb(e.contextNodeId)&&Ys(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(Db(e.selectedNodeId)&&e.selectedNodeId&&mm(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Ys(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Ys(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(mm(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=ae(r.id);return O.navigate({contextNode:r,selectedIndex:pm(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as Bb,ulid as qt}from"ulid";var Co=Bb();function Fb(){let e=et();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return a("No workspace found in event log");let[r]=q(n.id),[o]=r?q(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Ob(){let e=Fb();return d(e)?e:O.navigate(e.value)}function ym({userId:e,userName:t}){let n=Co(),r=Co(),o=Co(),s=Co(),i=Co(),l=Ze(void 0,void 0);if(d(l))return l;let c=Ze(void 0,void 0);if(d(c))return c;let m=Ze(c.value,void 0);if(d(m))return m;let p=Ze(void 0,void 0);if(d(p))return p;let f=Ze(p.value,void 0);if(d(f))return f;let g=Ze(f.value,void 0);if(d(g))return g;let v=Ze(void 0,void 0);return d(v)?v:u("Created default events",[{id:qt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:qt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:qt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:c.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:qt(),userId:e,userName:t,action:"add.board",payload:{id:Os,name:"Closed",parent:n,rank:m.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Os,rank:v.value}},{id:qt(),userId:e,userName:t,action:"lock.node",payload:{id:Os}},{id:qt(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}var _b=()=>{let e=et();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Ub=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");z.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");z.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Dt(e,t=[]){if(_b())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=ge.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Io(s);return d(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Lt(e),{fatal:r,skipped:o}=gn(n);return r.length>0?a(`Materializing failed:
|
|
26
|
+
`).filter(Boolean).filter(i=>i!==rt);if(r.length===0)return u("State branch is storage-only",!1);let o=await U({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return l(`Failed to clean storage branch
|
|
27
|
+
${o.message}`);let s=await Br({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?l(s.message):u("Cleaned storage branch",!0)},kt=_a(async(e=process.cwd())=>{let t=await U({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?l("Not inside a Git repository"):u("Resolved repo root",t.value.stdout.trim())},e=>lt.resolve(e)),qA=_a(async e=>{let t=await U({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return l(t.message);let n=t.value.stdout.trim(),r=lt.isAbsolute(n)?n:lt.join(e,n);return u("Resolved git dir",r)},e=>lt.resolve(e));var tT=process.env.IS_LOCAL==="true",rt=".epiq",gn="events",Xa="media",wv="project.json",or=e=>Vt.join(e,rt),kr=e=>Vt.join(or(e),wv),Dt=e=>Vt.join(or(e),gn),Co=e=>Vt.join(or(e),Xa),cu=e=>Vt.join(e,rt),Mv=e=>{let t=Vt.join(e,rt);return Ro.existsSync(t)&&Ro.statSync(t).isDirectory()},No=e=>{let t=kr(e);return Ro.existsSync(t)&&Ro.statSync(t).isFile()},Ls=e=>{let t=Vt.resolve(e);for(;;){if(Mv(t))return u("Resolved closest .epiq root",t);let n=Vt.dirname(t);if(n===t)return l("No .epiq directory found in any parent");t=n}},Ja="No .epiq/project.json found in any parent",Se=e=>{let t=Vt.resolve(e);for(;;){if(No(t))return u("Resolved closest epiq project root",t);let n=Vt.dirname(t);if(n===t)return l(Ja);t=n}},uu=e=>{let t=Dt(e);try{return Ro.mkdirSync(t,{recursive:!0}),u("Resolved events dir",t)}catch(n){return l(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},zt=async()=>{let e=await kt(process.cwd());if(a(e))return e;let t=fe({repoRoot:e.value});return a(t)?t:u("Resolved persist root",t.value)};import{accessSync as Pv,copyFileSync as Lv,existsSync as Os,mkdirSync as mu,readdirSync as pu,readFileSync as kv,renameSync as Dv,rmSync as Bv,statSync as fu,unlinkSync as Fv,writeFileSync as Ov}from"node:fs";import Fr from"node:path";var Qa=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",We={writeToFile:(e,t)=>{try{let n=Fr.dirname(e);Os(n)||mu(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Ov(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return kv(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=We.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Os(e)&&fu(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Pv(e),!0}catch{return!1}},mkDir:e=>mu(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Fr.parse(t);for(;;){let r=Fr.join(t,e);try{if(Os(r)&&fu(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Fr.dirname(t)}return null},readFirstJSON(e){try{if(!We.dirExists(e))return null;let t=pu(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Fr.join(e,t);return We.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return We.dirExists(e)?pu(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Fv(e)}catch(t){(!Qa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Bv(e,{recursive:!0,force:!0})}catch(t){(!Qa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Fr.dirname(t)),!n?.overwrite&&Os(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Dv(e,t)}catch(r){if(Qa(r)&&r.code==="EXDEV"){Lv(e,t),this.rmFile(e);return}throw r}}};var Uv={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},gu=hn.object({logLevel:hn.enum(["info","error","debug"]),preferredEditor:hn.string().optional(),userName:hn.string().optional(),userId:hn.string().optional(),autoSync:hn.boolean().nullable().optional(),autoSyncDebounceMs:hn.number().optional(),attachmentMaxKb:hn.number().optional(),viewMode:hn.enum(["dense","wide"]).optional()}).partial(),jv="config.json",hu=un,Za=()=>_v.join(hu(),jv),el=()=>{try{return We.mkDir(hu()),u(`Ensured ~/${Pt} exists`,null)}catch{return l(`Unable to create ~/${Pt}`)}},$v=e=>{let t;try{t=JSON.parse(e)}catch{return l(`Invalid ~/${Pt}/config.json JSON`)}let n=gu.safeParse(t??{});return n.success?u("Parsed config",n.data):l(`Invalid ~/${Pt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Or=()=>{let e=el();if(a(e))return l(e.message);let t=Za(),n=We.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):$v(n)},yu=e=>{let t=el();if(a(t))return l(t.message);let n=gu.safeParse(e);if(!n.success)return l(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Za();try{return We.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
28
|
+
`),u("Config written",null)}catch{return l(`Unable to write ~/${Pt}/config.json`)}},vt=e=>{let t=Or();if(a(t))return l("Failed to read existing config");let n={...t.value,...e};return yu(n)},bt=()=>{let e=Za(),t=el();if(a(t))return l(`Unable to create ~/${Pt}`);if(!(We.readFile(e)!==null)){let I=yu(Uv);if(a(I))throw new Error(`Unable to create ~/${Pt}/config.json`)}let r=Or();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:d,autoSyncDebounceMs:c,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,g=Lr({userId:i,userName:s});if(a(g))return l(g.message);let v=g.value??{userId:i,userName:s};return!v.userName||!v.userId?l(`User name or ID not configured in ~/${Pt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:v.userName,userId:v.userId,autoSync:d??!1,autoSyncIntervalMs:c??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as Hv}from"react";var Ao={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},tl=new Set,Wv=()=>{for(let e of tl)e()},le=()=>Ao,vu=()=>Hv(e=>(tl.add(e),()=>{tl.delete(e)}),()=>Ao),Ye=e=>(Ao={...Ao,...e},Wv(),Ao);import{spawn as Gv}from"node:child_process";import nl from"node:process";var rl=e=>{let t=nl.platform==="darwin"?"open":nl.platform==="win32"?"cmd":"xdg-open",n=nl.platform==="win32"?["/c","start","",e]:[e];Gv(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as ny}from"node:fs/promises";import Yn from"chalk";import _g from"string-width";import{decodeTime as bu}from"ulid";var _s=1440*60*1e3,To=(e,t=Date.now())=>e>t+_s?t:e,Ce=e=>To(bu(e)),_r=e=>{let t=Date.now()+_s,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Us=e=>{try{return u("Decoded date",new Date(Ce(e)))}catch(t){return l("Decoding failed + "+t.message)}},Mn=e=>{if(!e?.id)return null;try{return bu(e.id)}catch{return null}};var js="removed",ot=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):l("Unable to find node in breadcrumb")},xu=["png","jpg","gif","webp"];var K={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function ol(e){return e.context===K.WORKSPACE}function B(e){return e.context===K.TICKET}function Pn(e){return e.context===K.TEXT}function gt(e){return e.context===K.FIELD}function wo(e){return e.context===K.FIELD_LIST}var Kt=e=>e.context===K.SWIMLANE,Ln=e=>e.context===K.BOARD,Mo=e=>e.context===K.COMMENT;import{useSyncExternalStore as LE}from"react";var b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Iu=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Su=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Eu=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Ru=(e,t)=>{if(Su(e,e.sequence))return S.MoveCursorLeftOfWord;if(Eu(e,e.sequence))return S.MoveCursorRightOfWord;if(Iu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.GetLastCommandFromHistory;case"down":return S.GetNextCommandFromHistory;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}},Cu=(e,t)=>{if(Su(e,e.sequence))return S.MoveCursorLeftOfWord;if(Eu(e,e.sequence))return S.MoveCursorRightOfWord;if(Iu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.NavPreviousItem;case"down":return S.NavNextItem;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}};import Nu from"string-width";function $s(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var yn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Vv=/\u001B\[[0-9;]*m/,sl="\x1B[0m",zv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),il=(e,t)=>{if(t<=0)return"";if(Nu(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let d of e.split(/(\u001B\[[0-9;]*m)/))if(d!==""){if(Vv.test(d)){o+=d,i=d!==sl&&d!=="\x1B[m";continue}for(let c of zv(d)){let m=Nu(c);if(s+m>r)return`${o}...${i?sl:""}`;o+=c,s+=m}}return`${o}...${i?sl:""}`},ye=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Au=e=>e.charAt(0).toUpperCase()+e.slice(1);var Tu=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},wu=(e,t)=>t?e.get(t)??[]:[];var Mu=new WeakMap,Kv=e=>{let t=Mu.get(e);return t||(t=Tu(e),Mu.set(e,t)),t};var Pu=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return wu(Kv(e),r).filter(s=>$s(r,s)>=n)};var qv={hint:"",hints:[],overlap:0,remainder:""},Lu=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return qv;let o=Pu({wordList:r,inputToMatch:e,overlapThreshold:1});return Yv(t,o)},Yv=(e,t)=>{let n=t[0]??"",r=$s(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,d=!!s,p=(d&&i?o:n)+(d&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as Qv}from"ulid";var Po=24n,Xv=Po*4n,qt=(1n<<Xv)-1n,Jv=/^[0-9a-f]+$/;function ku(e){return!e||!Jv.test(e)?l(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function xt(e,t=Po){if(e<0n)return l("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function st(e,t){if(!e&&!t)return xt(qt/2n,Po);let n=e?ku(e):u("Resolved lower bound",0n);if(a(n))return n;let r=t?ku(t):u("Resolved upper bound",qt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return l("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?l("No rank space available between neighbors"):xt(i,Po)}function Du(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=qt*BigInt(r+1)/(t+1n),s=xt(o,Po);if(a(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var al=(e,t)=>{let n=de(e),r=Du(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],d=r.value[s];if(!i||!d)return l("Unable to assign rebalance rank");o[i.id]=d}return u("Created rebalance event",{id:Qv(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as $b}from"ulid";var ve={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var O=e=>e.slice(-7).toUpperCase(),Hs=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?O(e).includes(n):!0};var be={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:K.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:O(e)},context:K.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:K.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:K.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:K.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:O(e)},context:K.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:K.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:K.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Zv=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ie,Ws]=Zv;var ll=(e,t)=>l(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...ll(e,t),convergence:!0}),ko=e=>a(e)&&e.convergence===!0,vn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!ko(n)),skipped:t.filter(ko)}},bn=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Bu=e=>{let t=R.getNode(e);if(!t||!B(t)||t.isDeleted)return null;let n=Ou(t);return a(n)?n:null},Fu=e=>{if(!cl())return null;for(let t of e){let n=Bu(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Bu(r);if(o)return o}return null},eb=(e,t)=>{let n=R.getNode(e);n&&R.updateNode({...n,log:[...n.log??[],t]})},tb=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},dl=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return tb(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},nb=e=>{we(t=>({...t,eventLog:[...t.eventLog,e]}))},rb=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?ll("Invalid user ID format",e):u("Valid user",null)},dt=null,ob=e=>{for(let[t,n]of e.nodeLog){let r=R.getNode(t);r&&R.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&we(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Fu([...e.virtualNodeIds])},sb=(e,t)=>{let n=rb(e);if(a(n))return n;let r=[...new Set(dl(e))];if(dt){for(let s of r){if(!t){let i=dt.nodeLog.get(s);i?i.push(e):dt.nodeLog.set(s,[e])}if(cl()){dt.virtualNodeIds.add(s);let i=h().nodes[s]?.parentNodeId;i&&dt.virtualNodeIds.add(i)}}return t||dt.appLog.push(e),null}t||(r.forEach(s=>eb(s,e)),nb(e));let o=Fu(r);return o||null},Lo=(e,t,n)=>R.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,ib={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=be.workspace(t,n,r),s=Do(o);if(a(s))return ll(s.message,e);let i=R.createNode(o);return a(i)?F(i.message??"Failed to initialize workspace",e):ol(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Lo(t,void 0,e);if(o)return o;let s=R.createNode(be.workspace(t,n,r));return a(s)?F(s.message??"Failed to add workspace",e):ol(s.value)?u("Added workspace",{action:e.action,result:s.value}):l("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Lo(t,r,e);if(s)return s;let i=R.createNode(be.board(t,n,r,o));return a(i)?F(i.message??"Unable to create board",e):Ln(i.value)?u("Added board",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Lo(t,r,e);if(s)return s;let i=R.createNode(be.swimlane(t,n,r,o));return a(i)?F(i.message??"Unable to create swimlane",e):Kt(i.value)?u("Added swimlane",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Lo(t,r,e);if(s)return s;let i=R.createNode(be.ticket(t,n,r,o));return a(i)?F(i.message??"Unable to create issue",e):B(i.value)?u("Added issue",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Lo(t,r,e);if(i)return i;let d=R.createNode(be.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ve.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?F(d.message??`Unable to create field: ${n}`,e):gt(d.value)?u("Added field",{action:e.action,result:d.value}):l("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!R.getNode(t))return F(`Unable to locate node with id ${t}`,e);let o=R.renameNode(t,n);return a(o)?F(o.message??"Unable to edit title",e):u("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=R.tombstoneNode(t);return a(n)?F(n.message??"Unable to delete node",e):u("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=R.createTag({id:t,name:n});return a(r)?F(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=R.tombstoneTag(t);return a(n)?F(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=R.restoreTag(t,n);return a(r)?F(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=R.createContributor({id:t,name:n});return a(r)?F(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=R.renameContributor(t,n);return a(r)?F(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=R.tombstoneContributor(t);return a(n)?F(n.message??"Unable to remove contributor",e):u("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=R.restoreContributor(t,n);return a(r)?F(r.message??"Unable to restore contributor",e):u("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=R.tag(t,n);return a(r)?F(r.message??"Unable to tag issue",e):u("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=R.untag(t,n);return a(r)?F(r.message??"Unable to untag issue",e):u("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=R.assign(t,n);return a(r)?F(r.message??"Unable to assign issue",e):u("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=R.unassign(t,n);return a(r)?F(r.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?F(o.message??"Failed to move node",e):u("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=R.editValue(t,n);return a(r)?F(r.message??"Unable to edit description",e):u("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.getNode(t);if(!o)return F("Unable to locate issue",e);if(!B(o))return F("Can only close issues",e);let s=R.getNode(ie);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=R.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?F(i.message??"Unable to close issue",e):u("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.getNode(t);if(!o)return F("Unable to locate issue",e);if(!B(o))return F("Can only reopen issues",e);let s=R.getNode(ie);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!R.getNode(n))return F("Reopen parent no longer exists",e);let d=R.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?F(d.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=R.lockNode(t);return a(n)?F(n.message??"Unable to lock node",e):u("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=R.getNode(r);if(!s)return F(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let i=R.updateNode({...s,rank:o});if(a(i))return F(i.message??"Unable to rebalance child",e)}return u("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=R.createComment({id:t,issue:n,authorId:r,authorName:R.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?F(s.message??"Unable to add comment",e):u("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=R.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let s=R.editComment(t,r);return a(s)?F(s.message??"Unable to edit comment",e):u("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=R.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let o=R.deleteComment(t);return a(o)?F(o.message??"Unable to delete comment",e):u("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,d=R.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(d)?F(d.message??"Unable to add attachment",e):u("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=R.getAttachment(t);if(!r)return F("Unable to locate attachment",e);if(r.issue!==n)return F("Attachment does not belong to issue",e);let o=R.deleteAttachment(t);return a(o)?F(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=R.linkUserId({contributorId:t,userId:e.userId});return a(n)?F(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function kn(e,t=!1){let n=ib[e.action];if(!n)return l(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!It()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&dt){if(dt.genesisApplied)return F("the workspace is already initialized",e);dt.genesisApplied=!0}let r;try{r=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(r))return r;let o=sb(e,t);return o||r}var Bt=e=>{let t=Gs(()=>{let n=dt===null;n&&(dt={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>kn(o));if(n&&dt){let o=ob(dt);if(o)return e.map(()=>o)}return r}finally{n&&(dt=null)}});return a(t)?e.map(()=>l(t.message)):t.value};import El from"node:path";import{decodeTime as wb,monotonicFactory as Mb}from"ulid";import{z as ar}from"zod";var ul=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";import Ae from"node:fs";import ir from"node:path";import{ulid as ab}from"ulid";var zs="~pending",ml=/~pending(-[0-9a-z]+)*$/i,Uu=/-f(\d+)$/,ju=e=>{let t=e.indexOf(".");return t===-1?`${e}${zs}`:e.slice(0,t)+zs+e.slice(t)},pl=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},$u=e=>{let[t,n]=pl(e);return ml.test(t)?t.replace(ml,"")+n:null},Hu=e=>e.replace(ml,""),Ks=e=>e.endsWith(".jsonl")&&$u(e)!==null,Wu=e=>{let[t]=pl(e),n=Uu.exec(t);return n&&Ks(e)?Number(n[1]):null},lb=e=>ju(e).replace(zs,`${zs}-${ab().toLowerCase()}`),db=(e,t)=>{let[n,r]=pl(e);return`${n.replace(Uu,"")}-f${t}${r}`},Gu=(e,t)=>ir.join(Dt(e),ju(t)),cb=(e,t)=>Math.max(0,Ae.statSync(e).size-(Wu(t)??0)),Vu=e=>{let t=Dt(e);try{return Ae.existsSync(t)?Ae.readdirSync(t).filter(Ks).some(n=>cb(ir.join(t,n),n)>0):!1}catch{return!0}},ub=3,zu=(e,t)=>{for(let n=1;;n++){let r=Ae.openSync(e,"a"),o;try{Ae.writeSync(r,t),o=Ae.fstatSync(r).ino}finally{Ae.closeSync(r)}let s;try{s=Ae.statSync(e).ino}catch{s=null}if(s===o||n>=ub)return}},mb=e=>{let t;try{t=Ae.openSync(e,"r")}catch{return!0}try{let{size:n}=Ae.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ae.readSync(t,r,0,1,n-1),r[0]===10}finally{Ae.closeSync(t)}},Vs=10,_u=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Vs)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ae.appendFileSync(e,Buffer.concat([Buffer.from(mb(e)?"":`
|
|
29
|
+
`),o,Buffer.from(o[o.length-1]===Vs?"":`
|
|
30
|
+
`)]));let s=0;for(let i of o)i===Vs&&s++;return o[o.length-1]!==Vs&&s++,{bytes:r,lines:s}},qs=(e,t)=>{let n=Dt(e);if(!Ae.existsSync(n))return u("No events directory",0);try{let r=Ae.readdirSync(n).filter(i=>$u(i)===t),o=ir.join(n,t),s=0;for(let i of r){let d=Wu(i);if(d!==null){let f=ir.join(n,i),g=Ae.readFileSync(f).subarray(d);s+=_u(o,g,!0).lines,Ae.rmSync(f,{force:!0});continue}let c=/~pending-/i.test(i)?i:lb(t),m=ir.join(n,c);c!==i&&Ae.renameSync(ir.join(n,i),m);let p=_u(o,Ae.readFileSync(m));s+=p.lines,Ae.renameSync(m,ir.join(n,db(c,p.bytes)))}return u("Folded pending logs",s)}catch(r){return l(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};import tm from"node:fs";import Js from"node:path";import{decodeTime as yb}from"ulid";import{z as bl}from"zod";import fl from"node:fs";import pb from"node:path";var Bo=e=>e?.code==="ENOENT",gl=3,hl=e=>fl.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),Yt=e=>{let t=Dt(e);for(let n=1;;n++){if(!fl.existsSync(t))return"none";let r=[],o=!1;for(let s of hl(t))try{let{size:i,mtimeMs:d}=fl.statSync(pb.join(t,s));r.push(`${s}:${i}:${d}`)}catch(i){if(!Bo(i))throw i;if(n<gl){o=!0;break}}if(!o)return r.join("|")}},Ku=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),yl=(e,t,n)=>{let r=Ku(t),o=Yt(e),s=Ku(o);for(let[i,d]of s)if(i!==n&&r.get(i)!==d)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},Dn=null,qu=e=>Dn&&Dn.root===e?Dn.signature:null,Yu=(e,t)=>{Dn={root:e,signature:t}},Xu=(e,t)=>{if(!Dn||Dn.root!==e)return;let n=yl(e,Dn.signature,t);Dn=n===null?null:{root:e,signature:n}};var fb=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"];var gb=new Set(fb),Ju=e=>gb.has(e),Qu=e=>({action:e.action,payload:e.payload});import{z as G}from"zod";var H=G.string().min(1),Ft=G.string(),Bn=G.string(),Ys=G.looseObject({id:H}),vl=G.looseObject({id:H,name:Ft,parent:H,rank:Bn}),hb={"init.workspace":G.looseObject({id:H,name:Ft,rank:Bn}),"add.workspace":G.looseObject({id:H,name:Ft,rank:Bn}),"add.board":vl,"add.swimlane":vl,"add.issue":vl,"add.field":G.looseObject({id:H,name:Ft,parent:H,rank:Bn}),"edit.title":G.looseObject({id:H,name:Ft}),"delete.node":Ys,"lock.node":Ys,"move.node":G.looseObject({id:H,parent:H,rank:Bn}),"edit.description":G.looseObject({id:H,md:G.string()}),"close.issue":G.looseObject({id:H,parent:H,rank:Bn}),"reopen.issue":G.looseObject({id:H,parent:H,rank:Bn}),"create.tag":G.looseObject({id:H,name:Ft}),"tombstone.tag":Ys,"restore.tag":G.looseObject({id:H,name:Ft}),"create.contributor":G.looseObject({id:H,name:Ft}),"rename.contributor":G.looseObject({id:H,name:Ft}),"tombstone.contributor":Ys,"restore.contributor":G.looseObject({id:H,name:Ft}),"link.contributor.user":G.looseObject({contributor:H}),"add.issue.assignee":G.looseObject({id:H,assignee:H}),"remove.issue.assignee":G.looseObject({id:H,assignee:H}),"add.issue.tag":G.looseObject({id:H,tag:H}),"remove.issue.tag":G.looseObject({id:H,tag:H}),"add.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"edit.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"delete.issue.comment":G.looseObject({id:H,issue:H}),"add.issue.attachment":G.looseObject({id:H,issue:H,hash:G.string().min(1),ext:G.string().min(1),name:Ft,bytes:G.number()}),"delete.issue.attachment":G.looseObject({id:H,issue:H}),"rebalance.children":G.looseObject({parent:H,ranks:G.record(G.string(),Bn)})},Zu=(e,t)=>{let r=hb[e].safeParse(t);return r.success?u("Payload is readable",void 0):l(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};var vb=bl.object({userId:bl.string().min(1).default("unknown"),userName:bl.string().min(1).default("unknown")}),Xs=e=>{let t=Object.entries(e).filter(([o])=>o!=="id"&&o!=="v"&&o!=="userId"&&o!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},bb=/^[0-9a-hjkmnp-tv-z]{26}$/i,xb=e=>bb.test(e)?e.toUpperCase():e,Ib=e=>{let t=Js.basename(e,".jsonl"),n=t.indexOf("."),r=Hu(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=vb.safeParse({userId:xb(r),userName:o});return s.success?u("Parsed event file actor",s.data):l(`Invalid event file name ${Js.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Sb=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?l(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?l("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},Eb=(e,t)=>t in e,Rb=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Cb=e=>{let{userId:t,userName:n,...r}=e,o=Sb(r);if(a(o))return l(o.message);let s=o.value,i=e.id?.[0];return i?Eb(r,s)?u("Decoded persisted event",Rb({id:i,action:s,payload:r[s],userId:t,userName:n})):l(`Persisted event is missing payload for action: ${s}`):l("Persisted event is missing id")},Il=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!im(s.v)){o.set(s.v,(o.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:Xs(s)});continue}let i=Cb(s);if(a(i)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:i.message,targetNodeId:Xs(s)});continue}let d=i.value.action;if(!Ju(d)){r.set(d,(r.get(d)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:d,targetNodeId:Xs(s)});continue}let c=Zu(d,i.value.payload);if(a(c)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:c.message,targetNodeId:Xs(s)});continue}n.push(i.value)}if(r.size>0){let s=[...r.entries()].map(([i,d])=>`${i} (x${d})`).join(", ");z.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(o.size>0){let s=[...o.entries()].map(([i,d])=>`v${i} (x${d})`).join(", ");z.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return u("Decoded reconstructed events",n)},Nb=(e,t)=>{let n=Ib(e);if(a(n))return l(n.message);let r;try{r=tm.readFileSync(e,"utf8")}catch(d){if(Bo(d))return u("Event file missing",null);throw d}let o=[],s=Js.basename(e),i=(d,c)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${d} (${c})`,targetNodeId:null})};for(let[d,c]of r.split(`
|
|
31
|
+
`).entries()){let m=c.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{i(d+1,"invalid JSON");continue}let f=sm(p);if(a(f)){i(d+1,f.message);continue}o.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return u("Parsed persisted events file",o)};function Fo(e,t){let n=Dt(e),r=Yt(e);if(!tm.existsSync(n))return u("No events found",[]);let o=[],s=[];for(let d=1;;d++){o=[],s=[];let c=!1;for(let m of hl(n)){let p=Nb(Js.join(n,m),s);if(a(p))return l(p.message);if(p.value===null){if(d<gl){c=!0;break}continue}o.push(...p.value)}if(!c)break}t?.push(...s);let i=Ab(o);return xn={root:e,signature:r,edge:i.at(-1)?.id?.[0]??null},u("All events loaded",i)}function St(e){let t=[],n=Fo(e,t);if(a(n))return l(n.message);let r=Il(n.value,t);return a(r)?l(r.message):u("Loaded merged events",{events:r.value,unreadable:t})}function Sl(e){let t=Fo(e);return a(t)?l(t.message):u("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function Fn(e){let t=St(e);return a(t)?l(t.message):u("Loaded merged events",t.value.events)}function Qs(e,t){let n=Fo(e);if(a(n))return l(n.message);let{appliedEvents:r,unappliedEvents:o}=Tb(n.value,t),s=Il(r);if(a(s))return l(s.message);let i=Il(o);return a(i)?l(i.message):u("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}var xn=null;function nm(e=process.cwd()){let t=Yt(e);if(xn&&xn.root===e&&xn.signature===t)return u("Loaded edge reference, unchanged",xn.edge);let n=Fo(e);return a(n)?l(n.message):u("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function rm(e,t,n){if(!xn||xn.root!==e)return;let r=yl(e,xn.signature,t);xn=r===null?null:{root:e,signature:r,edge:n}}var em=(e,t)=>e<t?-1:e>t?1:0,xl=(e,t)=>{let n=em(e.id[0],t.id[0]);return n!==0?n:em(JSON.stringify(e),JSON.stringify(t))},Ab=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let g=n.get(f)??[];g.push(m),n.set(f,g)}for(let m of n.values())m.sort(xl);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),g=f.id[0];if(o.has(g))continue;r.push(f),o.add(g);let v=n.get(g)??[];for(let I=v.length-1;I>=0;I--)p.push(v[I])}},i=(n.get(null)??[]).filter(m=>{let p=Object.keys(m).filter(f=>f!=="id"&&f!=="v"&&f!=="userId"&&f!=="userName");return p.length===1&&p[0]==="init.workspace"});for(let m of i)s(m);let d=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return o.has(p)?!1:f===null||!t.has(f)}).sort(xl);for(let m of d)s(m);let c=e.filter(m=>!o.has(m.id[0])).sort(xl);for(let m of c)s(m);return r},om=e=>_r(e.map(t=>{try{return yb(t.id[0])}catch{return null}}));function Zs(e){let t=Fo(e);if(a(t))return l(t.message);let n=om(t.value);return u("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var Tb=(e,t)=>{let n=new Set,r=[],o=[],s=om(e);for(let i=0;i<e.length;i++){let d=e[i],c=d.id[0],m=d.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(c),o.push(d)):r.push(d)}return{appliedEvents:r,unappliedEvents:o}};var lm=1,am=Mb(),Pb=0xffffffffffff,Lb=_s,kb=e=>{let t=Date.now(),n;try{n=wb(e)}catch{return t}return n>=Pb?t:n>t+Lb?(z.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},dm=ar.tuple([ar.string().min(1),ar.string().min(1).nullable()]),Db=ar.looseObject({v:ar.literal(lm),id:dm}),Bb=ar.looseObject({v:ar.number().int().positive(),id:dm}),sm=e=>{let t=Bb.safeParse(e);return t.success?u("Parsed persisted event envelope",t.data):l(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Fb=[1];var Ob=new Set(Fb),im=e=>Ob.has(e),_b=e=>{let t=Db.safeParse(e);return t.success?u("Parsed persisted event",t.data):l(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ne=()=>{let{userName:e,userId:t}=le();return e?t?Ba(t)?ws(e)?u("Successfully resolved actor ID",{userId:t,userName:e}):l("Invalid user name in config"):l("Invalid user ID in config"):l("User ID not configured"):l("User name not configured")},lr=({userId:e,userName:t})=>`${ul(e)}.${ul(t)}.jsonl`,Ub=(e,{userId:t,userName:n})=>{let r=lr({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return l(`Invalid event log file name: ${r}`);let s=El.join(Dt(e),r);return u("Successfully resolved event log path",s)},jb=(e,t)=>{let n={[e.action]:e.payload,v:lm,id:t};return _b(n)};function Rl(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=nm(e);if(a(o))return l(o.message);n=o.value}let r=n?am(kb(n)):am();return u("Minted event id",[r,n])}function ei({event:e,rootDir:t,edge:n,id:r}){try{let o=uu(t);if(a(o))return o;let s=Ub(t,{userId:e.userId,userName:e.userName});if(a(s))return s;let i=u("Resolved pending event log path",Gu(t,El.basename(s.value))),d=r?u("Minted event id",r):Rl(t,n);if(a(d))return l(d.message);let[c,m]=d.value,p=jb(Qu(e),[c,m]);if(a(p))return l(p.message);zu(i.value,`${JSON.stringify(p.value)}
|
|
32
|
+
`),n&&(n.current=c);let f=El.basename(i.value);return rm(t,f,c),Xu(t,f),u("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return l(`Failed to persist event: ${s}`)}}function cm(e,t,n){let r=Rl(t,n);if(a(r))return l(r.message);let o={...e,id:r.value[0]},s=kn(o);if(s.status!==Tn.Success)return s;let i=ei({event:o,rootDir:t,edge:n,id:r.value});return a(i)?i:s}function D(e,t){if(e.length===0||!e[0])return l("No events provided");if(h().readOnly)return l(h().readOnlyReason??"Cannot change the board while time travelling");let n=Gs(()=>{let r={},o=Hb(e[0],t,r);if(a(o))return l(o.message);let s=e.map(d=>cm(d,t,r)),i=s.filter(a);return i.length>0?l("Materialize and persist failed: "+i.map(d=>d.message).join(", ")):u("Materialization succeeded",s.map(d=>d.value))});return a(n)?l(n.message):n.value??l("Materialize and persist produced nothing")}var Hb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let r=R.getContributor(e.userId),o={id:$b(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return u("Contributor name is current",void 0);let s=cm(o,t,n);return a(s)?l(s.message):u("Contributor name recorded",void 0)};var dr=e=>e.trim().toLocaleLowerCase(),Cl=(e,t)=>dr(e).includes(dr(t));var Wb=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Gb=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},um=null,mm=new Map,Vb=()=>{let e=h().eventLog??[];if(e===um)return mm;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return um=e,mm=t,t},zb=e=>{let{contributors:t}=h(),n=Vb().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},pm=(e,t)=>{let n=dr(t.value);if(!n)return!0;switch(t.target){case"title":return Cl(e.title??"",n);case"description":return Cl(e.props.description??"",n);case"tag":return Wb(e).map(dr).some(o=>o.includes(n));case"assignee":return Gb(e).map(dr).some(o=>o.includes(n));case"actor":return zb(e).map(dr).some(o=>o.includes(n));case"ref":return Hs(e.id,t.value);default:return!0}};var Nl=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,Kb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,fm=(e,t)=>Object.values(e).filter(n=>Kb(n,t)).sort(Nl),gm=(e,t)=>{let n={};for(let r of Object.values(e)){if(B(r)&&t.length>0&&!t.every(s=>pm(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Nl);return n},hm=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Nl);return n};var ym=e=>ti(de(e),{at:"end"}),ti=(e,t={at:"end"})=>{let n=o=>a(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(st(void 0,void 0));let r=()=>n(st(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(st(void 0,o.rank)):l("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(st(o.rank,void 0)):l("Unable to resolve last sibling")}case"before":{let o=vm(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(st(i?.rank,s.rank))}case"after":{let o=vm(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(st(s.rank,i?.rank))}}},de=e=>{let t=h();if(!xm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return fm(t.nodes,e)},vm=(e,t)=>e.findIndex(n=>n.id===t),bm=(e,t,n={at:"end"})=>ti(de(t).filter(r=>r.id!==e),n),Xt=(e,t,n,r,o)=>{let s=bm(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=al(e,r);if(a(i))return i;let d=D([i.value],o);if(a(d))return d;let c=bm(t,e,n);return a(c)?c:c.value.needsRebalance?l("Rank rebalance failed to create space"):u("Resolved rank after rebalance",c.value.rank)},In=(e,t,n)=>{let r=ym(e);if(a(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=al(e,t);if(a(o))return o;let s=D([o.value],n);if(a(s))return s;let i=ym(e);return a(i)?i:i.value.needsRebalance?l("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var _={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=X(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||_.navigate({contextNode:o,selectedIndex:X(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=X(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;_.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Im(1),navigateToPreviousItem:()=>Im(-1),navigateToNextContainer:()=>Sm(1),navigateToPreviousContainer:()=>Sm(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},Im=e=>{let{selectedIndex:t,contextNode:n}=h(),r=X(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;_.navigate({selectedIndex:s,contextNode:n})},Sm=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=X(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let d=s.at(i+e)??s.at(0);if(!d)return;let c=X(d.id),m=Math.max(0,c.length-1),p=Math.min(Math.max(0,r),m),f=c.length?p:-1;_.navigate({contextNode:d,selectedIndex:f})};var Rm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Cm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},qb=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&>(t)&&t.childRenderAxis==="vertical"},ni=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=de(r.id);return _.navigate({contextNode:r,selectedIndex:Rm(t,o.length)}),!0},Nm=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ni(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=de(o.id).findIndex(d=>d.id===n.id);return i>=0?(_.navigate({contextNode:o,selectedIndex:i}),!0):Nm(o.id)},Em=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Nm(n))return!0;n=t[n]?.parentNodeId}return!1},Yb=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},Am=e=>{let{nodes:t,rootNodeId:n}=h();if(qb(e.contextNodeId)&&ni(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(Yb(e.selectedNodeId)&&e.selectedNodeId&&Em(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(ni(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&ni(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(Em(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return l("Unable to restore navigation");let o=de(r.id);return _.navigate({contextNode:r,selectedIndex:Rm(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as Xb,ulid as Jt}from"ulid";var Oo=Xb();function Jb(){let e=it();if(a(e))return l("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return l("No workspace found in event log");let[r]=X(n.id),[o]=r?X(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Qb(){let e=Jb();return a(e)?e:_.navigate(e.value)}function Tm({userId:e,userName:t}){let n=Oo(),r=Oo(),o=Oo(),s=Oo(),i=Oo(),d=st(void 0,void 0);if(a(d))return d;let c=st(void 0,void 0);if(a(c))return c;let m=st(c.value,void 0);if(a(m))return m;let p=st(void 0,void 0);if(a(p))return p;let f=st(p.value,void 0);if(a(f))return f;let g=st(f.value,void 0);if(a(g))return g;let v=st(void 0,void 0);return a(v)?v:u("Created default events",[{id:Jt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:d.value}},{id:Jt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Jt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:c.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Jt(),userId:e,userName:t,action:"add.board",payload:{id:Ws,name:"Closed",parent:n,rank:m.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ie,name:"Closed",parent:Ws,rank:v.value}},{id:Jt(),userId:e,userName:t,action:"lock.node",payload:{id:Ws}},{id:Jt(),userId:e,userName:t,action:"lock.node",payload:{id:ie}}])}var Zb=()=>{let e=it();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},ex=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");z.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");z.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Ot(e,t=[]){if(Zb())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=be.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Do(s);return a(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return l("Initialized Epiq project has no workspace init event");let n=Bt(e),{fatal:r,skipped:o}=vn(n);return r.length>0?l(`Materializing failed:
|
|
33
33
|
${r.map(s=>s.message).join(`
|
|
34
|
-
`)}`):(
|
|
35
|
-
|
|
36
|
-
`);
|
|
34
|
+
`)}`):(bn(o),Qb(),N({hasProjectDefinition:!0}),ex(t),u("State booted successfully",null))}import{WebSocket as tx}from"ws";var ri=new Set,wm=e=>{ri.add(e),e.on("close",()=>{ri.delete(e)}),e.on("error",()=>{ri.delete(e)})},cr=e=>{let t=JSON.stringify(e);for(let n of ri)n.readyState===tx.OPEN&&n.send(t)};var oi=e=>{It()&&(N({syncStatus:e}),cr({type:"sync-status",payload:e}))},Ur=(e="Syncing...")=>{oi({status:"syncing",msg:e})},ur=(e="Synced")=>{oi({status:"synced",msg:e})},Al=e=>{oi({status:"failed",msg:e})},si=e=>{oi({status:"offline",msg:e})},Te=e=>(Al(e),l(e));var _t=(e,t)=>(logger.error(`[boot:${e}] ${t}`),l(`[boot:${e}] ${t}`)),jr=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},ae=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t);import Ix from"node:fs";import Sn from"node:fs";import En from"node:path";import ii from"node:fs";import Mm from"node:path";var Xe=".epiq/project.json",Pm=e=>Mm.join(e,Xe),nx=e=>{if(!ii.existsSync(Pm(e)))return u("State branch carries no identity yet",null);let t=pt(e);return a(t)?l(`On the state branch: ${t.message}`):u("Read the state branch identity",t.value)},Tl=(e,t)=>{try{let n=Pm(e);return ii.mkdirSync(Mm.dirname(n),{recursive:!0}),ii.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
35
|
+
`,"utf8"),u("Wrote the state branch identity",void 0)}catch(n){return l(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},rx=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${Xe} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${Xe} > ${Xe}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
36
|
+
`);var Lm=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!ii.existsSync(kr(e)))return u("No project file to compare","no-checkout-file");let r=pt(e);if(a(r))return l(r.message);let o=nx(t);if(a(o))return l(o.message);if(o.value===null){let s=Tl(t,r.value);return a(s)?l(s.message):u("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?l(rx({checkout:r.value,branch:o.value,stateBranch:n})):u("The checkout and the state branch agree","matched")};import Qt from"node:fs";import _o from"node:path";var $r=e=>e.split(`
|
|
37
|
+
`).filter(t=>t.trim().length>0),km=e=>{let t=_o.join(e,rt,gn);try{if(!Qt.existsSync(t))return u("No events directory",[]);let n=Qt.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>$r(Qt.readFileSync(_o.join(t,r),"utf8")).length>0);return u("Looked for stranded event logs",n)}catch(n){return l(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Dm=e=>_o.join(e,rt,gn),Bm=e=>{let t=Dm(e),n=new Map;try{if(!Qt.existsSync(t))return n;for(let r of Qt.readdirSync(t))if(r.endsWith(".jsonl")&&!Ks(r))try{n.set(r,$r(Qt.readFileSync(_o.join(t,r),"utf8")))}catch(o){if(!Bo(o))throw o}}catch{return n}return n},ox=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Fm=(e,t)=>{if(t.size===0)return[];let n=Dm(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=_o.join(n,o);try{let d=Qt.existsSync(i)?Qt.readFileSync(i,"utf8"):null,c=new Set(d===null?[]:$r(d)),m=s.filter(f=>!c.has(f)).filter(ox);if(m.length===0)continue;Qt.mkdirSync(n,{recursive:!0});let p=d!==null&&d.length>0&&!d.endsWith(`
|
|
38
|
+
`);Qt.appendFileSync(i,`${p?`
|
|
37
39
|
`:""}${m.join(`
|
|
38
40
|
`)}
|
|
39
|
-
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},
|
|
40
|
-
`),
|
|
41
|
-
`));z.info("Creating initial commit");let r=await
|
|
42
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
43
|
-
${o.message}`):u("Created state branch",!0)},
|
|
44
|
-
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await
|
|
45
|
-
`+r.message);let o=r.value,s=o?await
|
|
46
|
-
`+s.message);let i=s.value;if(o&&i){let
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},
|
|
50
|
-
`+r.message);if(
|
|
51
|
-
`));z.info("Removing broken state branch worktree path"),
|
|
52
|
-
${o.message}`):u("Created state branch worktree",!0)},
|
|
53
|
-
`));
|
|
54
|
-
|
|
55
|
-
${
|
|
56
|
-
${c.message}`)}
|
|
57
|
-
${
|
|
58
|
-
${
|
|
59
|
-
${
|
|
60
|
-
${
|
|
61
|
-
${
|
|
62
|
-
${
|
|
63
|
-
|
|
64
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},wm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ht(e);if(d(o))return o;let s=o.value,i=[Ms(),await Id({repoRoot:e,stateBranchName:s}),await rr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await qb({stateBranchRoot:t,stateBranchName:s}),await Qc(t),n?await Yb({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(d(l))return a(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import ei from"node:fs";import Ed from"node:os";import Xb from"node:path";var Jb="epiq-sync.lock",Mm=600*1e3,Qb=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},Zb=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},ex=e=>e&&(e.hostname!==Ed.hostname()||Zb(e.pid))?Date.now()-e.startedAt>Mm:!0,Lm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Sd=e=>{try{return Qb(ei.readFileSync(e,"utf8"))}catch{return null}},Pm=(e,t)=>{let n={pid:process.pid,hostname:Ed.hostname(),startedAt:Date.now(),operation:t};try{return ei.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},tx=async({worktreeRoot:e,operation:t})=>{let n=await _a(e);if(d(n))return a(n.message);let r=Xb.join(n.value,Jb),o=()=>{try{let l=Sd(r);l&&l.pid===process.pid&&ei.rmSync(r)}catch{}};if(Pm(r,t))return u("Acquired sync lock",{acquired:!0,release:o});let s=Sd(r);if(!ex(s))return u("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?Lm(s):"unreadable lock file"}`);try{ei.rmSync(r,{force:!0})}catch{}if(Pm(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=Sd(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Ed.hostname(),startedAt:Date.now(),operation:"unknown"}})},ti=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await tx({worktreeRoot:e,operation:t});if(d(r))return a(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${Lm(r.value.heldBy)}`),u("State worktree is held by another process",null);let{release:o}=r.value;try{return u("Ran under the sync lock",await n())}finally{o()}};var rx=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=oe("getRepoRootDir",await wt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=oe("getStateBranchRoot",ue({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=oe("bootstrapStateBranchStorage",await wm({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(i))return a(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=oe("hasInProgressGitOperation(stateBranchRoot)",await Ns(s));if(d(l))return a(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let c=oe("ensureStateBranchLayout",Jc(r,s));return d(c)?a(c.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},ox=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=oe("stageStateBranchOwnEventFile",await Zs({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=oe("stageStateBranchMediaFiles",await Nm({stateBranchRoot:t}));if(d(o))return a(o.message);let s=oe("stageStateBranchEventConfig",await Am({stateBranchRoot:t}));if(d(s))return a(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=oe("hasStagedChanges(after stage)",await Hc(t,i));if(d(l))return a(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let c=oe("createStateBranchSyncCommit",await Tm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return d(c)?a(c.message):(logger.debug("[sync] created sync commit",c.value),u("Committed own event file",{createdCommit:!0,commitSha:c.value}))},Cd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Qs(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},km=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Ar();let n=oe("ensureSyncReady",await rx({cwd:e,ensureUpstream:!0}));if(d(n))return Te(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=oe("isDetachedHead(stateBranchRoot)",await Wc(o));if(d(i))return Te(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Te("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,c,m=!1,p=!1,f=oe("getStateBranch",Ht(r));if(d(f))return Te(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let v=oe("flushPendingLogs",$s(o,t));d(v)&&logger.error(`[sync] ${v.message}`);let x=oe("commitOwnEventFileToStateBranch",await ox({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(x))return Te(x.message);l=x.value.createdCommit,c=x.value.commitSha;let I=oe("hasRemote",await Xn({repoRoot:o}));if(d(I))return Te(I.message);if(!I.value)return Cd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s},"no remote");let R=oe("pullBranchRebaseIfPresent",await lo({cwd:o,branch:g}));if(d(R))return ao(R.message)?Cd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(R.message);m=R.value;let A=oe("isAheadOfUpstream",await jc(o));if(d(A))return Te(A.message);if(l||s||A.value){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let w=oe("pushStateBranch",await Ao({stateBranchRoot:o,repoRoot:r}));if(d(w)&&_c(w.message)){let M=oe("pullBranchRebaseIfPresent(retry)",await lo({cwd:o,branch:g}));if(d(M))return Te(M.message);m=m||M.value,w=oe("pushStateBranch(retry)",await Ao({stateBranchRoot:o,repoRoot:r}))}if(d(w))return ao(w.message)?Cd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(w.message);p=w.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let w=oe("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:o}));if(d(w))return Te(w.message);c=w.value.stdout.trim(),logger.debug("[sync] final sync commit sha",c)}return nr(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Rd=async(e,t)=>{let n=Im(e);try{return await t()}finally{let r=Sm(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ni=async e=>{let t=e.cwd??process.cwd(),n=await wt(t);if(d(n))return Te(n.message);let r=ue({repoRoot:n.value});if(d(r))return Te(r.message);let o=r.value;if(!nx.existsSync(o))return km(e);let s=await ti({worktreeRoot:o,operation:"sync",fn:()=>Rd(o,()=>km(e))});return d(s)?Te(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Xt=null,ri=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Xt,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Xt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Xt;logger.debug("[sync] syncAndReloadState creating promise"),Xt=sx();try{let e=await Xt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg}),d(e)&&h().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Xt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Xt=null}},sx=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let e=Dm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:e.message,syncStatus:h().syncStatus}),e;if(Xt)return Xt;logger.debug("[sync] syncAndReloadState:start");let t=oe("resolveActorId",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let n=Zn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=oe("syncEpiqWithRemote",await ni({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Te(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=Nd(o);return d(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),u("Synced",!0))},Nd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=oe("loadMergedEvents",bt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(t),message:(d(t),t.message),count:d(t)?void 0:t.value.events.length}),d(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),a(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=Dm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:n.message,syncStatus:h().syncStatus}),n;let r=fm(),o=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=oe("bootStateFromEventLog",Dt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(i),message:(d(i),i.message)}),d(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),a(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=oe("restoreNavigationAnchor",hm(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(s),message:d(s)?s.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),d(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),s):u("Reloaded state from event log",null)},Dm=()=>h().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Mr=3e3,Bm=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Mr?null:t},Fm=0,Ad,Td=!1,To=!1,wd=()=>{if(Td)return!0;let e=et();return d(e)?!1:e.value.syncStatus.status==="syncing"},ix=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-Fm;return Math.max(0,e-t)},Om=()=>{Ad||(Ad=setTimeout(async()=>{if(Ad=void 0,!!vt()){if(wd()){To=!0;return}To=!1,await ax()}},ix()))},ax=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!vt())return a("Cannot auto-sync before state is initialized");if(wd())return To=!0,a("Sync already in progress");Td=!0,Fm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ri()}finally{Td=!1,To&&Om()}},oi=()=>{vt()&&(To=!0,!wd()&&Om())};import wo from"node:fs";import Mo from"node:path";import{z as Pr}from"zod";var si="recent-projects.json",dx=20,lx=Pr.object({projectId:Pr.string().min(1),root:Pr.string().min(1),lastOpenedAt:Pr.number().finite()}),cx=Pr.object({projects:Pr.array(lx)}),Um=()=>Mo.join(ln(),si),Lr=e=>Mo.basename(e)||e,_m=e=>{let t=Mo.resolve(e);try{return wo.realpathSync(t)}catch{return t}},jm=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,$m=e=>{if(!po(e.root))return!1;let t=so(e.root);return!d(t)&&t.value===e.projectId},Hm=()=>{let e=Um();if(!wo.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(wo.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${si}: ${r instanceof Error?r.message:String(r)}`)}let n=cx.safeParse(t);return n.success?u("Read recent projects",n.data.projects):a(`Invalid ${si} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ux=e=>{let t=Um();try{wo.mkdirSync(Mo.dirname(t),{recursive:!0}),wo.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
65
|
-
`,"utf8")}catch(n){return a(`Unable to write ${si}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},bn=({exclude:e}={})=>{let t=Hm();if(d(t))return t;let n=e===void 0?null:_m(e);return u("Listed recent projects",t.value.filter(r=>n===null||_m(r.root)!==n).filter($m).sort(jm))},ii=({root:e,now:t=Date.now()})=>{let n=Mo.resolve(e),r=so(n);if(d(r))return a(r.message);let o=r.value,s=Hm(),i=d(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(c=>c.projectId!==o&&c.root!==n)].filter($m).sort(jm).slice(0,dx);return ux(l)};var Ln=()=>{let e=ie(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Wm=()=>{let e=xe(process.cwd());if(d(e))return!1;let t=$t(e.value);return ce(t)},Gm=e=>e===!0?"on":e===!1?"off":null,Vm=e=>e==="on"?!0:e==="off"?!1:null;var Ke={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:Ke.cyan,accent2:Ke.magenta,primary:Ke.white,secondary:Ke.grayDark,secondary2:Ke.grayLight,gray:Ke.gray,green:Ke.green,yellow:Ke.yellow,red:Ke.red};var T={red:Ke.red,yellow:Ke.yellow,green:Ke.green,blue:Ke.blue,magenta:Ke.magenta,cyan:Ke.cyan},kr={urgent:T.red,critical:T.red,important:T.red,blocker:T.red,asap:T.red,immediate:T.red,fail:T.red,failure:T.red,broken:T.red,bug:T.red,error:T.red,incident:T.red,outage:T.red,production:T.red,crash:T.red,security:T.red,warning:T.yellow,warn:T.yellow,risky:T.yellow,risk:T.yellow,attention:T.yellow,pending:T.yellow,review:T.yellow,"needs-review":T.yellow,qa:T.yellow,testing:T.yellow,test:T.yellow,validate:T.yellow,verification:T.yellow,staging:T.yellow,check:T.yellow,"follow-up":T.yellow,followup:T.yellow,waiting:T.yellow,blocked:T.yellow,hold:T.yellow,done:T.green,complete:T.green,completed:T.green,success:T.green,ok:T.green,stable:T.green,resolved:T.green,fixed:T.green,closed:T.green,merged:T.green,released:T.green,deployed:T.green,approved:T.green,verified:T.green,working:T.green,healthy:T.green,pass:T.green,passing:T.green,info:T.blue,information:T.blue,note:T.blue,docs:T.blue,documentation:T.blue,doc:T.blue,guide:T.blue,help:T.blue,explanation:T.blue,detail:T.blue,details:T.blue,context:T.blue,design:T.blue,discussion:T.blue,proposal:T.blue,idea:T.blue,feature:T.magenta,enhancement:T.magenta,improvement:T.magenta,refactor:T.magenta,refactoring:T.magenta,cleanup:T.magenta,optimize:T.magenta,optimization:T.magenta,perf:T.magenta,performance:T.magenta,upgrade:T.magenta,migration:T.magenta,modernize:T.magenta,debt:T.magenta,todo:T.cyan,next:T.cyan,planned:T.cyan,plan:T.cyan,future:T.cyan,backlog:T.cyan,investigate:T.cyan,explore:T.cyan,prototype:T.cyan};var mx=e=>e.props.tags??[],px=e=>e.props.assignees??[],kn=e=>mx(e).map(t=>C.getTag(t)).filter(t=>!!t),Dn=e=>px(e).map(t=>C.getContributor(t)).filter(t=>!!t),ai=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",kn(n))},di=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",Dn(n))};var E={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""};var fx=/^(\d+)(h|d|w|mo|y)$/,gx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,hx=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},yx=(e,t=new Date)=>{let n=e.match(fx);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},vx=e=>{let t=e.match(gx);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),c=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return hx({year:l,month:c,day:m,hour:p,minute:f})?new Date(l,c-1,m,p,f):null},or=e=>{let t=e.trim().toLowerCase();return yx(t)??vx(t)};var zm=/^(\d+)(s|m)?$/,li=e=>{let t=e.trim().toLowerCase().match(zm);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ci=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&zm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Km=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,bx=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Md=(e=bx)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var xx=["BOARD","TICKET","SWIMLANE","COMMENT"],ye={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Ix=[ye.EDITOR,ye.VIEW,ye.USERNAME,ye.AUTOSYNC,ye.SYNC_DEBOUNCE_MS,ye.ATTACHMENT_MAX_KB,ye.LOG_LEVEL],Sx=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[mt.TITLE,mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[mt.TITLE];case"COMMENT":return[mt.COMMENT];default:return[]}},Ld=[String(Mr),"5000","15000","30000","60000"],kd=["250","500","1000"],Xm=["10s","20s","30s","45s"],sr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],ui=[E.NEW,E.EDIT,E.DELETE,E.MOVE],Pd=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],qm=[E.FILTER,E.PEEK,E.REPLAY],Ex={WORKSPACE:[...sr,...ui],BOARD:[...qm,...sr,...ui],SWIMLANE:[...qm,...sr,...ui],TICKET:[...sr,...ui,...Pd],FIELD:[...sr,...Pd],FIELD_LIST:[...sr,...Pd],TEXT:[...sr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},Cx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Po=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Ym=e=>e.parentNodeId===he,Rx=({selectedNode:e,breadCrumb:t})=>{let n=Sx(e?.context);return Po({breadCrumb:t,selectedNode:e})?n.includes(mt.DESCRIPTION)?n:[...n,mt.DESCRIPTION]:n},Nx=({selectedNode:e,breadCrumb:t})=>{let n=Po({breadCrumb:t,selectedNode:e});return n?[Me.REF,Me.TITLE,...n.props?.description?.trim()?[Me.DESCRIPTION]:[],...kn(n).length>0?[Me.TAGS]:[],...Dn(n).length>0?[Me.ASSIGNEES]:[]]:e?[Me.REF,Me.TITLE]:[]},Dd=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Ax=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ln();if(!r)return[E.HELP,E.CONFIG];if(!Wm())return[E.HELP,E.INIT,E.OPEN];if(t)return[E.HELP,E.PEEK,E.REPLAY,E.EXPORT,E.CONFIG,E.YANK];let o=e?.context,s=o&&xx.includes(o),i=[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Ex[c]:[]))],l=Po({breadCrumb:n,selectedNode:e});return i.filter(c=>c===E.MOVE?!1:c===E.YANK?!!(l??e):c===E.EDIT?s||!!l:c===E.DELETE?s:c===E.UNTAG?!!(l&&kn(l).length>0):c===E.UNASSIGN?!!(l&&Dn(l).length>0):c===E.RE_OPEN_ISSUE?!!(l&&Ym(l)):c===E.CLOSE_ISSUE?!!(l&&!Ym(l)):!0)},Ne=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:Ax({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?Dd():[],[E.HELP]:[],[E.PEEK]:[...Md(),"now","prev","next"],[E.REPLAY]:[...Md()],[E.EDIT]:Rx({selectedNode:n,breadCrumb:o}),[E.YANK]:Nx({selectedNode:n,breadCrumb:o}),[E.COMMENT]:[],[E.DELETE]:["confirm"],[E.RE_OPEN_ISSUE]:["confirm"],[E.CLOSE_ISSUE]:["confirm"],[E.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[E.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[E.TAG]:[...new Set([...Object.keys(kr),...C.getExistingTags()])],[E.UNTAG]:[...ai()?.value?.map(({name:l})=>l)??[]],[E.UNASSIGN]:[...di()?.value?.map(({name:l})=>l)??[]],[E.ASSIGN]:C.getExistingAssignees(),[E.NEW]:Cx(s),[E.CONFIG]:[...Ix]}[e]??[]};import fp from"chalk";var Jm=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Lx from"zod";import Tx from"node:crypto";import Lo from"node:fs";import ep from"node:path";var Qm="/media/",Zm=e=>`${Qm}${e}`,Bd=(e,t)=>`})`;var Jt=500,wx=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,ir=(e,t)=>`${e}.${t}`,Mx=e=>wx.test(e),tp=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?u("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?u("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?u("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?u("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${lu.join(", ")}`),np=e=>Tx.createHash("sha256").update(e).digest("hex"),Px=(e,t=Jt)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=tp(e);return d(n)?n:u("Validated attachment data",{hash:np(e),ext:n.value,bytes:e.length})},rp=(e,t,n=Jt)=>{let r=Px(t,n);if(d(r))return r;let o=mo(e),s=ep.join(o,ir(r.value.hash,r.value.ext));try{Lo.existsSync(s)||(Lo.mkdirSync(o,{recursive:!0}),Lo.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},op=(e,t,n=Jt)=>{if(!Mx(t))return a("Invalid attachment file name");let r=ep.join(mo(e),t);if(!Lo.existsSync(r))return a("Attachment blob not found");let o;try{o=Lo.readFileSync(r)}catch(c){return a(`Unable to read attachment blob: ${c instanceof Error?c.message:String(c)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(np(o)!==s)return a("Attachment blob does not match its content hash");let l=tp(o);return d(l)?l:l.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var ko=50,Do=5e3,sp=()=>{let e=ee().commandMeta.inputString,t=Lx.coerce.number().int().min(ko).max(Do).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${ko}-${Do} KB (default ${Jt})`);let n=gt({attachmentMaxKb:t.data});return d(n)?n:(ze({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import Dr from"chalk";var Od={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ip=(e,t,n)=>Math.max(t,Math.min(n,e)),Fd=(e,t,n)=>e+(t-e)*n,ap=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kx=e=>e.toLowerCase().trim(),Dx=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),c=0,m=0,p=0;i>=0&&i<1?(c=s,m=l):i>=1&&i<2?(c=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(c=l,p=s):(c=s,p=l);let f=o-s/2;return[Math.round((c+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},dp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var Bx=(e,t,n)=>{let r=ip(n,0,1);return[Math.round(Fd(e[0],t[0],r)),Math.round(Fd(e[1],t[1],r)),Math.round(Fd(e[2],t[2],r))]};var Fx=(e,t,n)=>Bx(e,t,n),Bo=e=>{let t=ap(e)%360,n=Dx(t,Od.stringColor.saturation,Od.stringColor.lightness);return dp(n)},de=(e,t=kr)=>{let n=kx(e??"");return n&&t[n]?t[n]:Bo(n)};var lp=e=>{let t=Od.gradient.stops,n=ip(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return Fx(t[s],t[s+1],i)},mi=e=>dp(lp(e)),pi=e=>ap(e.toLowerCase().trim())/4294967295,cp=e=>{let t=pi(e);return lp(t)},Ox=e=>{let[t,n,r]=cp(e);return{normal:o=>Dr.bgRgb(t,n,r).black(o),cursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},_d=e=>{let[t,n,r]=cp(e);return{fg:o=>Dr.rgb(t,n,r)(o),fgCursor:o=>Dr.rgb(t,n,r).inverse(o),bg:o=>Dr.bgRgb(t,n,r).black(o),bgCursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},fi=e=>Ox(e).normal(` ${e} `);var st=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as _x}from"node:crypto";var Ux="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jx=e=>{let t=_x("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=Ux[Number(n>>s&31n)]}return r},De=(e,t)=>jx(`${e}:virtual:${t}`);import up from"chalk";var me=e=>up.dim(e),Be=e=>up.hex(y.primary)(e),He=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>pi(f)-pi(g)).slice(0,r).map(f=>fi(f)).join(" ");return p?`${me(e)}${p}${me(n)}`:""};var Qt={None:"none",Invalid:"invalid",Valid:"valid"};var $x=["BOARD","TICKET","SWIMLANE"],mp=()=>{let e=h().selectedNode;if(!e?.context)return W({message:me("Missing target context")});if($x.includes(e.context))return J();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===De(t?.parentNodeId??"","comments"))return J()}return W({message:me("Command not available in this context")})},le="<ENTER> to confirm",J=(e="",t=[])=>({message:me(e),validity:Qt.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:Qt.Invalid,message:e,completionWordList:t}),Fr=e=>e.length===0,pp=(e,t)=>{let n=Qe(h().breadCrumb,"BOARD");if(d(n))return W({message:Be("Command is not applicable in this context")});let r=ks(n.value.id);return d(r)?W({message:Be(`Unable to ${t}: board id is not a valid ULID`)}):Km({date:e,horizonDate:r.value})?null:W({message:Be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},gi=e=>` ${fp.hex("#000").bgHex(de(e))(` ${e} `)} `,Ud=({modifier:e})=>{let t="confirm";return e===t?J(le):W({message:Fr(e)?me("if you are certain, enter ")+fi(t):"",completionWordList:[t]})},Hx=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:me(n)}):J():W({message:Fr(r)?t:"",completionWordList:[...e]}),Br=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Fr(n)&&Fr(r)?W({message:e,completionWordList:[]}):J(t??le),Wx=({modifier:e,inputString:t})=>{let n=Dd();return!Fr(e)||!Fr(t)?J(le):W({message:n.length?me("number from the list, or a path"):me("path to an epiq project"),completionWordList:n})},Gx=({modifier:e,inputString:t})=>{let n=Ne(E.CONFIG);if(!n.includes(e))return W({message:He({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ye.EDITOR:{let r=[...Jm];return t.trim()?r.includes(t.trim())?J(le):W({message:He({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:He({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?J(le):W({message:He({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.USERNAME:return t.trim()?J(le):W({message:Be("Enter a user name. Saved in ")+fp.bgBlack("~/.epiq-global/config.json")});case ye.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?J(le):W({message:He({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ye.AUTOSYNC:{let r=["on","off"],o=ie().autoSync;if(!r.includes(t.trim())){let s=Gm(o);return W({message:He({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return J(le)}case ye.ATTACHMENT_MAX_KB:{let r=ie().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<ko||o>Do){let s=He({prefix:" examples: ",wordList:kd,minLengthForHints:0,inputString:t});return W({message:Be(`provide a size cap in KB (${ko}-${Do}). current: ${r??Jt} KB.`)+s,completionWordList:kd})}return J(le)}case ye.SYNC_DEBOUNCE_MS:{let r=ie().autoSyncIntervalMs,o=Bm(t);if(!t.trim()||o===null||o<Mr){let s=He({prefix:" examples: ",wordList:Ld,minLengthForHints:0,inputString:t});return W({message:Be(`provide duration above ${Mr}ms. current duration: ${r}ms.`)+s,completionWordList:Ld})}return J(le)}default:return W({message:Be("Unknown config option"),completionWordList:n})}},Vx=({modifier:e,inputString:t})=>{let n=Ne(E.EDIT);if(!n.length)return W({message:Be("Command not available in this context")});if(!n.includes(e)){let r=He({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||Be("Unknown edit option"),completionWordList:n})}switch(e){case mt.COMMENT:return t.trim()?J(le):W({message:me("write a comment...")});case mt.TITLE:return J(le);case mt.DESCRIPTION:{let{preferredEditor:r}=ie();return r?J(me("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:Be("Unknown edit option"),completionWordList:n})}},zx=({modifier:e})=>{let t=Ne(E.YANK);return t.length?t.includes(e)?J(le+me(" and copy to clipboard")):W({message:He({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:Be("Nothing selected to copy from")})},Kx={[E.EXPORT]:()=>J(le+me(", and create export markdown file")),[E.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return J(le);let n={message:me("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=or(r);if(!r||!o)return W(n);let s=pp(o,"peek");return s||J(le)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ci(e.modifier,e.inputString),r={message:me("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=or(t);if(!t||!o)return W(r);let s=pp(o,"replay");return s||(n&&li(n)===null?W({message:Be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):J("<ENTER> to replay board history",n?Xm:[]))},[E.EXIT]:()=>J(le+me(" and exit the application")),[E.INIT]:()=>J(le),[E.OPEN]:Wx,[E.PALETTE]:()=>J(le),[E.FILTER]:e=>{if(e.modifier==="clear")return J(le);let t=s=>Ne(E.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:He({wordList:Ne(E.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ne(E.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?W({message:He({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):J():W({message:He({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[E.NONE]:e=>{let t=Ne(E.NONE);return W({message:He({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[E.NEW]:e=>Hx({list:Ne(E.NEW),hint:He({wordList:Ne(E.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[E.HELP]:()=>J(le),[E.EDIT]:Vx,[E.COMMENT]:e=>{let t=Br({hint:me(`write a comment (max ${4e3} char)...`),onOk:me(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Qt.Invalid?t:e.inputString.length>4e3?J(Be("max input exceeded")):t},[E.CONFIG]:Gx,[E.YANK]:zx,[E.DELETE]:e=>{let t=mp();return t.validity==="invalid"?t:Ud(e)},[E.CLOSE_ISSUE]:e=>Ud(e),[E.RE_OPEN_ISSUE]:e=>Ud(e),[E.MOVE]:e=>{let t=mp();return t.validity==="invalid"?t:Br({hint:He({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ne(E.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[E.TAG]:e=>{let n=C.getExistingTags().slice(0,10).map(gi).join("");return Br({hint:n.length?me("create tag or reuse:")+n+me(""):me("create tag ...")})(e)},[E.UNTAG]:e=>{let t=ai();if(d(t))return W({message:Be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(gi).slice(0,10);return n.length?Br({hint:me(" ... ")+n.join("")})(e):W({message:Be("Issue has no tags"),completionWordList:[]})},[E.ASSIGN]:e=>{let t=C.getExistingAssignees().map(gi).slice(0,10);return Br({hint:me("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=di();if(d(t))return W({message:Be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(gi).slice(0,10);return n.length?Br({hint:me("remove assignee... ")+n.join("")})(e):W({message:Be("Issue has no assignees"),completionWordList:[]})},[E.SYNC]:()=>J(le)},gp=Object.fromEntries(Object.entries(Kx).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var hi=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var qx=3,Yx=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Xx=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Jx=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=qx&&!Yx.has(t)&&!/^\d+$/.test(t)),Qx=e=>{let t=new Map;for(let s of Xx(e))for(let i of Jx(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=hi.filter(s=>!r.has(s));return[...n,...o]},hp=hi,yp=-1,vp=()=>{let e=et();if(d(e))return hi;let t=e.value,n=t.eventLog.length;return n!==yp&&(hp=Qx(t),yp=n),hp};var bp=e=>Object.values(E).includes(e),xp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:c}=gp[n].validate(n,r,s),m=n!==E.PEEK&&n!==E.REPLAY,p=o==="command"||o==="modifier"?Ne(n):m?vp():[],{mode:f}=h(),g=f===b.COMMAND_LINE?i??"":"",v=[...c,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Iu(e,v):{hint:"",hints:[],remainder:"",overlap:0}}};var Ip=e=>{let t=e.trimStart(),n=eI(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=tI(e),l=bp(r)?r:null,c=l!==null,m=r!=="",p=l?Ne(l)??[]:[],f=l&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let v=s?"":i,x=Zx(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:c,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:v,inputString:x}},Zx=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},eI=e=>e.trim()?e.trim().split(/\s+/):[],tI=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as nI}from"react";var Or=e=>e===jd||e===":",jd=" ",qe={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Qt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},$d=new Set,Sp=()=>{for(let e of $d)e()},Hd=e=>($d.add(e),()=>$d.delete(e)),Zt=e=>{let n=e(qe),r=Ip(n.value),o=n.cursorPosition===n.value.length;qe={...n,commandMeta:xp(r,o)},Sp()},Fo=({message:e,status:t})=>{let n=structuredClone(qe);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,qe=n,Sp(),u(e,null)},Wd=e=>{Zt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Gd=e=>{Zt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Or(n[o-1]);)o--;for(;o>0&&!Or(n[o-1]);)o--}else{for(;o<n.length&&!Or(n[o]);)o++;for(;o<n.length&&Or(n[o]);)o++}return{...t,cursorPosition:o}})},Ep=()=>{Zt(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Cp=()=>{Zt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Or(t[r-1]);)r--;for(;r>0&&!Or(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},yi=e=>{Zt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},Rp=()=>{Zt(e=>({...e,commandIsPending:!0}))},Q=e=>{Zt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Np=({addToHistory:e=!0})=>{Zt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ap=()=>{Zt(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Tp=()=>{Zt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ee=()=>qe,wp=()=>nI(Hd,ee,ee),vi=()=>{let[e,...t]=qe.value.split(jd);return t.join(jd).trim()};var S={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function rI(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function oI(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function sI(e,t,n){let r=h().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Mp(e,t){let n=ee();if(e.sequence==="?"&&t!==b.PALETTE)return S.InitCommandPalette;if(e.sequence===":"&&t!==b.COMMAND_LINE)return S.InitCommandLine;if(t===b.MOVE)switch(e.name){case"m":case"return":return S.ConfirmMove}if(t===b.COMMAND_LINE)return pu(e,n.value);if(t===b.PALETTE)return fu(e,n.value);let r=rI(e)||oI(e);if(r)return iI(r,t);if(e.ctrl&&e.name==="c")return S.Exit;switch(e.name){case"r":return S.EditTitle;case"e":return S.EditDescription;case"n":return S.AddItem;case"m":return S.InitMove;case"d":return S.Delete;case"y":return S.Yank;case"return":return S.Confirm;case"space":return S.Confirm;case"v":return ie().viewMode==="wide"?S.SetViewDense:S.SetViewWide;case"q":case"escape":return S.Exit;default:return null}}function iI(e,t){let n=t===b.MOVE?{prevItem:S.MovePreviousItem,nextItem:S.MoveNextItem,prevContainer:S.MoveToPreviousContainer,nextContainer:S.MoveToNextContainer}:{prevItem:S.NavPreviousItem,nextItem:S.NavNextItem,prevContainer:S.NavToPreviousContainer,nextContainer:S.NavToNextContainer};return sI(h().contextNode.childRenderAxis,e,n)}var bi=e=>{let{context:t}=h().contextNode;if(!t)return U.None;switch(e){case E.EXIT:return U.Exit;case E.EXPORT:return U.Export;case E.INIT:return U.Init;case E.OPEN:return U.OpenProject;case E.DELETE:return U.Delete;case E.EDIT:return U.Edit;case E.COMMENT:return U.Comment;case E.HELP:return U.ViewHelp;case E.RE_OPEN_ISSUE:return U.ReopenIssue;case E.CLOSE_ISSUE:return U.CloseIssue;case E.TAG:return U.TagTicket;case E.UNTAG:return U.UntagTicket;case E.ASSIGN:return U.AssignUserToTicket;case E.UNASSIGN:return U.UnassignUserFromTicket;case E.NEW:return U.NewItem;case E.FILTER:return U.Filter;case E.MOVE:return U.Move;case E.PEEK:return U.Peek;case E.REPLAY:return U.Replay;case E.CONFIG:return U.Config;case E.YANK:return U.Yank;case E.SYNC:return U.Sync;default:return U.None}},U={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import ff from"node:fs";import iS from"node:path";import aS from"react";import{Box as oS}from"ink";import Ni from"react";import NI from"chalk";import{Box as Kd,Text as AI}from"ink";import en from"react";import{Text as Pp}from"ink";import Lp,{useEffect as kp,useState as aI}from"react";var Dp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ye=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Y(),r=Dp[n]??Dp.default,[o,s]=aI(0);if(kp(()=>{s(0)},[r]),kp(()=>{if(!e)return;let l=setInterval(()=>{s(c=>(c+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Lp.createElement(Pp,null,t);let i=r[o]??r[0]??t;return Lp.createElement(Pp,{color:y.accent,dimColor:o===1},i)};import{Box as Vd,Text as dI}from"ink";import xi from"react";var lI=(e,t,n,r)=>{let o=c=>Math.max(1,e[c]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},xt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),c=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/l)),p=Math.max(0,e.length-m),{start:f,end:g}=o?lI(o,e.length,c,i):s?{start:Math.min(p,Math.max(0,c-m+1)),end:Math.min(p,Math.max(0,c-m+1))+m}:{start:Math.min(p,Math.floor(c/m)*m),end:Math.min(p,Math.floor(c/m)*m)+m},v=Math.max(1,g-f),x=e.slice(f,g),I=e.length>v,R=i,A=I?Math.max(1,Math.floor(v/e.length*R)):R,w=Math.max(0,R-A),M=Math.max(1,e.length-v),k=I?Math.floor(f/M*w):0;return xi.createElement(Vd,{flexDirection:"row",height:i,width:"100%"},xi.createElement(Vd,{flexDirection:"column",flexGrow:1,height:i},x),xi.createElement(Vd,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((D,ve)=>xi.createElement(dI,{key:ve,color:I&&ve>=k&&ve<k+A?y.accent:y.secondary},I?"\u2502":" "))))};import{Box as jr,Text as $r}from"ink";import it from"react";var Bp,zd,cI=()=>{let{eventLog:e=[]}=h();if(zd&&Bp===e)return zd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Bp=e,zd=t,t},Ii=e=>cI().has(e);import{Text as uI}from"ink";import mI from"react";var pI=e=>e.toLowerCase().trim(),fI=(e,t=kr)=>{let n=pI(e);return t[n]?t[n]:Bo(n)},Bn=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:fn(o,n);return mI.createElement(uI,{underline:t,color:fI(o)},"@"+s,Ii(e)?"":"\u2197")};import{Text as gI}from"ink";import hI from"react";var _r=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getTag(e);if(!r)return;let o=n===void 0?r.name:fn(r.name,n);return hI.createElement(gI,{underline:t,backgroundColor:de(r.name),color:y.secondary}," "+o+" ")};import{useEffect as yI,useState as vI}from"react";var bI=80,Fp=1400,Si=new Set,Oo=null,xI=e=>(Si.add(e),Oo||(Oo=setInterval(()=>{for(let t of Si)t()},bI)),()=>{Si.delete(e),Si.size===0&&Oo&&(clearInterval(Oo),Oo=null)}),II=()=>{let e=Date.now()%Fp/Fp;return e<.5?e*2:(1-e)*2},Ur=e=>{let[,t]=vI(0);return yI(()=>{if(e)return xI(()=>t(n=>n+1))},[e]),mi(II())};var SI=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),fn(e.slice(o).trim(),n)]},Op=3,EI=2,CI=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},_p=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Ur(r),s=e-4,i=s-7-1,[l,c]=SI(Ie(t.title),i,s),m=c?null:fn(Ie(t.props.description),s)||null,p=kn(t),f=Dn(t).map(A=>({...A,name:A.name})),g=Math.max(1,s-Op),v=C.getCommentsByIssue(t.id),x=v.length?String(v.length).length+2+1:0,{shown:I,hidden:R}=CI([...p.map(A=>({id:A.id,isTag:!0,width:Math.min(A.name.length,g)+Op})),...f.map(A=>({id:A.id,isTag:!1,width:Math.min(A.name.length,g)+EI+(Ii(A.id)?0:1)}))],s-x);return it.createElement(jr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},it.createElement(jr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},it.createElement(jr,{justifyContent:"space-between"},it.createElement($r,{color:y.primary},l),it.createElement($r,{color:y.secondary2,dimColor:!0},_(t.id))),c&&it.createElement($r,{color:y.primary},c),m&&it.createElement($r,{color:y.secondary2,dimColor:!0},m)),it.createElement(jr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},it.createElement(jr,{flexDirection:"row"},I.map(A=>it.createElement(jr,{paddingRight:1,key:A.id},A.isTag?it.createElement(_r,{id:A.id,maxWidth:g}):it.createElement(Bn,{id:A.id,maxWidth:g}))),R>0&&it.createElement($r,{color:y.secondary2,dimColor:!0},"+",R)),v.length>0&&it.createElement($r,{color:y.accent},"[",v.length,"]")))};import{Box as ar,Text as _o}from"ink";import pt from"react";var RI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Up=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Ur(s),c=(r.props.tags??[]).map(D=>C.getTag(D)).filter(D=>!!D),m=(r.props.assignees??[]).map(D=>C.getContributor(D)).map(D=>D&&{...D,name:D.name}).filter(D=>!!D),p=1,f=c.length*(1+p),g=m.length*(2+p),v=c.map(D=>pt.createElement(ar,{key:D.id,paddingRight:p},pt.createElement(_o,{color:de(D.name)},"\u25A0"))),x=m.map(D=>pt.createElement(ar,{key:D.id,paddingRight:p},pt.createElement(_o,{color:Bo(D.name)},"@"+D.name.at(0)))),I=s?l:o?y.accent:i===b.MOVE?y.secondary:y.primary,R=C.getCommentsByIssue(r.id),A=R.length?String(R.length).length+2+p:0,w=R.length?pt.createElement(ar,{paddingRight:p},pt.createElement(_o,{color:y.accent},"[",R.length,"]")):null,M=f+g+A,k=Math.max(1,n-t-M-(M>0?1:0));return pt.createElement(ar,{justifyContent:"space-between"},pt.createElement(ar,null,pt.createElement(ar,{width:t},o?pt.createElement(Ye,{isSelected:!0}):pt.createElement(_o,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),pt.createElement(_o,{wrap:"truncate",color:I},RI(r.title,k))),pt.createElement(ar,null,v,x,w))};var TI=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:c,replay:m}=Y(),p=c[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Ur(g),x=`${e.title} ${NI.hex(y.secondary2).dim("("+p.length+")")}`,I=3,R=o?1:5,A=s&&i===-1,w=n-3-(o?1:0)-(A?2:0),M=Math.max(2,String(p.length).length+1),k=r-I-1,D=en.createElement(Kd,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},en.createElement(Ye,{isSelected:t}),en.createElement(AI,{bold:!0,color:g?v:t?y.accent:y.primary},x," ",e.readonly?"\u{1F512}":"")),ve=(Ve,Nt)=>{let dt=s&&i===Nt;if(!P(Ve))return null;let ke=f?.has(Ve.id)??!1;return o?en.createElement(Up,{key:Ve.id,index:Nt,labelWidth:M,width:w,ticket:Ve,isSelected:dt,isFlashing:ke,mode:l}):en.createElement(_p,{key:Ve.id,width:w,ticket:Ve,isSelected:dt,isFlashing:ke})};return en.createElement(Kd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},D,en.createElement(Kd,null,p.length>0&&en.createElement(xt,{selectedIndex:i,height:k,itemHeight:R},p.map(ve)),A&&en.createElement(Ye,{isSelected:!0})))},jp=en.memo(TI);import{Box as lr,Text as sl}from"ink";import Fe,{useMemo as jo}from"react";var $p=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Hp=(e,t,n)=>ge.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as Gr,Text as xn}from"ink";import Xe,{useEffect as wI,useMemo as MI,useRef as PI}from"react";import{decodeTime as Wp}from"ulid";var Wr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Ei=e=>String(e).padStart(2,"0"),Ci=e=>`${e.getFullYear()}-${Ei(e.getMonth()+1)}-${Ei(e.getDate())} ${Ei(e.getHours())}:${Ei(e.getMinutes())}`;var LI=e=>De(e,"attachments"),kI=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>Wp(t.id)-Wp(n.id)),Gp=e=>{for(let t of e)C.deleteNode(t.id)},DI=(e,t,n)=>ge.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),BI=(e,t)=>{let n=C.getNode(LI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>DI(o,s,n.id)).map(o=>C.createNode(o)).filter(ce).map(({value:o})=>o).filter(ut);return t.length>0&&h().selectedIndex<0&&O.navigate({contextNode:n,selectedIndex:0}),r},FI=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Vp({ticket:e,width:t,height:n}){let r=MI(()=>kI(e),[e]),o=PI([]);wI(()=>(Gp(o.current),o.current=BI(e,r),()=>{Gp(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Y(),l=Math.max(1,n-4),c=Math.max(12,t-32);return r.length===0?Xe.createElement(Gr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(xn,{color:y.primary},"No attachments yet."),Xe.createElement(Gr,{paddingTop:1},Xe.createElement(xn,{color:y.primary},"Attach images from the browser GUI"),Xe.createElement(xn,{color:y.accent}," epiq gui "),Xe.createElement(xn,{color:y.primary},"by dropping or pasting them."))):Xe.createElement(Gr,{flexDirection:"column",width:t,height:n},Xe.createElement(Gr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Xe.createElement(xn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Xe.createElement(xt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>c?m.name.slice(0,c-1)+"\u2026":m.name;return Xe.createElement(Gr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Xe.createElement(xn,{color:y.accent},f?"\u276F ":" "),Xe.createElement(Gr,{paddingLeft:1},Xe.createElement(xn,{color:y.secondary2},`#${p+1} `),Xe.createElement(xn,{color:f?y.accent:y.primary},g),Xe.createElement(xn,{color:y.secondary2}," "+FI(m.bytes)+" "+Wr(Re(m.id)))))})))}import{Box as Fn,Text as On}from"ink";import Pe,{useEffect as GI,useMemo as of,useRef as VI}from"react";import{decodeTime as sf}from"ulid";var Kp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,qd=e=>e.replace(Kp,"");var zp=e=>e==="additions"||e==="deletions",Yd=e=>{let t=Kp.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!zp(r.side)||!zp(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var qp=/```\n([\s\S]*?)\n?```\s*$/,Yp=e=>qp.exec(e)?.[1]??null,OI=/`[^`\n]+`[^\n]*\n?$/,Xp=e=>qd(e).replace(qp,"").replace(OI,"").trim(),_I=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Xd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${_I(e)}`;var UI=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},Uo=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},jI=/!\[([^\]]*)\]\([^)]*\)/g,$I=e=>e.replace(jI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),HI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),WI=4,Qp=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(WI)),Jd=e=>{let t=!1;return e.map(Qp).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Yd(n);if(r)return{kind:"caption",text:Xd(r)};let o=$I(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Uo(s[1]??"")}:{kind:"text",spans:Uo(o)}})},Zp=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Jp=(e,t)=>{let n=[];for(let r of Jd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of Zp(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of UI(HI(r.spans),t))n.push({kind:r.kind,spans:Uo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},ef=(e,t)=>{let n=Yd(e),r=n?Yp(e):null;if(!n||r===null)return Jp(qd(e).split(`
|
|
66
|
-
`),t);let o=Xp(e),s=r.split(`
|
|
67
|
-
`)
|
|
68
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:Xd(n)},...s.flatMap((c,m)=>Zp(c,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as tf,Text as dr}from"ink";import It from"react";var nf=({spans:e,bold:t,wrap:n})=>It.createElement(dr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?It.createElement(dr,{key:o,color:y.yellow},r.text):It.createElement(dr,{key:o},r.text))),Qd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return It.createElement(dr,null," ");case"fence":return It.createElement(dr,{color:y.secondary2},"```");case"caption":return It.createElement(dr,{color:y.accent,wrap:r},e.text);case"heading":return It.createElement(nf,{spans:e.spans,bold:!0,wrap:r});case"text":return It.createElement(nf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return It.createElement(dr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},rf=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return It.createElement(tf,{flexDirection:"column"},e.map((o,s)=>It.createElement(tf,{key:s},It.createElement(Qd,{line:o,width:t,gutter:r}))))};var zI=4,KI=e=>De(e,"comments"),qI=e=>C.getCommentsByIssue(e.id).sort((t,n)=>sf(t.id)-sf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),af=e=>{for(let t of e)C.deleteNode(t.id)},YI=(e,t)=>{let n=C.getNode(KI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>Hp(o,s,n.id)).map(C.createNode).filter(ce).map(({value:o})=>o).filter(yo);return t.length>0&&h().selectedIndex<0&&O.navigate({contextNode:n,selectedIndex:0}),r};function df({ticket:e,width:t,height:n}){let r=of(()=>qI(e),[e]),o=VI([]);GI(()=>(af(o.current),o.current=YI(e,r),()=>{af(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Y(),l=Math.max(1,n-4),c=Math.max(20,t-8),m=of(()=>r.map(f=>{let g=ef(f.md,c);return g.length>0?g:[{kind:"blank"}]}),[r,c]),p=m.map(f=>f.length+zI);return r.length===0?Pe.createElement(Fn,{flexDirection:"column",width:t,height:n,padding:1},Pe.createElement(On,{color:y.primary},"No comments yet."),Pe.createElement(Fn,{paddingTop:1},Pe.createElement(On,{color:y.primary},"Use"),Pe.createElement(On,{color:y.accent}," :comment "),Pe.createElement(On,{color:y.primary},"to add the first one."))):Pe.createElement(Fn,{flexDirection:"column",width:t,height:n},Pe.createElement(Fn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Pe.createElement(On,{color:y.secondary2},"Comments (",r.length,") ")),Pe.createElement(xt,{height:l,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let v=g===s;return Pe.createElement(Fn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Pe.createElement(Fn,{flexDirection:"row",paddingBottom:1},Pe.createElement(On,{color:y.accent},v?"\u276F ":" "),Pe.createElement(Fn,{paddingLeft:1},Pe.createElement(On,{color:y.secondary2},`#${g+1} `),Pe.createElement(Bn,{id:f.authorId}),Pe.createElement(On,{color:y.secondary2}," "+Wr(Re(f.id))))),Pe.createElement(Fn,{paddingLeft:3,paddingBottom:1},Pe.createElement(rf,{lines:m[g]??[],width:c})))})))}import{Box as Ri,Text as XI}from"ink";import In from"react";var lf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Y(),{title:o}=t,s=t.parentNodeId?C.getNode(t.parentNodeId):void 0,i=s&&P(s)?o===fe.ASSIGNEES?s.props.assignees??[]:o===fe.TAGS?(s.props.tags??[]).filter(l=>C.getTag(l)):[]:[];return In.createElement(Ri,{alignItems:"center",paddingTop:1},In.createElement(Ri,{minWidth:12},In.createElement(Ye,{isSelected:n}),In.createElement(XI,{color:n?y.accent:y.secondary2},o,":")),In.createElement(Ri,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,c)=>{let m=r.id===t.id&&c===e;return In.createElement(Ri,{key:`${o}-${l}`,paddingRight:2,minHeight:1},In.createElement(Ye,{isSelected:m}),o===fe.ASSIGNEES?In.createElement(Bn,{isSelected:m,id:l}):o===fe.TAGS?In.createElement(_r,{isSelected:m,id:l}):null)})))};import{Box as Vr,Text as tl}from"ink";import St,{useEffect as JI,useMemo as nl}from"react";var Zd=e=>Math.max(5,String(Math.max(e,1)).length+3),cf=(e,t)=>Math.max(0,e-6-Zd(t));var el=(e,t=0)=>Math.max(1,e-5-2*t);var QI="\u2029",uf=(e,t)=>`${e}::inline-line::${t}`,rl=new Map,mf=e=>{let t=rl.get(e)??[];rl.delete(e);for(let n of t)C.deleteNode(n)},ZI=(e,t)=>{mf(e);let n=[];t.forEach((r,o)=>{let s=yt(BigInt(o+1));if(!ce(s))return;let i=C.createNode(ge.text({id:uf(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));ce(i)&&n.push(i.value.id)}),rl.set(e,n)},ol=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=Y(),c=nl(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=nl(()=>c.join("\0"),[c]);JI(()=>(ZI(e,c),()=>{mf(e)}),[e,m]);let p=Zd(c.length),f=cf(s,c.length),v=nl(()=>Jd(c).map(x=>{if(x.kind==="code"||x.kind==="caption")return{...x,text:Za(x.text,f)};if(x.kind==="text"||x.kind==="heading"){let I=x.spans.map(R=>R.code?`\`${R.text}\``:R.text).join("");return{...x,spans:Uo(Za(I,f))}}return x}),[c,f]).map((x,I)=>{let R=l.id===e&&i===I;return St.createElement(Vr,{key:uf(e,I)},St.createElement(Vr,{flexShrink:0},St.createElement(tl,{color:R?y.primary:y.secondary2,dimColor:!R},`${I+1} `.padStart(p,"\xA0"))),x.kind==="blank"?St.createElement(tl,{backgroundColor:R?"gray":void 0},QI):St.createElement(Vr,null,St.createElement(Qd,{line:x,width:x.kind==="code"?f:0,wrap:"truncate-end"})))});return St.createElement(Vr,{flexDirection:"column",paddingTop:1},St.createElement(Vr,null,St.createElement(Ye,{isSelected:o}),St.createElement(tl,{color:o?y.accent:y.secondary2},t)),St.createElement(Vr,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},St.createElement(xt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},v)))};var eS=e=>De(e,"description"),tS=e=>De(e,"comments"),nS=e=>De(e,"history"),rS=e=>De(e,"attachments"),pf=({ticket:e,height:t})=>{let n=jo(()=>$p(e),[e]),{selectedIndex:r,contextNode:o}=Y(),s=process.stdout.columns||120,i=jo(()=>eS(e.id),[e.id]),l=jo(()=>tS(e.id),[e.id]),c=jo(()=>nS(e.id),[e.id]),m=jo(()=>rS(e.id),[e.id]),p=C.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===l||o.parentNodeId===l,v=o.id===c||o.parentNodeId===c,x=o.id===m||o.parentNodeId===m,I=q(e.id);if(g){let k=t-3;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(df,{ticket:e,width:s,height:k}))}if(x){let k=t-3;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(Vp,{ticket:e,width:s,height:k}))}if(v){let M=C.getNode(c),k=M&&ut(M)?M.props.value??"":"",D=el(t);return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},M?Fe.createElement(ol,{id:M.id,label:"Event log",text:k,selected:!1,maxWidth:s,rows:D}):null)}let R=I.reduce((M,k)=>ho(k)||k.id===l||k.id===m||k.id===c?M+1:M,0),A=el(t,R),w=(M,k)=>M.id===i?Fe.createElement(ol,{key:M.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:k,maxWidth:s,rows:A}):ho(M)?Fe.createElement(lf,{key:M.id,parent:M,selected:k,selectedIndex:r}):M.id===l?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(sl,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):M.id===m?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(sl,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Attachments (${p}) \u203A\u203A `)):M.id===c?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(sl,{backgroundColor:y.secondary,color:k?y.accent:y.primary}," History \u203A\u203A ")):null;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((M,k)=>w(M,f&&r===k)))};var sS=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let c=t.context,m=c===V.TICKET||c===V.FIELD_LIST||c===V.FIELD,p=c===V.BOARD||c===V.SWIMLANE,f=c===V.TICKET?t:r.find(R=>R.context===V.TICKET),g=Math.floor(l/3),v=Math.floor(l/Math.max(e.length,1)),x=Math.min(v,g),I=s==="dense";return Ni.createElement(oS,{flexDirection:"row",height:i},p&&e.map((R,A)=>{let w=t.id===R.id,M=w?n:-1,k=t.context===V.BOARD&&n===A;return Ni.createElement(jp,{key:R.id,height:i,width:x,swimlane:R,isSelected:k,isDense:I,isFocused:w,listSelectedIndex:M,mode:o})}),m&&f&&Ni.createElement(pf,{height:i,ticket:f}))},Ai=Ni.memo(sS);import{render as dS}from"ink";import{Writable as lS}from"node:stream";var $o=e=>String(e).padStart(2,"0"),cS=e=>{let t=e.getUTCFullYear(),n=$o(e.getUTCMonth()+1),r=$o(e.getUTCDate()),o=$o(e.getUTCHours()),s=$o(e.getUTCMinutes()),i=$o(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},uS=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",mS=async(e,{width:t,height:n})=>{let r="",o=new lS({write(i,l,c){let m=pS(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),c()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=dS(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},pS=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),gf=async()=>{let{viewMode:e}=ie(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(A=>A.context==="BOARD");if(!i)return a("No board found to export");let l=120,c=40,m=await mS(aS.createElement(Ai,{height:c,width:l,swimlanes:(s[i.id]??[]).filter(A=>A!==void 0&&Pt(A)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:c});if(!m)return a("Failed to render board export");let p=Cs(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=cS(f),v=`board_${uS(i.title)}_${g}.md`,x=Zc(p.value);ff.mkdirSync(x,{recursive:!0});let I=iS.join(x,v),R=`# Board - ${i.title}
|
|
41
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},sx=(e,t)=>{let n=new Set($r(t));return $r(e).filter(r=>!n.has(r))},ix=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
42
|
+
`),Om=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await He({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return u("No committed log to compare against",void 0);let o=sx(r.stdout,n);return o.length>0?l(ix(t,o,$r(r.stdout).length)):u("Event log only grew",void 0)};var ax="[epiq:init-repo]",Um=async e=>{let t=await He({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return u("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return l(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
43
|
+
`));z.info("Creating initial commit");let r=await U({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return l(r.message);let o=await U({args:["commit-tree",r.value.stdout.trim(),"-m",ax],cwd:e});if(a(o))return l(o.message);let s=await U({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?l(s.message):u("Created initial commit",!0)},_m=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",lx=async e=>{let t=await Fs(e);if(a(t))return l(t.message);let n=await qc(e);return a(n)?l(n.message):u("Built sync commit message",`[sync|branch:${_m(t.value)}:sha:${_m(n.value)}]`)},wl=async({repoRoot:e,stateBranchName:t})=>{z.info(`Creating ${t}`);let n=await U({args:["commit-tree",ru,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return l(`Failed to create state branch commit
|
|
44
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await U({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?l(`Failed to create ${t}
|
|
45
|
+
${o.message}`):u("Created state branch",!0)},Uo=async({repoRoot:e,stateBranchName:t})=>{let n=await Bs({repoRoot:e,branch:t});if(a(n))return l(`Ensure local state branch failed
|
|
46
|
+
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await fn({repoRoot:e});if(a(r))return l(`Ensure local state branch failed
|
|
47
|
+
`+r.message);let o=r.value,s=o?await bo({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(a(s))return l(`Ensure local state branch failed
|
|
48
|
+
`+s.message);let i=s.value;if(o&&i){let d=await pe.fetch({cwd:e,remote:ft,branch:t});if(a(d))return l(`Failed to fetch ${t} from remote
|
|
49
|
+
${d.message}`)}if(i){let d=await U({args:["branch","--track",t,`${ft}/${t}`],cwd:e});return a(d)?l(`Failed to create local ${t} from remote
|
|
50
|
+
${d.message}`):u("Created local state branch from remote",!0)}return wl({repoRoot:e,stateBranchName:t})},dx=async({repoRoot:e,branch:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return l(n.message);let r=n.value.stdout.split(`
|
|
51
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},cx=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=So(En.dirname(t));if(a(r))return l(`Failed to create state branch worktree
|
|
52
|
+
`+r.message);if(Sn.existsSync(t)&&!Sn.existsSync(En.join(t,".git"))){let s=km(t);if(a(s))return l(s.message);if(s.value.length>0)return l([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
53
|
+
`));z.info("Removing broken state branch worktree path"),au(t)}z.info("Creating state branch worktree");let o=await pe.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?l(`Failed to create state branch worktree
|
|
54
|
+
${o.message}`):u("Created state branch worktree",!0)},On=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await mx({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(r))return r;let o=Lm({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(o)?l(o.message):(o.value==="stamped"&&z.info("Stamped the state branch with this project\u2019s identity"),r)},ux=(e,t)=>{let n=Dr(sr());return En.dirname(e)===n&&En.dirname(t)===n},mx=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await dx({repoRoot:e,branch:n});if(a(r))return l(r.message);let o=Dr(t),s=r.value?Dr(r.value):null;if(s&&s===o&&Sn.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o&&ux(s,o))return l([`The state branch ${n} is checked out under project ${En.basename(s)}, but this checkout names project ${En.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${Xe} here`,`with \`git show ${n}:${Xe}\`, and keep the branch's.`].join(`
|
|
55
|
+
`));if(s&&s!==o){let c=await Qc(s);if(a(c))return l(c.message);if(c.value||Vu(s))return l([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
56
|
+
`));z.info("Moving state branch worktree to expected location");let m=await pe.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return l(`Failed to remove existing state branch worktree
|
|
57
|
+
${m.message}`)}if(s&&!Sn.existsSync(s)){z.info("Pruning stale state branch worktree");let c=await pe.worktreePrune({cwd:e});if(a(c))return l(`Failed to prune stale worktrees
|
|
58
|
+
${c.message}`)}let i=await Kc({repoRoot:e,worktreeRoot:t});if(a(i))return l(i.message);let d=Sn.existsSync(t);if(i.value&&d)return u("State branch worktree already exists",!1);if(i.value&&!d){z.info("Pruning missing registered state branch worktree");let c=await pe.worktreePrune({cwd:e});if(a(c))return l(`Failed to prune stale worktrees
|
|
59
|
+
${c.message}`)}return cx({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},px=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Fs(e);if(a(n))return l(n.message);if(n.value===t)return u("State branch already checked out",!1);(await He({cwd:e,args:["rebase","--abort"]})).exitCode===0&&z.info("Aborted stale state branch rebase");let o=await pe.checkout({cwd:e,branch:t});return a(o)?l(`Failed to checkout ${t}
|
|
60
|
+
${o.message}`):u("Checked out state branch",!0)},fx=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ka(t);if(a(n))return l(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await fn({repoRoot:t});if(a(r))return l(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=Gt(e);if(a(o))return o;let s=o.value,i=await bo({repoRoot:t,branch:s});if(a(i))return l(i.message);if(!i.value)return u("Remote state branch missing; upstream will be configured on first push",!1);z.info(`Configuring ${s} upstream`);let d=await pe.fetch({cwd:t,remote:ft,branch:s});if(a(d))return l(`Failed to fetch ${s}
|
|
61
|
+
${d.message}`);let c=await pe.setUpstream({cwd:t,branch:s,upstream:`${ft}/${s}`});return a(c)?l(`Failed to set state branch upstream
|
|
62
|
+
${c.message}`):u("Configured state branch upstream",!0)},ai=async({stateBranchRoot:e,eventFileName:t})=>{let n=ou(t),r=En.join(e,n);if(!Sn.existsSync(r))return u("No event file to stage",null);let o=await Om({stateBranchRoot:e,relativePath:n,workingContent:Sn.readFileSync(r,"utf8")});if(a(o))return l(o.message);let s=await pe.stage({cwd:e,pathspec:[n]});return a(s)?l(`Failed to stage state branch event file
|
|
63
|
+
${s.message}`):u("Staged state branch event file",n)},jm=async({stateBranchRoot:e})=>{let t=su(),n=En.join(e,t);if(!Sn.existsSync(n))return u("No media directory to stage",null);let r=await pe.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?l(`Failed to stage state branch media files
|
|
64
|
+
${r.message}`):u("Staged state branch media files",t)},$m=async({stateBranchRoot:e})=>{let t=[qa(),Ya(),Xe].filter(r=>Sn.existsSync(En.join(e,r)));if(t.length===0)return u("No event log config to stage",[]);let n=await pe.stage({cwd:e,pathspec:t});return a(n)?l(`Failed to stage event log config
|
|
65
|
+
${n.message}`):u("Staged event log config",t)},Hm=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await lx(e);return a(r)?l(`Create state branch sync commit failed
|
|
66
|
+
`+r.message):Br({cwd:t,message:r.value,pathspec:n})},jo=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ka(t);if(a(n))return l(n.message);let r=Gt(e);if(a(r))return r;let o=r.value,s=n.value?await pe.push({cwd:t}):await pe.push({cwd:t,remote:ft,branch:o,setUpstream:!0});if(a(s))return l(`Failed during state branch push
|
|
67
|
+
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},Wm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Gt(e);if(a(o))return o;let s=o.value,i=[Eo(),await Uo({repoRoot:e,stateBranchName:s}),await On({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await px({stateBranchRoot:t,stateBranchName:s}),await du(t),n?await fx({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let d of i){if(a(d))return l(d.message);r=r||!!d.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import li from"node:fs";import Pl from"node:os";import gx from"node:path";var hx="epiq-sync.lock",Gm=600*1e3,yx=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},vx=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},bx=e=>e&&(e.hostname!==Pl.hostname()||vx(e.pid))?Date.now()-e.startedAt>Gm:!0,zm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ml=e=>{try{return yx(li.readFileSync(e,"utf8"))}catch{return null}},Vm=(e,t)=>{let n={pid:process.pid,hostname:Pl.hostname(),startedAt:Date.now(),operation:t};try{return li.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},xx=async({worktreeRoot:e,operation:t})=>{let n=await za(e);if(a(n))return l(n.message);let r=gx.join(n.value,hx),o=()=>{try{let d=Ml(r);d&&d.pid===process.pid&&li.rmSync(r)}catch{}};if(Vm(r,t))return u("Acquired sync lock",{acquired:!0,release:o});let s=Ml(r);if(!bx(s))return u("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?zm(s):"unreadable lock file"}`);try{li.rmSync(r,{force:!0})}catch{}if(Vm(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=Ml(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Pl.hostname(),startedAt:Date.now(),operation:"unknown"}})},di=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await xx({worktreeRoot:e,operation:t});if(a(r))return l(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${zm(r.value.heldBy)}`),u("State worktree is held by another process",null);let{release:o}=r.value;try{return u("Ran under the sync lock",await n())}finally{o()}};var Sx=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=ae("getRepoRootDir",await kt(e));if(a(n))return l(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=ae("getStateBranchRoot",fe({repoRoot:r}));if(a(o))return l(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=ae("bootstrapStateBranchStorage",await Wm({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(i))return l(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let d=ae("hasInProgressGitOperation(stateBranchRoot)",await Ds(s));if(a(d))return l(d.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:d.value}),d.value)return logger.info("[sync] state branch git operation in progress"),l("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let c=ae("ensureStateBranchLayout",lu(r,s));return a(c)?l(c.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},Ex=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=ae("stageStateBranchOwnEventFile",await ai({stateBranchRoot:t,eventFileName:n}));if(a(r))return l(r.message);let o=ae("stageStateBranchMediaFiles",await jm({stateBranchRoot:t}));if(a(o))return l(o.message);let s=ae("stageStateBranchEventConfig",await $m({stateBranchRoot:t}));if(a(s))return l(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let d=ae("hasStagedChanges(after stage)",await Zc(t,i));if(a(d))return l(d.message);if(logger.debug("[sync] state branch change check after stage result",{changed:d.value}),!d.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let c=ae("createStateBranchSyncCommit",await Hm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(c)?l(c.message):(logger.debug("[sync] created sync commit",c.value),u("Committed own event file",{createdCommit:!0,commitSha:c.value}))},Ll=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return si(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Km=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),l("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),l("Own event file must end with .jsonl");Ur();let n=ae("ensureSyncReady",await Sx({cwd:e,ensureUpstream:!0}));if(a(n))return Te(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=ae("isDetachedHead(stateBranchRoot)",await eu(o));if(a(i))return Te(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Te("Cannot run :sync while the state branch is in detached HEAD state");let d=!1,c,m=!1,p=!1,f=ae("getStateBranch",Gt(r));if(a(f))return Te(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let v=ae("flushPendingLogs",qs(o,t));a(v)&&logger.error(`[sync] ${v.message}`);let I=ae("commitOwnEventFileToStateBranch",await Ex({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(I))return Te(I.message);d=I.value.createdCommit,c=I.value.commitSha;let x=ae("hasRemote",await fn({repoRoot:o}));if(a(x))return Te(x.message);if(!x.value)return Ll({repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,bootstrapped:s},"no remote");let C=ae("pullBranchRebaseIfPresent",await Io({cwd:o,branch:g}));if(a(C))return xo(C.message)?Ll({repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,bootstrapped:s}):Te(C.message);m=C.value;let A=ae("isAheadOfUpstream",await Jc(o));if(a(A))return Te(A.message);if(d||s||A.value){logger.info("[sync] pushing state branch",{createdCommit:d,bootstrapped:s,stateBranchRoot:o});let M=ae("pushStateBranch",await jo({stateBranchRoot:o,repoRoot:r}));if(a(M)&&Yc(M.message)){let w=ae("pullBranchRebaseIfPresent(retry)",await Io({cwd:o,branch:g}));if(a(w))return Te(w.message);m=m||w.value,M=ae("pushStateBranch(retry)",await jo({stateBranchRoot:o,repoRoot:r}))}if(a(M))return xo(M.message)?Ll({repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,bootstrapped:s}):Te(M.message);p=M.value}if(d){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let M=ae("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(a(M))return Te(M.message);c=M.value.stdout.trim(),logger.debug("[sync] final sync commit sha",c)}return ur(p?"Synced and pushed":m||d?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,pulled:m,pushed:p,bootstrapped:s,offline:!1})},kl=async(e,t)=>{let n=Bm(e);try{return await t()}finally{let r=Fm(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ci=async e=>{let t=e.cwd??process.cwd(),n=await kt(t);if(a(n))return Te(n.message);let r=fe({repoRoot:n.value});if(a(r))return Te(r.message);let o=r.value;if(!Ix.existsSync(o))return Km(e);let s=await di({worktreeRoot:o,operation:"sync",fn:()=>kl(o,()=>Km(e))});return a(s)?Te(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Zt=null,ui=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Zt,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Zt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Zt;logger.debug("[sync] syncAndReloadState creating promise"),Zt=Rx();try{let e=await Zt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg}),a(e)&&h().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Zt||l(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Zt=null}},Rx=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let e=qm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:e.message,syncStatus:h().syncStatus}),e;if(Zt)return Zt;logger.debug("[sync] syncAndReloadState:start");let t=ae("resolveActorId",ne());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),l("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let n=lr(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ae("syncEpiqWithRemote",await ci({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Te(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=Dl(o);return a(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),u("Synced",!0))},Dl=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ae("loadMergedEvents",St(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),l(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=qm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:n.message,syncStatus:h().syncStatus}),n;let r=Cm(),o=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ae("bootStateFromEventLog",Ot(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),l(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ae("restoreNavigationAnchor",Am(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),a(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),s):u("Reloaded state from event log",null)},qm=()=>h().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),l("Will not re-materialize if not in default mode, to not lose edit data"));var Hr=3e3,Ym=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Hr?null:t},Xm=0,Bl,Fl=!1,$o=!1,Ol=()=>{if(Fl)return!0;let e=it();return a(e)?!1:e.value.syncStatus.status==="syncing"},Cx=()=>{let e=le().autoSyncIntervalMs??1e4,t=Date.now()-Xm;return Math.max(0,e-t)},Jm=()=>{Bl||(Bl=setTimeout(async()=>{if(Bl=void 0,!!It()){if(Ol()){$o=!0;return}$o=!1,await Nx()}},Cx()))},Nx=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return l("Cannot auto-sync while peeking");if(!It())return l("Cannot auto-sync before state is initialized");if(Ol())return $o=!0,l("Sync already in progress");Fl=!0,Xm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ui()}finally{Fl=!1,$o&&Jm()}},mi=()=>{It()&&($o=!0,!Ol()&&Jm())};import Ho from"node:fs";import Wo from"node:path";import{z as Wr}from"zod";var pi="recent-projects.json",Ax=20,Tx=Wr.object({projectId:Wr.string().min(1),root:Wr.string().min(1),lastOpenedAt:Wr.number().finite()}),wx=Wr.object({projects:Wr.array(Tx)}),Zm=()=>Wo.join(un(),pi),Gr=e=>Wo.basename(e)||e,Qm=e=>{let t=Wo.resolve(e);try{return Ho.realpathSync(t)}catch{return t}},ep=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,tp=e=>{if(!No(e.root))return!1;let t=vo(e.root);return!a(t)&&t.value===e.projectId},np=()=>{let e=Zm();if(!Ho.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(Ho.readFileSync(e,"utf8"))}catch(r){return l(`Invalid ${pi}: ${r instanceof Error?r.message:String(r)}`)}let n=wx.safeParse(t);return n.success?u("Read recent projects",n.data.projects):l(`Invalid ${pi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Mx=e=>{let t=Zm();try{Ho.mkdirSync(Wo.dirname(t),{recursive:!0}),Ho.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
68
|
+
`,"utf8")}catch(n){return l(`Unable to write ${pi}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},Rn=({exclude:e}={})=>{let t=np();if(a(t))return t;let n=e===void 0?null:Qm(e);return u("Listed recent projects",t.value.filter(r=>n===null||Qm(r.root)!==n).filter(tp).sort(ep))},fi=({root:e,now:t=Date.now()})=>{let n=Wo.resolve(e),r=vo(n);if(a(r))return l(r.message);let o=r.value,s=np(),i=a(s)?[]:s.value,d=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(c=>c.projectId!==o&&c.root!==n)].filter(tp).sort(ep).slice(0,Ax);return Mx(d)};var _n=()=>{let e=le(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},rp=()=>{let e=Se(process.cwd());if(a(e))return!1;let t=pt(e.value);return me(t)},op=e=>e===!0?"on":e===!1?"off":null,sp=e=>e==="on"?!0:e==="off"?!1:null;var Je={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:Je.cyan,accent2:Je.magenta,primary:Je.white,secondary:Je.grayDark,secondary2:Je.grayLight,gray:Je.gray,green:Je.green,yellow:Je.yellow,red:Je.red};var T={red:Je.red,yellow:Je.yellow,green:Je.green,blue:Je.blue,magenta:Je.magenta,cyan:Je.cyan},Vr={urgent:T.red,critical:T.red,important:T.red,blocker:T.red,asap:T.red,immediate:T.red,fail:T.red,failure:T.red,broken:T.red,bug:T.red,error:T.red,incident:T.red,outage:T.red,production:T.red,crash:T.red,security:T.red,warning:T.yellow,warn:T.yellow,risky:T.yellow,risk:T.yellow,attention:T.yellow,pending:T.yellow,review:T.yellow,"needs-review":T.yellow,qa:T.yellow,testing:T.yellow,test:T.yellow,validate:T.yellow,verification:T.yellow,staging:T.yellow,check:T.yellow,"follow-up":T.yellow,followup:T.yellow,waiting:T.yellow,blocked:T.yellow,hold:T.yellow,done:T.green,complete:T.green,completed:T.green,success:T.green,ok:T.green,stable:T.green,resolved:T.green,fixed:T.green,closed:T.green,merged:T.green,released:T.green,deployed:T.green,approved:T.green,verified:T.green,working:T.green,healthy:T.green,pass:T.green,passing:T.green,info:T.blue,information:T.blue,note:T.blue,docs:T.blue,documentation:T.blue,doc:T.blue,guide:T.blue,help:T.blue,explanation:T.blue,detail:T.blue,details:T.blue,context:T.blue,design:T.blue,discussion:T.blue,proposal:T.blue,idea:T.blue,feature:T.magenta,enhancement:T.magenta,improvement:T.magenta,refactor:T.magenta,refactoring:T.magenta,cleanup:T.magenta,optimize:T.magenta,optimization:T.magenta,perf:T.magenta,performance:T.magenta,upgrade:T.magenta,migration:T.magenta,modernize:T.magenta,debt:T.magenta,todo:T.cyan,next:T.cyan,planned:T.cyan,plan:T.cyan,future:T.cyan,backlog:T.cyan,investigate:T.cyan,explore:T.cyan,prototype:T.cyan};var Px=e=>e.props.tags??[],Lx=e=>e.props.assignees??[],Un=e=>Px(e).map(t=>R.getTag(t)).filter(t=>!!t),jn=e=>Lx(e).map(t=>R.getContributor(t)).filter(t=>!!t),gi=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?l("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Un(n))},hi=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?l("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",jn(n))};var E={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""};var kx=/^(\d+)(h|d|w|mo|y)$/,Dx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Bx=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Fx=(e,t=new Date)=>{let n=e.match(kx);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Ox=e=>{let t=e.match(Dx);if(!t)return null;let[,n,r,o,s,i]=t,d=Number(n),c=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return Bx({year:d,month:c,day:m,hour:p,minute:f})?new Date(d,c-1,m,p,f):null},mr=e=>{let t=e.trim().toLowerCase();return Fx(t)??Ox(t)};var ip=/^(\d+)(s|m)?$/,yi=e=>{let t=e.trim().toLowerCase().match(ip);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},vi=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&ip.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},ap=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,_x=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],_l=(e=_x)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var Ux=["BOARD","TICKET","SWIMLANE","COMMENT"],xe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},ht={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},jx=[xe.EDITOR,xe.VIEW,xe.USERNAME,xe.AUTOSYNC,xe.SYNC_DEBOUNCE_MS,xe.ATTACHMENT_MAX_KB,xe.LOG_LEVEL],$x=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[ht.TITLE,ht.DESCRIPTION];case"BOARD":case"SWIMLANE":return[ht.TITLE];case"COMMENT":return[ht.COMMENT];default:return[]}},jl=[String(Hr),"5000","15000","30000","60000"],$l=["250","500","1000"],cp=["10s","20s","30s","45s"],pr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],bi=[E.NEW,E.EDIT,E.DELETE,E.MOVE],Ul=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],lp=[E.FILTER,E.PEEK,E.REPLAY],Hx={WORKSPACE:[...pr,...bi],BOARD:[...lp,...pr,...bi],SWIMLANE:[...lp,...pr,...bi],TICKET:[...pr,...bi,...Ul],FIELD:[...pr,...Ul],FIELD_LIST:[...pr,...Ul],TEXT:[...pr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},Wx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Go=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&B(n)),dp=e=>e.parentNodeId===ie,Gx=({selectedNode:e,breadCrumb:t})=>{let n=$x(e?.context);return Go({breadCrumb:t,selectedNode:e})?n.includes(ht.DESCRIPTION)?n:[...n,ht.DESCRIPTION]:n},Vx=({selectedNode:e,breadCrumb:t})=>{let n=Go({breadCrumb:t,selectedNode:e});return n?[Me.REF,Me.TITLE,...n.props?.description?.trim()?[Me.DESCRIPTION]:[],...Un(n).length>0?[Me.TAGS]:[],...jn(n).length>0?[Me.ASSIGNEES]:[]]:e?[Me.REF,Me.TITLE]:[]},Hl=()=>{let e=Rn({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},zx=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=_n();if(!r)return[E.HELP,E.CONFIG];if(!rp())return[E.HELP,E.INIT,E.OPEN];if(t)return[E.HELP,E.PEEK,E.REPLAY,E.EXPORT,E.CONFIG,E.YANK];let o=e?.context,s=o&&Ux.includes(o),i=[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Hx[c]:[]))],d=Go({breadCrumb:n,selectedNode:e});return i.filter(c=>c===E.MOVE?!1:c===E.YANK?!!(d??e):c===E.EDIT?s||!!d:c===E.DELETE?s:c===E.UNTAG?!!(d&&Un(d).length>0):c===E.UNASSIGN?!!(d&&jn(d).length>0):c===E.RE_OPEN_ISSUE?!!(d&&dp(d)):c===E.CLOSE_ISSUE?!!(d&&!dp(d)):!0)},Ne=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:zx({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?Hl():[],[E.HELP]:[],[E.PEEK]:[..._l(),"now","prev","next"],[E.REPLAY]:[..._l()],[E.EDIT]:Gx({selectedNode:n,breadCrumb:o}),[E.YANK]:Vx({selectedNode:n,breadCrumb:o}),[E.COMMENT]:[],[E.DELETE]:["confirm"],[E.RE_OPEN_ISSUE]:["confirm"],[E.CLOSE_ISSUE]:["confirm"],[E.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[E.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[E.TAG]:[...new Set([...Object.keys(Vr),...R.getExistingTags()])],[E.UNTAG]:[...gi()?.value?.map(({name:d})=>d)??[]],[E.UNASSIGN]:[...hi()?.value?.map(({name:d})=>d)??[]],[E.ASSIGN]:R.getExistingAssignees(),[E.NEW]:Wx(s),[E.CONFIG]:[...jx]}[e]??[]};import Tp from"chalk";var up=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Jx from"zod";import Kx from"node:crypto";import Vo from"node:fs";import fp from"node:path";var mp="/media/",pp=e=>`${mp}${e}`,Wl=(e,t)=>`})`;var en=500,qx=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,fr=(e,t)=>`${e}.${t}`,Yx=e=>qx.test(e),gp=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?u("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?u("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?u("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?u("Sniffed image type","webp"):l(`Unsupported image format. Allowed: ${xu.join(", ")}`),hp=e=>Kx.createHash("sha256").update(e).digest("hex"),Xx=(e,t=en)=>{if(e.length===0)return l("Attachment is empty");if(e.length>t*1024)return l(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=gp(e);return a(n)?n:u("Validated attachment data",{hash:hp(e),ext:n.value,bytes:e.length})},yp=(e,t,n=en)=>{let r=Xx(t,n);if(a(r))return r;let o=Co(e),s=fp.join(o,fr(r.value.hash,r.value.ext));try{Vo.existsSync(s)||(Vo.mkdirSync(o,{recursive:!0}),Vo.writeFileSync(s,t))}catch(i){return l(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},vp=(e,t,n=en)=>{if(!Yx(t))return l("Invalid attachment file name");let r=fp.join(Co(e),t);if(!Vo.existsSync(r))return l("Attachment blob not found");let o;try{o=Vo.readFileSync(r)}catch(c){return l(`Unable to read attachment blob: ${c instanceof Error?c.message:String(c)}`)}if(o.length>n*1024)return l(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(hp(o)!==s)return l("Attachment blob does not match its content hash");let d=gp(o);return a(d)?d:d.value!==i?l("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var zo=50,Ko=5e3,bp=()=>{let e=re().commandMeta.inputString,t=Jx.coerce.number().int().min(zo).max(Ko).safeParse(e);if(!t.success)return l(`Attachment size cap must be ${zo}-${Ko} KB (default ${en})`);let n=vt({attachmentMaxKb:t.data});return a(n)?n:(Ye({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import zr from"chalk";var Vl={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},xp=(e,t,n)=>Math.max(t,Math.min(n,e)),Gl=(e,t,n)=>e+(t-e)*n,Ip=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Qx=e=>e.toLowerCase().trim(),Zx=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,d=s*(1-Math.abs(i%2-1)),c=0,m=0,p=0;i>=0&&i<1?(c=s,m=d):i>=1&&i<2?(c=d,m=s):i>=2&&i<3?(m=s,p=d):i>=3&&i<4?(m=d,p=s):i>=4&&i<5?(c=d,p=s):(c=s,p=d);let f=o-s/2;return[Math.round((c+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Sp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var eI=(e,t,n)=>{let r=xp(n,0,1);return[Math.round(Gl(e[0],t[0],r)),Math.round(Gl(e[1],t[1],r)),Math.round(Gl(e[2],t[2],r))]};var tI=(e,t,n)=>eI(e,t,n),qo=e=>{let t=Ip(e)%360,n=Zx(t,Vl.stringColor.saturation,Vl.stringColor.lightness);return Sp(n)},ce=(e,t=Vr)=>{let n=Qx(e??"");return n&&t[n]?t[n]:qo(n)};var Ep=e=>{let t=Vl.gradient.stops,n=xp(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return tI(t[s],t[s+1],i)},xi=e=>Sp(Ep(e)),Ii=e=>Ip(e.toLowerCase().trim())/4294967295,Rp=e=>{let t=Ii(e);return Ep(t)},nI=e=>{let[t,n,r]=Rp(e);return{normal:o=>zr.bgRgb(t,n,r).black(o),cursor:o=>zr.bgRgb(t,n,r).white.bold(o)}},zl=e=>{let[t,n,r]=Rp(e);return{fg:o=>zr.rgb(t,n,r)(o),fgCursor:o=>zr.rgb(t,n,r).inverse(o),bg:o=>zr.bgRgb(t,n,r).black(o),bgCursor:o=>zr.bgRgb(t,n,r).white.bold(o)}},Si=e=>nI(e).normal(` ${e} `);var Qe=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as rI}from"node:crypto";var oI="0123456789ABCDEFGHJKMNPQRSTVWXYZ",sI=e=>{let t=rI("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=oI[Number(n>>s&31n)]}return r},De=(e,t)=>sI(`${e}:virtual:${t}`);import Cp from"chalk";var ge=e=>Cp.dim(e),Be=e=>Cp.hex(y.primary)(e),Ge=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>Ii(f)-Ii(g)).slice(0,r).map(f=>Si(f)).join(" ");return p?`${ge(e)}${p}${ge(n)}`:""};var tn={None:"none",Invalid:"invalid",Valid:"valid"};var iI=["BOARD","TICKET","SWIMLANE"],Np=()=>{let e=h().selectedNode;if(!e?.context)return W({message:ge("Missing target context")});if(iI.includes(e.context))return ee();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===De(t?.parentNodeId??"","comments"))return ee()}return W({message:ge("Command not available in this context")})},ue="<ENTER> to confirm",ee=(e="",t=[])=>({message:ge(e),validity:tn.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:tn.Invalid,message:e,completionWordList:t}),qr=e=>e.length===0,Ap=(e,t)=>{let n=ot(h().breadCrumb,"BOARD");if(a(n))return W({message:Be("Command is not applicable in this context")});let r=Us(n.value.id);return a(r)?W({message:Be(`Unable to ${t}: board id is not a valid ULID`)}):ap({date:e,horizonDate:r.value})?null:W({message:Be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Ei=e=>` ${Tp.hex("#000").bgHex(ce(e))(` ${e} `)} `,Kl=({modifier:e})=>{let t="confirm";return e===t?ee(ue):W({message:qr(e)?ge("if you are certain, enter ")+Si(t):"",completionWordList:[t]})},aI=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:ge(n)}):ee():W({message:qr(r)?t:"",completionWordList:[...e]}),Kr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>qr(n)&&qr(r)?W({message:e,completionWordList:[]}):ee(t??ue),lI=({modifier:e,inputString:t})=>{let n=Hl();return!qr(e)||!qr(t)?ee(ue):W({message:n.length?ge("number from the list, or a path"):ge("path to an epiq project"),completionWordList:n})},dI=({modifier:e,inputString:t})=>{let n=Ne(E.CONFIG);if(!n.includes(e))return W({message:Ge({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case xe.EDITOR:{let r=[...up];return t.trim()?r.includes(t.trim())?ee(ue):W({message:Ge({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:Ge({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case xe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?ee(ue):W({message:Ge({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case xe.USERNAME:return t.trim()?ee(ue):W({message:Be("Enter a user name. Saved in ")+Tp.bgBlack("~/.epiq-global/config.json")});case xe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?ee(ue):W({message:Ge({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case xe.AUTOSYNC:{let r=["on","off"],o=le().autoSync;if(!r.includes(t.trim())){let s=op(o);return W({message:Ge({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return ee(ue)}case xe.ATTACHMENT_MAX_KB:{let r=le().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<zo||o>Ko){let s=Ge({prefix:" examples: ",wordList:$l,minLengthForHints:0,inputString:t});return W({message:Be(`provide a size cap in KB (${zo}-${Ko}). current: ${r??en} KB.`)+s,completionWordList:$l})}return ee(ue)}case xe.SYNC_DEBOUNCE_MS:{let r=le().autoSyncIntervalMs,o=Ym(t);if(!t.trim()||o===null||o<Hr){let s=Ge({prefix:" examples: ",wordList:jl,minLengthForHints:0,inputString:t});return W({message:Be(`provide duration above ${Hr}ms. current duration: ${r}ms.`)+s,completionWordList:jl})}return ee(ue)}default:return W({message:Be("Unknown config option"),completionWordList:n})}},cI=({modifier:e,inputString:t})=>{let n=Ne(E.EDIT);if(!n.length)return W({message:Be("Command not available in this context")});if(!n.includes(e)){let r=Ge({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||Be("Unknown edit option"),completionWordList:n})}switch(e){case ht.COMMENT:return t.trim()?ee(ue):W({message:ge("write a comment...")});case ht.TITLE:return ee(ue);case ht.DESCRIPTION:{let{preferredEditor:r}=le();return r?ee(ge("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:Be("Unknown edit option"),completionWordList:n})}},uI=({modifier:e})=>{let t=Ne(E.YANK);return t.length?t.includes(e)?ee(ue+ge(" and copy to clipboard")):W({message:Ge({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:Be("Nothing selected to copy from")})},mI={[E.EXPORT]:()=>ee(ue+ge(", and create export markdown file")),[E.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ee(ue);let n={message:ge("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=mr(r);if(!r||!o)return W(n);let s=Ap(o,"peek");return s||ee(ue)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=vi(e.modifier,e.inputString),r={message:ge("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=mr(t);if(!t||!o)return W(r);let s=Ap(o,"replay");return s||(n&&yi(n)===null?W({message:Be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ee("<ENTER> to replay board history",n?cp:[]))},[E.EXIT]:()=>ee(ue+ge(" and exit the application")),[E.INIT]:()=>ee(ue),[E.OPEN]:lI,[E.PALETTE]:()=>ee(ue),[E.FILTER]:e=>{if(e.modifier==="clear")return ee(ue);let t=s=>Ne(E.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:Ge({wordList:Ne(E.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ne(E.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?W({message:Ge({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):ee():W({message:Ge({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[E.NONE]:e=>{let t=Ne(E.NONE);return W({message:Ge({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[E.NEW]:e=>aI({list:Ne(E.NEW),hint:Ge({wordList:Ne(E.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[E.HELP]:()=>ee(ue),[E.EDIT]:cI,[E.COMMENT]:e=>{let t=Kr({hint:ge(`write a comment (max ${4e3} char)...`),onOk:ge(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===tn.Invalid?t:e.inputString.length>4e3?ee(Be("max input exceeded")):t},[E.CONFIG]:dI,[E.YANK]:uI,[E.DELETE]:e=>{let t=Np();return t.validity==="invalid"?t:Kl(e)},[E.CLOSE_ISSUE]:e=>Kl(e),[E.RE_OPEN_ISSUE]:e=>Kl(e),[E.MOVE]:e=>{let t=Np();return t.validity==="invalid"?t:Kr({hint:Ge({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ne(E.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[E.TAG]:e=>{let n=R.getExistingTags().slice(0,10).map(Ei).join("");return Kr({hint:n.length?ge("create tag or reuse:")+n+ge(""):ge("create tag ...")})(e)},[E.UNTAG]:e=>{let t=gi();if(a(t))return W({message:Be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ei).slice(0,10);return n.length?Kr({hint:ge(" ... ")+n.join("")})(e):W({message:Be("Issue has no tags"),completionWordList:[]})},[E.ASSIGN]:e=>{let t=R.getExistingAssignees().map(Ei).slice(0,10);return Kr({hint:ge("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=hi();if(a(t))return W({message:Be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ei).slice(0,10);return n.length?Kr({hint:ge("remove assignee... ")+n.join("")})(e):W({message:Be("Issue has no assignees"),completionWordList:[]})},[E.SYNC]:()=>ee(ue)},wp=Object.fromEntries(Object.entries(mI).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ri=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var pI=3,fI=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),gI=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},hI=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=pI&&!fI.has(t)&&!/^\d+$/.test(t)),yI=e=>{let t=new Map;for(let s of gI(e))for(let i of hI(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=Ri.filter(s=>!r.has(s));return[...n,...o]},Mp=Ri,Pp=-1,Lp=()=>{let e=it();if(a(e))return Ri;let t=e.value,n=t.eventLog.length;return n!==Pp&&(Mp=yI(t),Pp=n),Mp};var kp=e=>Object.values(E).includes(e),Dp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:d,completionWordList:c}=wp[n].validate(n,r,s),m=n!==E.PEEK&&n!==E.REPLAY,p=o==="command"||o==="modifier"?Ne(n):m?Lp():[],{mode:f}=h(),g=f===b.COMMAND_LINE?i??"":"",v=[...c,...p];return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Lu(e,v):{hint:"",hints:[],remainder:"",overlap:0}}};var Bp=e=>{let t=e.trimStart(),n=bI(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=xI(e),d=kp(r)?r:null,c=d!==null,m=r!=="",p=d?Ne(d)??[]:[],f=d&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let v=s?"":i,I=vI(t,d,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:d,isCommandKeyword:c,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:v,inputString:I}},vI=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},bI=e=>e.trim()?e.trim().split(/\s+/):[],xI=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as II}from"react";var Yr=e=>e===ql||e===":",ql=" ",Ze={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:tn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Yl=new Set,Fp=()=>{for(let e of Yl)e()},Xl=e=>(Yl.add(e),()=>Yl.delete(e)),nn=e=>{let n=e(Ze),r=Bp(n.value),o=n.cursorPosition===n.value.length;Ze={...n,commandMeta:Dp(r,o)},Fp()},Yo=({message:e,status:t})=>{let n=structuredClone(Ze);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ze=n,Fp(),u(e,null)},Jl=e=>{nn(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ql=e=>{nn(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Yr(n[o-1]);)o--;for(;o>0&&!Yr(n[o-1]);)o--}else{for(;o<n.length&&!Yr(n[o]);)o++;for(;o<n.length&&Yr(n[o]);)o++}return{...t,cursorPosition:o}})},Op=()=>{nn(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},_p=()=>{nn(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Yr(t[r-1]);)r--;for(;r>0&&!Yr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ci=e=>{nn(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,d=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:d,commandIsPending:!1}})},Up=()=>{nn(e=>({...e,commandIsPending:!0}))},te=e=>{nn(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},jp=({addToHistory:e=!0})=>{nn(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},$p=()=>{nn(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Hp=()=>{nn(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},re=()=>Ze,Wp=()=>II(Xl,re,re),Ni=()=>{let[e,...t]=Ze.value.split(ql);return t.join(ql).trim()};var S={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function SI(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function EI(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function RI(e,t,n){let r=h().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Gp(e,t){let n=re();if(e.sequence==="?"&&t!==b.PALETTE)return S.InitCommandPalette;if(e.sequence===":"&&t!==b.COMMAND_LINE)return S.InitCommandLine;if(t===b.MOVE)switch(e.name){case"m":case"return":return S.ConfirmMove}if(t===b.COMMAND_LINE)return Ru(e,n.value);if(t===b.PALETTE)return Cu(e,n.value);let r=SI(e)||EI(e);if(r)return CI(r,t);if(e.ctrl&&e.name==="c")return S.Exit;switch(e.name){case"r":return S.EditTitle;case"e":return S.EditDescription;case"n":return S.AddItem;case"m":return S.InitMove;case"d":return S.Delete;case"y":return S.Yank;case"return":return S.Confirm;case"space":return S.Confirm;case"v":return le().viewMode==="wide"?S.SetViewDense:S.SetViewWide;case"q":case"escape":return S.Exit;default:return null}}function CI(e,t){let n=t===b.MOVE?{prevItem:S.MovePreviousItem,nextItem:S.MoveNextItem,prevContainer:S.MoveToPreviousContainer,nextContainer:S.MoveToNextContainer}:{prevItem:S.NavPreviousItem,nextItem:S.NavNextItem,prevContainer:S.NavToPreviousContainer,nextContainer:S.NavToNextContainer};return RI(h().contextNode.childRenderAxis,e,n)}var Ai=e=>{let{context:t}=h().contextNode;if(!t)return j.None;switch(e){case E.EXIT:return j.Exit;case E.EXPORT:return j.Export;case E.INIT:return j.Init;case E.OPEN:return j.OpenProject;case E.DELETE:return j.Delete;case E.EDIT:return j.Edit;case E.COMMENT:return j.Comment;case E.HELP:return j.ViewHelp;case E.RE_OPEN_ISSUE:return j.ReopenIssue;case E.CLOSE_ISSUE:return j.CloseIssue;case E.TAG:return j.TagTicket;case E.UNTAG:return j.UntagTicket;case E.ASSIGN:return j.AssignUserToTicket;case E.UNASSIGN:return j.UnassignUserFromTicket;case E.NEW:return j.NewItem;case E.FILTER:return j.Filter;case E.MOVE:return j.Move;case E.PEEK:return j.Peek;case E.REPLAY:return j.Replay;case E.CONFIG:return j.Config;case E.YANK:return j.Yank;case E.SYNC:return j.Sync;default:return j.None}},j={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import Tf from"node:fs";import CS from"node:path";import NS from"react";import{Box as ES}from"ink";import Di from"react";import VI from"chalk";import{Box as td,Text as zI}from"ink";import rn from"react";import{Text as Vp}from"ink";import zp,{useEffect as Kp,useState as NI}from"react";var qp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},et=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=J(),r=qp[n]??qp.default,[o,s]=NI(0);if(Kp(()=>{s(0)},[r]),Kp(()=>{if(!e)return;let d=setInterval(()=>{s(c=>(c+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return zp.createElement(Vp,null,t);let i=r[o]??r[0]??t;return zp.createElement(Vp,{color:y.accent,dimColor:o===1},i)};import{Box as Zl,Text as AI}from"ink";import Ti from"react";var TI=(e,t,n,r)=>{let o=c=>Math.max(1,e[c]??1),s=n,i=n+1,d=o(n);for(;i<t&&d+o(i)<=r;)d+=o(i),i++;for(;s>0&&d+o(s-1)<=r;)s--,d+=o(s);return{start:s,end:i}},Et=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),c=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/d)),p=Math.max(0,e.length-m),{start:f,end:g}=o?TI(o,e.length,c,i):s?{start:Math.min(p,Math.max(0,c-m+1)),end:Math.min(p,Math.max(0,c-m+1))+m}:{start:Math.min(p,Math.floor(c/m)*m),end:Math.min(p,Math.floor(c/m)*m)+m},v=Math.max(1,g-f),I=e.slice(f,g),x=e.length>v,C=i,A=x?Math.max(1,Math.floor(v/e.length*C)):C,M=Math.max(0,C-A),w=Math.max(1,e.length-v),L=x?Math.floor(f/w*M):0;return Ti.createElement(Zl,{flexDirection:"row",height:i,width:"100%"},Ti.createElement(Zl,{flexDirection:"column",flexGrow:1,height:i},I),Ti.createElement(Zl,{flexDirection:"column",width:1,height:C},Array.from({length:C}).map((k,Ie)=>Ti.createElement(AI,{key:Ie,color:x&&Ie>=L&&Ie<L+A?y.accent:y.secondary},x?"\u2502":" "))))};import{Box as Qr,Text as Zr}from"ink";import ct from"react";var Yp,ed,wI=()=>{let{eventLog:e=[]}=h();if(ed&&Yp===e)return ed;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Yp=e,ed=t,t},wi=e=>wI().has(e);import{Text as MI}from"ink";import PI from"react";var LI=e=>e.toLowerCase().trim(),kI=(e,t=Vr)=>{let n=LI(e);return t[n]?t[n]:qo(n)},$n=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:yn(o,n);return PI.createElement(MI,{underline:t,color:kI(o)},"@"+s,wi(e)?"":"\u2197")};import{Text as DI}from"ink";import BI from"react";var Xr=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getTag(e);if(!r)return;let o=n===void 0?r.name:yn(r.name,n);return BI.createElement(DI,{underline:t,backgroundColor:ce(r.name),color:y.secondary}," "+o+" ")};import{useEffect as FI,useState as OI}from"react";var _I=80,Xp=1400,Mi=new Set,Xo=null,UI=e=>(Mi.add(e),Xo||(Xo=setInterval(()=>{for(let t of Mi)t()},_I)),()=>{Mi.delete(e),Mi.size===0&&Xo&&(clearInterval(Xo),Xo=null)}),jI=()=>{let e=Date.now()%Xp/Xp;return e<.5?e*2:(1-e)*2},Jr=e=>{let[,t]=OI(0);return FI(()=>{if(e)return UI(()=>t(n=>n+1))},[e]),xi(jI())};var $I=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),yn(e.slice(o).trim(),n)]},Jp=3,HI=2,WI=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,d=i>0?String(i).length+1:0;if(r+s.width+d>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Qp=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Jr(r),s=e-4,i=s-7-1,[d,c]=$I(ye(t.title),i,s),m=c?null:yn(ye(t.props.description),s)||null,p=Un(t),f=jn(t).map(A=>({...A,name:A.name})),g=Math.max(1,s-Jp),v=R.getCommentsByIssue(t.id),I=v.length?String(v.length).length+2+1:0,{shown:x,hidden:C}=WI([...p.map(A=>({id:A.id,isTag:!0,width:Math.min(A.name.length,g)+Jp})),...f.map(A=>({id:A.id,isTag:!1,width:Math.min(A.name.length,g)+HI+(wi(A.id)?0:1)}))],s-I);return ct.createElement(Qr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},ct.createElement(Qr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},ct.createElement(Qr,{justifyContent:"space-between"},ct.createElement(Zr,{color:y.primary},d),ct.createElement(Zr,{color:y.secondary2,dimColor:!0},O(t.id))),c&&ct.createElement(Zr,{color:y.primary},c),m&&ct.createElement(Zr,{color:y.secondary2,dimColor:!0},m)),ct.createElement(Qr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},ct.createElement(Qr,{flexDirection:"row"},x.map(A=>ct.createElement(Qr,{paddingRight:1,key:A.id},A.isTag?ct.createElement(Xr,{id:A.id,maxWidth:g}):ct.createElement($n,{id:A.id,maxWidth:g}))),C>0&&ct.createElement(Zr,{color:y.secondary2,dimColor:!0},"+",C)),v.length>0&&ct.createElement(Zr,{color:y.accent},"[",v.length,"]")))};import{Box as gr,Text as Jo}from"ink";import yt from"react";var GI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Zp=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let d=Jr(s),c=(r.props.tags??[]).map(k=>R.getTag(k)).filter(k=>!!k),m=(r.props.assignees??[]).map(k=>R.getContributor(k)).map(k=>k&&{...k,name:k.name}).filter(k=>!!k),p=1,f=c.length*(1+p),g=m.length*(2+p),v=c.map(k=>yt.createElement(gr,{key:k.id,paddingRight:p},yt.createElement(Jo,{color:ce(k.name)},"\u25A0"))),I=m.map(k=>yt.createElement(gr,{key:k.id,paddingRight:p},yt.createElement(Jo,{color:qo(k.name)},"@"+k.name.at(0)))),x=s?d:o?y.accent:i===b.MOVE?y.secondary:y.primary,C=R.getCommentsByIssue(r.id),A=C.length?String(C.length).length+2+p:0,M=C.length?yt.createElement(gr,{paddingRight:p},yt.createElement(Jo,{color:y.accent},"[",C.length,"]")):null,w=f+g+A,L=Math.max(1,n-t-w-(w>0?1:0));return yt.createElement(gr,{justifyContent:"space-between"},yt.createElement(gr,null,yt.createElement(gr,{width:t},o?yt.createElement(et,{isSelected:!0}):yt.createElement(Jo,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),yt.createElement(Jo,{wrap:"truncate",color:x},GI(r.title,L))),yt.createElement(gr,null,v,I,M))};var KI=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:d})=>{let{renderedChildrenIndex:c,replay:m}=J(),p=c[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Jr(g),I=`${e.title} ${VI.hex(y.secondary2).dim("("+p.length+")")}`,x=3,C=o?1:5,A=s&&i===-1,M=n-3-(o?1:0)-(A?2:0),w=Math.max(2,String(p.length).length+1),L=r-x-1,k=rn.createElement(td,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},rn.createElement(et,{isSelected:t}),rn.createElement(zI,{bold:!0,color:g?v:t?y.accent:y.primary},I," ",e.readonly?"\u{1F512}":"")),Ie=(Ke,Mt)=>{let mt=s&&i===Mt;if(!B(Ke))return null;let $e=f?.has(Ke.id)??!1;return o?rn.createElement(Zp,{key:Ke.id,index:Mt,labelWidth:w,width:M,ticket:Ke,isSelected:mt,isFlashing:$e,mode:d}):rn.createElement(Qp,{key:Ke.id,width:M,ticket:Ke,isSelected:mt,isFlashing:$e})};return rn.createElement(td,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},k,rn.createElement(td,null,p.length>0&&rn.createElement(Et,{selectedIndex:i,height:L,itemHeight:C},p.map(Ie)),A&&rn.createElement(et,{isSelected:!0})))},ef=rn.memo(KI);import{Box as yr,Text as pd}from"ink";import Fe,{useMemo as Zo}from"react";var tf=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},nf=(e,t,n)=>be.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as no,Text as Cn}from"ink";import tt,{useEffect as qI,useMemo as YI,useRef as XI}from"react";import{decodeTime as rf}from"ulid";var to=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Pi=e=>String(e).padStart(2,"0"),Li=e=>`${e.getFullYear()}-${Pi(e.getMonth()+1)}-${Pi(e.getDate())} ${Pi(e.getHours())}:${Pi(e.getMinutes())}`;var JI=e=>De(e,"attachments"),QI=e=>R.getAttachmentsByIssue(e.id).sort((t,n)=>rf(t.id)-rf(n.id)),of=e=>{for(let t of e)R.deleteNode(t.id)},ZI=(e,t,n)=>be.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),eS=(e,t)=>{let n=R.getNode(JI(e.id));if(!n||!gt(n))return[];let r=t.map((o,s)=>ZI(o,s,n.id)).map(o=>R.createNode(o)).filter(me).map(({value:o})=>o).filter(gt);return t.length>0&&h().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r},tS=e=>`${Math.max(1,Math.round(e/1024))} KB`;function sf({ticket:e,width:t,height:n}){let r=YI(()=>QI(e),[e]),o=XI([]);qI(()=>(of(o.current),o.current=eS(e,r),()=>{of(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=J(),d=Math.max(1,n-4),c=Math.max(12,t-32);return r.length===0?tt.createElement(no,{flexDirection:"column",width:t,height:n,padding:1},tt.createElement(Cn,{color:y.primary},"No attachments yet."),tt.createElement(no,{paddingTop:1},tt.createElement(Cn,{color:y.primary},"Attach images from the browser GUI"),tt.createElement(Cn,{color:y.accent}," epiq gui "),tt.createElement(Cn,{color:y.primary},"by dropping or pasting them."))):tt.createElement(no,{flexDirection:"column",width:t,height:n},tt.createElement(no,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},tt.createElement(Cn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),tt.createElement(Et,{height:d,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>c?m.name.slice(0,c-1)+"\u2026":m.name;return tt.createElement(no,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},tt.createElement(Cn,{color:y.accent},f?"\u276F ":" "),tt.createElement(no,{paddingLeft:1},tt.createElement(Cn,{color:y.secondary2},`#${p+1} `),tt.createElement(Cn,{color:f?y.accent:y.primary},g),tt.createElement(Cn,{color:y.secondary2}," "+tS(m.bytes)+" "+to(Ce(m.id)))))})))}import{Box as Hn,Text as Wn}from"ink";import Pe,{useEffect as dS,useMemo as bf,useRef as cS}from"react";import{decodeTime as xf}from"ulid";var lf=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,nd=e=>e.replace(lf,"");var af=e=>e==="additions"||e==="deletions",rd=e=>{let t=lf.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!af(r.side)||!af(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var df=/```\n([\s\S]*?)\n?```\s*$/,cf=e=>df.exec(e)?.[1]??null,nS=/`[^`\n]+`[^\n]*\n?$/,uf=e=>nd(e).replace(df,"").replace(nS,"").trim(),rS=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},od=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${rS(e)}`;var oS=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let d=i;for(;d.length>n;)s&&(o.push(s),s=""),o.push(d.slice(0,n)),d=d.slice(n);s?s.length+1+d.length<=n?s=`${s} ${d}`:(o.push(s),s=d):s=d}return s&&o.push(s),o},Qo=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},sS=/!\[([^\]]*)\]\([^)]*\)/g,iS=e=>e.replace(sS,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),aS=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),lS=4,pf=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(lS)),sd=e=>{let t=!1;return e.map(pf).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=rd(n);if(r)return{kind:"caption",text:od(r)};let o=iS(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Qo(s[1]??"")}:{kind:"text",spans:Qo(o)}})},ff=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],mf=(e,t)=>{let n=[];for(let r of sd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of ff(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of oS(aS(r.spans),t))n.push({kind:r.kind,spans:Qo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},gf=(e,t)=>{let n=rd(e),r=n?cf(e):null;if(!n||r===null)return mf(nd(e).split(`
|
|
69
|
+
`),t);let o=uf(e),s=r.split(`
|
|
70
|
+
`).map(pf),i=n.side===n.endSide?n.start:void 0,d=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...mf(o.split(`
|
|
71
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:od(n)},...s.flatMap((c,m)=>ff(c,Math.max(1,t-d)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as hf,Text as hr}from"ink";import Rt from"react";var yf=({spans:e,bold:t,wrap:n})=>Rt.createElement(hr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?Rt.createElement(hr,{key:o,color:y.yellow},r.text):Rt.createElement(hr,{key:o},r.text))),id=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return Rt.createElement(hr,null," ");case"fence":return Rt.createElement(hr,{color:y.secondary2},"```");case"caption":return Rt.createElement(hr,{color:y.accent,wrap:r},e.text);case"heading":return Rt.createElement(yf,{spans:e.spans,bold:!0,wrap:r});case"text":return Rt.createElement(yf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Rt.createElement(hr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},vf=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return Rt.createElement(hf,{flexDirection:"column"},e.map((o,s)=>Rt.createElement(hf,{key:s},Rt.createElement(id,{line:o,width:t,gutter:r}))))};var uS=4,mS=e=>De(e,"comments"),pS=e=>R.getCommentsByIssue(e.id).sort((t,n)=>xf(t.id)-xf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),If=e=>{for(let t of e)R.deleteNode(t.id)},fS=(e,t)=>{let n=R.getNode(mS(e.id));if(!n||!gt(n))return[];let r=t.map((o,s)=>nf(o,s,n.id)).map(R.createNode).filter(me).map(({value:o})=>o).filter(Mo);return t.length>0&&h().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r};function Sf({ticket:e,width:t,height:n}){let r=bf(()=>pS(e),[e]),o=cS([]);dS(()=>(If(o.current),o.current=fS(e,r),()=>{If(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=J(),d=Math.max(1,n-4),c=Math.max(20,t-8),m=bf(()=>r.map(f=>{let g=gf(f.md,c);return g.length>0?g:[{kind:"blank"}]}),[r,c]),p=m.map(f=>f.length+uS);return r.length===0?Pe.createElement(Hn,{flexDirection:"column",width:t,height:n,padding:1},Pe.createElement(Wn,{color:y.primary},"No comments yet."),Pe.createElement(Hn,{paddingTop:1},Pe.createElement(Wn,{color:y.primary},"Use"),Pe.createElement(Wn,{color:y.accent}," :comment "),Pe.createElement(Wn,{color:y.primary},"to add the first one."))):Pe.createElement(Hn,{flexDirection:"column",width:t,height:n},Pe.createElement(Hn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Pe.createElement(Wn,{color:y.secondary2},"Comments (",r.length,") ")),Pe.createElement(Et,{height:d,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let v=g===s;return Pe.createElement(Hn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Pe.createElement(Hn,{flexDirection:"row",paddingBottom:1},Pe.createElement(Wn,{color:y.accent},v?"\u276F ":" "),Pe.createElement(Hn,{paddingLeft:1},Pe.createElement(Wn,{color:y.secondary2},`#${g+1} `),Pe.createElement($n,{id:f.authorId}),Pe.createElement(Wn,{color:y.secondary2}," "+to(Ce(f.id))))),Pe.createElement(Hn,{paddingLeft:3,paddingBottom:1},Pe.createElement(vf,{lines:m[g]??[],width:c})))})))}import{Box as ki,Text as gS}from"ink";import Nn from"react";var Ef=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=J(),{title:o}=t,s=t.parentNodeId?R.getNode(t.parentNodeId):void 0,i=s&&B(s)?o===ve.ASSIGNEES?s.props.assignees??[]:o===ve.TAGS?(s.props.tags??[]).filter(d=>R.getTag(d)):[]:[];return Nn.createElement(ki,{alignItems:"center",paddingTop:1},Nn.createElement(ki,{minWidth:12},Nn.createElement(et,{isSelected:n}),Nn.createElement(gS,{color:n?y.accent:y.secondary2},o,":")),Nn.createElement(ki,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((d,c)=>{let m=r.id===t.id&&c===e;return Nn.createElement(ki,{key:`${o}-${d}`,paddingRight:2,minHeight:1},Nn.createElement(et,{isSelected:m}),o===ve.ASSIGNEES?Nn.createElement($n,{isSelected:m,id:d}):o===ve.TAGS?Nn.createElement(Xr,{isSelected:m,id:d}):null)})))};import{Box as ro,Text as dd}from"ink";import Ct,{useEffect as hS,useMemo as cd}from"react";var ad=e=>Math.max(5,String(Math.max(e,1)).length+3),Rf=(e,t)=>Math.max(0,e-6-ad(t));var ld=(e,t=0)=>Math.max(1,e-5-2*t);var yS="\u2029",Cf=(e,t)=>`${e}::inline-line::${t}`,ud=new Map,Nf=e=>{let t=ud.get(e)??[];ud.delete(e);for(let n of t)R.deleteNode(n)},vS=(e,t)=>{Nf(e);let n=[];t.forEach((r,o)=>{let s=xt(BigInt(o+1));if(!me(s))return;let i=R.createNode(be.text({id:Cf(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));me(i)&&n.push(i.value.id)}),ud.set(e,n)},md=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:d}=J(),c=cd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=cd(()=>c.join("\0"),[c]);hS(()=>(vS(e,c),()=>{Nf(e)}),[e,m]);let p=ad(c.length),f=Rf(s,c.length),v=cd(()=>sd(c).map(I=>{if(I.kind==="code"||I.kind==="caption")return{...I,text:il(I.text,f)};if(I.kind==="text"||I.kind==="heading"){let x=I.spans.map(C=>C.code?`\`${C.text}\``:C.text).join("");return{...I,spans:Qo(il(x,f))}}return I}),[c,f]).map((I,x)=>{let C=d.id===e&&i===x;return Ct.createElement(ro,{key:Cf(e,x)},Ct.createElement(ro,{flexShrink:0},Ct.createElement(dd,{color:C?y.primary:y.secondary2,dimColor:!C},`${x+1} `.padStart(p,"\xA0"))),I.kind==="blank"?Ct.createElement(dd,{backgroundColor:C?"gray":void 0},yS):Ct.createElement(ro,null,Ct.createElement(id,{line:I,width:I.kind==="code"?f:0,wrap:"truncate-end"})))});return Ct.createElement(ro,{flexDirection:"column",paddingTop:1},Ct.createElement(ro,null,Ct.createElement(et,{isSelected:o}),Ct.createElement(dd,{color:o?y.accent:y.secondary2},t)),Ct.createElement(ro,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Ct.createElement(Et,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},v)))};var bS=e=>De(e,"description"),xS=e=>De(e,"comments"),IS=e=>De(e,"history"),SS=e=>De(e,"attachments"),Af=({ticket:e,height:t})=>{let n=Zo(()=>tf(e),[e]),{selectedIndex:r,contextNode:o}=J(),s=process.stdout.columns||120,i=Zo(()=>bS(e.id),[e.id]),d=Zo(()=>xS(e.id),[e.id]),c=Zo(()=>IS(e.id),[e.id]),m=Zo(()=>SS(e.id),[e.id]),p=R.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===d||o.parentNodeId===d,v=o.id===c||o.parentNodeId===c,I=o.id===m||o.parentNodeId===m,x=X(e.id);if(g){let L=t-3;return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(Sf,{ticket:e,width:s,height:L}))}if(I){let L=t-3;return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(sf,{ticket:e,width:s,height:L}))}if(v){let w=R.getNode(c),L=w&>(w)?w.props.value??"":"",k=ld(t);return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},w?Fe.createElement(md,{id:w.id,label:"Event log",text:L,selected:!1,maxWidth:s,rows:k}):null)}let C=x.reduce((w,L)=>wo(L)||L.id===d||L.id===m||L.id===c?w+1:w,0),A=ld(t,C),M=(w,L)=>w.id===i?Fe.createElement(md,{key:w.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:L,maxWidth:s,rows:A}):wo(w)?Fe.createElement(Ef,{key:w.id,parent:w,selected:L,selectedIndex:r}):w.id===d?Fe.createElement(yr,{key:w.id,paddingTop:1},Fe.createElement(et,{isSelected:L}),Fe.createElement(pd,{backgroundColor:y.secondary,color:L?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):w.id===m?Fe.createElement(yr,{key:w.id,paddingTop:1},Fe.createElement(et,{isSelected:L}),Fe.createElement(pd,{backgroundColor:y.secondary,color:L?y.accent:y.primary},` Attachments (${p}) \u203A\u203A `)):w.id===c?Fe.createElement(yr,{key:w.id,paddingTop:1},Fe.createElement(et,{isSelected:L}),Fe.createElement(pd,{backgroundColor:y.secondary,color:L?y.accent:y.primary}," History \u203A\u203A ")):null;return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},x.map((w,L)=>M(w,f&&r===L)))};var RS=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:d})=>{let c=t.context,m=c===K.TICKET||c===K.FIELD_LIST||c===K.FIELD,p=c===K.BOARD||c===K.SWIMLANE,f=c===K.TICKET?t:r.find(C=>C.context===K.TICKET),g=Math.floor(d/3),v=Math.floor(d/Math.max(e.length,1)),I=Math.min(v,g),x=s==="dense";return Di.createElement(ES,{flexDirection:"row",height:i},p&&e.map((C,A)=>{let M=t.id===C.id,w=M?n:-1,L=t.context===K.BOARD&&n===A;return Di.createElement(ef,{key:C.id,height:i,width:I,swimlane:C,isSelected:L,isDense:x,isFocused:M,listSelectedIndex:w,mode:o})}),m&&f&&Di.createElement(Af,{height:i,ticket:f}))},Bi=Di.memo(RS);import{render as AS}from"ink";import{Writable as TS}from"node:stream";var es=e=>String(e).padStart(2,"0"),wS=e=>{let t=e.getUTCFullYear(),n=es(e.getUTCMonth()+1),r=es(e.getUTCDate()),o=es(e.getUTCHours()),s=es(e.getUTCMinutes()),i=es(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},MS=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",PS=async(e,{width:t,height:n})=>{let r="",o=new TS({write(i,d,c){let m=LS(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),c()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=AS(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},LS=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),wf=async()=>{let{viewMode:e}=le(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(A=>A.context==="BOARD");if(!i)return l("No board found to export");let d=120,c=40,m=await PS(NS.createElement(Bi,{height:c,width:d,swimlanes:(s[i.id]??[]).filter(A=>A!==void 0&&Kt(A)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:d,height:c});if(!m)return l("Failed to render board export");let p=Ls(process.cwd());if(a(p))return l("Unable to export, epiq root not found");let f=new Date,g=wS(f),v=`board_${MS(i.title)}_${g}.md`,I=cu(p.value);Tf.mkdirSync(I,{recursive:!0});let x=CS.join(I,v),C=`# Board - ${i.title}
|
|
69
72
|
Date: ${f.toISOString()}
|
|
70
73
|
|
|
71
74
|
\`\`\`text
|
|
72
75
|
${m}
|
|
73
76
|
\`\`\`
|
|
74
|
-
`;return
|
|
75
|
-
`).map(c=>c.trim()),s=r.filter(c=>!o.some(m=>m===c||m===c.replace(/\/$/,"")||m==="/"+c||m==="/"+c.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let
|
|
77
|
+
`;return Tf.writeFileSync(x,C,"utf8"),u("Exported board layout",x)};import{useSyncExternalStore as PO}from"react";var Fi,kS=new Set,Mf=()=>{for(let e of kS)e()};var Gn=()=>{if(!Fi)throw new Error("Ui state not initialized. Call initUiState() first.");return Fi};var Pf=(e={})=>(Fi=e,Mf(),u("UX state initialized",null)),DS=e=>{let t=Gn();return Fi=e(t),Mf(),u("UX state updated",null)},Vn=e=>DS(t=>({...t,...e}));import{ulid as yd}from"ulid";import{spawn as BS,spawnSync as FS}from"node:child_process";import OS from"node:os";import Lf from"node:path";import{ulid as _S}from"ulid";function fd(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function US(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Oi(){let{preferredEditor:e}=le(),t=[e?US(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function gd(e){let[t=""]=fd(e);return/(^|\/)code(-insiders)?$/.test(t)}function kf(e,t){let[n="",...r]=fd(e);return{command:n,args:[...r,...t]}}function Df(e,t){return kf(e,gd(e)?["--wait",t]:[t])}function jS(e,t,n,r="new"){return kf(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Bf(e){let t=Lf.join(OS.tmpdir(),"epiq");We.mkDir(t);let n=Lf.join(t,_S());We.writeToFile(n,e??"");let r=Oi();for(let o of r){let{command:s,args:i}=Df(o,n);if(!s)continue;let d=FS(s,i,{stdio:"inherit"});if(!d.error&&d.status===0){let c=We.readFile(n);if(c==null)return l("Unable to read edited file");let m=c.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return l("Unable to open editor")}var $S=new Set(["vim","vi","nvim","nano","pico","ed"]);function HS(e){let[t=""]=fd(e),n=t.split("/").pop()??t;return $S.has(n)}var WS=600;function Ff({command:e,args:t},n){return new Promise(r=>{if(!e){r(l(`"${n}" is not a usable editor command`));return}let o=BS(e,t,{stdio:"ignore",detached:!0}),s=!1,i=c=>{s||(s=!0,clearTimeout(d),r(c))};o.on("error",c=>i(l(c.message))),o.on("exit",c=>{i(c===0?u("Opened editor",!0):l(`"${n}" exited with code ${c}`))});let d=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},WS)})}function GS(e,t){return HS(e)?Promise.resolve(l(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):Ff(Df(e,t),e)}function hd(e,t,n,r="new"){return Ff(jS(e,t,n,r),e)}async function Of(e){let t=Oi();if(t.length===0)return l("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=l("Unable to open editor");for(let r of t){let o=await GS(r,e);if(!a(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var _f=async e=>{let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(e.modifier===ht.DESCRIPTION)return zS();if(r&&Mo(r))return VS(e);if(e.modifier===ht.TITLE){let o=ne();if(a(o))return l("Unable to resolve user ID");let s=r;if(!s)return l("Missing node");if(s.readonly)return l("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return l("Provide a title");let d=await zt();return a(d)?d:D([{id:yd(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],d.value)}return l("Unknown edit command")},VS=async e=>{let t=ne();if(a(t))return l("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=h(),o=X(n.id)[r];if(!o||!Mo(o))return l("Select a comment first");if(o.readonly)return l("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return l("Unable to resolve comment issue");let i=h().nodes[s];if(!i||!B(i))return l("Unable to resolve comment issue");if(i.readonly)return l("Cannot edit readonly issue");let d=o.id.split(":").at(0)??"",c=R.getComment(d);if(!c||c.deleted)return l("Unable to resolve comment");if(c.issue!==i.id)return l("Comment does not belong to selected issue");if(c.authorId!==t.value.userId)return l("You can only edit your own comments"+c.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return l("Provide a comment");let p=await zt();if(a(p))return p;let f=p.value;return D([{id:yd(),action:"edit.issue.comment",payload:{id:c.id,issue:i.id,md:m},...t.value}],f)},zS=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let t=await zt();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=h(),s=ot([...r,o],"TICKET");if(a(s))return l("Edit target must be an issue");let i=s.value;if(!B(i))return l("Edit target must be an issue");if(i.readonly)return l("Cannot edit readonly issue");let d=X(i.id).find(f=>f.title===ve.DESCRIPTION);if(!d)return l("No target found");if(d.readonly)return l("Cannot edit readonly field");let c=i.props.description??"";if(typeof c!="string")return l("Selected field is not editable text");let m=Bf(c);if(a(m))return l("Failed to edit field");let p=m.value;return p===c?u("No changes made",null):D([{id:yd(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import qS from"node:fs";import bd from"node:path";import vd from"node:fs";import KS from"node:path";var Uf=async e=>{let t=KS.join(e,".gitignore"),n=vd.existsSync(t)?vd.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
78
|
+
`).map(c=>c.trim()),s=r.filter(c=>!o.some(m=>m===c||m===c.replace(/\/$/,"")||m==="/"+c||m==="/"+c.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let d=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
76
79
|
`);return n=n.trimEnd()+`
|
|
77
80
|
|
|
78
|
-
${
|
|
79
|
-
`,
|
|
80
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
81
|
-
`));let c=et();if(d(c))return Ho(16,c.message);let{rootNodeId:m,nodes:p}=c.value,f=p[m];return f?(O.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),u(s,null)):Ho(16,"Unable to resolve initialized root node")};import{ulid as LS}from"ulid";import{ulid as PS}from"ulid";var wf=null,jn=()=>structuredClone(wf),Wo=e=>{wf=e},Mf=()=>{let{contextNode:e,selectedIndex:t}=h(),r=ae(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},ul=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ae(t).filter(o=>o.id!==e);return qs(r,n)},Pf=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=ul({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:PS(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Lf=e=>{Wo(e);let t=An(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function ml(e){let t=Mf();if(d(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=ae(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let l=s[i+e];if(!l)return a("Missing sibling node");let c=Pf({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(c)?c:Lf(c.value)}function pl(e){let t=Mf();if(d(t))return t;let{contextNode:n,selectedIndex:r}=h(),s=ae(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Pf({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Lf(i.value)}var kf=()=>{let e=jn();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return a("Move parent not found");let o=ae(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(O.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Mi=(e,t="Moved preview")=>{if(d(e))return e;let n=kf();return d(n)?n:(N({mode:b.MOVE}),u(t,null))},Df=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=ee().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=ae(n.id)[r];if(!o)return N({mode:b.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=ae(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let l=s[i-1],c=s[i+1],m=c!=null?{at:"before",sibling:c.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=ul({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Wo({id:LS(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),u("Move initialized",null))}if(t==="next")return Mi(pl(1));if(t==="previous")return Mi(pl(-1));if(t==="to-next")return Mi(ml(1));if(t==="to-previous")return Mi(ml(-1));if(t==="confirm"){let s=jn();if(!s)return a("No pending move to confirm");let i=await Gt();if(d(i))return i;let l=B([s],i.value);if(d(l))return l;let c=kf();return d(c)?c:(Wo(null),N({mode:b.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Wo(null),N({mode:b.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Li}from"ulid";import{monotonicFactory as kS,ulid as DS}from"ulid";var BS=kS(),Pi=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=BS();return u("Created issue events",[{id:DS(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Bf=async(e,t)=>{let n=Z();if(d(n))return a("Unable to resolve user ID");let r=await Gt();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:l}=h(),c=m=>{let p=B([m],o);if(d(p))return p;let f=C.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=C.getNode(f.parentNodeId);return g?(O.navigate({contextNode:g,selectedIndex:C.getSiblings(f.parentNodeId).findIndex(({id:v})=>v===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=C.getNode(m);if(!p)return a("Workspace not found");let f=Pn(p.id,n.value,o);return d(f)?f:c({id:Li(),action:"add.board",payload:{id:Li(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Qe(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Pn(m.value.id,n.value,o);return d(p)?p:c({id:Li(),action:"add.swimlane",payload:{id:Li(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=q(i.id)[l],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let w=Qe(s,"SWIMLANE");return d(w)?null:w.value})();if(!p)return a("Unable to add issue in this context");let f=Pn(p.id,n.value,o);if(d(f))return f;let g=Pi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let v=g.value,x=B([...v],o);if(d(x))return x;if(!x.value[0])return a("Issue creation failed");let A=v.find(w=>w.action==="add.issue")?.payload.id;return A?(O.navigate({contextNode:p,selectedIndex:C.getSiblings(p.id).findIndex(({id:w})=>w===A)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};import US from"node:os";import _f from"node:path";var FS=e=>e.some(t=>t.action==="init.workspace"),Ff=async(e,t)=>{let n=Ht(e);return d(n)?a(n.message):lo({cwd:t,branch:n.value})},OS=e=>{let t=xe(process.cwd());if(d(t))return!1;let n=ue({repoRoot:t.value});return!d(n)&&n.value===e},ki=async e=>{let t=ue({repoRoot:e});if(d(t))return Bt(3,t.message);let n=t.value,r=await rr({repoRoot:e,stateBranchRoot:n,stateBranchName:Ss().stateBranch});if(d(r))return Bt(3,r.message);let o=bt(n);if(d(o))return Bt(3,o.message);if(!FS(o.value.events)){let m=await Ff(e,n);if(d(m)&&logger.info(3,m.message),o=bt(n),d(o))return Bt(3,o.message)}let{events:s,unreadable:i}=o.value,l=Dt(s,i);if(d(l))return Bt(4,l.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let c=ii({root:e});return d(c)&&logger.info(c.message),u("Loaded project",void 0)},_S=async e=>{let t=ue({repoRoot:e});if(d(t))return a(t.message);let n=t.value,r=await Xn({repoRoot:n});if(d(r))return a(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await ti({worktreeRoot:n,operation:"boot pull",fn:()=>Rd(n,()=>(Ar("Pulling"),Ff(e,n)))});if(d(o))return Te(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(d(s))return ao(s.message)?(Qs("Offline"),u("Offline",void 0)):Te(s.message);if(!s.value)return nr("Already synced"),u("Already synced",void 0);if(!OS(n))return u("Project changed during the pull",void 0);let i=Nd(n);return d(i)?i:(nr("Pulled"),u("Pulled and reloaded",void 0))},Di=e=>{_S(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Tr(t)}`)})},Of=()=>{let e=Dt([]);return d(e)?Bt(4,e.message):(N({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var jS=e=>e==="~"||e.startsWith("~/")?_f.join(US.homedir(),e.slice(1)):e,$S=(e,t)=>{let n=e.trim();if(!n)return a("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):a(`No recent project #${n}`)}let r=xe(_f.resolve(jS(n)));return d(r)?a(`No epiq project at ${n}`):u("Resolved project path",r.value)},Uf=async()=>{let e=vi();if(Q(""),h().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=bn({exclude:process.cwd()}),n=d(t)?[]:t.value,r=$S(e,n);if(d(r))return a(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return a(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await ki(o);return d(i)?(process.chdir(s),a(i.message)):(Di(o),u(`Opened ${Lr(o)}`,null))};var Bi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=Vs(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,c=Ot();if(d(c))return c;let m=Lt(i),{fatal:p,skipped:f}=gn(m);if(p.length>0)return Ot(),N(o),a(p.map(v=>v.message).join(", "));hn(f);let g=h().nodes[e];return g?(O.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(Ot(),N(o),a("Board did not exist at that date"))};var jf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)};var HS=20,WS=16,GS=150,Fi=null,Oi=null;var cr=()=>{Fi!==null&&(clearInterval(Fi),Fi=null),Oi!==null&&(clearTimeout(Oi),Oi=null)},$f=()=>{cr(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Hf=({events:e,startTime:t,durationMs:n})=>{cr();let r=e.length,o=Rr(e.map(f=>Rn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=jf(o),l=Math.max(1,Math.round(n*HS/1e3)),c=Math.max(Math.round(n/l),WS),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Fi=setInterval(()=>{m++;let f=m/l,g=[],v,x;for(;p<r&&i[p]<=f;){let R=e[p],A=An(R);if(d(A)){if(xo(A)){p++;continue}$f();return}g.push(...nd(R)),v=R,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let A=An(e[p]);if(d(A)&&!xo(A))break}let R=h().replay;N({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),cr(),Oi=setTimeout($f,GS);return}let I=h().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:v?x??I?.currentTime??t:I?.currentTime??t,currentLabel:v?_i(v):I?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:I?.flashNodeIds??[]}})},c)};var Wf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await wt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=ue({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=ee().commandMeta;if(cr(),r==="now"){let l=Mn(n.value);if(d(l))return a(l.message);let c=Ot();if(d(c))return c;let m=Lt(l.value),{fatal:p,skipped:f}=gn(m);return p.length>0?a(p.map(g=>g.message).join(", ")):(hn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=zs(n.value);if(d(l))return l;let c=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),m=c===void 0?null:Rn(c),p=(c===void 0?null:l.value.get(c.id)??null)??(m===null?null:go(m));if(p===null)return a(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=or(r||o.trim());if(!l)return a("Invalid peek date");s=l.getTime()}let i=Bi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var Gf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await wt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=ue({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=ee().commandMeta,{dateInput:s,durationInput:i}=ci(r,o);if(cr(),h().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let l=or(s);if(!l)return a("Invalid replay date");let c=i?li(i):15e3;if(c===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=h(),f=Bi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(Ot(),N(p),u("Nothing to replay from that point",!0)):(Hf({events:g,startTime:m,durationMs:c}),u("Replaying board history",!0))};import{spawn as zS}from"node:child_process";var KS=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},Vf=async e=>new Promise(t=>{let{command:n,args:r}=KS();try{let o=zS(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var Go=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Vf(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},zf=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=Po({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case Me.REF:return Go(_(o.id),"ref");case Me.TITLE:return Go(o.title,"title");case Me.DESCRIPTION:return r?Go(r.props?.description??"","description"):a("No issue in scope");case Me.TAGS:{if(!r)return a("No issue in scope");let s=kn(r).map(({name:i})=>i);return Go(s.join(", "),"tags")}case Me.ASSIGNEES:{if(!r)return a("No issue in scope");let s=Dn(r).map(({name:i})=>i);return Go(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var Kf=async()=>{Q(""),N({mode:b.DEFAULT});let e=et();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ri();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as qf}from"ulid";var Oe=async()=>{let e=await Gt();return d(e)?e:u("Resolved persist root",e.value)};var qS=e=>e.action==="add.issue.comment",Yf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await Oe();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=P(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let l=h().nodes[i];if(!l||!P(l))return a("Unable to resolve comment issue");let c=l.log?.filter(qS).find(m=>m.payload.id===s);return c?c.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:qf(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:qf(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)};import{ulid as YS}from"ulid";var Xf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!P(r))return a("Cannot close in this context");let o=h().nodes[he];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await Oe();if(d(s))return s;let i=s.value,l=Kt(o.id,r.id,{at:"end"},e.value,i);if(d(l))return l;let c=B([{id:YS(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],i);return d(c)?c:u("Issue closed",null)};import{ulid as XS}from"ulid";var Ui=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};var Jf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):at(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=h().nodes[he];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!P(s))return a("Target node is not issue");let l=Ui(s);if(!l)return a("Unable to resolve previous parent from issue history");if(l===i.id)return a("Previous parent resolves to closed swimlane");let c=h().nodes[l];if(!c)return a("Previous parent no longer exists");let m=await Oe();if(d(m))return m;let p=m.value,f=Kt(c.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=B([{id:XS(),action:"reopen.issue",payload:{id:s.id,parent:c.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)};import{ulid as JS}from"ulid";var Qf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=vi();if(!o)return a("Provide a title");let s=await Oe();return d(s)?s:B([{id:JS(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)};import{ulid as QS}from"ulid";var Zf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=C.findTagByName(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=h();if(!s)return a("Invalid untag target");let i=at(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let l=i.value;if(!P(l))return a("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await Oe();return d(m)?m:B([{id:QS(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)};import{ulid as fl}from"ulid";var eg=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=h();if(!o)return a("Invalid tag target");let s=at(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!P(i))return a("Target node is not issue");let l=await Oe();if(d(l))return l;let c=C.findTagByName(r),m=c?.id??fl();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...c?[]:[{id:fl(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:fl(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],l.value)};import{ulid as gl}from"ulid";var ji=()=>{let{eventLog:e=[],contributors:t}=h(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))};var tg=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:l}=h(),c=q(l.id)[i];if(!c)return a("Invalid assign target");let m=at(c.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!P(p))return a("Target node is not issue");let f=await Oe();if(d(f))return f;let g=ji(),v=!o&&s.toLowerCase()==="me",x,I;if(v)x=e.value.userId,I=g.find(w=>w.id===x)?.name??e.value.userName;else{let w=g.filter(k=>k.name===s);if(w.length>1)return a(`"${s}" matches ${w.length} contributors (${w.map(k=>k.id).join(", ")}). Assign from the GUI to choose by id.`);let M=w[0];if(!M&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=M?.id??gl(),I=M?.name??s}if((p.props.assignees??[]).includes(x))return a("Assignee already assigned");let A=!!h().contributors[x];return B([...A?[]:[{id:gl(),action:"create.contributor",payload:{id:x,name:I},...e.value}],{id:gl(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...e.value}],f.value)};import{ulid as ZS}from"ulid";var ng=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=h();if(!o)return a("Invalid unassign target");let s=at(o.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!P(i))return a("Target node is not issue");let l=i.props.assignees??[],c=r.toLowerCase()==="me",m=c?l.filter(g=>g===e.value.userId):ji().filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(c?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Oe();return d(f)?f:B([{id:ZS(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)};import{ulid as rg}from"ulid";var og=async e=>{let t=e.inputString.trim();if(!t)return a("Provide a comment");if(t.length>4e3)return a(`Cannot exceed ${4e3} characters`);let n=Z();if(d(n))return a("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=h(),s=Qe([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!i)return a("Invalid comment target");let l=i.context==="TICKET"?u("Resolved ticket",i):at(i.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let c=l.value;if(!P(c))return a("Target node is not issue");let m=await Oe();return d(m)?m:B([{id:rg(),action:"add.issue.comment",payload:{id:rg(),issue:c.id,author:n.value.userId,md:t},...n.value}],m.value)};import{ulid as tE}from"ulid";import eE from"zod";var sg=()=>{let e=ee().commandMeta.inputString,t=eE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=gt({autoSyncDebounceMs:t.data});return d(n)?n:(ze({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var ig=()=>{let e=ee().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Vm(e),n=gt({autoSync:t});return d(n)?n:(ze({autoSync:t}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var ag=()=>{let e=ee().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=gt({logLevel:e});return d(n)?n:(ze({logLevel:e}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var dg=e=>{let t=e.inputString.trim();switch(e.modifier){case ye.USERNAME:{if(process.env[dn])return a(`Cannot change the configured user while ${dn} names this process`);let n=Cr();if(d(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||tE();if(!i||!l)return a("Unable to resolve user name or id");let c=gt({userName:i,userId:l,preferredEditor:o??""});return d(c)?c:(ze({userName:i,userId:l}),N({mode:b.DEFAULT}),u(`Username set to "${i}"`,null))}case ye.EDITOR:{if(!t)return a("No editor provided");let n=gt({preferredEditor:t});return d(n)?n:(ze({preferredEditor:t}),N({mode:b.DEFAULT}),u(`Editor configuration set to "${t}"`,null))}case ye.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=gt({viewMode:t});return d(n)?n:(ze({viewMode:t}),N({mode:b.DEFAULT}),u(`View set to "${t}"`,null))}case ye.AUTOSYNC:return ig();case ye.LOG_LEVEL:return ag();case ye.SYNC_DEBOUNCE_MS:return sg();case ye.ATTACHMENT_MAX_KB:return sp();default:return a("Unknown config command")}};var $i=[{systemOnly:!0,intent:U.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Df},{intent:U.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:Yf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ne(E.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return we(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),u("Filter updated",null)}},{intent:U.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Un({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),u("Viewing help",null)}},{intent:U.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:Xf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:Jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:Tf},{intent:U.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Uf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:Bf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:Zf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:eg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:tg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:ng,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>og(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:Kf},{intent:U.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:Wf},{intent:U.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:Gf},{intent:U.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await gf();return d(e)?e:(N({mode:b.DEFAULT}),u("Export successful",!0))}},{intent:U.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(O.exit(),u("Exit successful",!0))},{intent:U.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Cf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>zf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>dg(t)}];var nE=new Set(["peek","replay","filter","view-help","yank"]),tn=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return a("No command to confirm");if(!e&&n===Qt.Invalid)return a("Invalid command");let s=bi(t);Rp();let{readOnly:i}=h();if(i&&!nE.has(s))return Fo({status:En.Fail,message:"Command not available in readonly state",value:null});let l=$i.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Fo({status:En.Fail,message:"Command not found",value:null});let c;try{c=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return Fo({status:En.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(c)?Fo(c):(Np({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&oi(),c)};var Hi=[{intent:S.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),Q("move cancel"),tn({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),Q("move start"),tn({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),Q("move confirm"),tn({isForceExecutedBySystem:!0}))}],Wi=[{intent:S.MovePreviousItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move previous"),tn({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move next"),tn({isForceExecutedBySystem:!0})):a("No pending move")}],lg=[{intent:S.MoveToNextContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move to-next"),tn({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveToPreviousContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move to-previous"),tn({isForceExecutedBySystem:!0})):a("No pending move")}];var cg={[V.WORKSPACE]:[...Hi,...Wi],[V.BOARD]:[...Hi,...Wi],[V.SWIMLANE]:[...Hi,...Wi,...lg],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]};import oE from"node:fs";import sE from"node:path";import{spawn as rE}from"node:child_process";function ug(e){let t=process.platform,o=rE(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var mg=e=>{let t=xe(process.cwd());if(d(t))return a("Unable to resolve project root");let n=ue({repoRoot:t.value});if(d(n))return a(n.message);let r=ir(e.hash,e.ext),o=sE.join(mo(n.value),r);return oE.existsSync(o)?(ug(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var pg=()=>{Q("");let{pendingNavTarget:e}=_n();N({mode:b.DEFAULT}),e&&O.navigate(e),Un({pendingNavTarget:void 0})},fg=[{intent:S.ExitCommandLine,mode:b.HELP,action:()=>(pg(),u("Exiting help",null))},{intent:S.Exit,mode:b.HELP,action:()=>(pg(),u("Closed help",null))},{intent:S.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:b.HELP,action:()=>(O.navigateToNextItem(),u("Navigating to next help item",null))},{intent:S.NavToPreviousContainer,mode:b.HELP,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:b.HELP,action:()=>(O.navigateToNextContainer(),u("Navigating to next help container",null))}];var iE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=_n();t&&O.navigate(t),Un({pendingNavTarget:void 0}),Q(`${e} `)},gg=()=>{Q("");let{pendingNavTarget:e}=_n();e&&O.navigate(e),Un({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},hg=[{intent:S.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{Q("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Un({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),u("Opening command palette",null)}},{intent:S.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!Nn(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(iE(t),u("Selected command",t)):u("No command selected",null)}},{intent:S.ExitCommandLine,mode:b.PALETTE,action:()=>(gg(),u("Exiting palette",null))},{intent:S.Exit,mode:b.PALETTE,action:()=>(gg(),u("Closed command palette",null))},{intent:S.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.PALETTE,action:()=>(O.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.PALETTE,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.PALETTE,action:()=>(O.navigateToNextContainer(),u("Navigating to next container",null))}];var yg=[{intent:S.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...fg,...hg,{intent:S.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.NEW} `),u("Adding new item",null))},{intent:S.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.DELETE} `),u("Deleting item",null))},{intent:S.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!ae(e?.id??"")?.length){let r=e?C.getAttachment(e.id):void 0;if(r)return mg(r);if(e?.title===fe.DESCRIPTION)return N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Propose command",!0);if(e?.title===fe.ASSIGNEES)return N({mode:b.COMMAND_LINE}),Q(`${E.ASSIGN} `),u("Propose command",!0);if(e?.title===fe.TAGS)return N({mode:b.COMMAND_LINE}),Q(`${E.TAG} `),u("Propose command",!0);if(t.title===fe.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Propose command",!0)}return O.enterChildNode(),u("Entering context",null)}},{intent:S.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===fe.DESCRIPTION?Me.DESCRIPTION:e?.title===fe.TAGS?Me.TAGS:e?.title===fe.ASSIGNEES?Me.ASSIGNEES:Me.REF,r=Ne(E.YANK).includes(t)?t:Me.REF;return N({mode:b.COMMAND_LINE}),Q(`${E.YANK} ${r}`),u("Propose command",!0)}},{intent:S.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} title ${h().selectedNode?.title}`),u("Exiting context",null))},{intent:S.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Exiting context",null))},{intent:S.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(O.enterParentNode(),u("Exiting context",null))},{intent:S.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.DEFAULT,action:()=>(O.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.DEFAULT,action:()=>(O.navigateToNextContainer(),u("Navigating to next container",null))}];var aE=500,dE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),vg=e=>{let t=dE(e);t&&yi(n=>(n+t).slice(0,aE))};var lE=[b.COMMAND_LINE,b.PALETTE],cE=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(Wd(-1),u("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(Wd(1),u("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Gd("left"),u("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Gd("right"),u("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(yi((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=h().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(vg(n??""),u("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Ep(),u("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(Cp(),u("Erasing input word",null))}],bg=[{intent:S.Confirm,mode:b.COMMAND_LINE,action:()=>(tn(),u("Executing command",null))},{intent:S.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),u("Viewing help",null))},...lE.flatMap(cE),{intent:S.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),u("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Ap(),u("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Tp(),u("Getting next command from history",null))}];var hl=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},xg=({keys:e})=>e.length===1?0:1,Ig=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(hl).filter(r=>r!==null).sort((r,o)=>xg(r)-xg(o))};function Sg(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Eg=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var nn,yl,vl=new Set,bl=()=>{for(let e of vl)e()},mE=e=>(vl.add(e),()=>vl.delete(e));function xl(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let c=Sg(t,o,r);if(d(c))return logger.error(c.message),c;let m=c.value,{context:p}=l,f=[...yg,...cg[p]??[],...bg],g=Ig(f,n),v=Eg(f),x=pE(o,s),I=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:v,selectedNode:I,renderedChildrenIndex:x})}var h=()=>{if(!nn)throw new Error("State not initialized. Call initWorkspaceState() first.");return nn},et=()=>nn?u("Retrieved state",nn):a("State not initialized. Call initWorkspaceState() first.");function Io(e){yl=e;let t=xe(process.cwd()),n=!1;if(!d(t)){let s=$t(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=xl(r);return d(o)?o:(nn=o.value,bl(),u("State initialized",null))}var ur=!1,Vo=null;function we(e){let t=h(),n=e(t);if(ur)return Vo=n,nn={...t,...n},u("State updated",null);let r=xl(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,bl(),u("State updated",null))}function Nu(e){if(ur)return u("Joined batch",e());ur=!0,Vo=null;let t=()=>{let n=Vo;if(ur=!1,Vo=null,n===null)return null;let r=xl(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,bl(),u("State updated",null))};try{let n=e(),r=t();return r&&d(r)?a(r.message):u("State updated",n)}finally{ur&&t()}}var lm=()=>ur,N=e=>we(t=>({...t,...e}));function mr(e,t,n){if(!ur)return we(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};o[t]=n;let s={...r,[e]:o};return Vo=s,nn={...r,...s},u("State updated",null)}var Y=()=>uE(mE,h,h),pE=sm,q=e=>h()?.renderedChildrenIndex[e]??[],Ot=()=>yl?Io(yl):a("Cannot reset state: no initial workspace found"),vt=()=>nn!==void 0;var at=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Il=(e,t)=>{let{nodes:n}=h(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},$n=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),C={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){we(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!P(t))return a("Can only comment on issues");let n=mr("comments",e.id,{...e,deleted:!1});return d(n)?a("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!P(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=mr("comments",e,o);return d(s)?a("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=mr("comments",e,n);return d(r)?a("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!P(t))return a("Can only attach to issues");let n=we(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=we(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return a("Edit target node not found");let o=$n(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=$n(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ae(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=$n(o,"move");if(i)return i;if(Il(t,e))return a("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),u("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=$n(o,"delete");if(s)return s;let i=new Set,l=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of ae(p.id))l(f.id)}};l(e);let c={...structuredClone(t)};for(let m of i){if(!c[m])return a("Unable to locate node to delete");c[m]={...c[m],isDeleted:!0}}return n?(N({nodes:c}),u("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:Ds,tombstoned:!0},r=we(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let r={...n,name:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=we(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=$n(r,"edit");if(o)return o;if(!P(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=$n(r,"edit");if(o)return o;if(!P(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return u("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(i),u("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=$n(r,"edit");if(o)return o;if(!P(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=$n(r,"edit");if(o)return o;if(!P(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return u("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},r=we(o=>({...o,tags:{...o.tags,[e]:n}}));return d(r)?a("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,tags:{...s.tags,[e]:r}}));return d(o)?a("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=we(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=mr("nodes",e.id,e);return d(t)?a("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=mr("nodes",e,n);return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=mr("nodes",e.id,e);return d(t)?t:u("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return ae(e)}};var fE=(e,t)=>e+" ".repeat(Math.max(0,t-Cg(e))),gE=(e,t)=>" ".repeat(Math.max(0,t-Cg(e)))+e,Gi=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),hE=(e,t)=>t?e<t?"up":e>t?"down":null:null,yE=(e,t)=>{let n=C.getNode(e.payload.parent),r=n?Hn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=hE(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Rg=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ng=e=>C.getAttachment(e)?.name??"",vE=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?Hn.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?Hn.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Hn.hex(de(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Hn.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Hn.dim(`(${Rg(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ng(e.payload.id);return t?`"${t}"`:""}default:return""}},bE=e=>{let t=Wr(Re(e));return Hn.gray(gE(t,8))},xE=12,IE=e=>fE(`${e}`,xE),SE=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=C.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Rg(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ng(e.payload.id);return t?`"${t}"`:""}default:return""}},_i=e=>[Gi(e.action),SE(e)].filter(Boolean).join(" "),Ag=(e,t)=>{let n=bE(e.id),r=IE(e.userName),o=Hn.dim("\u203A"),s=e.action==="move.node"?yE(e,t):[Gi(e.action),vE(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var EE=e=>De(e,"comments"),CE=e=>De(e,"description"),RE=e=>De(e,"assignees"),NE=e=>De(e,"tags"),AE=e=>De(e,"history"),TE=e=>De(e,"attachments"),Vi=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=C.getNode(e);if(!l){let p=C.createNode({...ge.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:u("Virtual field created",void 0)}if(!ut(l))return a(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=C.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},Tg=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=C.getNode(e);if(!i){let m=C.createNode({...ge.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:u("Virtual field list created",void 0)}if(!ho(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let c=C.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(c)?c:u("Virtual field list updated",void 0)},Au=e=>{let t=yt(Vt/4n),n=yt(Vt/2n),r=yt(Vt*3n/4n),o=yt(Vt*7n/8n),s=yt(Vt*15n/16n),i=yt(Vt*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;if(d(i))return i;let l=Vi({id:CE(e.id),name:fe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(l))return l;let c=Tg({id:RE(e.id),name:fe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let m=Tg({id:NE(e.id),name:fe.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=Vi({id:EE(e.id),name:fe.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=Vi({id:TE(e.id),name:fe.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=Vi({id:AE(e.id),name:fe.HISTORY,parentNodeId:e.id,rank:i.value,value:wE(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},wE=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Ag(r,n.get(r.action)??[])).join(`
|
|
82
|
-
`)},wg=!0,Mg=e=>{wg=e},rd=()=>wg;import tR from"node:http";import vr from"node:path";import{fileURLToPath as nR}from"node:url";var ME=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},Sl=(e,t)=>{let n=[];for(let r of e){let o=ME(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Rn(r);n.push({laneId:o,enteredAt:s===null?t:go(s)})}return n},zi=(e,t)=>Sl(e,t).at(-1)?.enteredAt??t;import{existsSync as Nl}from"node:fs";import{chmod as Al}from"node:fs/promises";import Ki from"node:path";import{chmodSync as PE,existsSync as LE,lstatSync as kE,mkdirSync as DE}from"node:fs";import BE from"node:os";import FE from"node:path";var El=(...e)=>{let t=FE.join(BE.tmpdir(),"epiq",...e);try{return LE(t)&&kE(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(DE(t,{recursive:!0,mode:448}),PE(t,448),u("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var OE=new Set(["create.tag","create.contributor","add.swimlane"]),_E=e=>{let t=new Map;for(let n of e){if(!OE.has(n.action))continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},UE=e=>{let t=new Map,n=new Map;for(let r of e){let o=r.payload;!o?.id||!o.parent||(r.action==="move.node"&&t.set(r.id,n.get(o.id)),n.set(o.id,o.parent))}return t},Lg=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},jE=e=>{let t=new Set,n=new Map;for(let r of e){let o=r.payload,s=o?.id;s&&(r.action==="add.issue"&&t.add(s),o.parent&&n.set(s,o.parent))}return{issueIds:t,parentById:n}},$E=(e,{issueIds:t,parentById:n})=>{let r=e.payload;if(r?.issue)return r.issue;let o=new Set,s=r?.id;for(;s!==void 0&&!o.has(s);){if(t.has(s))return s;o.add(s),s=n.get(s)}return null},Pg=90,HE=e=>{let t=e.trim().split(`
|
|
83
|
-
`)
|
|
84
|
-
`)
|
|
85
|
-
`)
|
|
86
|
-
`).filter(l=>l!==""),o=r.filter(l=>!Rl.test(l)&&!Hg.test(l));if(o.length>0)return a(`Could not parse ${o.length} line(s) of "git diff --raw --numstat" output, e.g. "${o[0]}"`);let s=new Map;for(let l of r){let c=Hg.exec(l);c&&s.set(c[3]??"",{insertions:c[1]==="-"?0:Number(c[1]),deletions:c[2]==="-"?0:Number(c[2])})}let i=r.filter(l=>Rl.test(l)).map(l=>{let c=Rl.exec(l),m=c?.[1]??"",p=c?.[2]??"",f=c?.[3]??"";return{path:f,beforeBlob:$g(m)?null:m,afterBlob:$g(p)?null:p,...s.get(f)??{insertions:0,deletions:0}}});return i.length===0?a("No changed files found for this commit"):u("Listed changed files with blob hashes",i)},zg=async e=>{if(!Gg(e.sha))return a("Invalid commit sha");let t=Yi(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=await eC(n,e.sha);if(d(r))return a(r.message);let o=r.value;if(o.length>ZE)return a(`Commit touches ${o.length} files \u2014 too many to show as a diff`);let s=o.flatMap(m=>[m.beforeBlob,m.afterBlob].filter(p=>p!==null)),i=await Rs(s,n);if(d(i))return a(i.message);let l=i.value,c=o.map(m=>({path:m.path,before:m.beforeBlob?l.get(m.beforeBlob)??"":"",after:m.afterBlob?l.get(m.afterBlob)??"":"",insertions:m.insertions,deletions:m.deletions}));return u("Loaded commit diff",{sha:e.sha,files:c})},Kg=e=>{let t=Mn(e);if(d(t))return a(t.message);let n=Ot();if(d(n))return a(n.message);qi=null;let r=Lt(t.value),{fatal:o,skipped:s}=gn(r);return o.length>0?a(o.map(i=>i.message).join(", ")):(hn(s),N({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},tC=(e,t)=>{qi=null;let n=Kg(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},wl=e=>Wn(async()=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=Vs(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=Ot();if(d(s))return s;let i=Lt(r),{fatal:l,skipped:c}=gn(i);return l.length>0?tC(t.value,l.map(m=>m.message).join(", ")):(hn(c),N({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),qi=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),qg=async e=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=zs(t.value);if(d(n))return a(n.message);let r=n.value.get(e.eventId)??null;return r===null?a("Event not found in the log"):wl({repoRoot:e.repoRoot,targetTime:r+1})},Yg=(e={})=>Wn(async()=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=Kg(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});import nC from"node:fs";var pr=e=>{let t=xe(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Qi=null,te=async(e,t)=>{let n=pr(e);if(d(n))return n;let r=ue({repoRoot:n.value});if(d(r))return a(r.message);let o=Ht(n.value);if(d(o))return a(o.message);if(!(Qi!==null&&Qi.repoRoot===n.value&&Qi.stateBranchRoot===r.value&&nC.existsSync(Yn(r.value)))){let p=await Id({repoRoot:n.value,stateBranchName:o.value});if(d(p))return a(p.message);let f=await rr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(d(f))return a(f.message);Qi={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await j({cwd:r.value,args:["pull","--ff-only"]});d(p)&&z.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=zt(r.value);if(_u(r.value)===l&&vt()&&tt().mode==="live")return u("Booted Epiq state, unchanged",i);let c=bt(r.value);if(d(c))return a(c.message);let m=Dt(c.value.events,c.value.unreadable);return d(m)?a(m.message):(Uu(r.value,l),u("Booted Epiq state",i))},ne=()=>{let e=ht();return d(e)?a(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},X=()=>{let e=et();return d(e)?a(e.message):e};var Kr=e=>(e.props.tags??[]).map(t=>C.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:de(t.name)}));var qr=e=>(e.props.assignees??[]).map(t=>C.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:de(n)}));import rC from"node:fs";import oC from"node:path";import{ulid as Ml}from"ulid";var sC=e=>{if(e.filePath)try{return u("Read attachment file",{data:rC.readFileSync(e.filePath),name:e.name??oC.basename(e.filePath)})}catch(t){return a(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):a("Provide either filePath or dataBase64")},Zi=()=>{let e=ht();return d(e)?Jt:e.value.attachmentMaxKb??Jt},Pl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=sC(e);if(d(s))return s;let i=rp(t.value.stateBranchRoot,s.value.data,Zi());if(d(i))return i;let l=Ie(s.value.name).trim()||"image",c=Ml(),m={id:Ml(),...n.value,action:"add.issue.attachment",payload:{id:c,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:l,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);if(d(p))return a(p.message);let f=ir(i.value.hash,i.value.ext);return u("Added issue attachment",{id:c,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Bd(l,f)})},Ll=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return a("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return a("You can only delete your own attachments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Attachment target must be an issue");if(s.readonly)return a("Cannot delete attachment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let l={id:Ml(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},kl=async e=>{let t=await te(e.repoRoot,{pull:!1});return d(t)?t:op(t.value.stateBranchRoot,e.fileName,Zi())};var iC=365*24*60*60*1e3,fr=()=>{let e=X();if(d(e))return e;let t=tt(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(I=>Nr(I)&&!I.isDeleted),s=Date.now()-iC,i=new Map,l=new Map;for(let I of r)if(!I.isDeleted){if(Pt(I)&&I.parentNodeId){let R=i.get(I.parentNodeId)??[];R.push(I),i.set(I.parentNodeId,R)}if(P(I)&&I.parentNodeId){if(I.parentNodeId===he&&Re(I.id)<s)continue;let R=l.get(I.parentNodeId)??[];R.push(I),l.set(I.parentNodeId,R)}}let c=new Set;for(let I of l.values())for(let R of I)c.add(R.id);let m=ht();if(d(m))return m;let p={},f=C.getCommentsGroupedByIssue();for(let I of r.filter(P))I.isDeleted||!c.has(I.id)||(p[I.id]=(f.get(I.id)??[]).map(R=>{let A=C.getContributor(R.authorId);return{id:R.id,issueId:R.issue,body:R.md,author:{id:R.authorId,name:A?.name??"Unknown",color:de(A?.name??R.authorId??"Unknown")},createdAt:Re(R.id)}}));let g=new Map;for(let I of e.value.eventLog)I.action==="add.issue.attachment"&&g.set(I.payload.id,I.payload.author);let v={},x=C.getAttachmentsGroupedByIssue();for(let I of r.filter(P))I.isDeleted||!c.has(I.id)||(v[I.id]=(x.get(I.id)??[]).map(R=>({id:R.id,issueId:R.issue,name:R.name,fileName:ir(R.hash,R.ext),bytes:R.bytes,createdAt:Re(R.id),canDelete:g.get(R.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((I,R)=>I.rank.localeCompare(R.rank)).map(I=>({id:I.id,ref:_(I.id),title:I.title,readonly:!!I.readonly||n,swimlanes:(i.get(I.id)??[]).sort((R,A)=>R.rank.localeCompare(A.rank)).map(R=>({id:R.id,title:R.title,readonly:!!R.readonly||n,issues:(l.get(R.id)??[]).sort((A,w)=>A.rank.localeCompare(w.rank)).map(A=>({id:A.id,ref:_(A.id),title:Ie(A.title),description:A.props.description??"",createdAt:Re(A.id),enteredLaneAt:zi(A.log??[],Re(A.id)),readonly:!!A.readonly||n,tags:Kr(A),assignees:qr(A),parentNodeId:A.parentNodeId,isClosed:A.parentNodeId===he})),parentNodeId:R.parentNodeId}))})),tags:C.getTags().map(I=>({...I,color:de(I.name)})),contributors:Object.values(e.value.contributors).map(I=>({...I,color:de(I.name)})),user:{name:m.value.userName??"",id:m.value.userId??"",color:de(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:v,attachmentMaxKb:Zi(),timeTravel:t})},Xg=null,aC=e=>{if(e===Xg)return;let t=ii({root:e});if(d(t)){z.info(t.message);return}Xg=e},Et=async(e={})=>{if(tt().mode!=="live")return fr();let t=await te(e.repoRoot,{pull:!1});return d(t)?t:(aC(t.value.repoRoot),fr())},qo=async(e={})=>{Ar();let t=pr(e.repoRoot);if(d(t))return a("Sync failed");let n=ne();if(d(n))return n;let r=await ni({cwd:t.value,ownEventFileName:Zn(n.value)});return d(r)?(bd(r.message),r):(nr(),u("Synced",r.value))};import{ulid as Ct}from"ulid";var Yo=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):a("Provide issueId or issueIds")},Yr=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):a(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Dl=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);d(o)?n.failed.push({id:r,ref:_(r),reason:o.message}):n.done.push({id:r,ref:_(r)})}return n},Xo=e=>{let t=X();if(d(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Issue not found"):P(n)?n.readonly?a("Issue is readonly"):u("Found issue",n):a("Target must be an issue")};var Zg=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Ol(e){let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(P).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==he).filter(l=>e.boardId?(l.parentNodeId?r[l.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(l=>!e.swimlaneId||l.parentNodeId===e.swimlaneId).filter(l=>!e.tag||Kr(l).some(c=>Zg(c.name,e.tag))).filter(l=>!e.assignee||qr(l).some(c=>Zg(c.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Ie((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Ie(l.title),swimlane:i(l),tags:Kr(l).map(c=>c.name),assignees:qr(l).map(c=>c.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Ie(l.title),description:l.props.description??"",createdAt:Re(l.id),enteredLaneAt:zi(l.log??[],Re(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===he,readonly:!!l.readonly,tags:Kr(l),assignees:qr(l)})))}var _l=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=Ie(e.title);if(!o)return a("Issue title cannot be empty");let s=e.description??"",i=st("Issue title",o,300)??st("Issue description",s,2e4);if(i)return a(i);if((e.tagNames?.length??0)>20)return a(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return a(`Cannot set more than ${20} assignees at once`);let l=Pn(e.parentId,n.value,t.value.stateBranchRoot);if(d(l))return l;let c=Pi({name:o,parent:e.parentId,user:n.value,rank:l.value});if(d(c))return c;let m=[...c.value],p=m.find(x=>x.action==="add.issue")?.payload.id;if(!p)return a("Unable to determine created issue id");s&&m.push({id:Ct(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let x of e.tagNames??[]){let I=Ie(x).trim();if(!I||f.some(M=>M.name===I))continue;let R=st("Tag name",I,60);if(R)return a(R);let A=C.findTagByName(I),w=A?.id??Ct();A||m.push({id:Ct(),...n.value,action:"create.tag",payload:{id:w,name:I}}),m.push({id:Ct(),...n.value,action:"add.issue.tag",payload:{id:p,tag:w}}),f.push({id:w,name:I})}let g=[];for(let x of e.assigneeNames??[]){let I=Ie(x).trim();if(!I||g.some(M=>M.name===I))continue;let R=st("Assignee name",I,80);if(R)return a(R);let A=Object.values(r.value.contributors).find(M=>M.name===I),w=A?.id??Ct();A||m.push({id:Ct(),...n.value,action:"create.contributor",payload:{id:w,name:I}}),m.push({id:Ct(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:w}}),g.push({id:w,name:I})}let v=B(m,t.value.stateBranchRoot);return d(v)?a(v.message):u("Created issue",{id:p,ref:_(p),title:o,parentId:e.parentId,description:s,tags:f,assignees:g})},dC=(e,t,n)=>{let r=Xo(e);if(d(r))return r;let o=Kt(he,e,{at:"end"},t,n);if(d(o))return o;let s={id:Ct(),...t,action:"close.issue",payload:{id:e,parent:he,rank:o.value}},i=B([s],n);return d(i)?a(i.message):u("Closed issue",{id:e,ref:_(e)})};async function Ul(e){let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=Yo(e);if(d(r))return r;let o=s=>dC(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yr("Closed",Dl(r.value,o)):o(r.value[0])}var jl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Target node is not issue");if(o.parentNodeId!==he)return a("Issue is not closed");let s=Ui(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===he)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let l=Kt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(l))return l;let c={id:Ct(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:l.value}},m=B([c],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,ref:_(o.id),parentId:i.id})},lC=(e,t,n,r)=>{let o=Xo(e);if(d(o))return o;let s=Kt(t.parentId,e,t.position??{at:"end"},n,r);if(d(s))return s;let i={id:Ct(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},l=B([i],r);return d(l)?a(l.message):u("Moved issue",{id:e,ref:_(e),parentId:t.parentId})};async function $l(e){let t=pr(e.repoRoot);if(d(t))return t;let n=ne();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=bt(r.value);if(d(o))return o;let s=Dt(o.value.events,o.value.unreadable);if(d(s))return s;let i=Yo(e);if(d(i))return i;let l=c=>lC(c,e,n.value,r.value);return e.issueIds?Yr("Moved",Dl(i.value,l)):l(i.value[0])}var Hl=e=>{let t=X();if(d(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Re(r.id),action:r.action,label:_i(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:{id:r.userId,name:r.userName,color:de(r.userName)}}))):a("Issue not found")},Wl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=st("Issue description",e.description,2e4);if(s)return a(s);let i=o.props.description??"";if(i===e.description)return u("No changes made",{id:e.issueId,ref:_(e.issueId),description:i});let l={id:Ct(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,ref:_(e.issueId),description:e.description})},Gl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Ie(e.title);if(!s.trim())return a("Issue title cannot be empty");let i=st("Issue title",s,300);if(i)return a(i);if(o.title===s)return u("No changes made",{id:e.issueId,ref:_(e.issueId),title:s});let l={id:Ct(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,ref:_(e.issueId),title:s})};import{ulid as Qo}from"ulid";var Vl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.boardId];if(!o)return a("Board not found");if(!Nr(o))return a("Target parent must be a board");if(o.readonly)return a("Cannot add a swimlane to a readonly board");if(tt().mode!=="live")return a("Cannot add a swimlane while time travelling");let s=Ie(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=st("Swimlane title",s,300);if(i)return a(i);let l=Pn(e.boardId,n.value,t.value.stateBranchRoot);if(d(l))return l;let c=Qo(),m={id:Qo(),...n.value,action:"add.swimlane",payload:{id:c,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Created swimlane",{id:c,ref:_(c),title:s,boardId:e.boardId})},zl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!Pt(o))return a("Edit target must be a swimlane");if(o.readonly)return a("Cannot edit readonly swimlane");let s=Ie(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=st("Swimlane title",s,300);if(i)return a(i);if(o.title===s)return u("No changes made",{id:e.swimlaneId,ref:_(e.swimlaneId),title:s});let l={id:Qo(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited swimlane title",{id:e.swimlaneId,ref:_(e.swimlaneId),title:s})},Kl=async e=>{let t=pr(e.repoRoot);if(d(t))return t;let n=ne();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=bt(r.value);if(d(o))return o;let s=Dt(o.value.events,o.value.unreadable);if(d(s))return s;let i=Kt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let l={id:Qo(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:i.value}},c=B([l],r.value);return d(c)?a(c.message):u("Moved swimlane",{id:e.swimlaneId,ref:_(e.swimlaneId),boardId:e.boardId})},ql=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!Pt(o))return a("Delete target must be a swimlane");let s={id:Qo(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:_(e.swimlaneId)})};import{ulid as Zo}from"ulid";async function Yl(e){let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=Yo(e);if(d(r))return r;let o=Ie(e.tagName).trim();if(!o)return a("Tag name cannot be empty");let s=st("Tag name",o,60);if(s)return a(s);let i={done:[],failed:[]};for(let v of r.value){let x=Xo(v);d(x)?i.failed.push({id:v,ref:_(v),reason:x.message}):i.done.push({id:v,ref:_(v)})}if(!e.issueIds&&i.failed[0])return a(i.failed[0].reason);if(i.done.length===0)return a(Yr("Tagged",i).message);let l=C.findTagByName(o),c=l?.id??Zo(),m=[...l?[]:[{id:Zo(),...n.value,action:"create.tag",payload:{id:c,name:o}}],...i.done.map(({id:v})=>({id:Zo(),...n.value,action:"add.issue.tag",payload:{id:v,tag:c}}))],p=B(m,t.value.stateBranchRoot);if(d(p))return a(p.message);let f={id:c,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Yr("Tagged",i);return d(g)?g:u(g.message,{...g.value,tag:f})}var Xl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.tags[e.tagId];if(!o)return a("Tag not found");if(o.tombstoned)return a("Tag is already deleted");let s=[{id:Zo(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=B(s,t.value.stateBranchRoot);return d(i)?a(i.message):u("Deleted tag",{id:o.id,name:o.name})};var Jl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Zo(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,ref:_(e.issueId),tagId:e.tagId})};import{ulid as gr}from"ulid";var cC=()=>{let e=et(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},th=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n};var nh=async(e,t)=>{let n=gd(e);if(d(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},Ql=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let R=r.value.contributors[s],A=R?void 0:await nh(t.value.stateBranchRoot,s);if(!R&&!A)return a("Unknown assignee id");let w=R??A,M=[...R?[]:[{id:gr(),...n.value,action:"create.contributor",payload:{id:w.id,name:w.name}}],{id:gr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:w.id}}],k=B(M,t.value.stateBranchRoot);return d(k)?a(k.message):u("Added issue assignee",{id:e.issueId,ref:_(e.issueId),assignee:{id:w.id,name:w.name}})}let i=Ie(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=st("Assignee name",i,80);if(l)return a(l);let m=[...th(cC(),r.value.contributors).entries()].filter(([,R])=>R===i);if(m.length>1)return a(`"${i}" matches ${m.length} contributors (${m.map(([R])=>R).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=gr(),g=i]=p??[],x=[...!!r.value.contributors[f]?[]:[{id:gr(),...n.value,action:"create.contributor",payload:{id:f,name:g}}],{id:gr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],I=B(x,t.value.stateBranchRoot);return d(I)?a(I.message):u("Added issue assignee",{id:e.issueId,ref:_(e.issueId),assignee:{id:f,name:g}})},Zl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await nh(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:gr(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(i,t.value.stateBranchRoot);return d(l)?a(l.message):u("Tombstoned contributor",{id:e.contributorId,name:Ds})};var ec=async(e={})=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=Mn(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Dg(o.value,e.boardId):o.value,i=new Map,l=new Set,c=new Set,m=gd(t.value.stateBranchRoot);if(d(m))return a(m.message);for(let v of m.value)v.userId&&c.add(v.userId);for(let v of s)v.userId&&(i.set(v.userId,v.userName??""),l.add(v.userId));let p=r.value.contributors,g=[...th(i,p).entries()].map(([v,x])=>({id:v,name:x,color:de(x),isSelf:v===n.value.userId,isExternal:!l.has(v),isRemoved:p[v]?.tombstoned===!0,hasAuthoredAnywhere:c.has(v)}));return u("Listed board contributors",g)},tc=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:gr(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,ref:_(e.issueId),assigneeId:e.assigneeId})};import{ulid as ea}from"ulid";var es=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=ea(),l={id:ea(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},ts=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:ea(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},nc=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only edit your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot edit comment on readonly issue");if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return a("Comment was deleted");let l=e.body.trim();if(!l)return a("Comment cannot be empty");if(l.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let c={id:ea(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([c],t.value.stateBranchRoot);return d(m)?a(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})};var rn="1.8.5";import uC from"node:fs";import rh from"node:path";var ns=Number(process.env.EPIQ_GUI_PORT)||3710,rc="/api/instance",oc="epiq",ta=e=>{try{return uC.realpathSync(rh.resolve(e))}catch{return rh.resolve(e)}},mC=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===oc&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},oh=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${rc}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return mC(s)?s:null}catch{return null}finally{clearTimeout(r)}};var pC=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),hr=e=>d(e)?e:u(e.message,pC(e.value)),sh=(e,t)=>{let n=(e.boards??[]).flatMap(r=>r.swimlanes??[]).flatMap(r=>r.issues??[]).find(r=>r.id===t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}};var fC=15e3,ih=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=xe(e.project.repoRoot);if(d(g))return null;let v=ue({repoRoot:g.value});return d(v)?null:zt(v.value)}let l=()=>{let g=Cr();return d(g)?(z.error(g.message),null):g.value},c=()=>{let g=l();if(!g)return!1;let{autoSync:v,preferredEditor:x}=g,I=ht(),R=d(I)?null:I.value.userName;return!!(v&&R&&x)},m=()=>{let g=l()?.autoSyncDebounceMs??fC;return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await Wn(async()=>{if(tt().mode!=="live")return;await qo({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let v=hr(await Et({repoRoot:e.project.repoRoot}));d(v)||tr({type:"state",payload:v})})}finally{r=!1,f()}}};function f(){n||!c()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,dispose:()=>{n=!0,t&&clearTimeout(t)}}};var gC=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),sc=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!gC.has(n.hostname)},ah=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:sc(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as QC}from"ws";var on=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var hC=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},dh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...on(i),changed:i.addedCount+i.removed})).reduce((i,l)=>i===null||l.changed>i.changed?l:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>hC(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var _e={line:["//"],block:[["/*","*/"]]},Rt={line:["#"],block:[]},ic={line:["--"],block:[]},Xr={line:[],block:[["<!--","-->"]]},yC={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),na=$("TypeScript",_e),ra=$("JavaScript",_e),lh={ts:na,tsx:na,mts:na,cts:na,js:ra,jsx:ra,mjs:ra,cjs:ra,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",_e),rs:$("Rust",_e),java:$("Java",_e),kt:$("Kotlin",_e),swift:$("Swift",_e),c:$("C",_e),h:$("C",_e),cc:$("C++",_e),cpp:$("C++",_e),hpp:$("C++",_e),cs:$("C#",_e),php:$("PHP",_e),scala:$("Scala",_e),dart:$("Dart",_e),lua:$("Lua",ic),hs:$("Haskell",ic),sql:$("SQL",ic),ex:$("Elixir",Rt),exs:$("Elixir",Rt),pl:$("Perl",Rt),r:$("R",Rt),jl:$("Julia",Rt),sh:$("Shell",Rt),bash:$("Shell",Rt),zsh:$("Shell",Rt),vue:$("Vue",Xr),svelte:$("Svelte",Xr),html:$("HTML",Xr),xml:$("XML",Xr),md:$("Markdown",Xr),mdx:$("Markdown",Xr),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",_e),less:$("CSS",_e),yml:$("YAML",Rt),yaml:$("YAML",Rt),toml:$("TOML",Rt),ini:$("INI",Rt),json:$("JSON",yC)},vC="Other",ch=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},yr=e=>lh[ch(e)]?.name??vC,rs=e=>lh[ch(e)]?.comment??null,bC=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],xC=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jr=e=>xC.test(e)||bC.some(t=>t.test(e)),IC=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,SC=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,EC=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,_t=e=>IC.test(e)||SC.test(e)||EC.test(e),uh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),mh=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),ph=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),CC=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,RC=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,fh=e=>CC.test(e),gh=e=>RC.test(e);var hh=/\b(TODO|FIXME|HACK|XXX)\b/,NC=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,ac=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},AC=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},yh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,c=0;for(let p of e.files){if(p.binary||_t(p.path))continue;let f=rs(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=yr(p.path),v=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let I=ac(x,f);if(hh.test(x)&&i++,I==="blank"){s++;continue}if(I==="comment"){r++,v.comment++,f&&NC.test(AC(x,f))&&c++;continue}o++,v.code++}for(let{text:x}of p.removedLines)hh.test(x)&&l++;n.set(g,v)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:l,commentedOutCodeLines:c}};var TC=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,oa=6,dc=10,wC=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},MC=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},PC=e=>{if(e.length<oa*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+oa<=e.length;r++){let o=e.slice(r,r+oa);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
87
|
-
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let l=0;l<oa;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},vh=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,l=null,c=[];for(let[m,p]of e.files.entries()){if(_t(p.path)&&t.push(on(p)),uh(p.path)&&n.push(on(p)),mh(p.path)&&r.push(on(p)),ph(p.path)&&(o=!0),p.binary||_t(p.path))continue;let f=p.added.map(x=>x.text),g=wC(f),v=p.status!=="deleted";for(let x of f){TC.test(x)&&s++;let I=MC(x,g);I>i&&(i=I,l=on(p)),v&&c.push({text:x.trim(),file:m})}c.push({text:" ",file:m})}return{generatedPaths:t.slice(0,dc),dependencyManifests:n.slice(0,dc),buildOrCiPaths:r.slice(0,dc),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:l,duplicatedLines:PC(c)}};var bh=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let l=i.addedCount+i.removed;if(_t(i.path)){r+=l;continue}let c=yr(i.path),m=n.get(c)??{name:c,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,Jr(i.path)&&(m.addedInTests+=i.addedCount),n.set(c,m)}let o=[...n.values()].reduce((i,l)=>i+l.added+l.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,l)=>l.added+l.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}};var LC=200,lc=2e5,kC=5e4,xh=25,DC=64*1024*1024,cc="",BC=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,FC=/^diff --git a\/(.+) b\/\1$/,Ih=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Sh=(e,t)=>e===null?"added":t===null?"deleted":"modified",OC=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),_C=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,l=!1,c=0,m=(f,g)=>g==="modified"&&f==="added"?"added":g,p=(f,g)=>{let v=n.get(f);if(v)return v.entry.status=m(v.entry.status,g),v.entry.shas.includes(r)||v.entry.shas.push(r),v;let I={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,I),I};for(let f of t.split(`
|
|
88
|
-
`))
|
|
89
|
-
`)){
|
|
90
|
-
`)){let A=ac(R,v);A==="comment"&&I.comment++,A==="code"&&I.code++}c.set(x,I)}let m=new Map;for(let[p,f]of c){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Rh=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||_t(l.path))&&Jr(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(on(l)),l.status==="deleted"&&o.push(on(l));for(let{text:c}of l.added)fh(c)&&s++,gh(c)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var HC=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Nh=async({repoRoot:e,ref:t,commits:n})=>{let r=await Eh({repoRoot:e,shas:n.map(l=>l.sha)});if(d(r))return a(r.message);let o=r.value,s=HC(n),i=s?await Ch({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:dh({commits:n,patch:o}),languages:bh({patch:o,languagesBefore:i?.languages??null}),tests:Rh({patch:o}),comments:yh({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:vh({patch:o})})};var WC=32,os=new Map;var GC=(e,t)=>{if(os.set(e,t),os.size>WC){let n=os.keys().next();n.done||os.delete(n.value)}return t},sa=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return a("idOrRef must not be empty");let n=t.length>7?_(t):t.toUpperCase(),r=xe(e.repoRoot??process.cwd());if(d(r))return a(r.message);let o=r.value,s=await Ji({repoRoot:o,ref:n});if(d(s))return a(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),l=[o,n,i.map(p=>p.sha).join(",")].join(" "),c=os.get(l);if(c)return u("Derived issue stats",c);let m=await Nh({repoRoot:o,ref:n,commits:i});return d(m)?a(m.message):u("Derived issue stats",GC(l,m.value))};var VC="Filed here",Ah=(e,t)=>e.set(t,(e.get(t)??0)+1),Th=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?VC:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),wh=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[c,m]of l.entries()){if(m!==e)continue;s++,Ah(r,l[c-1]??null);let p=l[c+1];p!==void 0&&(i++,Ah(o,p))}return{arrived:s,departed:i,arrivesFrom:Th(r,s,n),movesOnTo:Th(o,i,n)}};var Mh=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var ss=1440*60*1e3,zC=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*ss,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,c]of i.entries()){let m=s.get(c.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((c.enteredAt-o)/ss)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/ss)-1);for(let v=f;v<=g;v++)m[v].push(o+v*ss-c.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((c,m)=>({t:o+m*ss,median:Mh(c.sort((p,f)=>p-f)),count:c.length}))]))},Ph=({laneId:e,journeys:t,now:n,days:r})=>zC({laneIds:[e],journeys:t,now:n,days:r})[e];var KC=40,qC=30,YC=()=>({tickets:0,commits:0,insertions:0,deletions:0}),XC=async(e,t)=>{let n=YC();for(let r of t.slice(0,KC)){let o=await sa({repoRoot:e,idOrRef:_(r)});d(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},Lh=async e=>{let t=X();if(d(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return a("Swimlane not found");let o=Object.values(n).filter(P),s=o.map(c=>Sl(c.log??[],Re(c.id))),i=wh(e.swimlaneId,s.map(c=>c.map(m=>m.laneId)),c=>n[c]?.title??"Elsewhere"),l=o.filter(c=>c.parentNodeId===e.swimlaneId).map(c=>c.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Re(e.swimlaneId),...i,stayTrend:Ph({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:qC}),code:await XC(e.repoRoot,l)})};var kh=new Set(["sync","issues:create","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Dh=e=>{let t=bn({exclude:e});return d(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Lr(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Bh=e=>{let t=bn();if(d(t))return a(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):a(`Not a recent project: ${e}`)};import{z as L}from"zod";var K=L.string().min(1),Fh=L.discriminatedUnion("at",[L.object({at:L.literal("start")}),L.object({at:L.literal("end")}),L.object({at:L.literal("before"),sibling:K}),L.object({at:L.literal("after"),sibling:K})]),is=L.number().finite(),se=(e,t)=>L.object({type:L.literal(e),payload:t}),ia=e=>L.object({type:L.literal(e)}),JC=L.discriminatedUnion("type",[ia("state:get"),ia("issues:list"),ia("sync"),ia("time-travel:live"),se("project:open",L.object({root:L.string().min(1)})),se("issues:create",L.object({title:L.string(),parentId:K,description:L.string().optional(),tagNames:L.array(L.string()).optional()})),se("swimlane:create",L.object({title:L.string(),boardId:K})),se("swimlane:edit:title",L.object({swimlaneId:K,title:L.string()})),se("swimlane:delete",L.object({swimlaneId:K})),se("swimlane:move",L.object({swimlaneId:K,boardId:K,position:Fh.optional()})),se("issues:move",L.object({issueId:K,parentId:K,position:Fh.optional()})),se("issue:edit:title",L.object({issueId:K,title:L.string()})),se("issue:edit:description",L.object({issueId:K,description:L.string()})),se("issue:tag:add",L.object({issueId:K,tagName:L.string()})),se("issue:tag:remove",L.object({issueId:K,tagId:K})),se("contributor:remove",L.object({contributorId:K})),se("tag:remove",L.object({tagId:K})),L.object({type:L.literal("contributors:get"),payload:L.object({boardId:K.optional()}).optional()}),se("issue:assignee:add",L.object({issueId:K,assigneeId:K.optional(),assigneeName:L.string().optional(),createUnlinked:L.boolean().optional()})),se("issue:assignee:remove",L.object({issueId:K,assigneeId:K})),se("issue:close",L.object({issueId:K})),se("issue:reopen",L.object({issueId:K})),se("issue:comment:add",L.object({issueId:K,body:L.string()})),se("issue:comment:delete",L.object({issueId:K,commentId:K})),se("issue:comment:edit",L.object({issueId:K,commentId:K,body:L.string()})),se("issue:get",L.object({issueId:K})),L.object({type:L.literal("timeline:get"),payload:L.object({start:is.optional(),end:is.optional(),boardId:K.optional(),requestId:L.number().finite().optional()}).optional()}),L.object({type:L.literal("commits:get"),payload:L.object({start:is.optional(),end:is.optional(),requestId:L.number().finite().optional()}).optional()}),se("time-travel:scrub",L.object({targetTime:is})),se("time-travel:checkout-event",L.object({eventId:L.string().min(1)})),se("commit:inspect",L.object({sha:L.string()})),se("commit:diff:get",L.object({sha:L.string()})),se("issue:commits:get",L.object({issueId:K})),se("issue:stats:get",L.object({issueId:K})),se("swimlane:stats:get",L.object({swimlaneId:K}))]);var Oh=e=>{let t=JC.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var ZC=1024*1024,uc=()=>{tr({type:"state",payload:hr(fr())})},re=(e,t)=>{e.send(JSON.stringify(t))},as=async(e,t)=>{let n=hr(await Et({repoRoot:t}));return d(n)&&n.message===Ga?re(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Dh(t)}}):re(e,{type:"state",payload:n})},eR=async(e,t)=>{let n=()=>re(e,{type:"state",payload:hr(fr())});if(tt().mode!=="live")return n();let r=await Et({repoRoot:t});return tt().mode!=="live"?n():re(e,{type:"state",payload:hr(r)})},We=async(e,t,n,r,o)=>{if(re(e,{type:r,payload:o}),d(o))return re(e,{type:"failed",payload:o.message});n(),eR(e,t)},_h=(e,t,{onStateChanged:n,getPort:r})=>{new QC({server:e,path:"/ws",maxPayload:ZC,verifyClient:s=>!sc(s.origin,r())}).on("connection",s=>{vm(s),s.on("message",async i=>{let l=async c=>{let{type:m}=c,p=t.repoRoot;if(m==="project:open"){let f=Bh(c.payload.root);return re(s,{type:"project:open:result",payload:f}),d(f)?void 0:(t.repoRoot=f.value,as(s,f.value))}if(m==="timeline:get"){let{requestId:f,...g}=c.payload??{};return re(s,{type:"timeline",requestId:f,payload:await Wg({repoRoot:p,...g})})}if(m==="issue:get"){let f=c.payload?.issueId,g=fr(),v=Hl(f);return re(s,{type:"issue",payload:d(g)?g:u("Issue detail",{...sh(g.value,f),history:d(v)?[]:v.value})})}if(m==="commits:get"){let{requestId:f,...g}=c.payload??{};return re(s,{type:"commits",requestId:f,payload:await Tl({repoRoot:p,...g})})}if(m==="commit:inspect")return re(s,{type:"commit:inspect:result",payload:await Vg({repoRoot:p,sha:c.payload.sha})});if(m==="commit:diff:get"){let{sha:f}=c.payload;return re(s,{type:"commit:diff:result",payload:{sha:f,result:await zg({repoRoot:p,sha:f})}})}if(m==="issue:commits:get"){let{issueId:f}=c.payload;return re(s,{type:"issue:commits:result",payload:{issueId:f,result:await Ji({repoRoot:p,ref:_(f)})}})}if(m==="issue:stats:get"){let{issueId:f}=c.payload;return re(s,{type:"issue:stats:result",payload:{issueId:f,result:await sa({repoRoot:p,idOrRef:_(f)})}})}if(m==="swimlane:stats:get"){let{swimlaneId:f}=c.payload;return re(s,{type:"swimlane:stats:result",payload:{swimlaneId:f,result:await Lh({repoRoot:p,swimlaneId:f})}})}if(m==="time-travel:scrub"){let f=await wl({repoRoot:p,targetTime:c.payload.targetTime});return re(s,{type:"time-travel:result",payload:f}),d(f)?void 0:uc()}if(m==="time-travel:checkout-event"){let f=await qg({repoRoot:p,eventId:c.payload.eventId});return re(s,{type:"time-travel:result",payload:f}),d(f)?void 0:uc()}if(m==="time-travel:live"){let f=await Yg({repoRoot:p});return re(s,{type:"time-travel:result",payload:f}),d(f)?void 0:uc()}if(m==="state:get")return as(s,p);if(m==="sync"){let f=await qo({repoRoot:p});return re(s,{type:"sync:result",payload:f}),n(),as(s,p)}if(m==="issue:comment:add"){let f=await es({repoRoot:p,...c.payload});return We(s,p,n,"issue:comment:add:result",f)}if(m==="issue:comment:edit"){let f=await nc({repoRoot:p,...c.payload});return We(s,p,n,"issue:comment:edit:result",f)}if(m==="issue:comment:delete"){let f=await ts({repoRoot:p,...c.payload});return re(s,{type:"issue:comment:delete:result",payload:f}),d(f)?re(s,{type:"failed",payload:f.message}):(n(),as(s,p))}if(m==="issue:edit:description"){let f=await Wl({repoRoot:p,...c.payload});return We(s,p,n,"issue:edit:description:result",f)}if(m==="issue:edit:title"){let f=await Gl({repoRoot:p,...c.payload});return We(s,p,n,"issue:edit:title:result",f)}if(m==="issue:tag:add"){let f=await Yl({repoRoot:p,...c.payload});return We(s,p,n,"issue:tag:add:result",f)}if(m==="issue:tag:remove"){let f=await Jl({repoRoot:p,...c.payload});return We(s,p,n,"issue:tag:remove:result",f)}if(m==="contributor:remove"){let f=await Zl({repoRoot:p,...c.payload});return We(s,p,n,"contributor:remove:result",f)}if(m==="tag:remove"){let f=await Xl({repoRoot:p,...c.payload});return We(s,p,n,"tag:remove:result",f)}if(m==="contributors:get")return re(s,{type:"contributors",payload:await ec({repoRoot:p,...c.payload})});if(m==="issue:assignee:add"){let f=await Ql({repoRoot:p,...c.payload});return We(s,p,n,"issue:assignee:add:result",f)}if(m==="issue:assignee:remove"){let f=await tc({repoRoot:p,...c.payload});return We(s,p,n,"issue:assignee:remove:result",f)}if(m==="issues:list")return re(s,{type:"issues",payload:await Ol({repoRoot:p})});if(m==="issues:create"){let f=await _l({...c.payload,repoRoot:p});return re(s,{type:"issues:create:result",payload:f}),d(f)?tr({type:"failed",payload:f.message}):(n(),as(s,p))}if(m==="swimlane:create"){let f=await Vl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:create:result",f)}if(m==="swimlane:edit:title"){let f=await zl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:edit:title:result",f)}if(m==="swimlane:delete"){let f=await ql({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:delete:result",f)}if(m==="swimlane:move"){if(!c.payload.position)return re(s,{type:"error",message:"Missing move position"});let f=await Kl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:move:result",f)}if(m==="issues:move"){if(!c.payload.position)return re(s,{type:"error",message:"Missing move position"});let f=await $l({...c.payload,repoRoot:p});return We(s,p,n,"issues:move:result",f)}if(m==="issue:close"){let f=await Ul({repoRoot:p,issueId:c.payload.issueId});return We(s,p,n,"issue:close:result",f)}if(m==="issue:reopen"){let f=await jl({repoRoot:p,issueId:c.payload.issueId});return We(s,p,n,"issue:reopen:result",f)}return re(s,{type:"error",message:"Unknown message type"})};try{let c=Oh(JSON.parse(i.toString()));if(!c.ok)return re(s,{type:"error",message:c.error});let m=c.message;return kh.has(m.type)?await Wn(async()=>tt().mode!=="live"?re(s,{type:"failed",payload:"Read-only while viewing history"}):l(m)):await l(m)}catch(c){return re(s,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var rR=vr.dirname(nR(import.meta.url)),oR=process.env.IS_LOCAL==="true"?vr.resolve(process.cwd(),"dist/gui"):vr.join(rR,"gui"),aa,sR=async()=>(aa===void 0&&(aa=await import("node:sea").catch(()=>null)),aa?.isSea()?aa:null),Ee=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},iR=e=>Ee(e,409,{isError:!0,message:"Read-only while viewing history"}),da=(e,t)=>Wn(async()=>tt().mode!=="live"?iR(e):t()),Uh=async(e,t=1024*1024)=>new Promise((n,r)=>{let o=[],s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),aR=2*1024*1024,dR={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},lR=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",jh=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=vr.resolve(oR),o=vr.resolve(r,n),s=vr.relative(r,o);if(s.startsWith("..")||vr.isAbsolute(s))return Ee(t,403,{isError:!0,message:"Forbidden"});let i=await sR();try{let l=i?Buffer.from(i.getAsset(`gui/${s}`)):await $h(o);return t.writeHead(200,{"content-type":lR(o)}),t.end(l)}catch{return Ee(t,404,{isError:!0,message:`Not found: ${n}`})}},cR=async(e,t=ns)=>new Promise((n,r)=>{let o=s=>{let i=c=>{if(e.off("listening",l),c.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(c)},l=()=>{e.off("error",i);let c=e.address();if(!c||typeof c=="string"){r(new Error("Unable to resolve address"));return}n(c.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),Hh=async e=>{Mg(!1);let t=0,n={repoRoot:e.repoRoot},r=tR.createServer(async(i,l)=>{let c=new URL(i.url??"/","http://127.0.0.1"),m=ah({method:i.method,origin:i.headers.origin,contentType:i.headers["content-type"]},t);if(m)return Ee(l,m.status,{isError:!0,message:m.message});if(i.method==="GET"&&c.pathname===rc)return Ee(l,200,{app:oc,repoRoot:ta(n.repoRoot),version:rn,pid:process.pid});if(c.pathname==="/api/state")return Ee(l,200,await Et({repoRoot:n.repoRoot}));if(i.method==="POST"&&c.pathname==="/api/comments")try{let p=await Uh(i);if(!p.issueId||!p.body?.trim())return Ee(l,400,{isError:!0,message:"Missing issueId or body"});let f=p.issueId,g=p.body;return await da(l,async()=>{let v=await es({repoRoot:n.repoRoot,issueId:f,body:g});return d(v)?Ee(l,400,{isError:!0,message:v.message}):Ee(l,200,await Et({repoRoot:n.repoRoot}))})}catch(p){return Ee(l,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add comment"})}if(i.method==="POST"&&c.pathname==="/api/attachments")try{let p=await Uh(i,aR);if(!p.issueId||!p.dataBase64)return Ee(l,400,{isError:!0,message:"Missing issueId or dataBase64"});let f=p.issueId,g=p.dataBase64,v=p.name??"";return await da(l,async()=>{let x=await Pl({repoRoot:n.repoRoot,issueId:f,name:v,dataBase64:g});return d(x)?Ee(l,400,{isError:!0,message:x.message}):Ee(l,200,{...await Et({repoRoot:n.repoRoot}),attachment:x.value})})}catch(p){return Ee(l,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add attachment"})}if(i.method==="DELETE"&&c.pathname.startsWith("/api/attachments/")){let p=decodeURIComponent(c.pathname.replace("/api/attachments/",""));return p?da(l,async()=>{let f=await Ll({repoRoot:n.repoRoot,attachmentId:p});return d(f)?Ee(l,400,{isError:!0,message:f.message}):Ee(l,200,await Et({repoRoot:n.repoRoot}))}):Ee(l,400,{isError:!0,message:"Missing attachment id"})}if(i.method==="GET"&&c.pathname.startsWith("/media/")){let p=decodeURIComponent(c.pathname.replace("/media/","")),f=await kl({repoRoot:n.repoRoot,fileName:p});if(d(f))return Ee(l,404,{isError:!0,message:f.message});try{let g=await $h(f.value.filePath);return l.writeHead(200,{"content-type":dR[f.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),l.end(g)}catch{return Ee(l,404,{isError:!0,message:"Attachment blob not found"})}}if(i.method==="DELETE"&&c.pathname.startsWith("/api/comments/")){let p=decodeURIComponent(c.pathname.replace("/api/comments/",""));return p?da(l,async()=>{let f=await ts({repoRoot:n.repoRoot,commentId:p});return d(f)?Ee(l,400,{isError:!0,message:f.message}):Ee(l,200,await Et({repoRoot:n.repoRoot}))}):Ee(l,400,{isError:!0,message:"Missing comment id"})}return c.pathname.startsWith("/board/")?jh("/",l):jh(c.pathname,l)});try{t=await cR(r)}catch(i){return a(i instanceof Error?`Unable to start GUI server: ${i.message}`:`Unable to start GUI server: ${String(i)}`)}let o=ih({project:n});_h(r,n,{onStateChanged:()=>o.queueSync(),getPort:()=>t}),r.on("close",o.dispose);let s=r.address();return!s||typeof s=="string"?(r.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${s.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var Gh=async e=>{let t=Ir({});if(d(t))return a(t.message);let n=ht();ce(n)&&ze(n.value);let r=await oh(ns);if(r&&r.repoRoot===ta(e.repoRoot)){let i=`http://127.0.0.1:${ns}`;return console.log(`Epiq GUI already running for this project at ${Wh.cyan(i)}`),Xa(i),u("Reused running GUI",{url:i})}let o=await Hh({...e,boardId:""});if(d(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Wh.cyan(s)}`),Xa(s),u("Started GUI",{url:s})};import{Box as Kn}from"ink";import Ce from"react";import{Box as mc,Text as ds}from"ink";import Ut,{useEffect as uR,useMemo as mR}from"react";import{ulid as pR}from"ulid";var Vh=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ut.createElement(ds,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?Ut.createElement(ds,{color:n,dimColor:o},e):Ut.createElement(ds,{color:n,dimColor:o},e.slice(0,l),Ut.createElement(ds,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},zh=pR(),fR=e=>`${e}`,gR=e=>{let{pendingNavTarget:t}=_n();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Ne(E.NONE,{breadCrumb:n,contextNode:r,readOnly:h().readOnly,selectedNode:o}));return[...new Set(Object.values(E))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==E.PALETTE).map(i=>{let l=bi(i),c=$i.find(m=>m.intent===l);return{command:i,description:c?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,l)=>i.isAvailable!==l.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(l.command))},hR=e=>ge.text({id:zh,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),yR=(e,t,n)=>ge.text({id:fR(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),pc=[],vR=e=>{Kh();let t=C.createNode(hR(h().rootNodeId));d(t)||!Nn(t.value)||(pc=[t.value,...e.map((n,r)=>yR(n,r,zh)).map(C.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0}))},Kh=()=>{let e=pc.map(t=>t.id);pc=[];for(let t of e)C.deleteNode(t)};function qh({width:e,height:t}){let r=wp().value.trim().toLowerCase(),o=mR(()=>gR(r),[r]);uR(()=>(vR(o),()=>{Kh()}),[o]);let s=h().selectedIndex;return Ut.createElement(mc,{flexDirection:"column",width:e,height:t-2},Ut.createElement(xt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let c=l===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ut.createElement(mc,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ut.createElement(ds,{color:m,dimColor:!i.isAvailable},c?"\u276F ":" ",Ut.createElement(Vh,{text:hu(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ut.createElement(mc,{paddingLeft:2},Ut.createElement(Vh,{text:p+i.description,match:r.length>=2?r:"",color:c&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as kR}from"ink";import ua from"react";import cs from"chalk";import{Box as fc,Text as Qh}from"ink";import ls,{useEffect as Zh,useMemo as bR,useState as ey}from"react";var Qr=["\u2803","\u2806","\u2830","\u2818"],Yh=120,Xh=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qr.length+Qr.length)%Qr.length;return Qr[r]}return e?"?":":"},Jh=({infoMessage:e,isPending:t})=>t&&e.includes(le)?"":e;var ty=cs.hex(y.secondary),xR=cs.inverse,IR=cs.inverse.hex(y.secondary2),SR={hint:"",hints:[],overlap:0,remainder:""},ry=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},ER=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>cs.bgHex(n).black(r),bgCursor:r=>cs.bgHex(n).inverse.black(r)}}return _d(t)},CR=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ry({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},ny=()=>({value:qe.value,cursorPosition:qe.cursorPosition,commandIsPending:qe.commandIsPending,autoCompletion:qe.commandMeta.autoCompletion??SR,infoMessage:qe.commandMeta.infoMessage,validationStatus:qe.commandMeta.validity,command:qe.commandMeta.command,inputString:qe.commandMeta.inputString,modifier:qe.commandMeta.modifier}),RR=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,oy=({width:e,mode:t})=>{let[n,r]=ey(ny());Zh(()=>{let w=()=>{let k=ny();r(D=>RR(D,k)?D:k)},M=Hd(w);return w(),()=>{M()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:c,command:m,modifier:p,validationStatus:f}=n,g=l&&f===Qt.Invalid,v=Jh({infoMessage:i,isPending:l}),[x,I]=ey(0);Zh(()=>{if(!l){I(0);return}let w=setInterval(()=>{I(M=>(M+1)%Qr.length)},Yh);return()=>{clearInterval(w)}},[l]);let R=Xh({isPalette:t===b.PALETTE,isPending:l,frame:x}),A=bR(()=>{let w=Math.max(0,Math.min(s,o.length)),M=ry({value:o,command:m}),k=CR({value:o,command:m,modifier:p}),D=m?_d(m):null,ve=ER({command:m,modifier:p}),Ve=(lt,ct)=>{let Ra=M&&ct>=M.start&&ct<M.end,Na=k&&ct>=k.start&&ct<k.end;return Ra&&D?D.fg(lt):Na&&ve?ve.bg(lt):lt},Nt=(lt,ct)=>{let Ra=M&&ct>=M.start&&ct<M.end,Na=k&&ct>=k.start&&ct<k.end;return Ra&&D?D.fgCursor(lt):Na&&ve?ve.bgCursor(lt):xR(lt)},dt=o.slice(0,w),ke=o[w]??" ",Sn=w<o.length?o.slice(w+1):"",qn=Array.from(dt).map((lt,ct)=>Ve(lt,ct)).join(""),vs=Nt(ke,w),ro=Array.from(Sn).map((lt,ct)=>Ve(lt,w+1+ct)).join("");if(c.hint){let lt=c.hint[c.overlap]??ke;vs=IR(lt),ro=ty(c.remainder.slice(1)+Sn)}return qn+vs+ro},[o,s,c,m,p]);return ls.createElement(fc,{flexDirection:"column",justifyContent:"flex-start"},ls.createElement(fc,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},ls.createElement(fc,null,ls.createElement(Qh,null,ty(R),A),v&&ls.createElement(Qh,{wrap:"truncate",color:g?y.red:y.secondary2},` ${v} `))))};import{Box as NR,Text as us}from"ink";import Zr from"react";var sy=" ",AR=({keys:e,label:t})=>e.length+1+t.length,TR=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?sy.length:0)+AR(o);if(r+i>t-4)break;n.push(o),r+=i}return n},iy=({width:e,availableHints:t})=>{let n=TR(t,e);return Zr.createElement(NR,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?Zr.createElement(us,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>Zr.createElement(us,{key:`${o}-${s}`},i>0?sy:"",Zr.createElement(us,{color:y.accent},o),Zr.createElement(us,{color:y.secondary2}," ",s)))):Zr.createElement(us,{color:y.secondary2},"\xA0"))};import{Box as wR,Text as la}from"ink";import ms,{useEffect as MR,useRef as eo,useState as PR}from"react";var LR=40,ca=.3,gc="\u2500",ay=1,dy=16,ly=({width:e})=>{let{replay:t}=Y(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*ay,[l,c]=PR(0),m=eo(r);m.current=r;let p=eo(0),f=eo(0),g=eo(0),v=eo(0),x=eo(0);if(MR(()=>{if(!n){p.current=0,g.current=0,v.current=0,x.current=0,c(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let M=setInterval(()=>{let k=Date.now(),D=m.current;if(D!==g.current){let ke=D-g.current,Sn=k-f.current;if(ke<0)v.current=0,x.current=0;else if(ke>0&&Sn>0){let qn=ke/Sn;v.current=v.current===0?qn:v.current*(1-ca)+qn*ca,x.current=x.current===0?ke:x.current*(1-ca)+ke*ca}p.current=D,f.current=k,g.current=D}let ve=k-f.current,Ve=Math.min(x.current,v.current*ve),Nt=Math.min(1,p.current+Ve),dt=Math.round(Nt*i);c(ke=>ke===dt?ke:dt)},LR);return()=>clearInterval(M)},[n,i]),!t)return null;let I=M=>{let k=s>1?M/(s-1):0,D=Math.round(k*(dy-1))/(dy-1);return mi(D)},R=Math.min(s,Math.floor(l/ay)),A=[];for(let M=0;M<R;M++){let k=I(M),D=A[A.length-1];D&&D.color===k?D.text+=gc:A.push({text:gc,color:k})}let w=gc.repeat(Math.max(0,s-R));return ms.createElement(wR,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},ms.createElement(la,{color:y.secondary2},"\u25B6"),ms.createElement(la,null,A.map((M,k)=>ms.createElement(la,{key:k,color:M.color},M.text)),ms.createElement(la,{color:y.secondary,dimColor:!0},w)))};var ps=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=Y(),o=t===b.COMMAND_LINE||t===b.PALETTE;return ua.createElement(kR,null,o?ua.createElement(oy,{width:e,mode:t}):r==="replay"?ua.createElement(ly,{width:e}):ua.createElement(iy,{width:e,mode:t,availableHints:n}))};import{Box as Gn,Text as to}from"ink";import nt,{useEffect as DR,useMemo as BR}from"react";import{ulid as cy}from"ulid";var pa=cy(),FR=()=>[...new Set([...h().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(hl).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),OR=e=>ge.text({id:pa,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),_R=(e,t,n)=>ge.text({id:cy(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),ma=[],uy=()=>{let e=ma.filter(n=>n.id!==pa).map(n=>n.id),t=ma.filter(n=>n.id===pa).map(n=>n.id);ma=[];for(let n of[...e,...t])C.deleteNode(n)},UR=e=>{uy();let t=C.createNode(OR(h().rootNodeId));if(d(t)||!Nn(t.value))return logger.error("Could not attach help nodes");ma=[t.value,...e.map((n,r)=>_R(n,r,pa)).map(C.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0})},my=({width:e,height:t})=>{let n=BR(()=>FR(),[]);DR(()=>(UR(n),()=>{uy()}),[n]);let r=h().selectedIndex;return nt.createElement(Gn,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},nt.createElement(Gn,{paddingX:1,justifyContent:"center"},nt.createElement(to,{color:y.accent},"Help"),nt.createElement(to,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),nt.createElement(Gn,{paddingX:1,marginTop:1},nt.createElement(Gn,{width:20,justifyContent:"flex-end"},nt.createElement(to,{color:y.secondary},"Key(s)")),nt.createElement(Gn,{flexGrow:1,width:40,paddingLeft:2},nt.createElement(to,{color:y.secondary},"Action"))),nt.createElement(xt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return nt.createElement(Gn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},nt.createElement(Gn,{width:20,justifyContent:"flex-end"},nt.createElement(to,{color:y.accent},o)),nt.createElement(Gn,{flexGrow:1,width:40,paddingLeft:2},nt.createElement(to,{color:l?y.primary:y.secondary2},s)))})))};import jR from"chalk";import{Box as br,Text as Ue}from"ink";import pe from"react";var $R=8,HR=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:e.value.slice(0,$R)},py=({width:e,height:t})=>{let n=HR();return pe.createElement(br,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(Ue,{color:y.accent,bold:!0},"Initialize project"),pe.createElement(Ue,null,`This folder is not an ${jR.hex(y.accent)("epiq")} project yet.`),pe.createElement(Ue,{color:y.primary},"To start tracking issues here, we need to initialize a new",pe.createElement(Ue,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),pe.createElement(br,{marginTop:1,flexDirection:"column"},pe.createElement(br,null,pe.createElement(Ue,{color:y.accent}," "),pe.createElement(Ue,{color:y.primary},"Type "),pe.createElement(Ue,{backgroundColor:y.secondary}," :init "))),pe.createElement(br,{marginTop:1},pe.createElement(Ue,{color:y.secondary2},"This will create, commit and push "),pe.createElement(Ue,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&pe.createElement(br,{marginTop:1,flexDirection:"column"},pe.createElement(Ue,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>pe.createElement(br,{key:r.projectId},pe.createElement(Ue,{color:y.accent},` ${o+1} `),pe.createElement(Ue,{color:y.primary},Lr(r.root)),pe.createElement(Ue,{color:y.secondary2},` ${r.root}`))),pe.createElement(br,{marginTop:1},pe.createElement(Ue,{color:y.accent}," "),pe.createElement(Ue,{color:y.primary},"Type "),pe.createElement(Ue,{backgroundColor:y.secondary}," :open 1 "),pe.createElement(Ue,{color:y.secondary2}," or "),pe.createElement(Ue,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as fa,Text as sn}from"ink";import Ge from"react";var WR=({isDone:e,command:t,value:n})=>Ge.createElement(fa,null,Ge.createElement(sn,{color:y.accent,dimColor:e},e?" \u2714 ":" "),Ge.createElement(sn,{dimColor:e},"Type "),Ge.createElement(sn,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&Ge.createElement(Ge.Fragment,null,Ge.createElement(sn,{dimColor:e}," "),Ge.createElement(sn,{color:y.secondary,dimColor:e},"<"+n+">"))),GR=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function hc({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l}=Ln(),c=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=c.findIndex(f=>!f.done),p=m===-1?void 0:c[m];return Ge.createElement(fa,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Ge.createElement(sn,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),Ge.createElement(sn,null,"Let's get you started - it's a breeze."),Ge.createElement(sn,{color:y.secondary2},"Remember - you can always search available commands by typing:",Ge.createElement(sn,{color:y.accent}," ? ")),p&&Ge.createElement(sn,{color:y.secondary2},p.message),Ge.createElement(fa,{flexDirection:"column"},c.map((f,g)=>m===-1||g<=m?Ge.createElement(fa,{key:f.key,marginBottom:1},Ge.createElement(WR,{isDone:f.done,command:f.command,value:f.done?GR(f.value):void 0})):null)))}import ba from"chalk";import{Box as gs,Text as no}from"ink";import Le from"react";import{Box as ga,Text as fy}from"ink";import Vn from"react";import VR from"chalk";var zR=e=>(C.getTag(e)?.name??"").length+3,KR=e=>{let t=C.getContributor(e);return(t?t.name:"").length+3},gy=({width:e})=>{let{viewMode:t}=ie(),n=Y(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],c=at(l?.id??o.id,"TICKET"),m=ce(c)?c.value:void 0,p=(m?.props.tags??[]).filter(D=>C.getTag(D)),f=m?.props.assignees??[],g=m?.parentNodeId?!Il(o.id,m.parentNodeId)&&t==="dense":!1,v=r.map((D,ve)=>{let Ve=ve===r.length-1,Nt=ae(D.id),dt=Ve?Nt?.[s]?.title:void 0;return`${ve?" / ":""}${D.title??""}${dt?` \u25B8 ${dt}`:""}`}).join(""),x=m?C.getCommentsByIssue(m.id):[],I=x.length?String(x.length).length+11:0,R=g?p.reduce((D,ve)=>D+zR(ve),0)+f.reduce((D,ve)=>D+KR(ve),0)+I:0,A=l?.id!=null&&!(t==="wide"&&P(l)),w=Math.max(0,e-R),M=v.substring(0,w)+(A?VR.hex(y.secondary2).dim(` ${_(l.id)}`):""),k=g?[...p.map(D=>Vn.createElement(ga,{key:`tag-${D}`,paddingLeft:1},Vn.createElement(_r,{id:D}))),...f.map(D=>Vn.createElement(ga,{key:`assignee-${D}`,paddingLeft:1},Vn.createElement(Bn,{id:D}))),x.length?Vn.createElement(ga,{key:"comments",paddingLeft:1},Vn.createElement(fy,{color:y.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Vn.createElement(ga,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Vn.createElement(fy,{color:y.secondary2},M),k)};import{Box as qR,Text as hy}from"ink";import ha from"react";var YR=({filters:e})=>ha.createElement(qR,{columnGap:1},ha.createElement(hy,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ha.createElement(hy,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),yy=ha.memo(YR);import{Box as XR,Text as ya}from"ink";import fs from"react";function vy(){let{eventLog:e,unappliedEvents:t}=Y(),n=e.at(-1)?.id,r=ks(n??""),o=ce(r)?Ci(r.value):"INVALID DATE";return fs.createElement(XR,{paddingLeft:1},fs.createElement(ya,{backgroundColor:y.accent,color:y.secondary}," Readonly "),fs.createElement(ya,{color:y.accent}," "+t.length+" edits ago at "+o+"."),fs.createElement(ya,{color:y.accent}," Resume with "),fs.createElement(ya,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as JR,Text as yc}from"ink";import va from"react";function by(){let{replay:e}=Y();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return va.createElement(JR,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},va.createElement(yc,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),va.createElement(yc,{color:y.secondary2},Ci(new Date(r))),va.createElement(yc,{color:y.accent},`${t}/${n} edits`))}import vc from"chalk";import{Box as QR,Text as xy}from"ink";import bc,{useEffect as ZR,useState as eN}from"react";var tN=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],nN=150,Iy=12,rN=.36,Sy=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},oN=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},sN=(e,t,n)=>{let r=Sy(e),o=Sy(t);return oN({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},iN=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return sN(s,i,o)};function Ey({syncStatus:e,autoSync:t}){let[n,r]=eN(0);ZR(()=>{if(e.status!=="syncing"){r(0);return}let l=0,c=setInterval(()=>{l+=1;let m=(Math.sin(l*rN)+1)/2,p=Math.round(m*(Iy-1));r(f=>f===p?f:p)},nN);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,offline:y.secondary2,pending:y.secondary2,syncing:iN(tN,n/(Iy-1))??""}[e.status];return bc.createElement(QR,null,bc.createElement(xy,null,vc.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),bc.createElement(xy,null,vc.hex(i)("\u25CF")+vc.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Ty from"chalk";import{Text as wy}from"ink";import My,{useEffect as cN,useState as uN}from"react";import xc from"chalk";var aN="https://registry.npmjs.org/epiq/latest",Ic=null,Cy=0,dN=1e3*60*60*24,Ry=e=>e.replace(/^v/,""),lN=(e,t)=>{let n=Ry(e).split(".").map(Number),r=Ry(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Ny=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Ic&&Date.now()-Cy<dN)return Ic;try{let t=await fetch(aN);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?lN(r,e)>0:!1};return Ic=o,Cy=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Ay=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?xc.hex(y.accent).dim(s):xc.hex(y.secondary).dim(s)).join(xc.hex(y.secondary2).dim("."))};function Py(){let[e,t]=uN({current:rn,latest:null,updateAvailable:!1});return cN(()=>{let n=!0;return Ny(rn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?My.createElement(wy,{dimColor:!0,color:y.secondary2},rn+" "):My.createElement(wy,null,Ty.hex(y.secondary2).dim(rn),Ty.hex(y.accent).dim(" \u2197 "),Ay(rn,e.latest))}function hs({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=Y(),{userName:i,preferredEditor:l,autoSync:c}=ie(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?fn(s.currentLabel,Math.max(0,p)):"";return Le.createElement(gs,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Le.createElement(gs,{paddingLeft:1},Le.createElement(no,{color:y.secondary2},g)):f?Le.createElement(no,null," "):o===b.PALETTE?Le.createElement(gs,null,Le.createElement(no,{color:y.accent},"Command Palette"),Le.createElement(no,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):Le.createElement(gs,{paddingLeft:1},e.length>0?Le.createElement(yy,{filters:e}):Le.createElement(gy,{width:p})),n==="live"?Le.createElement(gs,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Le.createElement(Ey,{autoSync:!!c,syncStatus:r}),Le.createElement(no,null,ba.hex(y.secondary2).dim("Mode: ")+ba.hex(y.secondary2).dim(o.padEnd(8," "))," "),Le.createElement(Ly,{icon:"@",value:i}),Le.createElement(Ly,{icon:"\u276F",value:l}),Le.createElement(Py,null)):"",n==="peek"?Le.createElement(vy,null):"",n==="replay"?Le.createElement(by,null):"")}function Ly({icon:e,value:t}){return Le.createElement(no,null,ba.dim(e)+ba.hex(y.accent)(` ${t??"-"} `))}import{Box as mN,Text as pN}from"ink";import ys from"react";import{Box as xa,Text as Sc}from"ink";import zn from"react";function Ec(){let e=Y(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?q(t?.id):[];return zn.createElement(xa,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},zn.createElement(xa,{padding:1,paddingTop:0,paddingBottom:0},zn.createElement(Sc,null,"Select a board:")),zn.createElement(xa,{padding:1,flexDirection:"column"},i.map((l,c)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===c,f=q(l.id).flatMap(({id:g})=>ae(g)).length;return zn.createElement(xa,{key:l.id??c},zn.createElement(Sc,{color:m?y.accent:y.secondary2},zn.createElement(Ye,{isSelected:m})),zn.createElement(Sc,{color:m?y.accent:y.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var fN=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=Y(),c=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return ys.createElement(mN,{flexDirection:"row"},e.context==="WORKSPACE"?ys.createElement(Ec,null):c?ys.createElement(Ai,{height:f,width:i,swimlanes:(l[c.id]??[]).filter(g=>g!==void 0&&Pt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):ys.createElement(pN,null))},ky=ys.memo(fN);import{useEffect as gN}from"react";var hN=e=>{gN(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=ie();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:c}=h();c==="default"&&!l&&oi(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Dy=({autoSync:e})=>(hN(e),null);function Cc({width:e,height:t}){let n=Y(),{autoSync:r,viewMode:o}=au(),s=n.filters;if(n.mode===b.HELP)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(my,{width:e,height:t}));if(n.mode===b.PALETTE)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{filters:s}),Ce.createElement(qh,{width:e,height:t-2}),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Ln(),l=!i,c=i&&!n.hasProjectDefinition;if(l)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{hideBreadCrumb:!0,filters:s}),Ce.createElement(hc,{height:t,width:e})),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:[]}));if(c)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{hideBreadCrumb:!0,filters:s}),Ce.createElement(py,{height:t,width:e})),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:[]}));let m=Qe(n.breadCrumb??[],"BOARD");if(ce(m)){let p=m.value.id,f=q(p).length,g=3,v=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,v)*Math.max(f,g)}return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(Dy,{autoSync:r}),Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{filters:s}),Ce.createElement(ky,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:n.availableHints}))}import yN from"readline";var Ia,Sa,an,vN=new Set([S.MoveCursorLeft,S.EraseInputWord,S.MoveCursorLeftOfWord,S.MoveCursorRight,S.MoveCursorRightOfWord,S.NavToPreviousContainer,S.NavToNextContainer,S.NavPreviousItem,S.NavNextItem,S.SetViewDense,S.SetViewWide,S.Confirm,S.Exit,S.Yank,S.InitCommandLine,S.InitCommandPalette,S.ExitCommandLine,S.CaptureInput,S.EraseInput,S.EraseInputWord,S.HideHelp,S.ViewHelp,S.SetViewDense,S.SetViewWide,S.GetLastCommandFromHistory,S.GetNextCommandFromHistory,S.AutoCompleteCommand]),bN=new Set([S.NavPreviousItem,S.NavNextItem,S.NavToPreviousContainer,S.NavToNextContainer,S.Confirm,S.Exit,S.InitCommandPalette,S.InitMove,S.MoveNextItem,S.MovePreviousItem,S.MoveToNextContainer,S.MoveToPreviousContainer,S.Delete,S.AddItem,S.EditTitle,S.EditDescription,S.ConfirmMove,S.Edit,S.ViewHelp,S.Yank]),By=async e=>{if(e.ctrl&&e.name==="c")return O.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=h(),s=Mp(e,n);if(!s||r&&!vN.has(s)||o==="replay"&&n===b.DEFAULT&&bN.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},xN=()=>async function(t,n){n.name!=="escape"&&(an&&(clearTimeout(an),an=void 0),await By(n))},IN=()=>async function(t){if(t.length===1&&t[0]===27){an&&clearTimeout(an),an=setTimeout(()=>{By({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),an=void 0},25);return}an&&(clearTimeout(an),an=void 0)};function Fy(){Ia&&process.stdin.removeListener("keypress",Ia),Sa&&process.stdin.removeListener("data",Sa),Ia=xN(),Sa=IN(),yN.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Sa),process.stdin.on("keypress",Ia)}async function Oy(){try{let e=Ir({});if(d(e))return Bt(0,e.message);let t=ht();ce(t)&&ze(t.value);let n=xe(process.cwd()),r=ce(n)?await ki(n.value):Of();if(d(r))return r;let o=Rc();return d(o)?Bt(6,o.message):(Fy(),ce(n)&&Di(n.value),u("Booted Epiq",void 0))}catch(e){return Bt(0,Tr(e))}}yf();var RN=`${jt.bold("Epiq CLI")}
|
|
81
|
+
${d}
|
|
82
|
+
`,vd.writeFileSync(t,n,"utf8"),z.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var YS=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return a(t)?t:u("Checked git diff",t.value.stdout.split(`
|
|
83
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},Y=(e,t)=>l(`[${e}] ${t}`),jf=async({cwd:e,user:t})=>{let n=Ps(),r=await kt(e);if(a(r))return Y(1,r.message);let o=r.value,s=await Ds(o);if(a(s))return Y(2,s.message);if(s.value)return Y(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await YS(o);if(a(i))return Y(2.5,i.message);if(i.value.length>0)return Y(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(No(o))return Y(4,"Epiq project already initialized");let{userId:d,userName:c}=t;if(!d||!c)return Y(5,"Missing Epiq user id");let m=await Um(o);if(a(m))return Y(6,m.message);let p=n.stateBranch,f=await Bs({repoRoot:o,branch:p});if(a(f))return Y(6,f.message);if(f.value)return Y(6,`State branch already exists: ${p}`);let g=await XS({repoRoot:o,stateBranch:p});if(a(g))return Y(6,g.message);if(g.value)return JS({repoRoot:o,stateBranch:p});let v=await wl({repoRoot:o,stateBranchName:p});if(a(v))return Y(6,v.message);let I=Eo();if(a(I))return Y(7,I.message);let x=bd.join(sr(),n.projectId),C=await On({repoRoot:o,stateBranchRoot:x,stateBranchName:p});if(a(C))return Y(8,C.message);let A=bd.join(x,".epiq");qS.mkdirSync(A,{recursive:!0});let M=Tm({userId:d,userName:c});if(a(M))return Y(9,M.message);for(let nt of M.value){let Mr=ei({event:nt,rootDir:x});if(a(Mr))return Y(9,Mr.message)}let w=lr({userId:d,userName:c}),L=qs(x,w);if(a(L))return Y(9,L.message);let k=Tl(x,n);if(a(k))return Y(9,k.message);let Ie=await ai({stateBranchRoot:x,eventFileName:w});if(a(Ie))return Y(10,Ie.message);let Ke=await pe.stage({cwd:x,pathspec:[Xe]});if(a(Ke))return Y(10,Ke.message);let Mt=await Br({cwd:x,message:"[epiq:init]"});if(a(Mt))return Y(10,Mt.message);let mt=await Uf(o);if(a(mt))return Y(11,mt.message);let $e=Oa({repoRoot:o,fileContents:n});if(a($e))return Y(12,$e.message);let An=await pe.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(a(An))return Y(13,An.message);let rr=await pe.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(rr))return Y(13,rr.message);let wr=[],ho=await U({cwd:o,args:["push","-u","origin","HEAD"]});a(ho)&&wr.push(`[init:14] ${ho.message}`);let qe=await jo({repoRoot:o,stateBranchRoot:x});return a(qe)&&wr.push(`[init:15] ${qe.message}`),u("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:p,stateBranchRoot:x,defaultEvents:M.value,warnings:wr})},XS=async({repoRoot:e,stateBranch:t})=>{let n=await fn({repoRoot:e});if(a(n))return l(n.message);if(!n.value)return u("No remote",!1);let r=await bo({repoRoot:e,branch:t});return a(r)?l(`Could not ask origin whether ${t} exists: ${r.message}`):r},JS=async({repoRoot:e,stateBranch:t})=>{let n=await U({cwd:e,args:["fetch","origin",t]});if(a(n))return Y(6,n.message);let r=await U({cwd:e,args:["show",`origin/${t}:${Xe}`]});if(a(r))return Y(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${Xe} from a checkout that has it, for example:`,"",` git show origin/main:${Xe} > ${Xe}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
84
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(I){return Y(6,`The identity on origin/${t} is not readable: ${I instanceof Error?I.message:String(I)}`)}let s=Oa({repoRoot:e,fileContents:o});if(a(s))return Y(12,s.message);let i=await pe.stage({cwd:e,pathspec:[Xe]});if(a(i))return Y(13,i.message);let d=await pe.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[Xe]});if(a(d))return Y(13,d.message);let c=Eo();if(a(c))return Y(7,c.message);let m=bd.join(sr(),o.projectId),p=await Uo({repoRoot:e,stateBranchName:t});if(a(p))return Y(8,p.message);let f=await On({repoRoot:e,stateBranchRoot:m,stateBranchName:t});if(a(f))return Y(8,f.message);let g=[],v=await U({cwd:e,args:["push","-u","origin","HEAD"]});return a(v)&&g.push(`[init:14] ${v.message}`),u("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:m,defaultEvents:[],warnings:g})};var ts=(e,t)=>l(`[${e}] ${t}`),$f=async()=>{te("");let e=_n();if(!e.isSetupDone||!e.userName)return ts(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=le(),n=t.userName,r=t.userId;if(!r||!n)return ts(5,"Missing Epiq user id");let o=await jf({cwd:process.cwd(),user:{userId:r,userName:n}});if(a(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let d=Bt(o.value.defaultEvents).filter(a);if(d.length>0)return ts(16,d.map(g=>g.message).join(`
|
|
85
|
+
`));let c=it();if(a(c))return ts(16,c.message);let{rootNodeId:m,nodes:p}=c.value,f=p[m];return f?(_.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),u(s,null)):ts(16,"Unable to resolve initialized root node")};import{ulid as ZS}from"ulid";import{ulid as QS}from"ulid";var Hf=null,zn=()=>structuredClone(Hf),ns=e=>{Hf=e},Wf=()=>{let{contextNode:e,selectedIndex:t}=h(),r=de(e.id)[t];return r?u("Resolved selected child",r):l("Target node not found")},xd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=de(t).filter(o=>o.id!==e);return ti(r,n)},Gf=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ne();if(a(r))return l("Unable to resolve user ID");let o=xd({parentId:t,id:e,position:n});return a(o)?o:u("Created pending move state",{id:QS(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Vf=e=>{ns(e);let t=kn(e,!0);return a(t)?t:u("Node moved successfully",t.value)};function Id(e){let t=Wf();if(a(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return l("Missing parent node id");let o=r[n.parentNodeId];if(!o)return l("Missing parent node");let s=de(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return l("Current node not found among siblings");let d=s[i+e];if(!d)return l("Missing sibling node");let c=Gf({id:t.value.id,parentId:d.id,position:{at:"end"}});return a(c)?c:Vf(c.value)}function Sd(e){let t=Wf();if(a(t))return t;let{contextNode:n,selectedIndex:r}=h(),s=de(n.id)[r+e];if(!s)return l("Missing sibling node");let i=Gf({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(i)?i:Vf(i.value)}var zf=()=>{let e=zn();if(!e)return l("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return l("Move parent not found");let o=de(n).findIndex(s=>s.id===t);return o===-1?l("Moved node not found among rendered children"):(_.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},_i=(e,t="Moved preview")=>{if(a(e))return e;let n=zf();return a(n)?n:(N({mode:b.MOVE}),u(t,null))},Kf=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t}=re().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=de(n.id)[r];if(!o)return N({mode:b.DEFAULT}),l("No move target");if(t==="start"){if(o.readonly)return l("Target node is read-only");if(r===-1)return l("No item selected");if(!o.parentNodeId)return l("Target has no parent");let s=de(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return l("Target not found among siblings");let d=s[i-1],c=s[i+1],m=c!=null?{at:"before",sibling:c.id}:d!=null?{at:"after",sibling:d.id}:{at:"start"},p=xd({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(ns({id:ZS(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),u("Move initialized",null))}if(t==="next")return _i(Sd(1));if(t==="previous")return _i(Sd(-1));if(t==="to-next")return _i(Id(1));if(t==="to-previous")return _i(Id(-1));if(t==="confirm"){let s=zn();if(!s)return l("No pending move to confirm");let i=await zt();if(a(i))return i;let d=D([s],i.value);if(a(d))return d;let c=zf();return a(c)?c:(ns(null),N({mode:b.DEFAULT}),u("Moved item",null))}return t==="cancel"?(ns(null),N({mode:b.DEFAULT}),u("Cancelling move",null)):l("Invalid move modifier")};import{ulid as ji}from"ulid";import{monotonicFactory as eE,ulid as tE}from"ulid";var nE=eE(),Ui=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=nE();return u("Created issue events",[{id:tE(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var qf=async(e,t)=>{let n=ne();if(a(n))return l("Unable to resolve user ID");let r=await zt();if(a(r))return r;let o=r.value;if(!t.inputString)return l(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:d}=h(),c=m=>{let p=D([m],o);if(a(p))return p;let f=R.getNode(p.value[0].result.id);if(!f)return l("Created node not found");if(!f.parentNodeId)return p;let g=R.getNode(f.parentNodeId);return g?(_.navigate({contextNode:g,selectedIndex:R.getSiblings(f.parentNodeId).findIndex(({id:v})=>v===f.id)}),p):l("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=R.getNode(m);if(!p)return l("Workspace not found");let f=In(p.id,n.value,o);return a(f)?f:c({id:ji(),action:"add.board",payload:{id:ji(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=ot(s,"BOARD");if(a(m))return l("Unable to add swimlane in this context");let p=In(m.value.id,n.value,o);return a(p)?p:c({id:ji(),action:"add.swimlane",payload:{id:ji(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=X(i.id)[d],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let M=ot(s,"SWIMLANE");return a(M)?null:M.value})();if(!p)return l("Unable to add issue in this context");let f=In(p.id,n.value,o);if(a(f))return f;let g=Ui({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(g))return g;let v=g.value,I=D([...v],o);if(a(I))return I;if(!I.value[0])return l("Issue creation failed");let A=v.find(M=>M.action==="add.issue")?.payload.id;return A?(_.navigate({contextNode:p,selectedIndex:R.getSiblings(p.id).findIndex(({id:M})=>M===A)}),u("Issue created",null)):l("Unable to determine ticket id")}return u("Success",null)};import iE from"node:os";import Jf from"node:path";var rE=e=>e.some(t=>t.action==="init.workspace"),Yf=async(e,t)=>{let n=Gt(e);return a(n)?l(n.message):Io({cwd:t,branch:n.value})},oE=e=>{let t=Se(process.cwd());if(a(t))return!1;let n=fe({repoRoot:t.value});return!a(n)&&n.value===e},$i=async e=>{let t=fe({repoRoot:e});if(a(t))return _t(3,t.message);let n=t.value,r=await On({repoRoot:e,stateBranchRoot:n,stateBranchName:Ps().stateBranch});if(a(r))return _t(3,r.message);let o=St(n);if(a(o))return _t(3,o.message);if(!rE(o.value.events)){let m=await Yf(e,n);if(a(m)&&logger.info(3,m.message),o=St(n),a(o))return _t(3,o.message)}let{events:s,unreadable:i}=o.value,d=Ot(s,i);if(a(d))return _t(4,d.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let c=fi({root:e});return a(c)&&logger.info(c.message),u("Loaded project",void 0)},sE=async e=>{let t=fe({repoRoot:e});if(a(t))return l(t.message);let n=t.value,r=await fn({repoRoot:n});if(a(r))return l(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await di({worktreeRoot:n,operation:"boot pull",fn:()=>kl(n,()=>(Ur("Pulling"),Yf(e,n)))});if(a(o))return Te(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return xo(s.message)?(si("Offline"),u("Offline",void 0)):Te(s.message);if(!s.value)return ur("Already synced"),u("Already synced",void 0);if(!oE(n))return u("Project changed during the pull",void 0);let i=Dl(n);return a(i)?i:(ur("Pulled"),u("Pulled and reloaded",void 0))},Hi=e=>{sE(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${jr(t)}`)})},Xf=()=>{let e=Ot([]);return a(e)?_t(4,e.message):(N({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var aE=e=>e==="~"||e.startsWith("~/")?Jf.join(iE.homedir(),e.slice(1)):e,lE=(e,t)=>{let n=e.trim();if(!n)return l("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):l(`No recent project #${n}`)}let r=Se(Jf.resolve(aE(n)));return a(r)?l(`No epiq project at ${n}`):u("Resolved project path",r.value)},Qf=async()=>{let e=Ni();if(te(""),h().hasProjectDefinition)return l("Already in a project; run epiq from another directory");let t=Rn({exclude:process.cwd()}),n=a(t)?[]:t.value,r=lE(e,n);if(a(r))return l(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(d){return l(`Unable to enter ${o}: ${d instanceof Error?d.message:String(d)}`)}let i=await $i(o);return a(i)?(process.chdir(s),l(i.message)):(Hi(o),u(`Opened ${Gr(o)}`,null))};var Wi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=Qs(n,t);if(a(s))return l(s.message);let{appliedEvents:i,unappliedEvents:d}=s.value,c=jt();if(a(c))return c;let m=Bt(i),{fatal:p,skipped:f}=vn(m);if(p.length>0)return jt(),N(o),l(p.map(v=>v.message).join(", "));bn(f);let g=h().nodes[e];return g?(_.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:d})):(jt(),N(o),l("Board did not exist at that date"))};var Zf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)};var dE=20,cE=16,uE=150,Gi=null,Vi=null;var vr=()=>{Gi!==null&&(clearInterval(Gi),Gi=null),Vi!==null&&(clearTimeout(Vi),Vi=null)},eg=()=>{vr(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},tg=({events:e,startTime:t,durationMs:n})=>{vr();let r=e.length,o=_r(e.map(f=>Mn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Zf(o),d=Math.max(1,Math.round(n*dE/1e3)),c=Math.max(Math.round(n/d),cE),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Gi=setInterval(()=>{m++;let f=m/d,g=[],v,I;for(;p<r&&i[p]<=f;){let C=e[p],A=kn(C);if(a(A)){if(ko(A)){p++;continue}eg();return}g.push(...dl(C)),v=C,I=o[p],p++}if(p>=r||m>=d){for(;p<r;p++){let A=kn(e[p]);if(a(A)&&!ko(A))break}let C=h().replay;N({unappliedEvents:[],replay:C&&{...C,progress:1,appliedCount:r}}),vr(),Vi=setTimeout(eg,uE);return}let x=h().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:v?I??x?.currentTime??t:x?.currentTime??t,currentLabel:v?zi(v):x?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:x?.flashNodeIds??[]}})},c)};var ng=async()=>{let e=ot(h().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=fe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=re().commandMeta;if(vr(),r==="now"){let d=Fn(n.value);if(a(d))return l(d.message);let c=jt();if(a(c))return c;let m=Bt(d.value),{fatal:p,skipped:f}=vn(m);return p.length>0?l(p.map(g=>g.message).join(", ")):(bn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let d=Zs(n.value);if(a(d))return d;let c=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),m=c===void 0?null:Mn(c),p=(c===void 0?null:d.value.get(c.id)??null)??(m===null?null:To(m));if(p===null)return l(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let d=mr(r||o.trim());if(!d)return l("Invalid peek date");s=d.getTime()}let i=Wi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var rg=async()=>{let e=ot(h().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=fe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=re().commandMeta,{dateInput:s,durationInput:i}=vi(r,o);if(vr(),h().syncStatus.status==="syncing")return l("Cannot replay while syncing, try again in a moment");let d=mr(s);if(!d)return l("Invalid replay date");let c=i?yi(i):15e3;if(c===null)return l("Invalid replay duration (try e.g. 30s or 2m)");let m=d.getTime(),p=h(),f=Wi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(jt(),N(p),u("Nothing to replay from that point",!0)):(tg({events:g,startTime:m,durationMs:c}),u("Replaying board history",!0))};import{spawn as pE}from"node:child_process";var fE=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},og=async e=>new Promise(t=>{let{command:n,args:r}=fE();try{let o=pE(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(l(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):l(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(l(`Clipboard tool not available (${n})`))}});var rs=async(e,t)=>{if(!e.trim())return l(`Nothing to copy: ${t} is empty`);let n=await og(e);return a(n)?n:u(`Copied ${t} to clipboard`,null)},sg=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=Go({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return l("Nothing selected to copy from");switch(e.modifier){case Me.REF:return rs(O(o.id),"ref");case Me.TITLE:return rs(o.title,"title");case Me.DESCRIPTION:return r?rs(r.props?.description??"","description"):l("No issue in scope");case Me.TAGS:{if(!r)return l("No issue in scope");let s=Un(r).map(({name:i})=>i);return rs(s.join(", "),"tags")}case Me.ASSIGNEES:{if(!r)return l("No issue in scope");let s=jn(r).map(({name:i})=>i);return rs(s.join(", "),"assignees")}default:return l("Yank one of: ref, title, description, tags, assignees")}};var ig=async()=>{te(""),N({mode:b.DEFAULT});let e=it();if(a(e))return l(e.message);if(e.value.syncStatus.status==="syncing")return l("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ui();return a(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as ag}from"ulid";var Oe=async()=>{let e=await zt();return a(e)?e:u("Resolved persist root",e.value)};var gE=e=>e.action==="add.issue.comment",lg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Unable to resolve child to delete");let o=await Oe();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=B(t)?t.id:t.parentNodeId;if(!i)return l("Unable to resolve comment issue");let d=h().nodes[i];if(!d||!B(d))return l("Unable to resolve comment issue");let c=d.log?.filter(gE).find(m=>m.payload.id===s);return c?c.payload.author!==e.value.userId?l("You can only delete your own comments"):D([{id:ag(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):l("Unable to resolve comment")}return D([{id:ag(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)};import{ulid as hE}from"ulid";var dg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Unable to close issue, no target found");if(!B(r))return l("Cannot close in this context");let o=h().nodes[ie];if(!o)return l("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return l("Issue is already closed");let s=await Oe();if(a(s))return s;let i=s.value,d=Xt(o.id,r.id,{at:"end"},e.value,i);if(a(d))return d;let c=D([{id:hE(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:d.value},...e.value}],i);return a(c)?c:u("Issue closed",null)};import{ulid as yE}from"ulid";var Ki=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};var cg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):ut(r.id,"TICKET");if(a(o))return l("Cannot reopen in this context");let s=o.value,i=h().nodes[ie];if(!i)return l("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return l("Issue is not closed");if(!B(s))return l("Target node is not issue");let d=Ki(s);if(!d)return l("Unable to resolve previous parent from issue history");if(d===i.id)return l("Previous parent resolves to closed swimlane");let c=h().nodes[d];if(!c)return l("Previous parent no longer exists");let m=await Oe();if(a(m))return m;let p=m.value,f=Xt(c.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let g=D([{id:yE(),action:"reopen.issue",payload:{id:s.id,parent:c.id,rank:f.value},...e.value}],p);return a(g)?g:u("Issue reopened",null)};import{ulid as vE}from"ulid";var ug=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Missing node");if(r.readonly)return l("Cannot rename readonly node");let o=Ni();if(!o)return l("Provide a title");let s=await Oe();return a(s)?s:D([{id:vE(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)};import{ulid as bE}from"ulid";var mg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let o=R.findTagByName(r);if(!o)return l(`Tag "${r}" does not exist`);let{selectedNode:s}=h();if(!s)return l("Invalid untag target");let i=ut(s.id,"TICKET");if(a(i))return l("Unable to untag issue in this context");let d=i.value;if(!B(d))return l("Target node is not issue");if(!(d.props.tags??[]).includes(o.id))return l("Issue is not tagged with that tag");let m=await Oe();return a(m)?m:D([{id:bE(),action:"remove.issue.tag",payload:{id:d.id,tag:o.id},...e.value}],m.value)};import{ulid as Ed}from"ulid";var pg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let{selectedNode:o}=h();if(!o)return l("Invalid tag target");let s=ut(o.id,"TICKET");if(a(s))return l("Unable to tag issue in this context");let i=s.value;if(!B(i))return l("Target node is not issue");let d=await Oe();if(a(d))return d;let c=R.findTagByName(r),m=c?.id??Ed();return(i.props.tags??[]).includes(m)?l("Already tagged with that tag"):D([...c?[]:[{id:Ed(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Ed(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],d.value)};import{ulid as Rd}from"ulid";var qi=()=>{let{eventLog:e=[],contributors:t}=h(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))};var fg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return l("Provide an assignee");let{selectedIndex:i,contextNode:d}=h(),c=X(d.id)[i];if(!c)return l("Invalid assign target");let m=ut(c.id,"TICKET");if(a(m))return l("Unable to assign issue in this context");let p=m.value;if(!B(p))return l("Target node is not issue");let f=await Oe();if(a(f))return f;let g=qi(),v=!o&&s.toLowerCase()==="me",I,x;if(v)I=e.value.userId,x=g.find(M=>M.id===I)?.name??e.value.userName;else{let M=g.filter(L=>L.name===s);if(M.length>1)return l(`"${s}" matches ${M.length} contributors (${M.map(L=>L.id).join(", ")}). Assign from the GUI to choose by id.`);let w=M[0];if(!w&&!o)return l(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);I=w?.id??Rd(),x=w?.name??s}if((p.props.assignees??[]).includes(I))return l("Assignee already assigned");let A=!!h().contributors[I];return D([...A?[]:[{id:Rd(),action:"create.contributor",payload:{id:I,name:x},...e.value}],{id:Rd(),action:"add.issue.assignee",payload:{id:p.id,assignee:I},...e.value}],f.value)};import{ulid as xE}from"ulid";var gg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee to remove");let{selectedNode:o}=h();if(!o)return l("Invalid unassign target");let s=ut(o.id,"TICKET");if(a(s))return l("Unable to unassign in this context");let i=s.value;if(!B(i))return l("Target node is not issue");let d=i.props.assignees??[],c=r.toLowerCase()==="me",m=c?d.filter(g=>g===e.value.userId):qi().filter(g=>g.name===r&&d.includes(g.id)).map(g=>g.id);if(m.length>1)return l(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return l(c?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Oe();return a(f)?f:D([{id:xE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)};import{ulid as hg}from"ulid";var yg=async e=>{let t=e.inputString.trim();if(!t)return l("Provide a comment");if(t.length>4e3)return l(`Cannot exceed ${4e3} characters`);let n=ne();if(a(n))return l("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=h(),s=ot([...r,o],"TICKET");if(a(s))return l("Edit target must be an issue");let i=s.value;if(!i)return l("Invalid comment target");let d=i.context==="TICKET"?u("Resolved ticket",i):ut(i.id,"TICKET");if(a(d))return l("Unable to comment on issue in this context");let c=d.value;if(!B(c))return l("Target node is not issue");let m=await Oe();return a(m)?m:D([{id:hg(),action:"add.issue.comment",payload:{id:hg(),issue:c.id,author:n.value.userId,md:t},...n.value}],m.value)};import{ulid as SE}from"ulid";import IE from"zod";var vg=()=>{let e=re().commandMeta.inputString,t=IE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return l("Auto sync duration must be a number of at least 3000 ms");let n=vt({autoSyncDebounceMs:t.data});return a(n)?n:(Ye({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var bg=()=>{let e=re().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return l("Invalid response");let t=sp(e),n=vt({autoSync:t});return a(n)?n:(Ye({autoSync:t}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var xg=()=>{let e=re().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return l("Invalid response");let n=vt({logLevel:e});return a(n)?n:(Ye({logLevel:e}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var Ig=e=>{let t=e.inputString.trim();switch(e.modifier){case xe.USERNAME:{if(process.env[cn])return l(`Cannot change the configured user while ${cn} names this process`);let n=Or();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,d=r||SE();if(!i||!d)return l("Unable to resolve user name or id");let c=vt({userName:i,userId:d,preferredEditor:o??""});return a(c)?c:(Ye({userName:i,userId:d}),N({mode:b.DEFAULT}),u(`Username set to "${i}"`,null))}case xe.EDITOR:{if(!t)return l("No editor provided");let n=vt({preferredEditor:t});return a(n)?n:(Ye({preferredEditor:t}),N({mode:b.DEFAULT}),u(`Editor configuration set to "${t}"`,null))}case xe.VIEW:{if(t!=="wide"&&t!=="dense")return l("Invalid view mode");let n=vt({viewMode:t});return a(n)?n:(Ye({viewMode:t}),N({mode:b.DEFAULT}),u(`View set to "${t}"`,null))}case xe.AUTOSYNC:return bg();case xe.LOG_LEVEL:return xg();case xe.SYNC_DEBOUNCE_MS:return vg();case xe.ATTACHMENT_MAX_KB:return bp();default:return l("Unknown config command")}};var Yi=[{systemOnly:!0,intent:j.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Kf},{intent:j.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:lg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=re().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ne(E.FILTER).map(d=>d.split(n)[0]).includes(i))(r))return l("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return we(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),u("Filter updated",null)}},{intent:j.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Vn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),u("Viewing help",null)}},{intent:j.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:dg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:cg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:$f},{intent:j.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:ug,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:mg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:pg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:fg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:gg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>yg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:ig},{intent:j.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:ng},{intent:j.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:rg},{intent:j.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await wf();return a(e)?e:(N({mode:b.DEFAULT}),u("Export successful",!0))}},{intent:j.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(_.exit(),u("Exit successful",!0))},{intent:j.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>_f(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>sg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>Ig(t)}];var EE=new Set(["peek","replay","filter","view-help","yank"]),on=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=re();if(!t)return l("No command to confirm");if(!e&&n===tn.Invalid)return l("Invalid command");let s=Ai(t);Up();let{readOnly:i}=h();if(i&&!EE.has(s))return Yo({status:Tn.Fail,message:"Command not available in readonly state",value:null});let d=Yi.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!d)return Yo({status:Tn.Fail,message:"Command not found",value:null});let c;try{c=await d.action(d,{command:t,inputString:o,modifier:r})}catch(m){return Yo({status:Tn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(c)?Yo(c):(jp({addToHistory:!e}),d.onSuccess?.(),le().autoSync&&mi(),c)};var Xi=[{intent:S.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),te("move cancel"),on({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),te("move start"),on({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),te("move confirm"),on({isForceExecutedBySystem:!0}))}],Ji=[{intent:S.MovePreviousItem,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move previous"),on({isForceExecutedBySystem:!0})):l("No pending move")},{intent:S.MoveNextItem,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move next"),on({isForceExecutedBySystem:!0})):l("No pending move")}],Sg=[{intent:S.MoveToNextContainer,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move to-next"),on({isForceExecutedBySystem:!0})):l("No pending move")},{intent:S.MoveToPreviousContainer,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move to-previous"),on({isForceExecutedBySystem:!0})):l("No pending move")}];var Eg={[K.WORKSPACE]:[...Xi,...Ji],[K.BOARD]:[...Xi,...Ji],[K.SWIMLANE]:[...Xi,...Ji,...Sg],[K.TICKET]:[],[K.FIELD]:[],[K.FIELD_LIST]:[],[K.TEXT]:[],[K.COMMENT]:[]};import CE from"node:fs";import NE from"node:path";import{spawn as RE}from"node:child_process";function Rg(e){let t=process.platform,o=RE(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var Cg=e=>{let t=Se(process.cwd());if(a(t))return l("Unable to resolve project root");let n=fe({repoRoot:t.value});if(a(n))return l(n.message);let r=fr(e.hash,e.ext),o=NE.join(Co(n.value),r);return CE.existsSync(o)?(Rg(o),u(`Opened ${e.name}`,null)):l("Attachment file not found \u2014 run :sync to fetch it")};var Ng=()=>{te("");let{pendingNavTarget:e}=Gn();N({mode:b.DEFAULT}),e&&_.navigate(e),Vn({pendingNavTarget:void 0})},Ag=[{intent:S.ExitCommandLine,mode:b.HELP,action:()=>(Ng(),u("Exiting help",null))},{intent:S.Exit,mode:b.HELP,action:()=>(Ng(),u("Closed help",null))},{intent:S.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:b.HELP,action:()=>(_.navigateToNextItem(),u("Navigating to next help item",null))},{intent:S.NavToPreviousContainer,mode:b.HELP,action:()=>(_.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:b.HELP,action:()=>(_.navigateToNextContainer(),u("Navigating to next help container",null))}];var AE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=Gn();t&&_.navigate(t),Vn({pendingNavTarget:void 0}),te(`${e} `)},Tg=()=>{te("");let{pendingNavTarget:e}=Gn();e&&_.navigate(e),Vn({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},wg=[{intent:S.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{te("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Vn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),u("Opening command palette",null)}},{intent:S.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!Pn(e))return l("Command only applicable on text nodes");if(e.props.disabled)return l("Command is not available in this context");let t=e.title;return t?(AE(t),u("Selected command",t)):u("No command selected",null)}},{intent:S.ExitCommandLine,mode:b.PALETTE,action:()=>(Tg(),u("Exiting palette",null))},{intent:S.Exit,mode:b.PALETTE,action:()=>(Tg(),u("Closed command palette",null))},{intent:S.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.PALETTE,action:()=>(_.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.PALETTE,action:()=>(_.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.PALETTE,action:()=>(_.navigateToNextContainer(),u("Navigating to next container",null))}];var Mg=[{intent:S.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),te(""),u("Entering command line mode",null))},...Ag,...wg,{intent:S.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.NEW} `),u("Adding new item",null))},{intent:S.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.DELETE} `),u("Deleting item",null))},{intent:S.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!de(e?.id??"")?.length){let r=e?R.getAttachment(e.id):void 0;if(r)return Cg(r);if(e?.title===ve.DESCRIPTION)return N({mode:b.COMMAND_LINE}),te(`${E.EDIT} description `),u("Propose command",!0);if(e?.title===ve.ASSIGNEES)return N({mode:b.COMMAND_LINE}),te(`${E.ASSIGN} `),u("Propose command",!0);if(e?.title===ve.TAGS)return N({mode:b.COMMAND_LINE}),te(`${E.TAG} `),u("Propose command",!0);if(t.title===ve.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),te(`${E.EDIT} description `),u("Propose command",!0)}return _.enterChildNode(),u("Entering context",null)}},{intent:S.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===ve.DESCRIPTION?Me.DESCRIPTION:e?.title===ve.TAGS?Me.TAGS:e?.title===ve.ASSIGNEES?Me.ASSIGNEES:Me.REF,r=Ne(E.YANK).includes(t)?t:Me.REF;return N({mode:b.COMMAND_LINE}),te(`${E.YANK} ${r}`),u("Propose command",!0)}},{intent:S.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.EDIT} title ${h().selectedNode?.title}`),u("Exiting context",null))},{intent:S.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.EDIT} description `),u("Exiting context",null))},{intent:S.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(_.enterParentNode(),u("Exiting context",null))},{intent:S.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.DEFAULT,action:()=>(_.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(_.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.DEFAULT,action:()=>(_.navigateToNextContainer(),u("Navigating to next container",null))}];var TE=500,wE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Pg=e=>{let t=wE(e);t&&Ci(n=>(n+t).slice(0,TE))};var ME=[b.COMMAND_LINE,b.PALETTE],PE=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(Jl(-1),u("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(Jl(1),u("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Ql("left"),u("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Ql("right"),u("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(Ci((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=h().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(Pg(n??""),u("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Op(),u("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(_p(),u("Erasing input word",null))}],Lg=[{intent:S.Confirm,mode:b.COMMAND_LINE,action:()=>(on(),u("Executing command",null))},{intent:S.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),u("Viewing help",null))},...ME.flatMap(PE),{intent:S.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),u("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>($p(),u("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Hp(),u("Getting next command from history",null))}];var Cd=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},kg=({keys:e})=>e.length===1?0:1,Dg=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(Cd).filter(r=>r!==null).sort((r,o)=>kg(r)-kg(o))};function Bg(e,t,n){let r=t[e];if(!r)return l("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?l("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Fg=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Nt,Nd,Ad=new Set,Td=()=>{for(let e of Ad)e()},kE=e=>(Ad.add(e),()=>Ad.delete(e));function wd(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return l("derive(): contextNodeId is missing");if(!r)return l("derive(): rootNode is missing");if(!o[r])return l("derive(): unable to find root node");let d=o[t];if(!d)return l("Unable to derive state, contextNode not found");let c=Bg(t,o,r);if(a(c))return logger.error(c.message),c;let m=c.value,{context:p}=d,f=[...Mg,...Eg[p]??[],...Lg],g=Dg(f,n),v=Fg(f),I=DE(o,s),x=I[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:d,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:v,selectedNode:x,renderedChildrenIndex:I})}var h=()=>{if(!Nt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Nt},it=()=>Nt?u("Retrieved state",Nt):l("State not initialized. Call initWorkspaceState() first.");function Do(e){Nd=e;let t=Se(process.cwd()),n=!1;if(!a(t)){let s=pt(t.value);if(a(s))return l(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=wd(r);return a(o)?o:(Nt=o.value,Td(),u("State initialized",null))}var br=!1,os=null;function we(e){let t=h(),n=e(t);if(br)return n.nodes!==t.nodes&&(Kn=null),os=n,Nt={...t,...n},u("State updated",null);let r=wd(n);return a(r)?l(r.message??"Unable to update state"):(Nt=r.value,Td(),u("State updated",null))}function Gs(e){if(br)return u("Joined batch",e());br=!0,os=null,Kn=new Set;let t=()=>{let n=os;if(br=!1,os=null,n===null)return null;let r=wd(n);return a(r)?l(r.message??"Unable to update state"):(Nt=r.value,Td(),u("State updated",null))};try{let n=e(),r=t();return r&&a(r)?l(r.message):u("State updated",n)}finally{br&&t()}}var xm=()=>br,N=e=>we(t=>({...t,...e}));function xr(e,t,n){if(!br)return we(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};if(e==="nodes"){let i=o[t],d=n;i?.parentNodeId&&Kn?.add(i.parentNodeId),d.parentNodeId&&Kn?.add(d.parentNodeId)}o[t]=n;let s={...r,[e]:o};return os=s,Nt={...r,...s},u("State updated",null)}var J=()=>LE(kE,h,h),Kn=null,Og=null,DE=(e,t)=>{let n=Nt?.renderedChildrenIndex,r=n!==void 0&&Kn!==null&&e===Og&&t.length===0&&Nt?.filters.length===0,o;if(r){o={...n};let s=hm(e,Kn);for(let i of Kn){let d=s[i];d?o[i]=d:delete o[i]}}else o=gm(e,t);return Og=e,Kn=new Set,o},X=e=>h()?.renderedChildrenIndex[e]??[],jt=()=>Nd?Do(Nd):l("Cannot reset state: no initial workspace found"),It=()=>Nt!==void 0;var ut=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return l("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return l(`No ancestor found for context: ${t}`)},Md=(e,t)=>{let{nodes:n}=h(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},qn=(e,t)=>e?e.readonly?l({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:l("Node not found"),R={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.userId&&n.userId!==t)return l("Contributor is already linked to another user");let r={...n,userId:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){we(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create comment, missing issue");if(!B(t))return l("Can only comment on issues");let n=xr("comments",e.id,{...e,deleted:!1});return a(n)?l("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return l("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return l("Unable to edit comment, missing issue");if(!B(r))return l("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=xr("comments",e,o);return a(s)?l("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return l("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=xr("comments",e,n);return a(r)?l("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create attachment, missing issue");if(!B(t))return l("Can only attach to issues");let n=we(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?l("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return l("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=we(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?l("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return l("Edit target node not found");let o=qn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return l("Rename target node not found");let r=qn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return de(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),o=this.getNode(e),s=this.getNode(t);if(!o)return l("Node not found");if(!s)return l("Target parent not found");if(r===e)return l("Cannot move root node");if(e===t)return l("Cannot move node into itself");let i=qn(o,"move");if(i)return i;if(Md(t,e))return l("Cannot move node into its own descendant");let d={...o,parentNodeId:t,rank:n};return this.updateNode(d),u("Moved node successfully",d)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return l("Node not found");if(r===e)return l("Cannot delete root node");let s=qn(o,"delete");if(s)return s;let i=new Set,d=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of de(p.id))d(f.id)}};d(e);let c={...structuredClone(t)};for(let m of i){if(!c[m])return l("Unable to locate node to delete");c[m]={...c[m],isDeleted:!0}}return n?(N({nodes:c}),u("Successfully tomb stoned",o)):l("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return l("Contributor not found");let n={...t,name:js,tombstoned:!0},r=we(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?l("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.tombstoned)return l("Cannot rename a removed contributor");let r={...n,name:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=we(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?l("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to assign contributor, missing contributor");if(!r)return l("Unable to assign contributor, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return l("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to unassign, missing contributor");if(!r)return l("Unable to unassign, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return u("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(d=>d!==t)}};return this.updateNode(i),u("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return l("Unable to add tag, missing tag");if(!r)return l("Unable to add tag, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return l("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return l("Unable to remove tag, missing tag");if(!r)return l("Unable to remove tag, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return u("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(d=>d!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return l("Tag not found");let n={...t,tombstoned:!0},r=we(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?l("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return l("Tag not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?l("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=we(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?l("Could not create tag"):u("Tag created",e)},createNode(e){let t=xr("nodes",e.id,e);return a(t)?l("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return l("Failed to locate node");let n={...t,readonly:!0},r=xr("nodes",e,n);return a(r)?l(r.message):u("Locked node",n)},updateNode(e){let t=xr("nodes",e.id,e);return a(t)?t:u("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return de(e)}};var BE=(e,t)=>e+" ".repeat(Math.max(0,t-_g(e))),FE=(e,t)=>" ".repeat(Math.max(0,t-_g(e)))+e,Qi=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),OE=(e,t)=>t?e<t?"up":e>t?"down":null:null,_E=(e,t)=>{let n=R.getNode(e.payload.parent),r=n?Yn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=OE(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Ug=e=>`${Math.max(1,Math.round(e/1024))} KB`,jg=e=>R.getAttachment(e)?.name??"",UE=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?Yn.bgHex(ce(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?Yn.bgHex(ce(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Yn.hex(ce(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Yn.hex(ce(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Yn.dim(`(${Ug(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=jg(e.payload.id);return t?`"${t}"`:""}default:return""}},jE=e=>{let t=to(Ce(e));return Yn.gray(FE(t,8))},$E=12,HE=e=>BE(`${e}`,$E),WE=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=R.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ug(e.payload.bytes)})`;case"delete.issue.attachment":{let t=jg(e.payload.id);return t?`"${t}"`:""}default:return""}},zi=e=>[Qi(e.action),WE(e)].filter(Boolean).join(" "),$g=(e,t)=>{let n=jE(e.id),r=HE(e.userName),o=Yn.dim("\u203A"),s=e.action==="move.node"?_E(e,t):[Qi(e.action),UE(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var GE=e=>De(e,"comments"),VE=e=>De(e,"description"),zE=e=>De(e,"assignees"),KE=e=>De(e,"tags"),qE=e=>De(e,"history"),YE=e=>De(e,"attachments"),Zi=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let d=R.getNode(e);if(!d){let p=R.createNode({...be.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:u("Virtual field created",void 0)}if(!gt(d))return l(`Existing virtual node ${e} is not a field`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.props.value!==o||d.readonly!==s||d.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=R.updateNode({...d,title:t,parentNodeId:n,rank:r,props:{...d.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:u("Virtual field updated",void 0)},Hg=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=R.getNode(e);if(!i){let m=R.createNode({...be.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:u("Virtual field list created",void 0)}if(!wo(i))return l(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let c=R.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(c)?c:u("Virtual field list updated",void 0)},Ou=e=>{let t=xt(qt/4n),n=xt(qt/2n),r=xt(qt*3n/4n),o=xt(qt*7n/8n),s=xt(qt*15n/16n),i=xt(qt*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(i))return i;let d=Zi({id:VE(e.id),name:ve.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let c=Hg({id:zE(e.id),name:ve.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(c))return c;let m=Hg({id:KE(e.id),name:ve.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=Zi({id:GE(e.id),name:ve.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=Zi({id:YE(e.id),name:ve.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let g=Zi({id:qE(e.id),name:ve.HISTORY,parentNodeId:e.id,rank:i.value,value:XE(e),readonly:!0,childRenderAxis:"vertical"});return a(g)?g:u("Ticket virtual nodes materialized",void 0)},XE=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>$g(r,n.get(r.action)??[])).join(`
|
|
86
|
+
`)},Wg=!0,Gg=e=>{Wg=e},cl=()=>Wg;import AC from"node:http";import Ar from"node:path";import{fileURLToPath as TC}from"node:url";var JE=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},Pd=(e,t)=>{let n=[];for(let r of e){let o=JE(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Mn(r);n.push({laneId:o,enteredAt:s===null?t:To(s)})}return n},ea=(e,t)=>Pd(e,t).at(-1)?.enteredAt??t;import{existsSync as Bd}from"node:fs";import{chmod as Fd}from"node:fs/promises";import ta from"node:path";import{chmodSync as QE,existsSync as ZE,lstatSync as eR,mkdirSync as tR}from"node:fs";import nR from"node:os";import rR from"node:path";var Ld=(...e)=>{let t=rR.join(nR.tmpdir(),"epiq",...e);try{return ZE(t)&&eR(t).isSymbolicLink()?l(`Refusing to write through a symlink at ${t}`):(tR(t,{recursive:!0,mode:448}),QE(t,448),u("Prepared private temp dir",t))}catch(n){return l(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var oR=new Set(["create.tag","create.contributor","add.swimlane"]),sR=e=>{let t=new Map;for(let n of e){if(!oR.has(n.action))continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},iR=e=>{let t=new Map,n=new Map;for(let r of e){let o=r.payload;!o?.id||!o.parent||(r.action==="move.node"&&t.set(r.id,n.get(o.id)),n.set(o.id,o.parent))}return t},zg=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},aR=e=>{let t=new Set,n=new Map;for(let r of e){let o=r.payload,s=o?.id;s&&(r.action==="add.issue"&&t.add(s),o.parent&&n.set(s,o.parent))}return{issueIds:t,parentById:n}},lR=(e,{issueIds:t,parentById:n})=>{let r=e.payload;if(r?.issue)return r.issue;let o=new Set,s=r?.id;for(;s!==void 0&&!o.has(s);){if(t.has(s))return s;o.add(s),s=n.get(s)}return null},dR=new Set(["add.issue","move.node","close.issue","reopen.issue"]),cR=(e,t)=>{let n=new Map;return e.map((r,o)=>{let s=t[o]??null;if(s===null)return{lane:null,laneBefore:null};let i=r.payload,d=null;if(dR.has(r.action)&&i?.id===s&&i.parent){let c=n.get(s);c!==void 0&&c!==i.parent&&(d=c),n.set(s,i.parent)}return{lane:n.get(s)??null,laneBefore:d}})},Vg=90,uR=e=>{let t=e.trim().split(`
|
|
87
|
+
`)[0]?.trim()??"";return t.length>Vg?`${t.slice(0,Vg).trimEnd()}\u2026`:t},mR=(e,t,n)=>{let r=e.payload,o=zg(e),s=e.action?Qi(e.action):"";if(r?.md!==void 0){let d=uR(r.md);return d?`${s}: ${d}`:s}if(e.action==="move.node"&&r?.parent){let d=t.get(r.parent);return d?n.get(e.id)===r.parent?`Moved within ${d}`:`Moved to ${d}`:s}let i=o!==void 0?t.get(o)??"":r?.assignee!==void 0?t.get(r.assignee)??"":r?.name!==void 0?`"${r.name}"`:"";return[s,i].filter(Boolean).join(" ")},kd=(e,t,n)=>{if(!e)return null;let r=t.get(e)??n??e;return{id:e,name:r,color:ce(r)}},pR=(e,t)=>{let n=e.payload;return{actor:kd(e.userId,t,e.userName),tag:kd(zg(e),t),assignee:kd(n?.assignee,t)}},Kg=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let d=o.action==="close.issue"?r(i):null,c=s.parent??s.issue;return c&&t.set(i,c),d!==null?d:n.has(i)?i:r(i)})},qg=(e,t)=>{let n=Kg(e);return e.filter((r,o)=>n[o]===t)},fR=e=>{let t=sR(e),n=iR(e),r=aR(e),o=e.map(m=>lR(m,r)),s=cR(e,o),i=Kg(e),d=_r(e.map(m=>Mn(m)));return e.flatMap((m,p)=>{let f=d[p]??null;return f===null?[]:[{id:m.id,t:f,action:m.action,label:mR(m,t,n),issue:o[p]??null,...s[p],board:i[p]??null,...pR(m,t)}]}).sort((m,p)=>m.t-p.t)},gR=e=>{let t=new Map;for(let r of e){if(r.issue===null||r.lane===null)continue;let o=t.get(r.issue)??[],s=o[o.length-1];(s===void 0||s.lane!==r.lane)&&(o.push({t:r.t,lane:r.lane,board:r.board}),t.set(r.issue,o))}let n=new Map;for(let[r,o]of t){let s=o[o.length-1];n.set(r,{changes:o,from:o[0].t,closedFrom:s.lane===ie?s.t:null})}return n},hR=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return e[n-1]},Yg=(e,t,n)=>{let r={};for(let[o,s]of e){if(s.from>=t||s.closedFrom!==null&&s.closedFrom<t)continue;let i=hR(s.changes,t);i===void 0||i.lane===ie||n&&i.board!==n||(r[o]=i.lane)}return r},yR=e=>{let t={};for(let n of e){let r=n.payload;!r?.id||r.name===void 0||(n.action==="add.swimlane"||n.action==="edit.title"&&r.id in t)&&(t[r.id]=r.name)}return t},ss=null,Xg=e=>{let t=Yt(e);if(ss&&ss.root===e&&ss.signature===t)return u("Timeline entries, cached",ss.index);let n=Fn(e);if(a(n))return l(n.message);let r=fR(n.value),o={entries:r,lanes:gR(r),laneNames:yR(n.value)};return ss={root:e,signature:t,index:o},u("Timeline entries, built",o)};var Jg=1e5,vR=2e4,na=null,Qg=Promise.resolve(),Xn=e=>{let t=Qg.then(e,e);return Qg=t.then(()=>{},()=>{}),t},ra=e=>{let t=Se(e??process.cwd());return a(t)?l(t.message):u("Resolved Epiq repo root",t.value)},oa=e=>{let t=ra(e);return a(t)?t:fe({repoRoot:t.value})},Ve=()=>{if(!It())return{mode:"live",asOfTime:null};let{timeMode:e}=h();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:na}},Zg=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return n},oh=async(e={})=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=Xg(t.value);if(a(n))return l(n.message);let r=n.value.entries,o=Date.now(),s=e.end??o,i=e.start??r[0]?.t??s;if(s<=i)return u("Empty time window",{bucketMs:0,buckets:[],events:[],lanesAtStart:{},laneNames:n.value.laneNames,closedLane:ie,earliest:i,latest:s});let d=Zg(r,i),c=Zg(r,s),m=r.slice(d,c).filter(I=>!e.boardId||I.board===e.boardId).map(({board:I,...x})=>x),p=m.map(I=>I.t),f=Math.max(1,Math.ceil((s-i)/Jg)),g=new Map;for(let I of p){let x=Math.min(Jg-1,Math.floor((I-i)/f)),C=i+x*f;g.set(C,(g.get(C)??0)+1)}let v=[...g.entries()].sort(([I],[x])=>I-x).map(([I,x])=>({t:I,count:x}));return u("Computed event timeline",{bucketMs:f,buckets:v,events:m.length>vR?[]:m,lanesAtStart:Yg(n.value.lanes,i,e.boardId),laneNames:n.value.laneNames,closedLane:ie,earliest:i,latest:s})},is="",eh="",bR=5e3,oo=null;var Od=async(e={})=>{let t=ra(e.repoRoot);if(a(t))return l(t.message);let n=pt(t.value);if(a(n))return l(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&oo&&oo.repoRoot===t.value&&oo.stateBranch===n.value.stateBranch&&Date.now()-oo.fetchedAt<bR)return u("Computed commit timeline",oo.result);let o=await U({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${eh}%H${is}%at${is}%an${is}%s`]});if(a(o))return l(o.message);let s=o.value.stdout.split(eh).filter(i=>i.trim().length>0).map(i=>{let[d,...c]=i.split(`
|
|
88
|
+
`),[m,p,f,...g]=(d??"").split(is);if(!m||!p)return null;let v=c.join(" "),I=Number(/(\d+) insertion/.exec(v)?.[1]??0),x=Number(/(\d+) deletion/.exec(v)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",subject:g.join(is),linesChanged:I+x,insertions:I,deletions:x}}).filter(i=>i!==null).filter(i=>(e.start===void 0||i.time>=e.start)&&(e.end===void 0||i.time<=e.end));return r&&(oo={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),u("Computed commit timeline",s)},sa=async e=>{let t=e.ref.trim();if(!t)return l("ref must not be empty");if(t.length!==7)return l(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await Od({repoRoot:e.repoRoot});if(a(n))return l(n.message);let r=`${t.toUpperCase()} `,o=d=>d.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[d,c]of s.entries()){if(!o(c))continue;let m=s[d+1];i.push({...c,precedingSha:m&&o(m)?m.sha:null})}return u("Matched commits by ref",i)},sh=e=>/^[0-9a-f]{7,40}$/i.test(e),xR=async(e,t)=>{let n=await U({cwd:e,args:["show",t]});if(a(n))return l(n.message);let r=Ld("commit-diffs");if(a(r))return l(r.message);let o=ta.join(r.value,`${t}.diff`);return Bd(o)||(We.writeToFile(o,n.value.stdout),await Fd(o,292)),Of(o)},IR=12,SR=800,th=async(e,t,n)=>{let r=await U({cwd:e,args:["show",`${t}:${n}`]});return a(r)?"":r.value.stdout},ER=async(e,t)=>{let n=await U({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(a(n))return l(n.message);let r=n.value.stdout.split(`
|
|
89
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?l("No changed files found for this commit"):u("Listed changed files",r)},RR=async(e,t,n)=>{let r=await ER(e,t);if(a(r))return l(r.message);let o=r.value;if(o.length>IR)return l(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Ld("commit-diffs",t);if(a(s))return l(s.message);let i=s.value,d=await Promise.all(o.map(async(g,v)=>{let[I,x]=await Promise.all([th(e,`${t}~1`,g),th(e,t,g)]),C=ta.basename(g),A=ta.join(i,String(v),"before",C),M=ta.join(i,String(v),"after",C);return Bd(A)||(We.writeToFile(A,I),await Fd(A,292)),Bd(M)||(We.writeToFile(M,x),await Fd(M,292)),{beforePath:A,afterPath:M}})),[c,...m]=d;if(!c)return l("No changed files found for this commit");let p=await hd(n,c.beforePath,c.afterPath,"new");if(a(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,SR));let f=await Promise.all(m.map(({beforePath:g,afterPath:v})=>hd(n,g,v,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},ih=async e=>{if(!sh(e.sha))return l("Invalid commit sha");let t=ra(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=Oi()[0];if(r&&gd(r)){let o=await RR(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return xR(n,e.sha)},CR=200,nh=e=>/^0+$/.test(e),Dd=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,rh=/^(\d+|-)\t(\d+|-)\t(.+)$/,NR=async(e,t)=>{let n=await U({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",`${t}~1`,t]});if(a(n))return l(n.message);let r=n.value.stdout.split(`
|
|
90
|
+
`).filter(d=>d!==""),o=r.filter(d=>!Dd.test(d)&&!rh.test(d));if(o.length>0)return l(`Could not parse ${o.length} line(s) of "git diff --raw --numstat" output, e.g. "${o[0]}"`);let s=new Map;for(let d of r){let c=rh.exec(d);c&&s.set(c[3]??"",{insertions:c[1]==="-"?0:Number(c[1]),deletions:c[2]==="-"?0:Number(c[2])})}let i=r.filter(d=>Dd.test(d)).map(d=>{let c=Dd.exec(d),m=c?.[1]??"",p=c?.[2]??"",f=c?.[3]??"";return{path:f,beforeBlob:nh(m)?null:m,afterBlob:nh(p)?null:p,...s.get(f)??{insertions:0,deletions:0}}});return i.length===0?l("No changed files found for this commit"):u("Listed changed files with blob hashes",i)},ah=async e=>{if(!sh(e.sha))return l("Invalid commit sha");let t=ra(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=await NR(n,e.sha);if(a(r))return l(r.message);let o=r.value;if(o.length>CR)return l(`Commit touches ${o.length} files \u2014 too many to show as a diff`);let s=o.flatMap(m=>[m.beforeBlob,m.afterBlob].filter(p=>p!==null)),i=await ks(s,n);if(a(i))return l(i.message);let d=i.value,c=o.map(m=>({path:m.path,before:m.beforeBlob?d.get(m.beforeBlob)??"":"",after:m.afterBlob?d.get(m.afterBlob)??"":"",insertions:m.insertions,deletions:m.deletions}));return u("Loaded commit diff",{sha:e.sha,files:c})},lh=e=>{let t=Fn(e);if(a(t))return l(t.message);let n=jt();if(a(n))return l(n.message);na=null;let r=Bt(t.value),{fatal:o,skipped:s}=vn(r);return o.length>0?l(o.map(i=>i.message).join(", ")):(bn(s),N({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},AR=(e,t)=>{na=null;let n=lh(e);return a(n)?l(`${t} (recovery to live also failed: ${n.message})`):l(t)},_d=e=>Xn(async()=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=Qs(t.value,e.targetTime);if(a(n))return l(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=jt();if(a(s))return s;let i=Bt(r),{fatal:d,skipped:c}=vn(i);return d.length>0?AR(t.value,d.map(m=>m.message).join(", ")):(bn(c),N({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),na=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),dh=async e=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=Zs(t.value);if(a(n))return l(n.message);let r=n.value.get(e.eventId)??null;return r===null?l("Event not found in the log"):_d({repoRoot:e.repoRoot,targetTime:r+1})},ch=(e={})=>Xn(async()=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=lh(t.value);return a(n)?l(n.message):u("Returned to live state",!0)});import TR from"node:fs";var Ir=e=>{let t=Se(e??process.cwd());return a(t)?l(t.message):u("Resolved Epiq repo root",t.value)},ia=null,Q=async(e,t)=>{let n=Ir(e);if(a(n))return n;let r=fe({repoRoot:n.value});if(a(r))return l(r.message);let o=Gt(n.value);if(a(o))return l(o.message);if(!(ia!==null&&ia.repoRoot===n.value&&ia.stateBranchRoot===r.value&&TR.existsSync(or(r.value)))){let p=await Uo({repoRoot:n.value,stateBranchName:o.value});if(a(p))return l(p.message);let f=await On({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(f))return l(f.message);ia={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await U({cwd:r.value,args:["pull","--ff-only"]});a(p)&&z.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},d=Yt(r.value);if(qu(r.value)===d&&It()&&Ve().mode==="live")return u("Booted Epiq state, unchanged",i);let c=St(r.value);if(a(c))return l(c.message);let m=Ot(c.value.events,c.value.unreadable);return a(m)?l(m.message):(Yu(r.value,d),u("Booted Epiq state",i))},Z=()=>{let e=bt();return a(e)?l(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):l("Unable to retrieve user name"):l("Unable to retrieve user id")},V=()=>{let e=it();return a(e)?l(e.message):e};var so=e=>(e.props.tags??[]).map(t=>R.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ce(t.name)}));var io=e=>(e.props.assignees??[]).map(t=>R.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:ce(n)}));import wR from"node:fs";import MR from"node:path";import{ulid as jd}from"ulid";var _e=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Issue not found"):B(n)?n.readonly?l("Issue is readonly"):u("Found issue",n):l("Target must be an issue")},Jn=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Swimlane not found"):Kt(n)?n.readonly?l("Swimlane is readonly"):u("Found swimlane",n):l("Target must be a swimlane")},Ud=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Board not found"):Ln(n)?n.readonly?l("Board is readonly"):u("Found board",n):l("Target must be a board")};var PR=e=>{if(e.filePath)try{return u("Read attachment file",{data:wR.readFileSync(e.filePath),name:e.name??MR.basename(e.filePath)})}catch(t){return l(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):l("Provide either filePath or dataBase64")},aa=()=>{let e=bt();return a(e)?en:e.value.attachmentMaxKb??en},$d=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=PR(e);if(a(s))return s;let i=yp(t.value.stateBranchRoot,s.value.data,aa());if(a(i))return i;let d=ye(s.value.name).trim()||"image",c=jd(),m={id:jd(),...n.value,action:"add.issue.attachment",payload:{id:c,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:d,bytes:i.value.bytes}},p=D([m],t.value.stateBranchRoot);if(a(p))return l(p.message);let f=fr(i.value.hash,i.value.ext);return u("Added issue attachment",{id:c,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Wl(d,f)})},Hd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return l("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return l("You can only delete your own attachments");let s=_e(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let d={id:jd(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Wd=async e=>{let t=await Q(e.repoRoot,{pull:!1});return a(t)?t:vp(t.value.stateBranchRoot,e.fileName,aa())};var LR=365*24*60*60*1e3,Sr=()=>{let e=V();if(a(e))return e;let t=Ve(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(x=>Ln(x)&&!x.isDeleted),s=Date.now()-LR,i=new Map,d=new Map;for(let x of r)if(!x.isDeleted){if(Kt(x)&&x.parentNodeId){let C=i.get(x.parentNodeId)??[];C.push(x),i.set(x.parentNodeId,C)}if(B(x)&&x.parentNodeId){if(x.parentNodeId===ie&&Ce(x.id)<s)continue;let C=d.get(x.parentNodeId)??[];C.push(x),d.set(x.parentNodeId,C)}}let c=new Set;for(let x of d.values())for(let C of x)c.add(C.id);let m=bt();if(a(m))return m;let p={},f=R.getCommentsGroupedByIssue();for(let x of r.filter(B))x.isDeleted||!c.has(x.id)||(p[x.id]=(f.get(x.id)??[]).map(C=>{let A=R.getContributor(C.authorId);return{id:C.id,issueId:C.issue,body:C.md,author:{id:C.authorId,name:A?.name??"Unknown",color:ce(A?.name??C.authorId??"Unknown")},createdAt:Ce(C.id)}}));let g=new Map;for(let x of e.value.eventLog)x.action==="add.issue.attachment"&&g.set(x.payload.id,x.payload.author);let v={},I=R.getAttachmentsGroupedByIssue();for(let x of r.filter(B))x.isDeleted||!c.has(x.id)||(v[x.id]=(I.get(x.id)??[]).map(C=>({id:C.id,issueId:C.issue,name:C.name,fileName:fr(C.hash,C.ext),bytes:C.bytes,createdAt:Ce(C.id),canDelete:g.get(C.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((x,C)=>x.rank.localeCompare(C.rank)).map(x=>({id:x.id,ref:O(x.id),title:x.title,readonly:!!x.readonly||n,swimlanes:(i.get(x.id)??[]).sort((C,A)=>C.rank.localeCompare(A.rank)).map(C=>({id:C.id,title:C.title,readonly:!!C.readonly||n,issues:(d.get(C.id)??[]).sort((A,M)=>A.rank.localeCompare(M.rank)).map(A=>({id:A.id,ref:O(A.id),title:ye(A.title),description:A.props.description??"",createdAt:Ce(A.id),enteredLaneAt:ea(A.log??[],Ce(A.id)),readonly:!!A.readonly||n,tags:so(A),assignees:io(A),parentNodeId:A.parentNodeId,isClosed:A.parentNodeId===ie})),parentNodeId:C.parentNodeId}))})),tags:R.getTags().map(x=>({...x,color:ce(x.name)})),contributors:Object.values(e.value.contributors).map(x=>({...x,color:ce(x.name)})),user:{name:m.value.userName??"",id:m.value.userId??"",color:ce(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:v,attachmentMaxKb:aa(),timeTravel:t})},uh=null,kR=e=>{if(e===uh)return;let t=fi({root:e});if(a(t)){z.info(t.message);return}uh=e},At=async(e={})=>{if(Ve().mode!=="live")return Sr();let t=await Q(e.repoRoot,{pull:!1});return a(t)?t:(kR(t.value.repoRoot),Sr())},as=async(e={})=>{Ur();let t=Ir(e.repoRoot);if(a(t))return l("Sync failed");let n=Z();if(a(n))return n;let r=await ci({cwd:t.value,ownEventFileName:lr(n.value)});return a(r)?(Al(r.message),r):(ur(),u("Synced",r.value))};import{ulid as Tt}from"ulid";var ls=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):l("Provide issueId or issueIds")},ao=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):l(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Gd=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:O(r),reason:o.message}):n.done.push({id:r,ref:O(r)})}return n};var fh=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Kd(e){let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=V();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(B).filter(d=>!d.isDeleted).filter(d=>e.includeClosed||d.parentNodeId!==ie).filter(d=>e.boardId?(d.parentNodeId?r[d.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(d=>!e.swimlaneId||d.parentNodeId===e.swimlaneId).filter(d=>!e.tag||so(d).some(c=>fh(c.name,e.tag))).filter(d=>!e.assignee||io(d).some(c=>fh(c.name,e.assignee))).filter(d=>!o||d.title.toLowerCase().includes(o)||(d.props.description??"").toLowerCase().includes(o)),i=d=>ye((d.parentNodeId?r[d.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(d=>({id:d.id,ref:O(d.id),title:ye(d.title),swimlane:i(d),tags:so(d).map(c=>c.name),assignees:io(d).map(c=>c.name)}))):u("Listed issues",s.map(d=>({id:d.id,ref:O(d.id),title:ye(d.title),description:d.props.description??"",createdAt:Ce(d.id),enteredLaneAt:ea(d.log??[],Ce(d.id)),parentNodeId:d.parentNodeId,isClosed:d.parentNodeId===ie,readonly:!!d.readonly,tags:so(d),assignees:io(d)})))}var qd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=ye(e.title);if(!o)return l("Issue title cannot be empty");let s=e.description??"",i=Qe("Issue title",o,300)??Qe("Issue description",s,2e4);if(i)return l(i);if((e.tagNames?.length??0)>20)return l(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return l(`Cannot set more than ${20} assignees at once`);let d=Jn(e.parentId);if(a(d))return d;let c=In(e.parentId,n.value,t.value.stateBranchRoot);if(a(c))return c;let m=Ui({name:o,parent:e.parentId,user:n.value,rank:c.value});if(a(m))return m;let p=[...m.value],f=p.find(x=>x.action==="add.issue")?.payload.id;if(!f)return l("Unable to determine created issue id");s&&p.push({id:Tt(),...n.value,action:"edit.description",payload:{id:f,md:s}});let g=[];for(let x of e.tagNames??[]){let C=ye(x).trim();if(!C||g.some(L=>L.name===C))continue;let A=Qe("Tag name",C,60);if(A)return l(A);let M=R.findTagByName(C),w=M?.id??Tt();M||p.push({id:Tt(),...n.value,action:"create.tag",payload:{id:w,name:C}}),p.push({id:Tt(),...n.value,action:"add.issue.tag",payload:{id:f,tag:w}}),g.push({id:w,name:C})}let v=[];for(let x of e.assigneeNames??[]){let C=ye(x).trim();if(!C||v.some(L=>L.name===C))continue;let A=Qe("Assignee name",C,80);if(A)return l(A);let M=Object.values(r.value.contributors).find(L=>L.name===C),w=M?.id??Tt();M||p.push({id:Tt(),...n.value,action:"create.contributor",payload:{id:w,name:C}}),p.push({id:Tt(),...n.value,action:"add.issue.assignee",payload:{id:f,assignee:w}}),v.push({id:w,name:C})}let I=D(p,t.value.stateBranchRoot);return a(I)?l(I.message):u("Created issue",{id:f,ref:O(f),title:o,parentId:e.parentId,description:s,tags:g,assignees:v})},DR=(e,t,n)=>{let r=_e(e);if(a(r))return r;let o=Xt(ie,e,{at:"end"},t,n);if(a(o))return o;let s={id:Tt(),...t,action:"close.issue",payload:{id:e,parent:ie,rank:o.value}},i=D([s],n);return a(i)?l(i.message):u("Closed issue",{id:e,ref:O(e)})};async function Yd(e){let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=ls(e);if(a(r))return r;let o=s=>DR(s,n.value,t.value.stateBranchRoot);return e.issueIds?ao("Closed",Gd(r.value,o)):o(r.value[0])}var Xd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return l("Issue not found");if(!B(o))return l("Target must be an issue");if(o.parentNodeId!==ie)return l("Issue is not closed");let s=Ki(o);if(!s)return l("Unable to resolve previous parent from issue history");if(s===ie)return l("Previous parent resolves to closed swimlane");let i=Jn(s);if(a(i))return i;let d=i.value,c=Xt(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(c))return c;let m={id:Tt(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:c.value}},p=D([m],t.value.stateBranchRoot);return a(p)?l(p.message):u("Reopened issue",{id:o.id,ref:O(o.id),parentId:d.id})},BR=(e,t,n,r)=>{let o=_e(e);if(a(o))return o;let s=Jn(t.parentId);if(a(s))return s;let i=Xt(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let d={id:Tt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},c=D([d],r);return a(c)?l(c.message):u("Moved issue",{id:e,ref:O(e),parentId:t.parentId})};async function Jd(e){let t=Ir(e.repoRoot);if(a(t))return t;let n=Z();if(a(n))return n;let r=fe({repoRoot:t.value});if(a(r))return r;let o=St(r.value);if(a(o))return o;let s=Ot(o.value.events,o.value.unreadable);if(a(s))return s;let i=ls(e);if(a(i))return i;let d=c=>BR(c,e,n.value,r.value);return e.issueIds?ao("Moved",Gd(i.value,d)):d(i.value[0])}var Qd=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Ce(r.id),action:r.action,label:zi(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:{id:r.userId,name:r.userName,color:ce(r.userName)}}))):l("Issue not found")},Zd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=o.value,i=Qe("Issue description",e.description,2e4);if(i)return l(i);let d=s.props.description??"";if(d===e.description)return u("No changes made",{id:e.issueId,ref:O(e.issueId),description:d});let c={id:Tt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited issue description",{id:e.issueId,ref:O(e.issueId),description:e.description})},ec=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=o.value,i=ye(e.title);if(!i.trim())return l("Issue title cannot be empty");let d=Qe("Issue title",i,300);if(d)return l(d);if(s.title===i)return u("No changes made",{id:e.issueId,ref:O(e.issueId),title:i});let c={id:Tt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:i}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited issue title",{id:e.issueId,ref:O(e.issueId),title:i})};import{ulid as Qn}from"ulid";var tc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return l("Workspace not found");if(Ve().mode!=="live")return l("Cannot add a board while time travelling");let s=ye(e.title);if(!s.trim())return l("Board title cannot be empty");let i=Qe("Board title",s,300);if(i)return l(i);let d=In(o.id,n.value,t.value.stateBranchRoot);if(a(d))return d;let c=Qn(),m={id:Qn(),...n.value,action:"add.board",payload:{id:c,name:s,parent:o.id,rank:d.value}},p=D([m],t.value.stateBranchRoot);return a(p)?l(p.message):u("Created board",{id:c,ref:O(c),title:s})},nc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return l("Board not found");if(!Ln(o))return l("Edit target must be a board");if(o.readonly)return l("Cannot edit readonly board");if(Ve().mode!=="live")return l("Cannot rename a board while time travelling");let s=ye(e.title);if(!s.trim())return l("Board title cannot be empty");let i=Qe("Board title",s,300);if(i)return l(i);if(o.title===s)return u("No changes made",{id:e.boardId,ref:O(e.boardId),title:s});let d={id:Qn(),...n.value,action:"edit.title",payload:{id:e.boardId,name:s}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Edited board title",{id:e.boardId,ref:O(e.boardId),title:s})};var rc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Ud(e.boardId);if(a(o))return o;if(Ve().mode!=="live")return l("Cannot add a swimlane while time travelling");let s=ye(e.title);if(!s.trim())return l("Swimlane title cannot be empty");let i=Qe("Swimlane title",s,300);if(i)return l(i);let d=In(e.boardId,n.value,t.value.stateBranchRoot);if(a(d))return d;let c=Qn(),m={id:Qn(),...n.value,action:"add.swimlane",payload:{id:c,name:s,parent:e.boardId,rank:d.value}},p=D([m],t.value.stateBranchRoot);return a(p)?l(p.message):u("Created swimlane",{id:c,ref:O(c),title:s,boardId:e.boardId})},oc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Jn(e.swimlaneId);if(a(o))return o;let s=o.value,i=ye(e.title);if(!i.trim())return l("Swimlane title cannot be empty");let d=Qe("Swimlane title",i,300);if(d)return l(d);if(s.title===i)return u("No changes made",{id:e.swimlaneId,ref:O(e.swimlaneId),title:i});let c={id:Qn(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited swimlane title",{id:e.swimlaneId,ref:O(e.swimlaneId),title:i})},sc=async e=>{let t=Ir(e.repoRoot);if(a(t))return t;let n=Z();if(a(n))return n;let r=fe({repoRoot:t.value});if(a(r))return r;let o=St(r.value);if(a(o))return o;let s=Ot(o.value.events,o.value.unreadable);if(a(s))return s;let i=Jn(e.swimlaneId);if(a(i))return i;let d=Ud(e.boardId);if(a(d))return d;let c=Xt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(c))return c;let m={id:Qn(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:c.value}},p=D([m],r.value);return a(p)?l(p.message):u("Moved swimlane",{id:e.swimlaneId,ref:O(e.swimlaneId),boardId:e.boardId})},ic=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Jn(e.swimlaneId);if(a(o))return o;let s={id:Qn(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=D([s],t.value.stateBranchRoot);return a(i)?l(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:O(e.swimlaneId)})};import{ulid as ds}from"ulid";async function ac(e){let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=ls(e);if(a(r))return r;let o=ye(e.tagName).trim();if(!o)return l("Tag name cannot be empty");let s=Qe("Tag name",o,60);if(s)return l(s);let i={done:[],failed:[]};for(let v of r.value){let I=_e(v);a(I)?i.failed.push({id:v,ref:O(v),reason:I.message}):i.done.push({id:v,ref:O(v)})}if(!e.issueIds&&i.failed[0])return l(i.failed[0].reason);if(i.done.length===0)return l(ao("Tagged",i).message);let d=R.findTagByName(o),c=d?.id??ds(),m=[...d?[]:[{id:ds(),...n.value,action:"create.tag",payload:{id:c,name:o}}],...i.done.map(({id:v})=>({id:ds(),...n.value,action:"add.issue.tag",payload:{id:v,tag:c}}))],p=D(m,t.value.stateBranchRoot);if(a(p))return l(p.message);let f={id:c,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=ao("Tagged",i);return a(g)?g:u(g.message,{...g.value,tag:f})}var lc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return l("Tag not found");if(o.tombstoned)return l("Tag is already deleted");let s=[{id:ds(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=D(s,t.value.stateBranchRoot);return a(i)?l(i.message):u("Deleted tag",{id:o.id,name:o.name})};var dc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return l("Tag not found");let s={id:ds(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=D([s],t.value.stateBranchRoot);return a(i)?l(i.message):u("Removed issue tag",{id:e.issueId,ref:O(e.issueId),tagId:e.tagId})};import{ulid as Rr}from"ulid";var FR=()=>{let e=it(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},hh=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n};var yh=async(e,t)=>{let n=Sl(e);if(a(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},cc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let C=r.value.contributors[s],A=C?void 0:await yh(t.value.stateBranchRoot,s);if(!C&&!A)return l("Unknown assignee id");let M=C??A,w=[...C?[]:[{id:Rr(),...n.value,action:"create.contributor",payload:{id:M.id,name:M.name}}],{id:Rr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:M.id}}],L=D(w,t.value.stateBranchRoot);return a(L)?l(L.message):u("Added issue assignee",{id:e.issueId,ref:O(e.issueId),assignee:{id:M.id,name:M.name}})}let i=ye(e.assigneeName??"").trim();if(!i)return l("Provide assigneeId, self or assigneeName");let d=Qe("Assignee name",i,80);if(d)return l(d);let m=[...hh(FR(),r.value.contributors).entries()].filter(([,C])=>C===i);if(m.length>1)return l(`"${i}" matches ${m.length} contributors (${m.map(([C])=>C).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return l(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=Rr(),g=i]=p??[],I=[...!!r.value.contributors[f]?[]:[{id:Rr(),...n.value,action:"create.contributor",payload:{id:f,name:g}}],{id:Rr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],x=D(I,t.value.stateBranchRoot);return a(x)?l(x.message):u("Added issue assignee",{id:e.issueId,ref:O(e.issueId),assignee:{id:f,name:g}})},uc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;if(!r.value.contributors[e.contributorId])return l("Contributor not found");if(await yh(t.value.stateBranchRoot,e.contributorId))return l("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Rr(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],d=D(i,t.value.stateBranchRoot);return a(d)?l(d.message):u("Tombstoned contributor",{id:e.contributorId,name:js})};var mc=async(e={})=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Fn(t.value.stateBranchRoot);if(a(o))return l(o.message);let s=e.boardId?qg(o.value,e.boardId):o.value,i=new Map,d=new Set,c=new Set,m=Sl(t.value.stateBranchRoot);if(a(m))return l(m.message);for(let v of m.value)v.userId&&c.add(v.userId);for(let v of s)v.userId&&(i.set(v.userId,v.userName??""),d.add(v.userId));let p=r.value.contributors,g=[...hh(i,p).entries()].map(([v,I])=>({id:v,name:I,color:ce(I),isSelf:v===n.value.userId,isExternal:!d.has(v),isRemoved:p[v]?.tombstoned===!0,hasAuthoredAnywhere:c.has(v)}));return u("Listed board contributors",g)},pc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return l("Assignee not found");let s={id:Rr(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=D([s],t.value.stateBranchRoot);return a(i)?l(i.message):u("Removed issue assignee",{id:e.issueId,ref:O(e.issueId),assigneeId:e.assigneeId})};import{ulid as la}from"ulid";var cs=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return l("Comment cannot be empty");if(s.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=la(),d={id:la(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},us=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return l("Unable to resolve comment");if(o.payload.author!==n.value.userId)return l("You can only delete your own comments");let s=_e(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let d={id:la(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},fc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return l("Unable to resolve comment");if(o.payload.author!==n.value.userId)return l("You can only edit your own comments");let s=_e(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return l("Comment was deleted");let d=e.body.trim();if(!d)return l("Comment cannot be empty");if(d.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${d.length})`);let c={id:la(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:d}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:d})};var sn="1.8.6";import OR from"node:fs";import vh from"node:path";var ms=Number(process.env.EPIQ_GUI_PORT)||3710,gc="/api/instance",hc="epiq",da=e=>{try{return OR.realpathSync(vh.resolve(e))}catch{return vh.resolve(e)}},_R=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===hc&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},bh=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${gc}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return _R(s)?s:null}catch{return null}finally{clearTimeout(r)}};var UR=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),Cr=e=>a(e)?e:u(e.message,UR(e.value)),xh=(e,t)=>{let n=(e.boards??[]).flatMap(r=>r.swimlanes??[]).flatMap(r=>r.issues??[]).find(r=>r.id===t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}};var jR=15e3,Ih=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=Se(e.project.repoRoot);if(a(g))return null;let v=fe({repoRoot:g.value});return a(v)?null:Yt(v.value)}let d=()=>{let g=Or();return a(g)?(z.error(g.message),null):g.value},c=()=>{let g=d();if(!g)return!1;let{autoSync:v,preferredEditor:I}=g,x=bt(),C=a(x)?null:x.value.userName;return!!(v&&C&&I)},m=()=>{let g=d()?.autoSyncDebounceMs??jR;return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await Xn(async()=>{if(Ve().mode!=="live")return;await as({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let v=Cr(await At({repoRoot:e.project.repoRoot}));a(v)||cr({type:"state",payload:v})})}finally{r=!1,f()}}};function f(){n||!c()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,dispose:()=>{n=!0,t&&clearTimeout(t)}}};var $R=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),yc=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!$R.has(n.hostname)},Sh=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:yc(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as RC}from"ws";var an=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var HR=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},Eh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...an(i),changed:i.addedCount+i.removed})).reduce((i,d)=>i===null||d.changed>i.changed?d:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>HR(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var Ue={line:["//"],block:[["/*","*/"]]},wt={line:["#"],block:[]},vc={line:["--"],block:[]},lo={line:[],block:[["<!--","-->"]]},WR={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),ca=$("TypeScript",Ue),ua=$("JavaScript",Ue),Rh={ts:ca,tsx:ca,mts:ca,cts:ca,js:ua,jsx:ua,mjs:ua,cjs:ua,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",Ue),rs:$("Rust",Ue),java:$("Java",Ue),kt:$("Kotlin",Ue),swift:$("Swift",Ue),c:$("C",Ue),h:$("C",Ue),cc:$("C++",Ue),cpp:$("C++",Ue),hpp:$("C++",Ue),cs:$("C#",Ue),php:$("PHP",Ue),scala:$("Scala",Ue),dart:$("Dart",Ue),lua:$("Lua",vc),hs:$("Haskell",vc),sql:$("SQL",vc),ex:$("Elixir",wt),exs:$("Elixir",wt),pl:$("Perl",wt),r:$("R",wt),jl:$("Julia",wt),sh:$("Shell",wt),bash:$("Shell",wt),zsh:$("Shell",wt),vue:$("Vue",lo),svelte:$("Svelte",lo),html:$("HTML",lo),xml:$("XML",lo),md:$("Markdown",lo),mdx:$("Markdown",lo),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",Ue),less:$("CSS",Ue),yml:$("YAML",wt),yaml:$("YAML",wt),toml:$("TOML",wt),ini:$("INI",wt),json:$("JSON",WR)},GR="Other",Ch=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},Nr=e=>Rh[Ch(e)]?.name??GR,ps=e=>Rh[Ch(e)]?.comment??null,VR=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],zR=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,co=e=>zR.test(e)||VR.some(t=>t.test(e)),KR=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,qR=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,YR=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,$t=e=>KR.test(e)||qR.test(e)||YR.test(e),Nh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Ah=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Th=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),XR=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,JR=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,wh=e=>XR.test(e),Mh=e=>JR.test(e);var Ph=/\b(TODO|FIXME|HACK|XXX)\b/,QR=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,bc=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},ZR=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},Lh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,d=0,c=0;for(let p of e.files){if(p.binary||$t(p.path))continue;let f=ps(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=Nr(p.path),v=n.get(g)??{comment:0,code:0};for(let{text:I}of p.added){let x=bc(I,f);if(Ph.test(I)&&i++,x==="blank"){s++;continue}if(x==="comment"){r++,v.comment++,f&&QR.test(ZR(I,f))&&c++;continue}o++,v.code++}for(let{text:I}of p.removedLines)Ph.test(I)&&d++;n.set(g,v)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:d,commentedOutCodeLines:c}};var eC=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,ma=6,xc=10,tC=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},nC=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},rC=e=>{if(e.length<ma*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+ma<=e.length;r++){let o=e.slice(r,r+ma);if(o.some(d=>d.text.length<3))continue;let s=o.map(d=>d.text).join(`
|
|
91
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let d=0;d<ma;d++)n[i.at+d]=!0,n[r+d]=!0}return n.filter(Boolean).length},kh=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,d=null,c=[];for(let[m,p]of e.files.entries()){if($t(p.path)&&t.push(an(p)),Nh(p.path)&&n.push(an(p)),Ah(p.path)&&r.push(an(p)),Th(p.path)&&(o=!0),p.binary||$t(p.path))continue;let f=p.added.map(I=>I.text),g=tC(f),v=p.status!=="deleted";for(let I of f){eC.test(I)&&s++;let x=nC(I,g);x>i&&(i=x,d=an(p)),v&&c.push({text:I.trim(),file:m})}c.push({text:" ",file:m})}return{generatedPaths:t.slice(0,xc),dependencyManifests:n.slice(0,xc),buildOrCiPaths:r.slice(0,xc),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:d,duplicatedLines:rC(c)}};var Dh=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let d=i.addedCount+i.removed;if($t(i.path)){r+=d;continue}let c=Nr(i.path),m=n.get(c)??{name:c,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,co(i.path)&&(m.addedInTests+=i.addedCount),n.set(c,m)}let o=[...n.values()].reduce((i,d)=>i+d.added+d.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,d)=>d.added+d.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}};var oC=200,Ic=2e5,sC=5e4,Bh=25,iC=64*1024*1024,Sc="",aC=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,lC=/^diff --git a\/(.+) b\/\1$/,Fh=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Oh=(e,t)=>e===null?"added":t===null?"deleted":"modified",dC=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),cC=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,d=!1,c=0,m=(f,g)=>g==="modified"&&f==="added"?"added":g,p=(f,g)=>{let v=n.get(f);if(v)return v.entry.status=m(v.entry.status,g),v.entry.shas.includes(r)||v.entry.shas.push(r),v;let x={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,x),x};for(let f of t.split(`
|
|
92
|
+
`)){if(f.startsWith(Sc)){r=f.slice(Sc.length).trim(),o=null,s=null,i=null,d=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,d=!0,s=lC.exec(f)?.[1]??null;continue}if(d&&f.startsWith("Binary files ")&&s){let[,v=""]=/^Binary files (.*) differ$/.exec(f)??[],[I="",x=""]=v.split(" and ");o=p(s,Oh(I==="/dev/null"?null:I,x==="/dev/null"?null:x)),o.entry.binary=!0;continue}if(d&&f.startsWith("--- ")){i=Fh(f.slice(4),"a/");continue}if(d&&f.startsWith("+++ ")){let v=Fh(f.slice(4),"b/"),I=v??i??s;I&&(o=p(I,Oh(i,v)));continue}let g=aC.exec(f);if(g){c=Number(g[1]),d=!1;continue}if(o){if(f.startsWith("+")){let v=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<Ic&&(o.entry.added.push({sha:r,line:c,text:v}),e.retainedLines++),o.pendingByText.size<sC&&o.pendingByText.set(v,(o.pendingByText.get(v)??0)+1),c++;continue}if(f.startsWith("-")){let v=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<Ic&&(o.entry.removedLines.push({sha:r,line:0,text:v}),e.retainedLines++);let I=o.pendingByText.get(v)??0;I>0&&v.trim().length>2&&(e.selfChurn++,o.pendingByText.set(v,I-1))}}}},uC=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines});var _h=async({repoRoot:e,shas:t})=>{if(t.length===0)return u("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,oC).reverse(),r=dC(),o=0,s=0,i=!1;for(let c=0;c<n.length;c+=Bh){let m=n.slice(c,c+Bh),p=await U({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${Sc}%H`,...m]});if(a(p))return l(p.message);if(cC(r,p.value.stdout),o+=p.value.stdout.length,s+=m.length,o>iC){i=!0;break}}let d=uC(r);return u("Scanned ticket patch",{files:d.files,insertions:d.insertions,deletions:d.deletions,selfChurn:d.selfChurn,scannedCommits:s,truncated:i||s<t.length||d.retainedLines>=Ic})};var mC=40,pC=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Uh=async({repoRoot:e,sha:t})=>{let n=await He({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let p of n.stdout.split(`
|
|
93
|
+
`)){let f=pC.exec(p);if(!f)continue;let[,g="",v=""]=f;if($t(v))continue;let I=Nr(v);if(r.add(I),co(v)||!ps(v))continue;let x=o.get(I)??[];x.length<mC&&(x.push({blob:g,path:v}),o.set(I,x))}let s=[...o.values()].flat(),i=await ks(s.map(p=>p.blob),e);if(a(i))return{languages:r,commentShareByLanguage:new Map};let d=i.value,c=new Map;for(let{blob:p,path:f}of s){let g=d.get(p);if(g===void 0)continue;let v=ps(f),I=Nr(f),x=c.get(I)??{comment:0,code:0};for(let C of g.split(`
|
|
94
|
+
`)){let A=bc(C,v);A==="comment"&&x.comment++,A==="code"&&x.code++}c.set(I,x)}let m=new Map;for(let[p,f]of c){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var jh=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let d of e.files)if(!(d.binary||$t(d.path))&&co(d.path)){t+=d.addedCount,n+=d.removed,d.status==="added"&&r.push(an(d)),d.status==="deleted"&&o.push(an(d));for(let{text:c}of d.added)wh(c)&&s++,Mh(c)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var fC=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,$h=async({repoRoot:e,ref:t,commits:n})=>{let r=await _h({repoRoot:e,shas:n.map(d=>d.sha)});if(a(r))return l(r.message);let o=r.value,s=fC(n),i=s?await Uh({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:Eh({commits:n,patch:o}),languages:Dh({patch:o,languagesBefore:i?.languages??null}),tests:jh({patch:o}),comments:Lh({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:kh({patch:o})})};var gC=32,fs=new Map;var hC=(e,t)=>{if(fs.set(e,t),fs.size>gC){let n=fs.keys().next();n.done||fs.delete(n.value)}return t},pa=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return l("idOrRef must not be empty");let n=t.length>7?O(t):t.toUpperCase(),r=Se(e.repoRoot??process.cwd());if(a(r))return l(r.message);let o=r.value,s=await sa({repoRoot:o,ref:n});if(a(s))return l(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),d=[o,n,i.map(p=>p.sha).join(",")].join(" "),c=fs.get(d);if(c)return u("Derived issue stats",c);let m=await $h({repoRoot:o,ref:n,commits:i});return a(m)?l(m.message):u("Derived issue stats",hC(d,m.value))};var yC="Filed here",Hh=(e,t)=>e.set(t,(e.get(t)??0)+1),Wh=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?yC:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Gh=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let d of t)for(let[c,m]of d.entries()){if(m!==e)continue;s++,Hh(r,d[c-1]??null);let p=d[c+1];p!==void 0&&(i++,Hh(o,p))}return{arrived:s,departed:i,arrivesFrom:Wh(r,s,n),movesOnTo:Wh(o,i,n)}};var Vh=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var gs=1440*60*1e3,vC=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*gs,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[d,c]of i.entries()){let m=s.get(c.laneId);if(!m)continue;let p=i[d+1]?.enteredAt,f=Math.max(0,Math.ceil((c.enteredAt-o)/gs)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/gs)-1);for(let v=f;v<=g;v++)m[v].push(o+v*gs-c.enteredAt)}return Object.fromEntries([...s].map(([i,d])=>[i,d.map((c,m)=>({t:o+m*gs,median:Vh(c.sort((p,f)=>p-f)),count:c.length}))]))},zh=({laneId:e,journeys:t,now:n,days:r})=>vC({laneIds:[e],journeys:t,now:n,days:r})[e];var bC=40,xC=30,IC=()=>({tickets:0,commits:0,insertions:0,deletions:0}),SC=async(e,t)=>{let n=IC();for(let r of t.slice(0,bC)){let o=await pa({repoRoot:e,idOrRef:O(r)});a(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},Kh=async e=>{let t=V();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return l("Swimlane not found");let o=Object.values(n).filter(B),s=o.map(c=>Pd(c.log??[],Ce(c.id))),i=Gh(e.swimlaneId,s.map(c=>c.map(m=>m.laneId)),c=>n[c]?.title??"Elsewhere"),d=o.filter(c=>c.parentNodeId===e.swimlaneId).map(c=>c.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Ce(e.swimlaneId),...i,stayTrend:zh({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:xC}),code:await SC(e.repoRoot,d)})};var qh=new Set(["sync","issues:create","board:create","board:edit:title","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Yh=e=>{let t=Rn({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Gr(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Xh=e=>{let t=Rn();if(a(t))return l(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):l(`Not a recent project: ${e}`)};import{z as P}from"zod";var q=P.string().min(1),Jh=P.discriminatedUnion("at",[P.object({at:P.literal("start")}),P.object({at:P.literal("end")}),P.object({at:P.literal("before"),sibling:q}),P.object({at:P.literal("after"),sibling:q})]),hs=P.number().finite(),oe=(e,t)=>P.object({type:P.literal(e),payload:t}),fa=e=>P.object({type:P.literal(e)}),EC=P.discriminatedUnion("type",[fa("state:get"),fa("issues:list"),fa("sync"),fa("time-travel:live"),oe("project:open",P.object({root:P.string().min(1)})),oe("issues:create",P.object({title:P.string(),parentId:q,description:P.string().optional(),tagNames:P.array(P.string()).optional()})),oe("board:create",P.object({title:P.string()})),oe("board:edit:title",P.object({boardId:q,title:P.string()})),oe("swimlane:create",P.object({title:P.string(),boardId:q})),oe("swimlane:edit:title",P.object({swimlaneId:q,title:P.string()})),oe("swimlane:delete",P.object({swimlaneId:q})),oe("swimlane:move",P.object({swimlaneId:q,boardId:q,position:Jh.optional()})),oe("issues:move",P.object({issueId:q,parentId:q,position:Jh.optional()})),oe("issue:edit:title",P.object({issueId:q,title:P.string()})),oe("issue:edit:description",P.object({issueId:q,description:P.string()})),oe("issue:tag:add",P.object({issueId:q,tagName:P.string()})),oe("issue:tag:remove",P.object({issueId:q,tagId:q})),oe("contributor:remove",P.object({contributorId:q})),oe("tag:remove",P.object({tagId:q})),P.object({type:P.literal("contributors:get"),payload:P.object({boardId:q.optional()}).optional()}),oe("issue:assignee:add",P.object({issueId:q,assigneeId:q.optional(),assigneeName:P.string().optional(),createUnlinked:P.boolean().optional()})),oe("issue:assignee:remove",P.object({issueId:q,assigneeId:q})),oe("issue:close",P.object({issueId:q})),oe("issue:reopen",P.object({issueId:q})),oe("issue:comment:add",P.object({issueId:q,body:P.string()})),oe("issue:comment:delete",P.object({issueId:q,commentId:q})),oe("issue:comment:edit",P.object({issueId:q,commentId:q,body:P.string()})),oe("issue:get",P.object({issueId:q})),P.object({type:P.literal("timeline:get"),payload:P.object({start:hs.optional(),end:hs.optional(),boardId:q.optional(),requestId:P.number().finite().optional()}).optional()}),P.object({type:P.literal("commits:get"),payload:P.object({start:hs.optional(),end:hs.optional(),requestId:P.number().finite().optional()}).optional()}),oe("time-travel:scrub",P.object({targetTime:hs})),oe("time-travel:checkout-event",P.object({eventId:P.string().min(1)})),oe("commit:inspect",P.object({sha:P.string()})),oe("commit:diff:get",P.object({sha:P.string()})),oe("issue:commits:get",P.object({issueId:q})),oe("issue:stats:get",P.object({issueId:q})),oe("swimlane:stats:get",P.object({swimlaneId:q}))]);var Qh=e=>{let t=EC.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var CC=1024*1024,Ec=()=>{cr({type:"state",payload:Cr(Sr())})},se=(e,t)=>{e.send(JSON.stringify(t))},ys=async(e,t)=>{let n=Cr(await At({repoRoot:t}));return a(n)&&n.message===Ja?se(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Yh(t)}}):se(e,{type:"state",payload:n})},NC=async(e,t)=>{let n=()=>se(e,{type:"state",payload:Cr(Sr())});if(Ve().mode!=="live")return n();let r=await At({repoRoot:t});return Ve().mode!=="live"?n():se(e,{type:"state",payload:Cr(r)})},Le=async(e,t,n,r,o)=>{if(se(e,{type:r,payload:o}),a(o))return se(e,{type:"failed",payload:o.message});n(),NC(e,t)},Zh=(e,t,{onStateChanged:n,getPort:r})=>{new RC({server:e,path:"/ws",maxPayload:CC,verifyClient:s=>!yc(s.origin,r())}).on("connection",s=>{wm(s),s.on("message",async i=>{let d=async c=>{let{type:m}=c,p=t.repoRoot;if(m==="project:open"){let f=Xh(c.payload.root);return se(s,{type:"project:open:result",payload:f}),a(f)?void 0:(t.repoRoot=f.value,ys(s,f.value))}if(m==="timeline:get"){let{requestId:f,...g}=c.payload??{};return se(s,{type:"timeline",requestId:f,payload:await oh({repoRoot:p,...g})})}if(m==="issue:get"){let f=c.payload?.issueId,g=Sr(),v=Qd(f);return se(s,{type:"issue",payload:a(g)?g:u("Issue detail",{...xh(g.value,f),history:a(v)?[]:v.value})})}if(m==="commits:get"){let{requestId:f,...g}=c.payload??{};return se(s,{type:"commits",requestId:f,payload:await Od({repoRoot:p,...g})})}if(m==="commit:inspect")return se(s,{type:"commit:inspect:result",payload:await ih({repoRoot:p,sha:c.payload.sha})});if(m==="commit:diff:get"){let{sha:f}=c.payload;return se(s,{type:"commit:diff:result",payload:{sha:f,result:await ah({repoRoot:p,sha:f})}})}if(m==="issue:commits:get"){let{issueId:f}=c.payload;return se(s,{type:"issue:commits:result",payload:{issueId:f,result:await sa({repoRoot:p,ref:O(f)})}})}if(m==="issue:stats:get"){let{issueId:f}=c.payload;return se(s,{type:"issue:stats:result",payload:{issueId:f,result:await pa({repoRoot:p,idOrRef:O(f)})}})}if(m==="swimlane:stats:get"){let{swimlaneId:f}=c.payload;return se(s,{type:"swimlane:stats:result",payload:{swimlaneId:f,result:await Kh({repoRoot:p,swimlaneId:f})}})}if(m==="time-travel:scrub"){let f=await _d({repoRoot:p,targetTime:c.payload.targetTime});return se(s,{type:"time-travel:result",payload:f}),a(f)?void 0:Ec()}if(m==="time-travel:checkout-event"){let f=await dh({repoRoot:p,eventId:c.payload.eventId});return se(s,{type:"time-travel:result",payload:f}),a(f)?void 0:Ec()}if(m==="time-travel:live"){let f=await ch({repoRoot:p});return se(s,{type:"time-travel:result",payload:f}),a(f)?void 0:Ec()}if(m==="state:get")return ys(s,p);if(m==="sync"){let f=await as({repoRoot:p});return se(s,{type:"sync:result",payload:f}),n(),ys(s,p)}if(m==="issue:comment:add"){let f=await cs({repoRoot:p,...c.payload});return Le(s,p,n,"issue:comment:add:result",f)}if(m==="issue:comment:edit"){let f=await fc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:comment:edit:result",f)}if(m==="issue:comment:delete"){let f=await us({repoRoot:p,...c.payload});return se(s,{type:"issue:comment:delete:result",payload:f}),a(f)?se(s,{type:"failed",payload:f.message}):(n(),ys(s,p))}if(m==="issue:edit:description"){let f=await Zd({repoRoot:p,...c.payload});return Le(s,p,n,"issue:edit:description:result",f)}if(m==="issue:edit:title"){let f=await ec({repoRoot:p,...c.payload});return Le(s,p,n,"issue:edit:title:result",f)}if(m==="issue:tag:add"){let f=await ac({repoRoot:p,...c.payload});return Le(s,p,n,"issue:tag:add:result",f)}if(m==="issue:tag:remove"){let f=await dc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:tag:remove:result",f)}if(m==="contributor:remove"){let f=await uc({repoRoot:p,...c.payload});return Le(s,p,n,"contributor:remove:result",f)}if(m==="tag:remove"){let f=await lc({repoRoot:p,...c.payload});return Le(s,p,n,"tag:remove:result",f)}if(m==="contributors:get")return se(s,{type:"contributors",payload:await mc({repoRoot:p,...c.payload})});if(m==="issue:assignee:add"){let f=await cc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:assignee:add:result",f)}if(m==="issue:assignee:remove"){let f=await pc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:assignee:remove:result",f)}if(m==="issues:list")return se(s,{type:"issues",payload:await Kd({repoRoot:p})});if(m==="issues:create"){let f=await qd({...c.payload,repoRoot:p});return se(s,{type:"issues:create:result",payload:f}),a(f)?cr({type:"failed",payload:f.message}):(n(),ys(s,p))}if(m==="board:create"){let f=await tc({...c.payload,repoRoot:p});return Le(s,p,n,"board:create:result",f)}if(m==="board:edit:title"){let f=await nc({...c.payload,repoRoot:p});return Le(s,p,n,"board:edit:title:result",f)}if(m==="swimlane:create"){let f=await rc({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:create:result",f)}if(m==="swimlane:edit:title"){let f=await oc({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:edit:title:result",f)}if(m==="swimlane:delete"){let f=await ic({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:delete:result",f)}if(m==="swimlane:move"){if(!c.payload.position)return se(s,{type:"error",message:"Missing move position"});let f=await sc({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:move:result",f)}if(m==="issues:move"){if(!c.payload.position)return se(s,{type:"error",message:"Missing move position"});let f=await Jd({...c.payload,repoRoot:p});return Le(s,p,n,"issues:move:result",f)}if(m==="issue:close"){let f=await Yd({repoRoot:p,issueId:c.payload.issueId});return Le(s,p,n,"issue:close:result",f)}if(m==="issue:reopen"){let f=await Xd({repoRoot:p,issueId:c.payload.issueId});return Le(s,p,n,"issue:reopen:result",f)}return se(s,{type:"error",message:"Unknown message type"})};try{let c=Qh(JSON.parse(i.toString()));if(!c.ok)return se(s,{type:"error",message:c.error});let m=c.message;return qh.has(m.type)?await Xn(async()=>Ve().mode!=="live"?se(s,{type:"failed",payload:"Read-only while viewing history"}):d(m)):await d(m)}catch(c){return se(s,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var wC=Ar.dirname(TC(import.meta.url)),MC=process.env.IS_LOCAL==="true"?Ar.resolve(process.cwd(),"dist/gui"):Ar.join(wC,"gui"),ga,PC=async()=>(ga===void 0&&(ga=await import("node:sea").catch(()=>null)),ga?.isSea()?ga:null),Ee=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},LC=e=>Ee(e,409,{isError:!0,message:"Read-only while viewing history"}),ha=(e,t)=>Xn(async()=>Ve().mode!=="live"?LC(e):t()),ey=async(e,t=1024*1024)=>new Promise((n,r)=>{let o=[],s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),kC=2*1024*1024,DC={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},BC=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",ty=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=Ar.resolve(MC),o=Ar.resolve(r,n),s=Ar.relative(r,o);if(s.startsWith("..")||Ar.isAbsolute(s))return Ee(t,403,{isError:!0,message:"Forbidden"});let i=await PC();try{let d=i?Buffer.from(i.getAsset(`gui/${s}`)):await ny(o);return t.writeHead(200,{"content-type":BC(o)}),t.end(d)}catch{return Ee(t,404,{isError:!0,message:`Not found: ${n}`})}},FC=async(e,t=ms)=>new Promise((n,r)=>{let o=s=>{let i=c=>{if(e.off("listening",d),c.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(c)},d=()=>{e.off("error",i);let c=e.address();if(!c||typeof c=="string"){r(new Error("Unable to resolve address"));return}n(c.port)};e.once("error",i),e.once("listening",d),e.listen(s,"127.0.0.1")};o(t)}),ry=async e=>{Gg(!1);let t=0,n={repoRoot:e.repoRoot},r=AC.createServer(async(i,d)=>{let c=new URL(i.url??"/","http://127.0.0.1"),m=Sh({method:i.method,origin:i.headers.origin,contentType:i.headers["content-type"]},t);if(m)return Ee(d,m.status,{isError:!0,message:m.message});if(i.method==="GET"&&c.pathname===gc)return Ee(d,200,{app:hc,repoRoot:da(n.repoRoot),version:sn,pid:process.pid});if(c.pathname==="/api/state")return Ee(d,200,await At({repoRoot:n.repoRoot}));if(i.method==="POST"&&c.pathname==="/api/comments")try{let p=await ey(i);if(!p.issueId||!p.body?.trim())return Ee(d,400,{isError:!0,message:"Missing issueId or body"});let f=p.issueId,g=p.body;return await ha(d,async()=>{let v=await cs({repoRoot:n.repoRoot,issueId:f,body:g});return a(v)?Ee(d,400,{isError:!0,message:v.message}):Ee(d,200,await At({repoRoot:n.repoRoot}))})}catch(p){return Ee(d,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add comment"})}if(i.method==="POST"&&c.pathname==="/api/attachments")try{let p=await ey(i,kC);if(!p.issueId||!p.dataBase64)return Ee(d,400,{isError:!0,message:"Missing issueId or dataBase64"});let f=p.issueId,g=p.dataBase64,v=p.name??"";return await ha(d,async()=>{let I=await $d({repoRoot:n.repoRoot,issueId:f,name:v,dataBase64:g});return a(I)?Ee(d,400,{isError:!0,message:I.message}):Ee(d,200,{...await At({repoRoot:n.repoRoot}),attachment:I.value})})}catch(p){return Ee(d,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add attachment"})}if(i.method==="DELETE"&&c.pathname.startsWith("/api/attachments/")){let p=decodeURIComponent(c.pathname.replace("/api/attachments/",""));return p?ha(d,async()=>{let f=await Hd({repoRoot:n.repoRoot,attachmentId:p});return a(f)?Ee(d,400,{isError:!0,message:f.message}):Ee(d,200,await At({repoRoot:n.repoRoot}))}):Ee(d,400,{isError:!0,message:"Missing attachment id"})}if(i.method==="GET"&&c.pathname.startsWith("/media/")){let p=decodeURIComponent(c.pathname.replace("/media/","")),f=await Wd({repoRoot:n.repoRoot,fileName:p});if(a(f))return Ee(d,404,{isError:!0,message:f.message});try{let g=await ny(f.value.filePath);return d.writeHead(200,{"content-type":DC[f.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),d.end(g)}catch{return Ee(d,404,{isError:!0,message:"Attachment blob not found"})}}if(i.method==="DELETE"&&c.pathname.startsWith("/api/comments/")){let p=decodeURIComponent(c.pathname.replace("/api/comments/",""));return p?ha(d,async()=>{let f=await us({repoRoot:n.repoRoot,commentId:p});return a(f)?Ee(d,400,{isError:!0,message:f.message}):Ee(d,200,await At({repoRoot:n.repoRoot}))}):Ee(d,400,{isError:!0,message:"Missing comment id"})}return c.pathname.startsWith("/board/")||c.pathname==="/log"?ty("/",d):ty(c.pathname,d)});try{t=await FC(r)}catch(i){return l(i instanceof Error?`Unable to start GUI server: ${i.message}`:`Unable to start GUI server: ${String(i)}`)}let o=Ih({project:n});Zh(r,n,{onStateChanged:()=>o.queueSync(),getPort:()=>t}),r.on("close",o.dispose);let s=r.address();return!s||typeof s=="string"?(r.close(),l("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${s.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var sy=async e=>{let t=Lr({});if(a(t))return l(t.message);let n=bt();me(n)&&Ye(n.value);let r=await bh(ms);if(r&&r.repoRoot===da(e.repoRoot)){let i=`http://127.0.0.1:${ms}`;return console.log(`Epiq GUI already running for this project at ${oy.cyan(i)}`),rl(i),u("Reused running GUI",{url:i})}let o=await ry({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${oy.cyan(s)}`),rl(s),u("Started GUI",{url:s})};import{Box as nr}from"ink";import Re from"react";import{Box as Rc,Text as vs}from"ink";import Ht,{useEffect as OC,useMemo as _C}from"react";import{ulid as UC}from"ulid";var iy=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ht.createElement(vs,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),d=s.indexOf(i);return d===-1?Ht.createElement(vs,{color:n,dimColor:o},e):Ht.createElement(vs,{color:n,dimColor:o},e.slice(0,d),Ht.createElement(vs,{backgroundColor:r,bold:!0},e.slice(d,d+t.length)),e.slice(d+t.length))},ay=UC(),jC=e=>`${e}`,$C=e=>{let{pendingNavTarget:t}=Gn();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Ne(E.NONE,{breadCrumb:n,contextNode:r,readOnly:h().readOnly,selectedNode:o}));return[...new Set(Object.values(E))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==E.PALETTE).map(i=>{let d=Ai(i),c=Yi.find(m=>m.intent===d);return{command:i,description:c?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,d)=>i.isAvailable!==d.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(d.command))},HC=e=>be.text({id:ay,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),WC=(e,t,n)=>be.text({id:jC(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Cc=[],GC=e=>{ly();let t=R.createNode(HC(h().rootNodeId));a(t)||!Pn(t.value)||(Cc=[t.value,...e.map((n,r)=>WC(n,r,ay)).map(R.createNode).filter(me).map(({value:n})=>n).filter(Pn)],_.navigate({contextNode:t.value,selectedIndex:0}))},ly=()=>{let e=Cc.map(t=>t.id);Cc=[];for(let t of e)R.deleteNode(t)};function dy({width:e,height:t}){let r=Wp().value.trim().toLowerCase(),o=_C(()=>$C(r),[r]);OC(()=>(GC(o),()=>{ly()}),[o]);let s=h().selectedIndex;return Ht.createElement(Rc,{flexDirection:"column",width:e,height:t-2},Ht.createElement(Et,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,d)=>{let c=d===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ht.createElement(Rc,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ht.createElement(vs,{color:m,dimColor:!i.isAvailable},c?"\u276F ":" ",Ht.createElement(iy,{text:Au(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ht.createElement(Rc,{paddingLeft:2},Ht.createElement(iy,{text:p+i.description,match:r.length>=2?r:"",color:c&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as sN}from"ink";import ba from"react";import xs from"chalk";import{Box as Nc,Text as py}from"ink";import bs,{useEffect as fy,useMemo as VC,useState as gy}from"react";var uo=["\u2803","\u2806","\u2830","\u2818"],cy=120,uy=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%uo.length+uo.length)%uo.length;return uo[r]}return e?"?":":"},my=({infoMessage:e,isPending:t})=>t&&e.includes(ue)?"":e;var hy=xs.hex(y.secondary),zC=xs.inverse,KC=xs.inverse.hex(y.secondary2),qC={hint:"",hints:[],overlap:0,remainder:""},vy=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},YC=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ce(t);return{bg:r=>xs.bgHex(n).black(r),bgCursor:r=>xs.bgHex(n).inverse.black(r)}}return zl(t)},XC=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=vy({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},yy=()=>({value:Ze.value,cursorPosition:Ze.cursorPosition,commandIsPending:Ze.commandIsPending,autoCompletion:Ze.commandMeta.autoCompletion??qC,infoMessage:Ze.commandMeta.infoMessage,validationStatus:Ze.commandMeta.validity,command:Ze.commandMeta.command,inputString:Ze.commandMeta.inputString,modifier:Ze.commandMeta.modifier}),JC=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,by=({width:e,mode:t})=>{let[n,r]=gy(yy());fy(()=>{let M=()=>{let L=yy();r(k=>JC(k,L)?k:L)},w=Xl(M);return M(),()=>{w()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:d,autoCompletion:c,command:m,modifier:p,validationStatus:f}=n,g=d&&f===tn.Invalid,v=my({infoMessage:i,isPending:d}),[I,x]=gy(0);fy(()=>{if(!d){x(0);return}let M=setInterval(()=>{x(w=>(w+1)%uo.length)},cy);return()=>{clearInterval(M)}},[d]);let C=uy({isPalette:t===b.PALETTE,isPending:d,frame:I}),A=VC(()=>{let M=Math.max(0,Math.min(s,o.length)),w=vy({value:o,command:m}),L=XC({value:o,command:m,modifier:p}),k=m?zl(m):null,Ie=YC({command:m,modifier:p}),Ke=(qe,nt)=>{let Mr=w&&nt>=w.start&&nt<w.end,ka=L&&nt>=L.start&&nt<L.end;return Mr&&k?k.fg(qe):ka&&Ie?Ie.bg(qe):qe},Mt=(qe,nt)=>{let Mr=w&&nt>=w.start&&nt<w.end,ka=L&&nt>=L.start&&nt<L.end;return Mr&&k?k.fgCursor(qe):ka&&Ie?Ie.bgCursor(qe):zC(qe)},mt=o.slice(0,M),$e=o[M]??" ",An=M<o.length?o.slice(M+1):"",rr=Array.from(mt).map((qe,nt)=>Ke(qe,nt)).join(""),wr=Mt($e,M),ho=Array.from(An).map((qe,nt)=>Ke(qe,M+1+nt)).join("");if(c.hint){let qe=c.hint[c.overlap]??$e;wr=KC(qe),ho=hy(c.remainder.slice(1)+An)}return rr+wr+ho},[o,s,c,m,p]);return bs.createElement(Nc,{flexDirection:"column",justifyContent:"flex-start"},bs.createElement(Nc,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},bs.createElement(Nc,null,bs.createElement(py,null,hy(C),A),v&&bs.createElement(py,{wrap:"truncate",color:g?y.red:y.secondary2},` ${v} `))))};import{Box as QC,Text as Is}from"ink";import mo from"react";var xy=" ",ZC=({keys:e,label:t})=>e.length+1+t.length,eN=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?xy.length:0)+ZC(o);if(r+i>t-4)break;n.push(o),r+=i}return n},Iy=({width:e,availableHints:t})=>{let n=eN(t,e);return mo.createElement(QC,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?mo.createElement(Is,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>mo.createElement(Is,{key:`${o}-${s}`},i>0?xy:"",mo.createElement(Is,{color:y.accent},o),mo.createElement(Is,{color:y.secondary2}," ",s)))):mo.createElement(Is,{color:y.secondary2},"\xA0"))};import{Box as tN,Text as ya}from"ink";import Ss,{useEffect as nN,useRef as po,useState as rN}from"react";var oN=40,va=.3,Ac="\u2500",Sy=1,Ey=16,Ry=({width:e})=>{let{replay:t}=J(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Sy,[d,c]=rN(0),m=po(r);m.current=r;let p=po(0),f=po(0),g=po(0),v=po(0),I=po(0);if(nN(()=>{if(!n){p.current=0,g.current=0,v.current=0,I.current=0,c(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let w=setInterval(()=>{let L=Date.now(),k=m.current;if(k!==g.current){let $e=k-g.current,An=L-f.current;if($e<0)v.current=0,I.current=0;else if($e>0&&An>0){let rr=$e/An;v.current=v.current===0?rr:v.current*(1-va)+rr*va,I.current=I.current===0?$e:I.current*(1-va)+$e*va}p.current=k,f.current=L,g.current=k}let Ie=L-f.current,Ke=Math.min(I.current,v.current*Ie),Mt=Math.min(1,p.current+Ke),mt=Math.round(Mt*i);c($e=>$e===mt?$e:mt)},oN);return()=>clearInterval(w)},[n,i]),!t)return null;let x=w=>{let L=s>1?w/(s-1):0,k=Math.round(L*(Ey-1))/(Ey-1);return xi(k)},C=Math.min(s,Math.floor(d/Sy)),A=[];for(let w=0;w<C;w++){let L=x(w),k=A[A.length-1];k&&k.color===L?k.text+=Ac:A.push({text:Ac,color:L})}let M=Ac.repeat(Math.max(0,s-C));return Ss.createElement(tN,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},Ss.createElement(ya,{color:y.secondary2},"\u25B6"),Ss.createElement(ya,null,A.map((w,L)=>Ss.createElement(ya,{key:L,color:w.color},w.text)),Ss.createElement(ya,{color:y.secondary,dimColor:!0},M)))};var Es=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=J(),o=t===b.COMMAND_LINE||t===b.PALETTE;return ba.createElement(sN,null,o?ba.createElement(by,{width:e,mode:t}):r==="replay"?ba.createElement(Ry,{width:e}):ba.createElement(Iy,{width:e,mode:t,availableHints:n}))};import{Box as Zn,Text as fo}from"ink";import at,{useEffect as iN,useMemo as aN}from"react";import{ulid as Cy}from"ulid";var Ia=Cy(),lN=()=>[...new Set([...h().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(Cd).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),dN=e=>be.text({id:Ia,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),cN=(e,t,n)=>be.text({id:Cy(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),xa=[],Ny=()=>{let e=xa.filter(n=>n.id!==Ia).map(n=>n.id),t=xa.filter(n=>n.id===Ia).map(n=>n.id);xa=[];for(let n of[...e,...t])R.deleteNode(n)},uN=e=>{Ny();let t=R.createNode(dN(h().rootNodeId));if(a(t)||!Pn(t.value))return logger.error("Could not attach help nodes");xa=[t.value,...e.map((n,r)=>cN(n,r,Ia)).map(R.createNode).filter(me).map(({value:n})=>n).filter(Pn)],_.navigate({contextNode:t.value,selectedIndex:0})},Ay=({width:e,height:t})=>{let n=aN(()=>lN(),[]);iN(()=>(uN(n),()=>{Ny()}),[n]);let r=h().selectedIndex;return at.createElement(Zn,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},at.createElement(Zn,{paddingX:1,justifyContent:"center"},at.createElement(fo,{color:y.accent},"Help"),at.createElement(fo,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),at.createElement(Zn,{paddingX:1,marginTop:1},at.createElement(Zn,{width:20,justifyContent:"flex-end"},at.createElement(fo,{color:y.secondary},"Key(s)")),at.createElement(Zn,{flexGrow:1,width:40,paddingLeft:2},at.createElement(fo,{color:y.secondary},"Action"))),at.createElement(Et,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let d=i===r;return at.createElement(Zn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},at.createElement(Zn,{width:20,justifyContent:"flex-end"},at.createElement(fo,{color:y.accent},o)),at.createElement(Zn,{flexGrow:1,width:40,paddingLeft:2},at.createElement(fo,{color:d?y.primary:y.secondary2},s)))})))};import mN from"chalk";import{Box as Tr,Text as je}from"ink";import he from"react";var pN=8,fN=()=>{let e=Rn({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,pN)},Ty=({width:e,height:t})=>{let n=fN();return he.createElement(Tr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},he.createElement(je,{color:y.accent,bold:!0},"Initialize project"),he.createElement(je,null,`This folder is not an ${mN.hex(y.accent)("epiq")} project yet.`),he.createElement(je,{color:y.primary},"To start tracking issues here, we need to initialize a new",he.createElement(je,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),he.createElement(Tr,{marginTop:1,flexDirection:"column"},he.createElement(Tr,null,he.createElement(je,{color:y.accent}," "),he.createElement(je,{color:y.primary},"Type "),he.createElement(je,{backgroundColor:y.secondary}," :init "))),he.createElement(Tr,{marginTop:1},he.createElement(je,{color:y.secondary2},"This will create, commit and push "),he.createElement(je,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&he.createElement(Tr,{marginTop:1,flexDirection:"column"},he.createElement(je,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>he.createElement(Tr,{key:r.projectId},he.createElement(je,{color:y.accent},` ${o+1} `),he.createElement(je,{color:y.primary},Gr(r.root)),he.createElement(je,{color:y.secondary2},` ${r.root}`))),he.createElement(Tr,{marginTop:1},he.createElement(je,{color:y.accent}," "),he.createElement(je,{color:y.primary},"Type "),he.createElement(je,{backgroundColor:y.secondary}," :open 1 "),he.createElement(je,{color:y.secondary2}," or "),he.createElement(je,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as Sa,Text as ln}from"ink";import ze from"react";var gN=({isDone:e,command:t,value:n})=>ze.createElement(Sa,null,ze.createElement(ln,{color:y.accent,dimColor:e},e?" \u2714 ":" "),ze.createElement(ln,{dimColor:e},"Type "),ze.createElement(ln,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&ze.createElement(ze.Fragment,null,ze.createElement(ln,{dimColor:e}," "),ze.createElement(ln,{color:y.secondary,dimColor:e},"<"+n+">"))),hN=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Tc({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:d}=_n(),c=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:d,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=c.findIndex(f=>!f.done),p=m===-1?void 0:c[m];return ze.createElement(Sa,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},ze.createElement(ln,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),ze.createElement(ln,null,"Let's get you started - it's a breeze."),ze.createElement(ln,{color:y.secondary2},"Remember - you can always search available commands by typing:",ze.createElement(ln,{color:y.accent}," ? ")),p&&ze.createElement(ln,{color:y.secondary2},p.message),ze.createElement(Sa,{flexDirection:"column"},c.map((f,g)=>m===-1||g<=m?ze.createElement(Sa,{key:f.key,marginBottom:1},ze.createElement(gN,{isDone:f.done,command:f.command,value:f.done?hN(f.value):void 0})):null)))}import Aa from"chalk";import{Box as Cs,Text as go}from"ink";import ke from"react";import{Box as Ea,Text as wy}from"ink";import er from"react";import yN from"chalk";var vN=e=>(R.getTag(e)?.name??"").length+3,bN=e=>{let t=R.getContributor(e);return(t?t.name:"").length+3},My=({width:e})=>{let{viewMode:t}=le(),n=J(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,d=i[o.id]?.[s],c=ut(d?.id??o.id,"TICKET"),m=me(c)?c.value:void 0,p=(m?.props.tags??[]).filter(k=>R.getTag(k)),f=m?.props.assignees??[],g=m?.parentNodeId?!Md(o.id,m.parentNodeId)&&t==="dense":!1,v=r.map((k,Ie)=>{let Ke=Ie===r.length-1,Mt=de(k.id),mt=Ke?Mt?.[s]?.title:void 0;return`${Ie?" / ":""}${k.title??""}${mt?` \u25B8 ${mt}`:""}`}).join(""),I=m?R.getCommentsByIssue(m.id):[],x=I.length?String(I.length).length+11:0,C=g?p.reduce((k,Ie)=>k+vN(Ie),0)+f.reduce((k,Ie)=>k+bN(Ie),0)+x:0,A=d?.id!=null&&!(t==="wide"&&B(d)),M=Math.max(0,e-C),w=v.substring(0,M)+(A?yN.hex(y.secondary2).dim(` ${O(d.id)}`):""),L=g?[...p.map(k=>er.createElement(Ea,{key:`tag-${k}`,paddingLeft:1},er.createElement(Xr,{id:k}))),...f.map(k=>er.createElement(Ea,{key:`assignee-${k}`,paddingLeft:1},er.createElement($n,{id:k}))),I.length?er.createElement(Ea,{key:"comments",paddingLeft:1},er.createElement(wy,{color:y.accent},"[",I.length," comment",I.length===1?"":"s","]")):null]:[];return er.createElement(Ea,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},er.createElement(wy,{color:y.secondary2},w),L)};import{Box as xN,Text as Py}from"ink";import Ra from"react";var IN=({filters:e})=>Ra.createElement(xN,{columnGap:1},Ra.createElement(Py,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Ra.createElement(Py,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ly=Ra.memo(IN);import{Box as SN,Text as Ca}from"ink";import Rs from"react";function ky(){let{eventLog:e,unappliedEvents:t}=J(),n=e.at(-1)?.id,r=Us(n??""),o=me(r)?Li(r.value):"INVALID DATE";return Rs.createElement(SN,{paddingLeft:1},Rs.createElement(Ca,{backgroundColor:y.accent,color:y.secondary}," Readonly "),Rs.createElement(Ca,{color:y.accent}," "+t.length+" edits ago at "+o+"."),Rs.createElement(Ca,{color:y.accent}," Resume with "),Rs.createElement(Ca,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as EN,Text as wc}from"ink";import Na from"react";function Dy(){let{replay:e}=J();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Na.createElement(EN,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Na.createElement(wc,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Na.createElement(wc,{color:y.secondary2},Li(new Date(r))),Na.createElement(wc,{color:y.accent},`${t}/${n} edits`))}import Mc from"chalk";import{Box as RN,Text as By}from"ink";import Pc,{useEffect as CN,useState as NN}from"react";var AN=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],TN=150,Fy=12,wN=.36,Oy=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},MN=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},PN=(e,t,n)=>{let r=Oy(e),o=Oy(t);return MN({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},LN=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return PN(s,i,o)};function _y({syncStatus:e,autoSync:t}){let[n,r]=NN(0);CN(()=>{if(e.status!=="syncing"){r(0);return}let d=0,c=setInterval(()=>{d+=1;let m=(Math.sin(d*wN)+1)/2,p=Math.round(m*(Fy-1));r(f=>f===p?f:p)},TN);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,offline:y.secondary2,pending:y.secondary2,syncing:LN(AN,n/(Fy-1))??""}[e.status];return Pc.createElement(RN,null,Pc.createElement(By,null,Mc.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Pc.createElement(By,null,Mc.hex(i)("\u25CF")+Mc.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Wy from"chalk";import{Text as Gy}from"ink";import Vy,{useEffect as FN,useState as ON}from"react";import Lc from"chalk";var kN="https://registry.npmjs.org/epiq/latest",kc=null,Uy=0,DN=1e3*60*60*24,jy=e=>e.replace(/^v/,""),BN=(e,t)=>{let n=jy(e).split(".").map(Number),r=jy(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},$y=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(kc&&Date.now()-Uy<DN)return kc;try{let t=await fetch(kN);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?BN(r,e)>0:!1};return kc=o,Uy=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Hy=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Lc.hex(y.accent).dim(s):Lc.hex(y.secondary).dim(s)).join(Lc.hex(y.secondary2).dim("."))};function zy(){let[e,t]=ON({current:sn,latest:null,updateAvailable:!1});return FN(()=>{let n=!0;return $y(sn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Vy.createElement(Gy,{dimColor:!0,color:y.secondary2},sn+" "):Vy.createElement(Gy,null,Wy.hex(y.secondary2).dim(sn),Wy.hex(y.accent).dim(" \u2197 "),Hy(sn,e.latest))}function Ns({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=J(),{userName:i,preferredEditor:d,autoSync:c}=le(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?yn(s.currentLabel,Math.max(0,p)):"";return ke.createElement(Cs,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?ke.createElement(Cs,{paddingLeft:1},ke.createElement(go,{color:y.secondary2},g)):f?ke.createElement(go,null," "):o===b.PALETTE?ke.createElement(Cs,null,ke.createElement(go,{color:y.accent},"Command Palette"),ke.createElement(go,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):ke.createElement(Cs,{paddingLeft:1},e.length>0?ke.createElement(Ly,{filters:e}):ke.createElement(My,{width:p})),n==="live"?ke.createElement(Cs,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},ke.createElement(_y,{autoSync:!!c,syncStatus:r}),ke.createElement(go,null,Aa.hex(y.secondary2).dim("Mode: ")+Aa.hex(y.secondary2).dim(o.padEnd(8," "))," "),ke.createElement(Ky,{icon:"@",value:i}),ke.createElement(Ky,{icon:"\u276F",value:d}),ke.createElement(zy,null)):"",n==="peek"?ke.createElement(ky,null):"",n==="replay"?ke.createElement(Dy,null):"")}function Ky({icon:e,value:t}){return ke.createElement(go,null,Aa.dim(e)+Aa.hex(y.accent)(` ${t??"-"} `))}import{Box as _N,Text as UN}from"ink";import As from"react";import{Box as Ta,Text as Dc}from"ink";import tr from"react";function Bc(){let e=J(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?X(t?.id):[];return tr.createElement(Ta,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},tr.createElement(Ta,{padding:1,paddingTop:0,paddingBottom:0},tr.createElement(Dc,null,"Select a board:")),tr.createElement(Ta,{padding:1,flexDirection:"column"},i.map((d,c)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===c,f=X(d.id).flatMap(({id:g})=>de(g)).length;return tr.createElement(Ta,{key:d.id??c},tr.createElement(Dc,{color:m?y.accent:y.secondary2},tr.createElement(et,{isSelected:m})),tr.createElement(Dc,{color:m?y.accent:y.secondary2},d.title," (",f," issues)",d.readonly?" \u{1F512}":""))})))}var jN=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:d}=J(),c=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return As.createElement(_N,{flexDirection:"row"},e.context==="WORKSPACE"?As.createElement(Bc,null):c?As.createElement(Bi,{height:f,width:i,swimlanes:(d[c.id]??[]).filter(g=>g!==void 0&&Kt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):As.createElement(UN,null))},qy=As.memo(jN);import{useEffect as $N}from"react";var HN=e=>{$N(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=le();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:d,mode:c}=h();c==="default"&&!d&&mi(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Yy=({autoSync:e})=>(HN(e),null);function Fc({width:e,height:t}){let n=J(),{autoSync:r,viewMode:o}=vu(),s=n.filters;if(n.mode===b.HELP)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ay,{width:e,height:t}));if(n.mode===b.PALETTE)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{filters:s}),Re.createElement(dy,{width:e,height:t-2}),Re.createElement(Es,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=_n(),d=!i,c=i&&!n.hasProjectDefinition;if(d)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{hideBreadCrumb:!0,filters:s}),Re.createElement(Tc,{height:t,width:e})),Re.createElement(Es,{width:e,mode:n.mode,availableHints:[]}));if(c)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{hideBreadCrumb:!0,filters:s}),Re.createElement(Ty,{height:t,width:e})),Re.createElement(Es,{width:e,mode:n.mode,availableHints:[]}));let m=ot(n.breadCrumb??[],"BOARD");if(me(m)){let p=m.value.id,f=X(p).length,g=3,v=Math.floor(e/g),I=Math.floor(e/Math.max(f,1));e=Math.min(I,v)*Math.max(f,g)}return Re.createElement(nr,{flexDirection:"column"},Re.createElement(Yy,{autoSync:r}),Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{filters:s}),Re.createElement(qy,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),Re.createElement(Es,{width:e,mode:n.mode,availableHints:n.availableHints}))}import WN from"readline";var wa,Ma,dn,GN=new Set([S.MoveCursorLeft,S.EraseInputWord,S.MoveCursorLeftOfWord,S.MoveCursorRight,S.MoveCursorRightOfWord,S.NavToPreviousContainer,S.NavToNextContainer,S.NavPreviousItem,S.NavNextItem,S.SetViewDense,S.SetViewWide,S.Confirm,S.Exit,S.Yank,S.InitCommandLine,S.InitCommandPalette,S.ExitCommandLine,S.CaptureInput,S.EraseInput,S.EraseInputWord,S.HideHelp,S.ViewHelp,S.SetViewDense,S.SetViewWide,S.GetLastCommandFromHistory,S.GetNextCommandFromHistory,S.AutoCompleteCommand]),VN=new Set([S.NavPreviousItem,S.NavNextItem,S.NavToPreviousContainer,S.NavToNextContainer,S.Confirm,S.Exit,S.InitCommandPalette,S.InitMove,S.MoveNextItem,S.MovePreviousItem,S.MoveToNextContainer,S.MoveToPreviousContainer,S.Delete,S.AddItem,S.EditTitle,S.EditDescription,S.ConfirmMove,S.Edit,S.ViewHelp,S.Yank]),Xy=async e=>{if(e.ctrl&&e.name==="c")return _.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=h(),s=Gp(e,n);if(!s||r&&!GN.has(s)||o==="replay"&&n===b.DEFAULT&&VN.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(d){logger.error(d)}},zN=()=>async function(t,n){n.name!=="escape"&&(dn&&(clearTimeout(dn),dn=void 0),await Xy(n))},KN=()=>async function(t){if(t.length===1&&t[0]===27){dn&&clearTimeout(dn),dn=setTimeout(()=>{Xy({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),dn=void 0},25);return}dn&&(clearTimeout(dn),dn=void 0)};function Jy(){wa&&process.stdin.removeListener("keypress",wa),Ma&&process.stdin.removeListener("data",Ma),wa=zN(),Ma=KN(),WN.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Ma),process.stdin.on("keypress",wa)}async function Qy(){try{let e=Lr({});if(a(e))return _t(0,e.message);let t=bt();me(t)&&Ye(t.value);let n=Se(process.cwd()),r=me(n)?await $i(n.value):Xf();if(a(r))return r;let o=Oc();return a(o)?_t(6,o.message):(Jy(),me(n)&&Hi(n.value),u("Booted Epiq",void 0))}catch(e){return _t(0,jr(e))}}Pf();var JN=`${Wt.bold("Epiq CLI")}
|
|
91
95
|
|
|
92
|
-
${
|
|
93
|
-
${
|
|
96
|
+
${Wt.dim("Boot in directory:")}
|
|
97
|
+
${Wt.cyan("$ epiq")}
|
|
94
98
|
|
|
95
|
-
${
|
|
96
|
-
${
|
|
99
|
+
${Wt.dim("Launch GUI:")}
|
|
100
|
+
${Wt.cyan("$ epiq gui")}
|
|
97
101
|
|
|
98
|
-
${
|
|
99
|
-
${
|
|
100
|
-
`,
|
|
101
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
102
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
102
|
+
${Wt.dim("Act as somebody other than the configured user:")}
|
|
103
|
+
${Wt.cyan("$ epiq --as claude")}
|
|
104
|
+
`,_c=YN(JN,{importMeta:import.meta,version:sn,flags:{init:{type:"boolean",default:!1},as:{type:"string"}}}),Pa=_c.input[0];Pa&&Pa!=="gui"&&(console.error(Wt.red(`Unknown command: ${Pa}`)),process.exit(1));if(_c.flags.as!==void 0){let e=Fa(_c.flags.as,"--as");a(e)&&(console.error(Wt.red(e.message)),process.exit(1))}var Zy=process.stdout.columns||120,ev=process.stdout.rows||20,La=null,QN=e=>{try{return La?(La.rerender(e),u("Rerendered app",void 0)):(La=qN(e),u("Rendered app",void 0))}catch(t){return l(`Unable to render app: ${jr(t)}`)}},Oc=()=>QN(XN.createElement(Fc,{width:Zy,height:ev}));process.stdout.on("resize",()=>{if(Zy=process.stdout.columns||120,ev=process.stdout.rows||20,!La)return;let e=Oc();a(e)&&logger.info(`[boot:resize] ${e.message}`)});if(Pa==="gui"){let e=await sy({repoRoot:process.cwd()});a(e)&&(console.error(Wt.red(`Failed to start Epiq GUI:
|
|
105
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await Qy();a(e)&&(logger.info(e.message),console.error(Wt.red(`Failed to boot Epiq:
|
|
106
|
+
${e.message}`)),process.exitCode=1)}export{Oc as renderApp};
|