epiq 1.3.1 → 1.3.3
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 +1 -1
- package/dist/index.js +36 -36
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,67 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Qt from"chalk";import{render as
|
|
3
|
-
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import Qt from"chalk";import{render as gv}from"ink";import yv from"meow";import vv from"react";import ry from"chalk";var Pt={Success:"success",Fail:"fail"},a=e=>({status:Pt.Fail,message:e,value:null}),l=(e,t)=>({status:Pt.Success,message:e,value:t}),d=e=>e.status==="fail",te=e=>e.status==="success";import{spawn as Eu}from"node:child_process";import ds from"node:process";var ki=e=>{let t=ds.platform==="darwin"?"open":ds.platform==="win32"?"cmd":"xdg-open",n=ds.platform==="win32"?["/c","start","",e]:[e];Eu(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as wl}from"node:fs/promises";import qg from"node:http";import yn from"node:path";import{fileURLToPath as Yg}from"node:url";import{decodeTime as dl,ulid as ge}from"ulid";import xs from"node:fs";import Bu from"node:os";import nt from"node:path";import Gn from"node:fs";import{ulid as Su}from"ulid";import{z as kr}from"zod";import Wn from"node:fs";import st from"node:path";var Mv=process.env.IS_LOCAL==="true",it=".epiq",qe=".epiq-global",Mr="events",cs="media",Cu="project.json",jn=e=>st.join(e,it),Pr=e=>st.join(jn(e),Cu),Vn=e=>st.join(jn(e),Mr),Kn=e=>st.join(jn(e),cs),Di=e=>st.join(e,it),Nu=e=>{let t=st.join(e,it);return Wn.existsSync(t)&&Wn.statSync(t).isDirectory()},ls=e=>{let t=Pr(e);return Wn.existsSync(t)&&Wn.statSync(t).isFile()},Lr=e=>{let t=st.resolve(e);for(;;){if(Nu(t))return l("Resolved closest .epiq root",t);let n=st.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ye=e=>{let t=st.resolve(e);for(;;){if(ls(t))return l("Resolved closest epiq project root",t);let n=st.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Fi=e=>{let t=Vn(e);try{return Wn.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},at=async()=>{let e=await dt(process.cwd());if(d(e))return e;let t=Pe({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var Au="__epiq_state__",Ru=kr.object({projectId:kr.string().min(1),stateBranch:kr.string().min(1),createdAt:kr.iso.datetime()}),vn=()=>({projectId:Su(),stateBranch:Au,createdAt:new Date().toISOString()}),Lt=e=>{let t=Pr(e);if(!Gn.existsSync(t))return a("Missing .epiq/project.json");try{let n=Gn.readFileSync(t,"utf8"),r=JSON.parse(n),o=Ru.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Bi=e=>{let t=Lt(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},Ui=({repoRoot:e,fileContents:t})=>{let n=jn(e),r=Pr(e);try{if(Gn.mkdirSync(n,{recursive:!0}),Gn.existsSync(r)){let o=Lt(e);return d(o)?a(o.message):l("Project already initialized",null)}return Gn.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var us=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import zn from"fs";import gs from"path";import Tu from"util";var Oi=1e3,wu=50,ms=0,_i=()=>process.env.EPIQ_MCP==="true",$i=()=>{let e=process.cwd(),t=Lr(e);return d(t)?_i()?gs.join(process.cwd(),".epiq-mcp.log"):void 0:gs.join(t.value,it,"log","epiq.log")};function Mu(){let e=$i();if(!e||!zn.existsSync(e))return;let n=zn.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Oi)return;let r=n.slice(-Oi).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;zn.writeFileSync(e,r,"utf8")}function
|
|
7
|
-
`;zn.mkdirSync(
|
|
8
|
-
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))}
|
|
6
|
+
`;zn.writeFileSync(e,r,"utf8")}function ps(e,t,n=!1){let r=$i();if(!r)return;let o=Tu.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
+
`;zn.mkdirSync(gs.dirname(r),{recursive:!0}),zn.appendFileSync(r,c,"utf8"),ms++,ms>=wu&&(ms=0,Mu())}var fs=()=>_i()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",oe={info(...e){let t=fs();(t==="info"||t==="debug")&&ps("[Info]",e,!1)},debug(...e){fs()==="debug"&&ps("[Debug]",e,!0)},error(...e){let t=fs();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;ps("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=oe;import{spawn as Pu}from"node:child_process";import Dr from"node:fs";import qn from"node:path";var de={stage:({cwd:e,pathspec:t})=>_({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>_({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>_({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>_({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return _({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})};var hn=e=>{let t=Ye(e);if(d(t))return a("Unable to resolve epiq project root");let n=Lt(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},Xe="origin";var Hi=1e4,Lu={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Wi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Dr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=Pu("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Lu}),s=!1,i="",c="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Hi}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},Hi);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:i,stderr:p.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
9
9
|
`)))}),o.on("close",p=>{let f=p??1;if(n){u({stdout:i,stderr:c,exitCode:f});return}if(f!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
-
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),_=({args:e,cwd:t})=>
|
|
10
|
+
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),_=({args:e,cwd:t})=>Wi({args:e,cwd:t,allowFail:!1}),ct=({args:e,cwd:t})=>Wi({args:e,cwd:t,allowFail:!0}),xn=async({cwd:e,message:t})=>{let n=await de.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
11
|
${n.message}`);let r=await _({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
12
|
-
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},
|
|
13
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Yn).includes(r);return l("Checked worktree registration",o)},
|
|
12
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},ku=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",qn.isAbsolute(n)?n:qn.resolve(e,n))},Du=async e=>{let t=await ku(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Dr.existsSync(qn.join(n,s)))return l("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(Dr.existsSync(qn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},Fr=async e=>{let t=await Du(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},ys=async({repoRoot:e})=>{let n=(await ct({args:["remote","get-url",Xe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},Br=async({repoRoot:e,branch:t})=>{let n=await ct({args:["ls-remote","--heads",Xe,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Xe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Ur=async({repoRoot:e,branch:t})=>{let n=await ct({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},Yn=e=>{try{return Dr.realpathSync.native(e)}catch{return qn.resolve(e)}},ji=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=Yn(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Yn).includes(r);return l("Checked worktree registration",o)},vs=async e=>{let t=await ct({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Or=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},Vi=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Ki=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Fu=async e=>(await ct({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1);var hs=async({cwd:e,branch:t})=>{let n=await Br({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await Fu(e);if(d(r))return a(r.message);let o=await de.fetch({cwd:e,remote:Xe,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
14
14
|
${o.message}`);let s=await de.pullRebase({cwd:e,remote:Xe,branch:t});return d(s)?a(`Failed during pull --rebase
|
|
15
|
-
${s.message}`):l("Pulled with rebase",!0)},
|
|
15
|
+
${s.message}`):l("Pulled with rebase",!0)},Gi=async e=>{let t=await ct({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?l("No staged changes",!1):t.exitCode===1?l("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var zi=async e=>{let t=await Or(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Yi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",bs=e=>nt.join(it,Mr,e),Xi=()=>nt.join(it,cs),Ji=()=>nt.join(Bu.homedir(),qe),_r=()=>nt.join(Ji(),"worktrees"),Pe=({repoRoot:e})=>{let t=Bi(e);return d(t)?a(t.message):l("Resolved state branch root",nt.join(_r(),t.value))},Uu=e=>nt.join(e,it),qi=e=>nt.join(Uu(e),Mr);var Xn=e=>{try{return xs.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},$r=()=>{let e=Xn(Ji());if(d(e))return a(`Ensure epiq home failed.
|
|
16
16
|
`+e.message);let t=Xn(_r());return d(t)?a(`Ensure worktrees dir failed.
|
|
17
|
-
`+t.message):l("Ensured epiq storage",!0)},
|
|
17
|
+
`+t.message):l("Ensured epiq storage",!0)},Qi=e=>{xs.existsSync(e)&&(oe.debug("[sync] remove path",e),xs.rmSync(e,{recursive:!0,force:!0}))};var Zi=(e,t)=>{for(let n of[qi(e),qi(t)]){let r=Xn(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},ea=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
18
18
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
19
19
|
`).filter(Boolean).filter(i=>i!==it);if(r.length===0)return l("State branch is storage-only",!1);let o=await _({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
20
|
-
${o.message}`);let s=await xn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},dt=
|
|
20
|
+
${o.message}`);let s=await xn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},dt=us(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>nt.resolve(e)),xh=us(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=nt.isAbsolute(n)?n:nt.join(e,n);return l("Resolved git dir",r)},e=>nt.resolve(e));import Zt from"node:fs";import Hr from"node:path";var na=async e=>{if((await ct({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);oe.info("Creating initial commit");let n=await de.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},ta=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Ou=async e=>{let t=await Or(e);if(d(t))return a(t.message);let n=await Vi(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${ta(t.value)}:sha:${ta(n.value)}]`)},Is=async({repoRoot:e,stateBranchName:t})=>{oe.info(`Creating ${t}`);let n=await _({args:["commit-tree",Yi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
21
21
|
${n.message}`);let r=n.value.stdout.trim(),o=await _({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
22
|
-
${o.message}`):l("Created state branch",!0)},
|
|
22
|
+
${o.message}`):l("Created state branch",!0)},_u=async({repoRoot:e,stateBranchName:t})=>{let n=await ys({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
23
23
|
`+n.message);let r=n.value,o=r?await Br({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
24
24
|
`+o.message);let s=o.value;if(r&&s){let c=await de.fetch({cwd:e,remote:Xe,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
25
25
|
${c.message}`)}let i=await Ur({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
|
|
26
26
|
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await _({args:["branch","--track",t,`${Xe}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
27
|
-
${c.message}`):l("Created local state branch from remote",!0)}return
|
|
28
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)}
|
|
29
|
-
`+r.message);Zt.existsSync(t)&&!Zt.existsSync(Hr.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),
|
|
30
|
-
${o.message}`):l("Created state branch worktree",!0)},en=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await
|
|
27
|
+
${c.message}`):l("Created local state branch from remote",!0)}return Is({repoRoot:e,stateBranchName:t})},$u=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
28
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},Hu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Xn(Hr.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
29
|
+
`+r.message);Zt.existsSync(t)&&!Zt.existsSync(Hr.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),Qi(t)),oe.info("Creating state branch worktree");let o=await de.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
30
|
+
${o.message}`):l("Created state branch worktree",!0)},en=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await $u({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=Yn(t),s=r.value?Yn(r.value):null;if(s&&s===o&&Zt.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){oe.info("Moving state branch worktree to expected location");let u=await de.worktreeRemove({cwd:e,worktreeRoot:s});if(d(u))return a(`Failed to remove existing state branch worktree
|
|
31
31
|
${u.message}`)}if(s&&!Zt.existsSync(s)){oe.info("Pruning stale state branch worktree");let u=await de.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
32
|
-
${u.message}`)}let i=await
|
|
33
|
-
${u.message}`)}return
|
|
34
|
-
${o.message}`):l("Checked out state branch",!0)},
|
|
32
|
+
${u.message}`)}let i=await ji({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=Zt.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){oe.info("Pruning missing registered state branch worktree");let u=await de.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
33
|
+
${u.message}`)}return Hu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Wu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Or(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await ct({cwd:e,args:["rebase","--abort"]})).exitCode===0&&oe.info("Aborted stale state branch rebase");let o=await de.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
34
|
+
${o.message}`):l("Checked out state branch",!0)},ju=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vs(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await ys({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=hn(e);if(d(o))return o;let s=o.value,i=await Br({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);oe.info(`Configuring ${s} upstream`);let c=await de.fetch({cwd:t,remote:Xe,branch:s});if(d(c))return a(`Failed to fetch ${s}
|
|
35
35
|
${c.message}`);let u=await de.setUpstream({cwd:t,branch:s,upstream:`${Xe}/${s}`});return d(u)?a(`Failed to set state branch upstream
|
|
36
|
-
${u.message}`):l("Configured state branch upstream",!0)},Wr=async({stateBranchRoot:e,eventFileName:t})=>{let n=
|
|
37
|
-
${o.message}`):l("Staged state branch event file",void 0)},
|
|
38
|
-
${r.message}`):l("Staged state branch media files",void 0)},
|
|
39
|
-
`+n.message):xn({cwd:t,message:n.value})},Jn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await
|
|
40
|
-
${s.message}`):l("Pushed state branch",!0)},oa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=hn(e);if(d(o))return o;let s=o.value,i=[$r(),await Ou({repoRoot:e,stateBranchName:s}),await en({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Hu({stateBranchRoot:t,stateBranchName:s}),await Zi(t),n?await Wu({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as ju}from"ws";var jr=new Set,sa=e=>{jr.add(e),e.on("close",()=>{jr.delete(e)}),e.on("error",()=>{jr.delete(e)})},tn=e=>{let t=JSON.stringify(e);for(let n of jr)n.readyState===ju.OPEN&&n.send(t)};import{useSyncExternalStore as Hg}from"react";var L={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Is(e){return e.context===L.WORKSPACE}function A(e){return e.context===L.TICKET}function kt(e){return e.context===L.TEXT}function Oe(e){return e.context===L.FIELD}function Qn(e){return e.context===L.FIELD_LIST}var Dt=e=>e.context===L.SWIMLANE,Vr=e=>e.context===L.BOARD,Zn=e=>e.context===L.COMMENT;var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var ia=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",aa=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",da=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",ca=(e,t)=>{if(aa(e,e.sequence))return h.MoveCursorLeftOfWord;if(da(e,e.sequence))return h.MoveCursorRightOfWord;if(ia(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},la=(e,t)=>{if(aa(e,e.sequence))return h.MoveCursorLeftOfWord;if(da(e,e.sequence))return h.MoveCursorRightOfWord;if(ia(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Kr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var nn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",lt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ua=e=>e.charAt(0).toUpperCase()+e.slice(1);var ma=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},pa=(e,t)=>t?e.get(t)??[]:[];var fa=new WeakMap,Vu=e=>{let t=fa.get(e);return t||(t=ma(e),fa.set(e,t)),t};var ga=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return pa(Vu(e),r).filter(s=>Kr(r,s)>=n)};var Ku={hint:"",hints:[],overlap:0,remainder:""},ya=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Ku;let o=ga({wordList:r,inputToMatch:e,overlapThreshold:1});return Gu(t,o)},Gu=(e,t)=>{let n=t[0]??"",r=Kr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{useSyncExternalStore as zu}from"react";var er={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Es=new Set,qu=()=>{for(let e of Es)e()},K=()=>er,va=()=>zu(e=>(Es.add(e),()=>{Es.delete(e)}),()=>er),Fe=e=>(er={...er,...e},qu(),er);import{ulid as Ju}from"ulid";var bn=24n,Yu=bn*4n,rt=(1n<<Yu)-1n,Xu=/^[0-9a-f]+$/;function ha(e){return!e||!Xu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function _e(e,t=bn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Be(e,t){if(!e&&!t)return _e(rt/2n,bn);let n=e?ha(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?ha(t):l("Resolved upper bound",rt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return _e(rt/2n,bn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):_e(i,bn)}function xa(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=rt*BigInt(r+1)/(t+1n),s=_e(o,bn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var Cs=(e,t)=>{let n=q(e),r=xa(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:Ju(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as Zm}from"ulid";var It=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Ns=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},rn=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),I={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=he(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){he(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(!A(t))return a("Can only comment on issues");let n=he(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("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(!A(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=he(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("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=he(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!A(t))return a("Can only attach to issues");let n=he(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):l("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=he(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return a("Edit target node not found");let o=rn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=rn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return q(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),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=rn(o,"move");if(i)return i;if(Ns(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of q(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(E({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("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=rn(r,"edit");if(o)return o;if(!A(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),l("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=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("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=rn(r,"edit");if(o)return o;if(!A(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),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(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=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return q(e)}};var J={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var Ue=e=>e.slice(-7).toUpperCase(),ba=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Ue(e).includes(n):!0};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:L.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:Ue(e)},context:L.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.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:L.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:L.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:Ue(e)},context:L.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:L.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:L.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Ft from"chalk";import Ra from"string-width";import{decodeTime as rm}from"ulid";import En from"chalk";var Se={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"},v={accent:Se.cyan,accent2:Se.magenta,primary:Se.white,secondary:Se.grayDark,secondary2:Se.grayLight,gray:Se.gray,green:Se.green,yellow:Se.yellow,red:Se.red};var C={red:Se.red,yellow:Se.yellow,green:Se.green,blue:Se.blue,magenta:Se.magenta,cyan:Se.cyan},In={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var As={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ia=(e,t,n)=>Math.max(t,Math.min(n,e)),Ss=(e,t,n)=>e+(t-e)*n,Ea=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Qu=e=>e.toLowerCase().trim(),Zu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Ca=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var em=(e,t,n)=>{let r=Ia(n,0,1);return[Math.round(Ss(e[0],t[0],r)),Math.round(Ss(e[1],t[1],r)),Math.round(Ss(e[2],t[2],r))]};var tm=(e,t,n)=>em(e,t,n),tr=e=>{let n=Ea(e)%360,r=Zu(n,As.stringColor.saturation,As.stringColor.lightness);return Ca(r)},le=(e,t=In)=>{let n=Qu(e);return n&&t[n]?t[n]:tr(n)};var Na=e=>{let t=As.gradient.stops,n=Ia(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 tm(t[s],t[s+1],i)},Gr=e=>Ca(Na(e)),zr=e=>Ea(e.toLowerCase().trim())/4294967295,Sa=e=>{let t=zr(e);return Na(t)},nm=e=>{let[t,n,r]=Sa(e);return{normal:o=>En.bgRgb(t,n,r).black(o),cursor:o=>En.bgRgb(t,n,r).white.bold(o)}},Rs=e=>{let[t,n,r]=Sa(e);return{fg:o=>En.rgb(t,n,r)(o),fgCursor:o=>En.rgb(t,n,r).inverse(o),bg:o=>En.bgRgb(t,n,r).black(o),bgCursor:o=>En.bgRgb(t,n,r).white.bold(o)}},qr=e=>nm(e).normal(` ${e} `);import{decodeTime as Aa}from"ulid";var Cn=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"},Yr=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Xr=e=>{try{return l("Decoded date",new Date(Aa(e)))}catch(t){return a("Decoding failed + "+t.message)}},Nn=e=>{if(!e?.id)return null;try{return Aa(e.id)}catch{return null}};var om=(e,t)=>e+" ".repeat(Math.max(0,t-Ra(e))),sm=(e,t)=>" ".repeat(Math.max(0,t-Ra(e)))+e,Ta=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),im=(e,t)=>t?e<t?"up":e>t?"down":null:null,am=(e,t)=>{let n=I.getNode(e.payload.parent),r=n?Ft.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=im(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},wa=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ma=e=>I.getAttachment(e)?.name??"",dm=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(le(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(le(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(le(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(le(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Ft.dim(`(${wa(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ma(e.payload.id);return t?`"${t}"`:""}default:return""}},cm=e=>{let t=Cn(rm(e));return Ft.gray(sm(t,8))},lm=12,um=e=>om(`${e}`,lm),mm=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${wa(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ma(e.payload.id);return t?`"${t}"`:""}default:return""}},Pa=e=>[Ta(e.action),mm(e)].filter(Boolean).join(" "),La=(e,t)=>{let n=cm(e.id),r=um(e.userName),o=Ft.dim("\u203A"),s=e.action==="move.node"?am(e,t):[Ta(e.action),dm(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as pm}from"node:crypto";var fm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",gm=e=>{let t=pm("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+=fm[Number(n>>s&31n)]}return r},xe=(e,t)=>gm(`${e}:virtual:${t}`);var ym=e=>xe(e,"comments"),vm=e=>xe(e,"description"),hm=e=>xe(e,"assignees"),xm=e=>xe(e,"tags"),bm=e=>xe(e,"history"),Im=e=>xe(e,"attachments"),Jr=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Oe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},ka=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=I.getNode(e);if(!i){let m=I.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Qn(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 l("Virtual field list unchanged",void 0);let u=I.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},Da=e=>{let t=_e(rt/4n),n=_e(rt/2n),r=_e(rt*3n/4n),o=_e(rt*7n/8n),s=_e(rt*15n/16n),i=_e(rt*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 c=Jr({id:vm(e.id),name:J.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let u=ka({id:hm(e.id),name:J.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(u))return u;let m=ka({id:xm(e.id),name:J.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=Jr({id:ym(e.id),name:J.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=Jr({id:Im(e.id),name:J.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let b=Jr({id:bm(e.id),name:J.HISTORY,parentNodeId:e.id,rank:i.value,value:Em(e),readonly:!0,childRenderAxis:"vertical"});return d(b)?b:l("Ticket virtual nodes materialized",void 0)},Em=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=>La(r,n.get(r.action)??[])).join(`
|
|
41
|
-
`)};var Cm=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[me,Qr]=Cm;var k=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Fa=e=>{let t=I.getNode(e);if(!t||!A(t)||t.isDeleted)return null;let n=Da(t);return d(n)?n:null},Nm=e=>{for(let t of e){let n=Fa(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Fa(r);if(o)return o}return null},Sm=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Am=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ts=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 Am(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"create.contributor":case"link.contributor.user":default:return[]}},Rm=e=>{he(t=>({...t,eventLog:[...t.eventLog,e]}))},Tm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?k("Invalid user ID format",e):l("Valid user",null)},wm=(e,t)=>{let n=Tm(e);if(d(n))return n;let r=[...new Set(Ts(e))];t||(r.forEach(s=>Sm(s,e)),Rm(e));let o=Nm(r);return o||null},Mm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=nr(o);if(d(s))return k(s.message,e);let i=I.createNode(o);return d(i)?k(i.message??"Failed to initialize workspace",e):Is(i.value)?l("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=I.createNode(Q.workspace(t,n,r));return d(o)?k(o.message??"Failed to add workspace",e):Is(o.value)?l("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.board(t,n,r,o));return d(s)?k(s.message??"Unable to create board",e):Vr(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.swimlane(t,n,r,o));return d(s)?k(s.message??"Unable to create swimlane",e):Dt(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.ticket(t,n,r,o));return d(s)?k(s.message??"Unable to create issue",e):A(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=I.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(J.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?k(i.message??`Unable to create field: ${n}`,e):Oe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.tag(t,n);return d(r)?k(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.untag(t,n);return d(r)?k(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.assign(t,n);return d(r)?k(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!A(o))return k("Can only close issues",e);let s=I.getNode(me);if(!s)return k("Unable to locate target swimlane",e);if(n!==s.id)return k("Close target must be closed swimlane",e);let i=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?k(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!A(o))return k("Can only reopen issues",e);let s=I.getNode(me);if(!s)return k("Unable to locate closed swimlane",e);if(n===s.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("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=I.getNode(r);if(!s)return k(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let i=I.updateNode({...s,rank:o});if(d(i))return k(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=I.createComment({id:t,issue:n,authorId:r,authorName:I.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?k(s.message??"Unable to add comment",e):l("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=I.getComment(t);if(!o)return k("Unable to locate comment",e);if(o.issue!==n)return k("Comment does not belong to issue",e);let s=I.editComment(t,r);return d(s)?k(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=I.getComment(t);if(!r)return k("Unable to locate comment",e);if(r.issue!==n)return k("Comment does not belong to issue",e);let o=I.deleteComment(t);return d(o)?k(o.message??"Unable to delete comment",e):l("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,c=I.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?k(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=I.getAttachment(t);if(!r)return k("Unable to locate attachment",e);if(r.issue!==n)return k("Attachment does not belong to issue",e);let o=I.deleteAttachment(t);return d(o)?k(o.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return d(n)?k(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Bt(e,t=!1){let n=Mm[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=wm(e,t);return o||r}var Ut=e=>e.map(t=>Bt(t));import jm from"node:fs";import Vm from"node:path";import{decodeTime as Km,monotonicFactory as Gm}from"ulid";import{z as rr}from"zod";import Zr from"node:fs";import Ms from"node:path";import{decodeTime as km}from"ulid";import{z as ws}from"zod";var Pm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.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 Lm=new Set(Pm),Ba=e=>Lm.has(e),Ua=e=>({action:e.action,payload:e.payload});var Dm=ws.object({userId:ws.string().min(1).default("unknown"),userName:ws.string().min(1).default("unknown")}),Fm=e=>{let[t,n]=Ms.basename(e,".jsonl").split("."),r=Dm.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${Ms.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Bm=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Um=(e,t)=>t in e,Om=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),_m=e=>{let{userId:t,userName:n,...r}=e,o=Bm(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Um(r,s)?l("Decoded persisted event",Om({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Ps=e=>{let t=[],n=new Map;for(let r of e){let o=_m(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!Ba(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");oe.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return l("Decoded reconstructed events",t)},$m=e=>{if(!Zr.existsSync(e))return l("Event file missing",[]);let t=Fm(e);if(d(t))return a(t.message);let n=Zr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
42
|
-
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=
|
|
43
|
-
`,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function
|
|
36
|
+
${u.message}`):l("Configured state branch upstream",!0)},Wr=async({stateBranchRoot:e,eventFileName:t})=>{let n=bs(t),r=Hr.join(e,n);if(!Zt.existsSync(r))return l("No event file to stage",void 0);let o=await de.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
37
|
+
${o.message}`):l("Staged state branch event file",void 0)},ra=async({stateBranchRoot:e})=>{let t=Xi(),n=Hr.join(e,t);if(!Zt.existsSync(n))return l("No media directory to stage",void 0);let r=await de.stage({cwd:e,pathspec:[t]});return d(r)?a(`Failed to stage state branch media files
|
|
38
|
+
${r.message}`):l("Staged state branch media files",void 0)},oa=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ou(e);return d(n)?a(`Create state branch sync commit failed
|
|
39
|
+
`+n.message):xn({cwd:t,message:n.value})},Jn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vs(t);if(d(n))return a(n.message);let r=hn(e);if(d(r))return r;let o=r.value,s=n.value?await de.push({cwd:t}):await de.push({cwd:t,remote:Xe,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
|
|
40
|
+
${s.message}`):l("Pushed state branch",!0)},sa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=hn(e);if(d(o))return o;let s=o.value,i=[$r(),await _u({repoRoot:e,stateBranchName:s}),await en({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Wu({stateBranchRoot:t,stateBranchName:s}),await ea(t),n?await ju({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as Vu}from"ws";var jr=new Set,ia=e=>{jr.add(e),e.on("close",()=>{jr.delete(e)}),e.on("error",()=>{jr.delete(e)})},tn=e=>{let t=JSON.stringify(e);for(let n of jr)n.readyState===Vu.OPEN&&n.send(t)};import{useSyncExternalStore as Wg}from"react";var L={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Es(e){return e.context===L.WORKSPACE}function A(e){return e.context===L.TICKET}function kt(e){return e.context===L.TEXT}function Oe(e){return e.context===L.FIELD}function Qn(e){return e.context===L.FIELD_LIST}var Dt=e=>e.context===L.SWIMLANE,Vr=e=>e.context===L.BOARD,Zn=e=>e.context===L.COMMENT;var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var aa=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",da=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",ca=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",la=(e,t)=>{if(da(e,e.sequence))return h.MoveCursorLeftOfWord;if(ca(e,e.sequence))return h.MoveCursorRightOfWord;if(aa(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},ua=(e,t)=>{if(da(e,e.sequence))return h.MoveCursorLeftOfWord;if(ca(e,e.sequence))return h.MoveCursorRightOfWord;if(aa(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Kr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var nn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",lt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ma=e=>e.charAt(0).toUpperCase()+e.slice(1);var pa=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},fa=(e,t)=>t?e.get(t)??[]:[];var ga=new WeakMap,Ku=e=>{let t=ga.get(e);return t||(t=pa(e),ga.set(e,t)),t};var ya=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return fa(Ku(e),r).filter(s=>Kr(r,s)>=n)};var Gu={hint:"",hints:[],overlap:0,remainder:""},va=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Gu;let o=ya({wordList:r,inputToMatch:e,overlapThreshold:1});return zu(t,o)},zu=(e,t)=>{let n=t[0]??"",r=Kr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{useSyncExternalStore as qu}from"react";var er={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Cs=new Set,Yu=()=>{for(let e of Cs)e()},K=()=>er,ha=()=>qu(e=>(Cs.add(e),()=>{Cs.delete(e)}),()=>er),Fe=e=>(er={...er,...e},Yu(),er);import{ulid as Qu}from"ulid";var bn=24n,Xu=bn*4n,rt=(1n<<Xu)-1n,Ju=/^[0-9a-f]+$/;function xa(e){return!e||!Ju.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function _e(e,t=bn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Be(e,t){if(!e&&!t)return _e(rt/2n,bn);let n=e?xa(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?xa(t):l("Resolved upper bound",rt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return _e(rt/2n,bn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):_e(i,bn)}function ba(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=rt*BigInt(r+1)/(t+1n),s=_e(o,bn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var Ns=(e,t)=>{let n=q(e),r=ba(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:Qu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as ep}from"ulid";var It=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Ss=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},rn=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),I={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=he(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){he(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(!A(t))return a("Can only comment on issues");let n=he(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("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(!A(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=he(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("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=he(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!A(t))return a("Can only attach to issues");let n=he(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):l("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=he(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return a("Edit target node not found");let o=rn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=rn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return q(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),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=rn(o,"move");if(i)return i;if(Ss(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of q(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(E({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("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=rn(r,"edit");if(o)return o;if(!A(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),l("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=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("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=rn(r,"edit");if(o)return o;if(!A(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),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(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=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return q(e)}};var J={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var Ue=e=>e.slice(-7).toUpperCase(),Ia=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Ue(e).includes(n):!0};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:L.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:Ue(e)},context:L.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.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:L.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:L.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:Ue(e)},context:L.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:L.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:L.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Ft from"chalk";import Ta from"string-width";import{decodeTime as om}from"ulid";import En from"chalk";var Se={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"},v={accent:Se.cyan,accent2:Se.magenta,primary:Se.white,secondary:Se.grayDark,secondary2:Se.grayLight,gray:Se.gray,green:Se.green,yellow:Se.yellow,red:Se.red};var C={red:Se.red,yellow:Se.yellow,green:Se.green,blue:Se.blue,magenta:Se.magenta,cyan:Se.cyan},In={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var Rs={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ea=(e,t,n)=>Math.max(t,Math.min(n,e)),As=(e,t,n)=>e+(t-e)*n,Ca=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Zu=e=>e.toLowerCase().trim(),em=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Na=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var tm=(e,t,n)=>{let r=Ea(n,0,1);return[Math.round(As(e[0],t[0],r)),Math.round(As(e[1],t[1],r)),Math.round(As(e[2],t[2],r))]};var nm=(e,t,n)=>tm(e,t,n),tr=e=>{let n=Ca(e)%360,r=em(n,Rs.stringColor.saturation,Rs.stringColor.lightness);return Na(r)},le=(e,t=In)=>{let n=Zu(e);return n&&t[n]?t[n]:tr(n)};var Sa=e=>{let t=Rs.gradient.stops,n=Ea(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 nm(t[s],t[s+1],i)},Gr=e=>Na(Sa(e)),zr=e=>Ca(e.toLowerCase().trim())/4294967295,Aa=e=>{let t=zr(e);return Sa(t)},rm=e=>{let[t,n,r]=Aa(e);return{normal:o=>En.bgRgb(t,n,r).black(o),cursor:o=>En.bgRgb(t,n,r).white.bold(o)}},Ts=e=>{let[t,n,r]=Aa(e);return{fg:o=>En.rgb(t,n,r)(o),fgCursor:o=>En.rgb(t,n,r).inverse(o),bg:o=>En.bgRgb(t,n,r).black(o),bgCursor:o=>En.bgRgb(t,n,r).white.bold(o)}},qr=e=>rm(e).normal(` ${e} `);import{decodeTime as Ra}from"ulid";var Cn=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"},Yr=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Xr=e=>{try{return l("Decoded date",new Date(Ra(e)))}catch(t){return a("Decoding failed + "+t.message)}},Nn=e=>{if(!e?.id)return null;try{return Ra(e.id)}catch{return null}};var sm=(e,t)=>e+" ".repeat(Math.max(0,t-Ta(e))),im=(e,t)=>" ".repeat(Math.max(0,t-Ta(e)))+e,wa=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),am=(e,t)=>t?e<t?"up":e>t?"down":null:null,dm=(e,t)=>{let n=I.getNode(e.payload.parent),r=n?Ft.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=am(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Ma=e=>`${Math.max(1,Math.round(e/1024))} KB`,Pa=e=>I.getAttachment(e)?.name??"",cm=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(le(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(le(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(le(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(le(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Ft.dim(`(${Ma(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Pa(e.payload.id);return t?`"${t}"`:""}default:return""}},lm=e=>{let t=Cn(om(e));return Ft.gray(im(t,8))},um=12,mm=e=>sm(`${e}`,um),pm=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ma(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Pa(e.payload.id);return t?`"${t}"`:""}default:return""}},La=e=>[wa(e.action),pm(e)].filter(Boolean).join(" "),ka=(e,t)=>{let n=lm(e.id),r=mm(e.userName),o=Ft.dim("\u203A"),s=e.action==="move.node"?dm(e,t):[wa(e.action),cm(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as fm}from"node:crypto";var gm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ym=e=>{let t=fm("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+=gm[Number(n>>s&31n)]}return r},xe=(e,t)=>ym(`${e}:virtual:${t}`);var vm=e=>xe(e,"comments"),hm=e=>xe(e,"description"),xm=e=>xe(e,"assignees"),bm=e=>xe(e,"tags"),Im=e=>xe(e,"history"),Em=e=>xe(e,"attachments"),Jr=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Oe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},Da=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=I.getNode(e);if(!i){let m=I.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Qn(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 l("Virtual field list unchanged",void 0);let u=I.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},Fa=e=>{let t=_e(rt/4n),n=_e(rt/2n),r=_e(rt*3n/4n),o=_e(rt*7n/8n),s=_e(rt*15n/16n),i=_e(rt*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 c=Jr({id:hm(e.id),name:J.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let u=Da({id:xm(e.id),name:J.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(u))return u;let m=Da({id:bm(e.id),name:J.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=Jr({id:vm(e.id),name:J.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=Jr({id:Em(e.id),name:J.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let b=Jr({id:Im(e.id),name:J.HISTORY,parentNodeId:e.id,rank:i.value,value:Cm(e),readonly:!0,childRenderAxis:"vertical"});return d(b)?b:l("Ticket virtual nodes materialized",void 0)},Cm=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=>ka(r,n.get(r.action)??[])).join(`
|
|
41
|
+
`)};var Nm=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[me,Qr]=Nm;var k=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ba=e=>{let t=I.getNode(e);if(!t||!A(t)||t.isDeleted)return null;let n=Fa(t);return d(n)?n:null},Sm=e=>{for(let t of e){let n=Ba(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Ba(r);if(o)return o}return null},Am=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Rm=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},ws=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 Rm(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"create.contributor":case"link.contributor.user":default:return[]}},Tm=e=>{he(t=>({...t,eventLog:[...t.eventLog,e]}))},wm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?k("Invalid user ID format",e):l("Valid user",null)},Mm=(e,t)=>{let n=wm(e);if(d(n))return n;let r=[...new Set(ws(e))];t||(r.forEach(s=>Am(s,e)),Tm(e));let o=Sm(r);return o||null},Pm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=nr(o);if(d(s))return k(s.message,e);let i=I.createNode(o);return d(i)?k(i.message??"Failed to initialize workspace",e):Es(i.value)?l("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=I.createNode(Q.workspace(t,n,r));return d(o)?k(o.message??"Failed to add workspace",e):Es(o.value)?l("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.board(t,n,r,o));return d(s)?k(s.message??"Unable to create board",e):Vr(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.swimlane(t,n,r,o));return d(s)?k(s.message??"Unable to create swimlane",e):Dt(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.ticket(t,n,r,o));return d(s)?k(s.message??"Unable to create issue",e):A(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=I.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(J.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?k(i.message??`Unable to create field: ${n}`,e):Oe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.tag(t,n);return d(r)?k(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.untag(t,n);return d(r)?k(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.assign(t,n);return d(r)?k(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!A(o))return k("Can only close issues",e);let s=I.getNode(me);if(!s)return k("Unable to locate target swimlane",e);if(n!==s.id)return k("Close target must be closed swimlane",e);let i=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?k(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!A(o))return k("Can only reopen issues",e);let s=I.getNode(me);if(!s)return k("Unable to locate closed swimlane",e);if(n===s.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("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=I.getNode(r);if(!s)return k(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let i=I.updateNode({...s,rank:o});if(d(i))return k(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=I.createComment({id:t,issue:n,authorId:r,authorName:I.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?k(s.message??"Unable to add comment",e):l("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=I.getComment(t);if(!o)return k("Unable to locate comment",e);if(o.issue!==n)return k("Comment does not belong to issue",e);let s=I.editComment(t,r);return d(s)?k(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=I.getComment(t);if(!r)return k("Unable to locate comment",e);if(r.issue!==n)return k("Comment does not belong to issue",e);let o=I.deleteComment(t);return d(o)?k(o.message??"Unable to delete comment",e):l("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,c=I.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?k(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=I.getAttachment(t);if(!r)return k("Unable to locate attachment",e);if(r.issue!==n)return k("Attachment does not belong to issue",e);let o=I.deleteAttachment(t);return d(o)?k(o.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return d(n)?k(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Bt(e,t=!1){let n=Pm[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=Mm(e,t);return o||r}var Ut=e=>e.map(t=>Bt(t));import Vm from"node:fs";import Km from"node:path";import{decodeTime as Gm,monotonicFactory as zm}from"ulid";import{z as rr}from"zod";import Zr from"node:fs";import Ps from"node:path";import{decodeTime as Dm}from"ulid";import{z as Ms}from"zod";var Lm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.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 km=new Set(Lm),Ua=e=>km.has(e),Oa=e=>({action:e.action,payload:e.payload});var Fm=Ms.object({userId:Ms.string().min(1).default("unknown"),userName:Ms.string().min(1).default("unknown")}),Bm=e=>{let[t,n]=Ps.basename(e,".jsonl").split("."),r=Fm.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${Ps.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Um=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Om=(e,t)=>t in e,_m=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),$m=e=>{let{userId:t,userName:n,...r}=e,o=Um(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Om(r,s)?l("Decoded persisted event",_m({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Ls=e=>{let t=[],n=new Map;for(let r of e){let o=$m(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!Ua(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");oe.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return l("Decoded reconstructed events",t)},Hm=e=>{if(!Zr.existsSync(e))return l("Event file missing",[]);let t=Bm(e);if(d(t))return a(t.message);let n=Zr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
42
|
+
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=Ds(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function ks(e){let t=Vn(e);if(!Zr.existsSync(t))return l("No events found",[]);let n=Zr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Ps.join(t,o)),r=[];for(let o of n){let s=Hm(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",Wm(r))}function Et(e){let t=ks(e);return d(t)?a(t.message):Ls(t.value)}function _a(e,t){let n=ks(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=jm(n.value,t),s=Ls(r);if(d(s))return a(s.message);let i=Ls(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function $a(e=process.cwd()){let t=ks(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Wm=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 b=n.get(f)??[];b.push(m),n.set(f,b)}for(let m of n.values())m.sort((p,f)=>p.id[0].localeCompare(f.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let f=n.get(p)??[];for(let b of f)s(b)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return!o.has(p)&&f!==null&&!t.has(f)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},jm=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=Dm(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var ja=1,Ha=zm(),qm=rr.tuple([rr.string().min(1),rr.string().min(1).nullable()]),Ym=rr.looseObject({v:rr.literal(ja),id:qm}),Ds=e=>{let t=Ym.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Wa=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Xm=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Jm=e=>e.trim().length>0&&e.length<=80,se=()=>{let{userName:e,userId:t}=K();return e?t?Xm(t)?Jm(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},on=({userId:e,userName:t})=>`${Wa(e)}.${Wa(t)}.jsonl`,Qm=(e,{userId:t,userName:n})=>{let r=on({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=Km.join(Vn(e),r);return l("Successfully resolved event log path",s)},Zm=(e,t)=>{let n={[e.action]:e.payload,v:ja,id:t};return Ds(n)};function eo({event:e,rootDir:t}){try{let n=Fi(t);if(d(n))return n;let r=Qm(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=$a(t);if(d(o))return a(o.message);let s=o.value?Ha(Math.max(Date.now(),Gm(o.value)+1)):Ha(),i=Zm(Oa(e),[s,o.value]);return d(i)?a(i.message):(Vm.appendFileSync(r.value,`${JSON.stringify(i.value)}
|
|
43
|
+
`,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function Va(e,t){let n=Bt(e);if(n.status!==Pt.Success)return n;let r=eo({event:e,rootDir:t});return d(r)?r:n}function B(e,t){if(e.length===0||!e[0])return a("No events provided");let n=tp(e[0],t);if(d(n))return n;let r=e.map(s=>Va(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):l("Materialization succeeded",r.map(s=>s.value))}var tp=(e,t)=>{if(e.action==="create.contributor")return l("Contributor already being created",void 0);if(I.getContributor(e.userId))return l("Contributor exists",void 0);let n={id:ep(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=Va(n,t);return d(r)?a(r.message):l("Contributor created",void 0)};var Ka=e=>to(q(e),{at:"end"}),to=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Be(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Be(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Be(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=Ga(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Be(o?.rank,s.rank)):a("Sibling not found")}case"after":{let r=Ga(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Be(o.rank,s?.rank)):a("Sibling not found")}}},q=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ga=(e,t)=>e.findIndex(n=>n.id===t),za=(e,t,n={at:"end"})=>to(q(t).filter(r=>r.id!==e),n),sn=(e,t,n,r,o)=>{let s=za(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=Ns(e,r);if(d(i))return i;let c=B([i.value],o);if(d(c))return c;let u=za(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},Sn=(e,t,n)=>{let r=Ka(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=Ns(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=Ka(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var T={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=G(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||T.navigate({contextNode:o,selectedIndex:G(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();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=G(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;T.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>qa(1),navigateToPreviousItem:()=>qa(-1),navigateToNextContainer:()=>Ya(1),navigateToPreviousContainer:()=>Ya(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},qa=e=>{let{selectedIndex:t,contextNode:n}=g(),r=G(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;T.navigate({selectedIndex:s,contextNode:n})},Ya=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=G(o.id),i=s.findIndex(b=>b.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=G(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;T.navigate({contextNode:c,selectedIndex:f})};var Ja=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Qa=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},np=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&Oe(t)&&t.childRenderAxis==="vertical"},no=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=q(r.id);return T.navigate({contextNode:r,selectedIndex:Ja(t,o.length)}),!0},Za=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return no(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=q(o.id).findIndex(c=>c.id===n.id);return i>=0?(T.navigate({contextNode:o,selectedIndex:i}),!0):Za(o.id)},Xa=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Za(n))return!0;n=t[n]?.parentNodeId}return!1},rp=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},ed=e=>{let{nodes:t,rootNodeId:n}=g();if(np(e.contextNodeId)&&no(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(rp(e.selectedNodeId)&&e.selectedNodeId&&Xa(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(no(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&no(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Xa(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=q(r.id);return T.navigate({contextNode:r,selectedIndex:Ja(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};import{monotonicFactory as op,ulid as Ct}from"ulid";var or=op();function sp(){let e=Je();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)throw new Error("No workspace found in event log");let[r]=G(n.id),[o]=r?G(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?l("Resolved boot nav target",{contextNode:n,selectedIndex:0}):l("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function ip(){let e=sp();return d(e)?e:T.navigate(e.value)}function td({userId:e,userName:t}){let n=or(),r=or(),o=or(),s=or(),i=or(),c=Be(void 0,void 0);if(d(c))return c;let u=Be(void 0,void 0);if(d(u))return u;let m=Be(u.value,void 0);if(d(m))return m;let p=Be(void 0,void 0);if(d(p))return p;let f=Be(p.value,void 0);if(d(f))return f;let b=Be(f.value,void 0);if(d(b))return b;let N=Be(void 0,void 0);return d(N)?N:l("Created default events",[{id:Ct(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ct(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:b.value}},{id:Ct(),userId:e,userName:t,action:"add.board",payload:{id:Qr,name:"Closed",parent:n,rank:m.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:me,name:"Closed",parent:Qr,rank:N.value}},{id:Ct(),userId:e,userName:t,action:"lock.node",payload:{id:Qr}},{id:Ct(),userId:e,userName:t,action:"lock.node",payload:{id:me}}])}function an(e){if(!e.length){let r=Q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=nr(r);return d(o)?o:(E({hasProjectDefinition:!1,mode:y.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Ut(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
44
44
|
${n.map(r=>r.message).join(`
|
|
45
|
-
`)}`):(sp(),E({hasProjectDefinition:!0}),l("State booted successfully",null))}var dn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),ro=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)}},X=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ut=null,oo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ut,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),ut)return logger.debug("[sync] syncAndReloadState joining existing promise"),ut;logger.debug("[sync] syncAndReloadState creating promise"),ut=ip();try{let e=await ut;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),d(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({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}),ut||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),ut=null}},ip=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=td();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(ut)return ut;logger.debug("[sync] syncAndReloadState:start");let t=X("resolveActorId",se());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");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=on(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=X("syncEpiqWithRemote",await so({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),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Qe(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=X("loadMergedEvents",Et(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=td();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:i.message,syncStatus:g().syncStatus}),i;let c=Ja(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=X("bootStateFromEventLog",an(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=X("restoreNavigationAnchor",Za(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),d(m)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},td=()=>g().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var An=3e3,nd=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<An?null:t},rd=0,Ds,Fs=!1,sr=!1,Bs=()=>{if(Fs)return!0;let e=Je();return d(e)?!1:e.value.syncStatus.status==="syncing"},ap=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-rd;return Math.max(0,e-t)},od=()=>{Ds||(Ds=setTimeout(async()=>{if(Ds=void 0,!!Rn()){if(Bs()){sr=!0;return}sr=!1,await dp()}},ap()))},dp=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Rn())return a("Cannot auto-sync before state is initialized");if(Bs())return sr=!0,a("Sync already in progress");Fs=!0,rd=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await oo()}finally{Fs=!1,sr&&od()}},io=()=>{Rn()&&(sr=!0,!Bs()&&od())};var Ot=()=>{let e=K(),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}},sd=()=>{let e=Ye(process.cwd());if(d(e))return!1;let t=Lt(e.value);return te(t)},id=e=>e===!0?"on":e===!1?"off":null,ad=e=>e==="on"?!0:e==="off"?!1:null;var cp=e=>e.props.tags??[],lp=e=>e.props.assignees??[],_t=e=>cp(e).map(t=>I.getTag(t)).filter(t=>!!t),$t=e=>lp(e).map(t=>I.getContributor(t)).filter(t=>!!t),ao=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",_t(n))},co=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",$t(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",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",COFFEE:"coffee",NONE:""};var up=/^(\d+)(h|d|w|mo|y)$/,mp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,pp=({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},fp=(e,t=new Date)=>{let n=e.match(up);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}},gp=e=>{let t=e.match(mp);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return pp({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},cn=e=>{let t=e.trim().toLowerCase();return fp(t)??gp(t)};var dd=/^(\d+)(s|m)?$/,lo=e=>{let t=e.trim().toLowerCase().match(dd);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},uo=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&dd.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},cd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,yp=[{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}],Us=(e=yp)=>{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 vp=["BOARD","TICKET","SWIMLANE","COMMENT"],ne={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},$e={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},pe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},hp=[ne.EDITOR,ne.VIEW,ne.USERNAME,ne.AUTOSYNC,ne.SYNC_DEBOUNCE_MS,ne.ATTACHMENT_MAX_KB,ne.LOG_LEVEL],xp=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[$e.TITLE,$e.DESCRIPTION];case"BOARD":case"SWIMLANE":return[$e.TITLE];case"COMMENT":return[$e.COMMENT];default:return[]}},_s=[String(An),"5000","15000","30000","60000"],$s=["250","500","1000"],md=["10s","20s","30s","45s"],ln=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],mo=[x.NEW,x.EDIT,x.DELETE,x.MOVE],Os=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],ld=[x.FILTER,x.PEEK,x.REPLAY],bp={WORKSPACE:[...ln,...mo],BOARD:[...ld,...ln,...mo],SWIMLANE:[...ld,...ln,...mo],TICKET:[...ln,...mo,...Os],FIELD:[...ln,...Os],FIELD_LIST:[...ln,...Os],TEXT:[...ln],COMMENT:[x.EDIT,x.DELETE,x.YANK]},Ip=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ir=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&A(n)),ud=e=>e.parentNodeId===me,Ep=({selectedNode:e,breadCrumb:t})=>{let n=xp(e?.context);return ir({breadCrumb:t,selectedNode:e})?n.includes($e.DESCRIPTION)?n:[...n,$e.DESCRIPTION]:n},Cp=({selectedNode:e,breadCrumb:t})=>{let n=ir({breadCrumb:t,selectedNode:e});return n?[pe.REF,pe.TITLE,...n.props?.description?.trim()?[pe.DESCRIPTION]:[],..._t(n).length>0?[pe.TAGS]:[],...$t(n).length>0?[pe.ASSIGNEES]:[]]:e?[pe.REF,pe.TITLE]:[]},Np=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ot();if(!r)return[x.HELP,x.CONFIG];if(!sd())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let o=e?.context,s=o&&vp.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?bp[u]:[]))],c=ir({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(c??e):u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&_t(c).length>0):u===x.UNASSIGN?!!(c&&$t(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&ud(c)):u===x.CLOSE_ISSUE?!!(c&&!ud(c)):!0)},ie=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Np({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Us(),"now","prev","next"],[x.REPLAY]:[...Us()],[x.EDIT]:Ep({selectedNode:n,breadCrumb:o}),[x.YANK]:Cp({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(In),...I.getExistingTags()])],[x.UNTAG]:[...ao()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...co()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:I.getExistingAssignees(),[x.NEW]:Ip(s),[x.CONFIG]:[...hp],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Pd from"chalk";var pd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Le=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")},fd=["png","jpg","gif","webp"];import $p from"zod";import Lp from"node:os";import hd from"node:path";import{z as Nt}from"zod";import{accessSync as Sp,copyFileSync as Ap,existsSync as po,mkdirSync as gd,readdirSync as yd,readFileSync as Rp,renameSync as Tp,rmSync as wp,statSync as vd,unlinkSync as Mp,writeFileSync as Pp}from"node:fs";import Tn from"node:path";var Hs=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",He={writeToFile:(e,t)=>{try{let n=Tn.dirname(e);po(n)||gd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Pp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Rp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=He.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 po(e)&&vd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Sp(e),!0}catch{return!1}},mkDir:e=>gd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Tn.parse(t);for(;;){let r=Tn.join(t,e);try{if(po(r)&&vd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Tn.dirname(t)}return null},readFirstJSON(e){try{if(!He.dirExists(e))return null;let t=yd(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Tn.join(e,t);return He.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return He.dirExists(e)?yd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Mp(e)}catch(t){(!Hs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{wp(e,{recursive:!0,force:!0})}catch(t){(!Hs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Tn.dirname(t)),!n?.overwrite&&po(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Tp(e,t)}catch(r){if(Hs(r)&&r.code==="EXDEV"){Ap(e,t),this.rmFile(e);return}throw r}}};var kp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},xd=Nt.object({logLevel:Nt.enum(["info","error","debug"]),preferredEditor:Nt.string().optional(),userName:Nt.string().optional(),userId:Nt.string().optional(),autoSync:Nt.boolean().nullable().optional(),autoSyncDebounceMs:Nt.number().optional(),attachmentMaxKb:Nt.number().optional(),viewMode:Nt.enum(["dense","wide"]).optional()}).partial(),Dp="config.json",bd=()=>hd.join(Lp.homedir(),qe),Ws=()=>hd.join(bd(),Dp),js=()=>{try{return He.mkDir(bd()),l(`Ensured ~/${qe} exists`,null)}catch{return a(`Unable to create ~/${qe}`)}},Fp=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${qe}/config.json JSON`)}let n=xd.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${qe}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ar=()=>{let e=js();if(d(e))return a(e.message);let t=Ws(),n=He.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Fp(n)},Id=e=>{let t=js();if(d(t))return a(t.message);let n=xd.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ws();try{return He.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
46
|
-
`),l("Config written",null)}catch{return a(`Unable to write ~/${qe}/config.json`)}},Ze=e=>{let t=ar();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Id(n)},wn=()=>{let e=Ws(),t=js();if(d(t))return a(`Unable to create ~/${qe}`);if(!(He.readFile(e)!==null)){let b=Id(kp);if(d(b))throw new Error(`Unable to create ~/${qe}/config.json`)}let r=ar();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value;return!s||!i?a(`User name or ID not configured in ~/${qe}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import Bp from"node:crypto";import dr from"node:fs";import Ed from"node:path";var mt=500,Up=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Mn=(e,t)=>`${e}.${t}`,Op=e=>Up.test(e),Cd=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("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")))?l("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"))?l("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${fd.join(", ")}`),Nd=e=>Bp.createHash("sha256").update(e).digest("hex"),_p=(e,t=mt)=>{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=Cd(e);return d(n)?n:l("Validated attachment data",{hash:Nd(e),ext:n.value,bytes:e.length})},Sd=(e,t,n=mt)=>{let r=_p(t,n);if(d(r))return r;let o=Kn(e),s=Ed.join(o,Mn(r.value.hash,r.value.ext));try{dr.existsSync(s)||(dr.mkdirSync(o,{recursive:!0}),dr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",r.value)},Ad=(e,t,n=mt)=>{if(!Op(t))return a("Invalid attachment file name");let r=Ed.join(Kn(e),t);if(!dr.existsSync(r))return a("Attachment blob not found");let o;try{o=dr.readFileSync(r)}catch(u){return a(`Unable to read attachment blob: ${u instanceof Error?u.message:String(u)}`)}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(Nd(o)!==s)return a("Attachment blob does not match its content hash");let c=Cd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):l("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var cr=50,lr=5e3,Rd=()=>{let e=Y().commandMeta.inputString,t=$p.coerce.number().int().min(cr).max(lr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${cr}-${lr} KB (default ${mt})`);let n=Ze({attachmentMaxKb:t.data});return d(n)?n:(Fe({attachmentMaxKb:t.data}),E({mode:y.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))};import Td from"chalk";var Z=e=>Td.dim(e),be=e=>Td.hex(v.primary)(e),Ie=({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,b)=>zr(f)-zr(b)).slice(0,r).map(f=>qr(f)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""};var pt={None:"none",Invalid:"invalid",Valid:"valid"};var Pn=140,Hp=["BOARD","TICKET","SWIMLANE"],wd=()=>{let e=g().selectedNode;if(!e?.context)return F({message:Z("Missing target context")});if(Hp.includes(e.context))return V();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===xe(t?.parentNodeId??"","comments"))return V()}return F({message:Z("Command not available in this context")})},re="<ENTER> to confirm",V=(e="",t=[])=>({message:Z(e),validity:pt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:pt.Invalid,message:e,completionWordList:t}),go=e=>e.length===0,Md=(e,t)=>{let n=Le(g().breadCrumb,"BOARD");if(d(n))return F({message:be("Command is not applicable in this context")});let r=Xr(n.value.id);return d(r)?F({message:be(`Unable to ${t}: board id is not a valid ULID`)}):cd({date:e,horizonDate:r.value})?null:F({message:be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},fo=e=>` ${Pd.hex("#000").bgHex(le(e))(` ${e} `)} `,Vs=({modifier:e})=>{let t="confirm";return e===t?V(re):F({message:go(e)?Z("if you are certain, enter ")+qr(t):"",completionWordList:[t]})},Wp=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:Z(n)}):V():F({message:go(r)?t:"",completionWordList:[...e]}),un=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>go(n)&&go(r)?F({message:e,completionWordList:[]}):V(t??re),jp=({modifier:e,inputString:t})=>{let n=ie(x.CONFIG);if(!n.includes(e))return F({message:Ie({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ne.EDITOR:{let r=[...pd];return t.trim()?r.includes(t.trim())?V(re):F({message:Ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:Ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?V(re):F({message:Ie({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.USERNAME:return t.trim()?V(re):F({message:be("Enter a user name. Saved in ")+Pd.bgBlack("~/.epiq-global/config.json")});case ne.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?V(re):F({message:Ie({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ne.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=id(o);return F({message:Ie({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return V(re)}case ne.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<cr||o>lr){let s=Ie({prefix:" examples: ",wordList:$s,minLengthForHints:0,inputString:t});return F({message:be(`provide a size cap in KB (${cr}-${lr}). current: ${r??mt} KB.`)+s,completionWordList:$s})}return V(re)}case ne.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=nd(t);if(!t.trim()||o===null||o<An){let s=Ie({prefix:" examples: ",wordList:_s,minLengthForHints:0,inputString:t});return F({message:be(`provide duration above ${An}ms. current duration: ${r}ms.`)+s,completionWordList:_s})}return V(re)}default:return F({message:be("Unknown config option"),completionWordList:n})}},Vp=({modifier:e,inputString:t})=>{let n=ie(x.EDIT);if(!n.length)return F({message:be("Command not available in this context")});if(!n.includes(e)){let r=Ie({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||be("Unknown edit option"),completionWordList:n})}switch(e){case $e.COMMENT:return t.trim()?V(re):F({message:Z("write a comment...")});case $e.TITLE:return V(re);case $e.DESCRIPTION:{let{preferredEditor:r}=K();return r?V(Z("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:be("Unknown edit option"),completionWordList:n})}},Kp=({modifier:e})=>{let t=ie(x.YANK);return t.length?t.includes(e)?V(re+Z(" and copy to clipboard")):F({message:Ie({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):F({message:be("Nothing selected to copy from")})},Gp={[x.EXPORT]:()=>V(re+Z(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return V(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=cn(r);if(!r||!o)return F(n);let s=Md(o,"peek");return s||V(re)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=uo(e.modifier,e.inputString),r={message:Z("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=cn(t);if(!t||!o)return F(r);let s=Md(o,"replay");return s||(n&&lo(n)===null?F({message:be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):V("<ENTER> to replay board history",n?md:[]))},[x.EXIT]:()=>V(re+Z(" and exit the application")),[x.INIT]:()=>V(re),[x.PALETTE]:()=>V(re),[x.FILTER]:e=>{if(e.modifier==="clear")return V(re);let t=s=>ie(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:Ie({wordList:ie(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ie(x.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:Ie({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):V():F({message:Ie({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=ie(x.NONE);return F({message:Ie({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Wp({list:ie(x.NEW),hint:Ie({wordList:ie(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>V(re),[x.EDIT]:Vp,[x.COMMENT]:e=>{let t=un({hint:Z(`write a comment (max ${Pn} char)...`),onOk:Z(`(${e.inputString.length}/${Pn})`)})(e);return t.validity===pt.Invalid?t:e.inputString.length>Pn?V(be("max input exceeded")):t},[x.CONFIG]:jp,[x.YANK]:Kp,[x.DELETE]:e=>{let t=wd();return t.validity==="invalid"?t:Vs(e)},[x.CLOSE_ISSUE]:e=>Vs(e),[x.RE_OPEN_ISSUE]:e=>Vs(e),[x.MOVE]:e=>{let t=wd();return t.validity==="invalid"?t:un({hint:Ie({prefix:"hey hacker! These commands are blocked for you... ",wordList:ie(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(fo).join("");return un({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[x.UNTAG]:e=>{let t=ao();if(d(t))return F({message:be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(fo).slice(0,10);return n.length?un({hint:Z(" ... ")+n.join("")})(e):F({message:be("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=I.getExistingAssignees().map(fo).slice(0,10);return un({hint:Z("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=co();if(d(t))return F({message:be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(fo).slice(0,10);return n.length?un({hint:Z("remove assignee... ")+n.join("")})(e):F({message:be("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>V(re),[x.COFFEE]:e=>{let{modifier:t}=e,n=ie(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:Z("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):un({hint:Ie({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Ld=Object.fromEntries(Object.entries(Gp).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var yo=["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 zp=3,qp=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"]),Yp=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},Xp=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=zp&&!qp.has(t)&&!/^\d+$/.test(t)),Jp=e=>{let t=new Map;for(let s of Yp(e))for(let i of Xp(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=yo.filter(s=>!r.has(s));return[...n,...o]},kd=yo,Dd=-1,Fd=()=>{let e=Je();if(d(e))return yo;let t=e.value,n=t.eventLog.length;return n!==Dd&&(kd=Jp(t),Dd=n),kd};var Bd=e=>Object.values(x).includes(e),Ud=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Ld[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?ie(n):m?Fd():[],{mode:f}=g(),b=f===y.COMMAND_LINE?i??"":"",N=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:b,autoCompletion:t?ya(e,N):{hint:"",hints:[],remainder:"",overlap:0}}};var Od=e=>{let t=e.trimStart(),n=Zp(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=ef(e),c=Bd(r)?r:null,u=c!==null,m=r!=="",p=c?ie(c)??[]:[],f=c&&p.includes(o)?o:"",b="word";n.length===0||n.length===1&&!s?b="command":(n.length===1&&s||n.length===2&&!s)&&(b="modifier");let N=s?"":i,S=Qp(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:b,inputToMatch:N,inputString:S}},Qp=(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},Zp=e=>e.trim()?e.trim().split(/\s+/):[],ef=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as tf}from"react";var Ln=e=>e===Ks||e===":",Ks=" ",Ae={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:pt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Gs=new Set,_d=()=>{for(let e of Gs)e()},zs=e=>(Gs.add(e),()=>Gs.delete(e)),ft=e=>{let n=e(Ae),r=Od(n.value),o=n.cursorPosition===n.value.length;Ae={...n,commandMeta:Ud(r,o)},_d()},ur=({message:e,status:t})=>{let n=structuredClone(Ae);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ae=n,_d(),l(e,null)},qs=e=>{ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ys=e=>{ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ln(n[o-1]);)o--;for(;o>0&&!Ln(n[o-1]);)o--}else{for(;o<n.length&&!Ln(n[o]);)o++;for(;o<n.length&&Ln(n[o]);)o++}return{...t,cursorPosition:o}})},$d=()=>{ft(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}})},Hd=()=>{ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ln(t[r-1]);)r--;for(;r>0&&!Ln(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},vo=e=>{ft(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,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Wd=()=>{ft(e=>({...e,commandIsPending:!0}))},W=e=>{ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},jd=({addToHistory:e=!0})=>{ft(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Vd=()=>{ft(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}})},Kd=()=>{ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Y=()=>Ae,Gd=()=>tf(zs,Y,Y),zd=()=>{let[e,...t]=Ae.value.split(Ks);return t.join(Ks).trim()};var h={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 nf(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function rf(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function of(e,t,n){let r=g().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 qd(e,t){let n=Y();if(e.sequence==="?"&&t!==y.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return h.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===y.COMMAND_LINE)return ca(e,n.value);if(t===y.PALETTE)return la(e,n.value);let r=nf(e)||rf(e);if(r)return sf(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"y":return h.Yank;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return K().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function sf(e,t){let n=t===y.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return of(g().contextNode.childRenderAxis,e,n)}var ho=e=>{let{context:t}=g().contextNode;if(!t)return w.None;switch(e){case x.EXIT:return w.Exit;case x.EXPORT:return w.Export;case x.COFFEE:return w.Coffee;case x.INIT:return w.Init;case x.DELETE:return w.Delete;case x.EDIT:return w.Edit;case x.COMMENT:return w.Comment;case x.HELP:return w.ViewHelp;case x.RE_OPEN_ISSUE:return w.ReopenIssue;case x.CLOSE_ISSUE:return w.CloseIssue;case x.TAG:return w.TagTicket;case x.UNTAG:return w.UntagTicket;case x.ASSIGN:return w.AssignUserToTicket;case x.UNASSIGN:return w.UnassignUserFromTicket;case x.NEW:return w.NewItem;case x.FILTER:return w.Filter;case x.MOVE:return w.Move;case x.PEEK:return w.Peek;case x.REPLAY:return w.Replay;case x.CONFIG:return w.Config;case x.YANK:return w.Yank;case x.SYNC:return w.Sync;default:return w.None}},w={Exit:"exit",Init:"init",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",Coffee:"coffee"};import{ulid as we}from"ulid";import fc from"node:fs";import Xf from"node:path";import Jf from"react";import{Box as qf}from"ink";import No from"react";import Ef from"chalk";import{Box as Js,Text as Cf}from"ink";import gt from"react";import{Text as Yd}from"ink";import Xd,{useEffect as Jd,useState as af}from"react";var Qd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=H(),r=Qd[n]??Qd.default,[o,s]=af(0);if(Jd(()=>{s(0)},[r]),Jd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Xd.createElement(Yd,null,t);let i=r[o]??r[0]??t;return Xd.createElement(Yd,{color:v.accent,dimColor:o===1},i)};import{Box as Xs,Text as df}from"ink";import xo from"react";var et=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),f=p+c,b=e.slice(p,f),N=e.length>c,S=s,R=N?Math.max(1,Math.floor(c/e.length*S)):S,M=Math.max(0,S-R),U=Math.max(1,e.length-c),j=N?Math.floor(p/U*M):0;return xo.createElement(Xs,{flexDirection:"row",height:s,width:"100%"},xo.createElement(Xs,{flexDirection:"column",flexGrow:1,height:s},b),xo.createElement(Xs,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((D,z)=>xo.createElement(df,{key:z,color:N&&z>=j&&z<j+R?v.accent:v.secondary},N?"\u2502":" "))))};import{Box as Fn,Text as Io}from"ink";import tt from"react";import{Text as cf}from"ink";import lf from"react";var uf=e=>e.toLowerCase().trim(),mf=(e,t=In)=>{let n=uf(e);return t[n]?t[n]:tr(n)},Ht=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return lf.createElement(cf,{underline:t,color:mf(n.name)},"@"+n.name)};import{Text as pf}from"ink";import ff from"react";var kn=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return ff.createElement(pf,{underline:t,backgroundColor:le(n.name),color:v.secondary}," "+n.name+" ")};import{useEffect as gf,useState as yf}from"react";var vf=80,Zd=1400,bo=new Set,mr=null,hf=e=>(bo.add(e),mr||(mr=setInterval(()=>{for(let t of bo)t()},vf)),()=>{bo.delete(e),bo.size===0&&mr&&(clearInterval(mr),mr=null)}),xf=()=>{let e=Date.now()%Zd/Zd;return e<.5?e*2:(1-e)*2},Dn=e=>{let[,t]=yf(0);return gf(()=>{if(e)return hf(()=>t(n=>n+1))},[e]),Gr(xf())};var bf=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),nn(e.slice(r).trim(),t)]},ec=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Dn(r),s=e-4,[i,c]=bf(lt(t.title),s),u=c?null:nn(lt(t.props.description),s)||null,m=_t(t),p=$t(t);return tt.createElement(Fn,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?v.accent:v.secondary,justifyContent:"space-between"},tt.createElement(Fn,{paddingLeft:1,flexDirection:"column"},tt.createElement(Io,{color:v.primary},i),c&&tt.createElement(Io,{color:v.primary},c),u&&tt.createElement(Io,{color:v.secondary2,dimColor:!0},u)),tt.createElement(Fn,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},tt.createElement(Fn,{flexDirection:"row"},m.map(f=>tt.createElement(Fn,{paddingRight:1,key:f.id},tt.createElement(kn,{key:f.id,id:f.id}))),p.map(f=>tt.createElement(Fn,{paddingRight:1,key:f.id},tt.createElement(Ht,{key:f.id,id:f.id})))),tt.createElement(Io,{wrap:"truncate",color:v.secondary2,dimColor:!0},Ue(t.id))))};import{Box as mn,Text as pr}from"ink";import We from"react";var If=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,tc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=Dn(r),c=(t.props.tags??[]).map(D=>I.getTag(D)).filter(D=>!!D),u=(t.props.assignees??[]).map(D=>I.getContributor(D)).filter(D=>!!D),m=1,p=c.length*(1+m),f=u.length*(2+m),b=c.map(D=>We.createElement(mn,{key:D.id,paddingRight:m},We.createElement(pr,{color:le(D.name)},"\u25A0"))),N=u.map(D=>We.createElement(mn,{key:D.id,paddingRight:m},We.createElement(pr,{color:tr(D.name)},"@"+D.name.at(0)))),S=r?i:n?v.accent:s===y.MOVE?v.secondary:v.primary,R=4,M=I.getCommentsByIssue(t.id),U=M.length?String(M.length).length+2+m:0,j=M.length?We.createElement(mn,{paddingRight:m},We.createElement(pr,{color:v.accent},"[",M.length,"]")):null;return We.createElement(mn,{borderBottom:!0,justifyContent:"space-between"},We.createElement(mn,null,We.createElement(mn,{width:R},n?We.createElement(Re,{isSelected:n}):We.createElement(pr,{color:"gray",dimColor:!0},o+1)),We.createElement(pr,{wrap:"truncate",color:S},If(t.title,e-p-f-U-18))),We.createElement(mn,null,b,N,j))};var Nf=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=H(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,b=f?.has(e.id)??!1,N=Dn(b),S=`${e.title} ${Ef.hex(v.secondary2).dim("("+p.length+")")}`,R=3,M=o?1:5,U=s&&i===-1,j=n-(U?7:5),D=r-R-(o?2:1),z=gt.createElement(Js,{borderStyle:"round",borderColor:v.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},gt.createElement(Re,{isSelected:t}),gt.createElement(Cf,{bold:!0,color:b?N:t?v.accent:v.primary},S," ",e.readonly?"\u{1F512}":"")),$=(P,O)=>{let Ge=s&&i===O;if(!A(P))return null;let Ne=f?.has(P.id)??!1;return o?gt.createElement(tc,{key:P.id,index:O,width:n,ticket:P,isSelected:Ge,isFlashing:Ne,mode:c}):gt.createElement(ec,{key:P.id,width:j,ticket:P,isSelected:Ge,isFlashing:Ne})};return gt.createElement(Js,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?v.accent:v.secondary,paddingRight:1,paddingLeft:1,height:r},z,gt.createElement(Js,{padding:o?1:0},p.length>0&>.createElement(et,{selectedIndex:i,height:D,itemHeight:M},p.map($)),U&>.createElement(Re,{isSelected:!0})))},nc=gt.memo(Nf);import{Box as pn,Text as ri}from"ink";import Ee,{useMemo as fr}from"react";var rc=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},oc=(e,t,n)=>Q.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 Bn,Text as St}from"ink";import Te,{useEffect as Sf,useMemo as Af,useRef as Rf}from"react";import{decodeTime as Qs}from"ulid";var Tf=e=>xe(e,"attachments"),wf=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Qs(t.id)-Qs(n.id)),sc=e=>{for(let t of e)I.deleteNode(t.id)},Mf=(e,t,n)=>Q.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Pf=(e,t)=>{let n=I.getNode(Tf(e.id));if(!n||!Oe(n))return[];let r=t.map((o,s)=>Mf(o,s,n.id)).map(o=>I.createNode(o)).filter(te).map(({value:o})=>o).filter(Oe);return t.length>0&&g().selectedIndex<0&&T.navigate({contextNode:n,selectedIndex:0}),r},Lf=e=>`${Math.max(1,Math.round(e/1024))} KB`;function ic({ticket:e,width:t,height:n}){let r=Af(()=>wf(e),[e]),o=Rf([]);Sf(()=>(sc(o.current),o.current=Pf(e,r),()=>{sc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Te.createElement(Bn,{flexDirection:"column",width:t,height:n,padding:1},Te.createElement(St,{color:v.primary},"No attachments yet."),Te.createElement(Bn,{paddingTop:1},Te.createElement(St,{color:v.primary},"Attach images from the browser GUI"),Te.createElement(St,{color:v.accent}," epiq gui "),Te.createElement(St,{color:v.primary},"by dropping or pasting them."))):Te.createElement(Bn,{flexDirection:"column",width:t,height:n},Te.createElement(Bn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:v.secondary,borderStyle:"single",paddingBottom:1},Te.createElement(St,{color:v.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Te.createElement(et,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,b=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Te.createElement(Bn,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Te.createElement(St,{color:v.accent},f?"\u276F ":" "),Te.createElement(Bn,{paddingLeft:1},Te.createElement(St,{color:v.secondary2},`#${p+1} `),Te.createElement(St,{color:f?v.accent:v.primary},b),Te.createElement(St,{color:v.secondary2}," "+Lf(m.bytes)+" "+Cn(Qs(m.id)))))})))}import{Box as Wt,Text as At}from"ink";import fe,{useEffect as kf,useMemo as Df,useRef as Ff}from"react";import{decodeTime as Zs}from"ulid";var Bf=e=>xe(e,"comments"),Uf=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Zs(t.id)-Zs(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),ac=e=>{for(let t of e)I.deleteNode(t.id)},Of=(e,t)=>{let n=I.getNode(Bf(e.id));if(!n||!Oe(n))return[];let r=t.map((o,s)=>oc(o,s,n.id)).map(I.createNode).filter(te).map(({value:o})=>o).filter(Zn);return t.length>0&&g().selectedIndex<0&&T.navigate({contextNode:n,selectedIndex:0}),r},_f=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function dc({ticket:e,width:t,height:n}){let r=Df(()=>Uf(e),[e]),o=Ff([]);kf(()=>(ac(o.current),o.current=Of(e,r),()=>{ac(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?fe.createElement(Wt,{flexDirection:"column",width:t,height:n,padding:1},fe.createElement(At,{color:v.primary},"No comments yet."),fe.createElement(Wt,{paddingTop:1},fe.createElement(At,{color:v.primary},"Use"),fe.createElement(At,{color:v.accent}," :comment "),fe.createElement(At,{color:v.primary},"to add the first one."))):fe.createElement(Wt,{flexDirection:"column",width:t,height:n},fe.createElement(Wt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:v.secondary,borderStyle:"single",paddingBottom:1},fe.createElement(At,{color:v.secondary2},"Comments (",r.length,") ")),fe.createElement(et,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return fe.createElement(Wt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:v.secondary,borderStyle:"single"},fe.createElement(Wt,{flexDirection:"row",paddingBottom:1},fe.createElement(At,{color:v.accent},f?"\u276F ":" "),fe.createElement(Wt,{paddingLeft:1},fe.createElement(At,{color:v.secondary2},`#${p+1} `),fe.createElement(Ht,{id:m.authorId}),fe.createElement(At,{color:v.secondary2}," "+Cn(Zs(m.id))))),fe.createElement(Wt,{paddingLeft:3,paddingBottom:1},fe.createElement(At,{color:v.primary},_f(m.md,u))))})))}import{Box as Eo,Text as $f}from"ink";import Rt from"react";var cc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=H(),{title:o}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,i=s&&A(s)?o===J.ASSIGNEES?s.props.assignees??[]:o===J.TAGS?s.props.tags??[]:[]:[];return Rt.createElement(Eo,{alignItems:"center",paddingTop:1},Rt.createElement(Eo,{minWidth:12},Rt.createElement(Re,{isSelected:n}),Rt.createElement($f,{color:n?v.accent:v.secondary2},o,":")),Rt.createElement(Eo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return Rt.createElement(Eo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Rt.createElement(Re,{isSelected:m}),o===J.ASSIGNEES?Rt.createElement(Ht,{isSelected:m,id:c}):o===J.TAGS?Rt.createElement(kn,{isSelected:m,id:c}):null)})))};import{Box as Co,Text as ei}from"ink";import Tt,{useEffect as Hf,useMemo as lc}from"react";var Wf="\u2029",uc=(e,t)=>`${e}::inline-line::${t}`,ti=new Map,mc=e=>{let t=ti.get(e)??[];ti.delete(e);for(let n of t)I.deleteNode(n)},jf=(e,t)=>{mc(e);let n=[];t.forEach((r,o)=>{let s=_e(BigInt(o+1));if(!te(s))return;let i=I.createNode(Q.text({id:uc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),ti.set(e,n)},ni=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=H(),u=lc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=lc(()=>u.join("\0"),[u]);Hf(()=>(jf(e,u),()=>{mc(e)}),[e,m]);let p=b=>String(b).replace(/\r?\n/g,""),f=u.map((b,N)=>{let S=c.id===e&&i===N;return Tt.createElement(Co,{key:uc(e,N)},Tt.createElement(ei,{color:S?v.primary:v.secondary2,dimColor:!S},`${N+1} `.padStart(5,"\xA0")),Tt.createElement(ei,{backgroundColor:S?"gray":void 0},p(b.length?nn(b,s-10):Wf)))});return Tt.createElement(Co,{flexDirection:"column",paddingTop:1},Tt.createElement(Co,null,Tt.createElement(Re,{isSelected:o}),Tt.createElement(ei,{color:o?v.accent:v.secondary2},t)),Tt.createElement(Co,{flexDirection:"row",borderStyle:"round",borderColor:v.secondary,paddingLeft:1,marginLeft:1},Tt.createElement(et,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var Vf=e=>xe(e,"description"),Kf=e=>xe(e,"comments"),Gf=e=>xe(e,"history"),zf=e=>xe(e,"attachments"),pc=({ticket:e,height:t})=>{let n=fr(()=>rc(e),[e]),{selectedIndex:r,contextNode:o}=H(),s=process.stdout.columns||120,i=fr(()=>Vf(e.id),[e.id]),c=fr(()=>Kf(e.id),[e.id]),u=fr(()=>Gf(e.id),[e.id]),m=fr(()=>zf(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,f=o.id===e.id,b=o.id===c||o.parentNodeId===c,N=o.id===u||o.parentNodeId===u,S=o.id===m||o.parentNodeId===m,R=G(e.id);if(b){let O=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(dc,{ticket:e,width:s,height:O}))}if(S){let O=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(ic,{ticket:e,width:s,height:O}))}if(N){let P=I.getNode(u),O=P&&Oe(P)?P.props.value??"":"",Ne=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},P?Ee.createElement(ni,{id:P.id,label:"Event log",text:O,selected:!1,maxWidth:s,height:Ne}):null)}let M=R.reduce((P,O)=>Qn(O)||O.id===c||O.id===m||O.id===u?P+1:P,0),U=2,j=3,D=M,z=t-j-D-U,$=(P,O)=>P.id===i?Ee.createElement(ni,{key:P.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:O,maxWidth:s,height:z}):Qn(P)?Ee.createElement(cc,{key:P.id,parent:P,selected:O,selectedIndex:r}):P.id===c?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(ri,{backgroundColor:v.secondary,color:O?v.accent:v.primary},` Comments (${n}) \u203A\u203A `)):P.id===m?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(ri,{backgroundColor:v.secondary,color:O?v.accent:v.primary},` Attachments (${p}) \u203A\u203A `)):P.id===u?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(ri,{backgroundColor:v.secondary,color:O?v.accent:v.primary}," History \u203A\u203A ")):null;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((P,O)=>$(P,f&&r===O)))};var Yf=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===L.TICKET||u===L.FIELD_LIST||u===L.FIELD,p=u===L.BOARD||u===L.SWIMLANE,f=u===L.TICKET?t:r.find(M=>M.context===L.TICKET),b=Math.floor(c/3),N=Math.floor(c/Math.max(e.length,1)),S=Math.min(N,b),R=s==="dense";return No.createElement(qf,{flexDirection:"row",height:i},p&&e.map((M,U)=>{let j=t.id===M.id,D=j?n:-1,z=t.context===L.BOARD&&n===U;return No.createElement(nc,{key:M.id,height:i,width:S,swimlane:M,isSelected:z,isDense:R,isFocused:j,listSelectedIndex:D,mode:o})}),m&&f&&No.createElement(pc,{height:i,ticket:f}))},So=No.memo(Yf);import{render as Qf}from"ink";import{Writable as Zf}from"node:stream";var gr=e=>String(e).padStart(2,"0"),eg=e=>{let t=e.getUTCFullYear(),n=gr(e.getUTCMonth()+1),r=gr(e.getUTCDate()),o=gr(e.getUTCHours()),s=gr(e.getUTCMinutes()),i=gr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},tg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",ng=async(e,{width:t,height:n})=>{let r="",o=new Zf({write(i,c,u){let m=rg(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Qf(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},rg=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),gc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),i=r.find(U=>U.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await ng(Jf.createElement(So,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(U=>U!==void 0&&Dt(U)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=Lr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,b=eg(f),N=`board_${tg(i.title)}_${b}.md`,S=ki(p.value);fc.mkdirSync(S,{recursive:!0});let R=Xf.join(S,N),M=`# Board - ${i.title}
|
|
45
|
+
`)}`):(ip(),E({hasProjectDefinition:!0}),l("State booted successfully",null))}var dn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),ro=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)}},X=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ut=null,oo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ut,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),ut)return logger.debug("[sync] syncAndReloadState joining existing promise"),ut;logger.debug("[sync] syncAndReloadState creating promise"),ut=ap();try{let e=await ut;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),d(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({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}),ut||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),ut=null}},ap=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=nd();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(ut)return ut;logger.debug("[sync] syncAndReloadState:start");let t=X("resolveActorId",se());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");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=on(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=X("syncEpiqWithRemote",await so({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),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Qe(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=X("loadMergedEvents",Et(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=nd();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:i.message,syncStatus:g().syncStatus}),i;let c=Qa(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=X("bootStateFromEventLog",an(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=X("restoreNavigationAnchor",ed(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),d(m)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},nd=()=>g().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var An=3e3,rd=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<An?null:t},od=0,Fs,Bs=!1,sr=!1,Us=()=>{if(Bs)return!0;let e=Je();return d(e)?!1:e.value.syncStatus.status==="syncing"},dp=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-od;return Math.max(0,e-t)},sd=()=>{Fs||(Fs=setTimeout(async()=>{if(Fs=void 0,!!Rn()){if(Us()){sr=!0;return}sr=!1,await cp()}},dp()))},cp=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Rn())return a("Cannot auto-sync before state is initialized");if(Us())return sr=!0,a("Sync already in progress");Bs=!0,od=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await oo()}finally{Bs=!1,sr&&sd()}},io=()=>{Rn()&&(sr=!0,!Us()&&sd())};var Ot=()=>{let e=K(),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}},id=()=>{let e=Ye(process.cwd());if(d(e))return!1;let t=Lt(e.value);return te(t)},ad=e=>e===!0?"on":e===!1?"off":null,dd=e=>e==="on"?!0:e==="off"?!1:null;var lp=e=>e.props.tags??[],up=e=>e.props.assignees??[],_t=e=>lp(e).map(t=>I.getTag(t)).filter(t=>!!t),$t=e=>up(e).map(t=>I.getContributor(t)).filter(t=>!!t),ao=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",_t(n))},co=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",$t(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",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",COFFEE:"coffee",NONE:""};var mp=/^(\d+)(h|d|w|mo|y)$/,pp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,fp=({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},gp=(e,t=new Date)=>{let n=e.match(mp);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}},yp=e=>{let t=e.match(pp);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return fp({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},cn=e=>{let t=e.trim().toLowerCase();return gp(t)??yp(t)};var cd=/^(\d+)(s|m)?$/,lo=e=>{let t=e.trim().toLowerCase().match(cd);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},uo=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&cd.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},ld=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,vp=[{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}],Os=(e=vp)=>{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 hp=["BOARD","TICKET","SWIMLANE","COMMENT"],ne={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},$e={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},pe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},xp=[ne.EDITOR,ne.VIEW,ne.USERNAME,ne.AUTOSYNC,ne.SYNC_DEBOUNCE_MS,ne.ATTACHMENT_MAX_KB,ne.LOG_LEVEL],bp=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[$e.TITLE,$e.DESCRIPTION];case"BOARD":case"SWIMLANE":return[$e.TITLE];case"COMMENT":return[$e.COMMENT];default:return[]}},$s=[String(An),"5000","15000","30000","60000"],Hs=["250","500","1000"],pd=["10s","20s","30s","45s"],ln=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],mo=[x.NEW,x.EDIT,x.DELETE,x.MOVE],_s=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],ud=[x.FILTER,x.PEEK,x.REPLAY],Ip={WORKSPACE:[...ln,...mo],BOARD:[...ud,...ln,...mo],SWIMLANE:[...ud,...ln,...mo],TICKET:[...ln,...mo,..._s],FIELD:[...ln,..._s],FIELD_LIST:[...ln,..._s],TEXT:[...ln],COMMENT:[x.EDIT,x.DELETE,x.YANK]},Ep=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ir=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&A(n)),md=e=>e.parentNodeId===me,Cp=({selectedNode:e,breadCrumb:t})=>{let n=bp(e?.context);return ir({breadCrumb:t,selectedNode:e})?n.includes($e.DESCRIPTION)?n:[...n,$e.DESCRIPTION]:n},Np=({selectedNode:e,breadCrumb:t})=>{let n=ir({breadCrumb:t,selectedNode:e});return n?[pe.REF,pe.TITLE,...n.props?.description?.trim()?[pe.DESCRIPTION]:[],..._t(n).length>0?[pe.TAGS]:[],...$t(n).length>0?[pe.ASSIGNEES]:[]]:e?[pe.REF,pe.TITLE]:[]},Sp=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ot();if(!r)return[x.HELP,x.CONFIG];if(!id())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let o=e?.context,s=o&&hp.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Ip[u]:[]))],c=ir({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(c??e):u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&_t(c).length>0):u===x.UNASSIGN?!!(c&&$t(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&md(c)):u===x.CLOSE_ISSUE?!!(c&&!md(c)):!0)},ie=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Sp({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Os(),"now","prev","next"],[x.REPLAY]:[...Os()],[x.EDIT]:Cp({selectedNode:n,breadCrumb:o}),[x.YANK]:Np({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(In),...I.getExistingTags()])],[x.UNTAG]:[...ao()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...co()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:I.getExistingAssignees(),[x.NEW]:Ep(s),[x.CONFIG]:[...xp],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Ld from"chalk";var fd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Le=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")},gd=["png","jpg","gif","webp"];import Hp from"zod";import kp from"node:os";import xd from"node:path";import{z as Nt}from"zod";import{accessSync as Ap,copyFileSync as Rp,existsSync as po,mkdirSync as yd,readdirSync as vd,readFileSync as Tp,renameSync as wp,rmSync as Mp,statSync as hd,unlinkSync as Pp,writeFileSync as Lp}from"node:fs";import Tn from"node:path";var Ws=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",He={writeToFile:(e,t)=>{try{let n=Tn.dirname(e);po(n)||yd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Lp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Tp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=He.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 po(e)&&hd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Ap(e),!0}catch{return!1}},mkDir:e=>yd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Tn.parse(t);for(;;){let r=Tn.join(t,e);try{if(po(r)&&hd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Tn.dirname(t)}return null},readFirstJSON(e){try{if(!He.dirExists(e))return null;let t=vd(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Tn.join(e,t);return He.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return He.dirExists(e)?vd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Pp(e)}catch(t){(!Ws(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Mp(e,{recursive:!0,force:!0})}catch(t){(!Ws(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Tn.dirname(t)),!n?.overwrite&&po(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{wp(e,t)}catch(r){if(Ws(r)&&r.code==="EXDEV"){Rp(e,t),this.rmFile(e);return}throw r}}};var Dp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},bd=Nt.object({logLevel:Nt.enum(["info","error","debug"]),preferredEditor:Nt.string().optional(),userName:Nt.string().optional(),userId:Nt.string().optional(),autoSync:Nt.boolean().nullable().optional(),autoSyncDebounceMs:Nt.number().optional(),attachmentMaxKb:Nt.number().optional(),viewMode:Nt.enum(["dense","wide"]).optional()}).partial(),Fp="config.json",Id=()=>xd.join(kp.homedir(),qe),js=()=>xd.join(Id(),Fp),Vs=()=>{try{return He.mkDir(Id()),l(`Ensured ~/${qe} exists`,null)}catch{return a(`Unable to create ~/${qe}`)}},Bp=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${qe}/config.json JSON`)}let n=bd.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${qe}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ar=()=>{let e=Vs();if(d(e))return a(e.message);let t=js(),n=He.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Bp(n)},Ed=e=>{let t=Vs();if(d(t))return a(t.message);let n=bd.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=js();try{return He.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
46
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${qe}/config.json`)}},Ze=e=>{let t=ar();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Ed(n)},wn=()=>{let e=js(),t=Vs();if(d(t))return a(`Unable to create ~/${qe}`);if(!(He.readFile(e)!==null)){let b=Ed(Dp);if(d(b))throw new Error(`Unable to create ~/${qe}/config.json`)}let r=ar();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value;return!s||!i?a(`User name or ID not configured in ~/${qe}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import Up from"node:crypto";import dr from"node:fs";import Cd from"node:path";var mt=500,Op=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Mn=(e,t)=>`${e}.${t}`,_p=e=>Op.test(e),Nd=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("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")))?l("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"))?l("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${gd.join(", ")}`),Sd=e=>Up.createHash("sha256").update(e).digest("hex"),$p=(e,t=mt)=>{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=Nd(e);return d(n)?n:l("Validated attachment data",{hash:Sd(e),ext:n.value,bytes:e.length})},Ad=(e,t,n=mt)=>{let r=$p(t,n);if(d(r))return r;let o=Kn(e),s=Cd.join(o,Mn(r.value.hash,r.value.ext));try{dr.existsSync(s)||(dr.mkdirSync(o,{recursive:!0}),dr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",r.value)},Rd=(e,t,n=mt)=>{if(!_p(t))return a("Invalid attachment file name");let r=Cd.join(Kn(e),t);if(!dr.existsSync(r))return a("Attachment blob not found");let o;try{o=dr.readFileSync(r)}catch(u){return a(`Unable to read attachment blob: ${u instanceof Error?u.message:String(u)}`)}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(Sd(o)!==s)return a("Attachment blob does not match its content hash");let c=Nd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):l("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var cr=50,lr=5e3,Td=()=>{let e=Y().commandMeta.inputString,t=Hp.coerce.number().int().min(cr).max(lr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${cr}-${lr} KB (default ${mt})`);let n=Ze({attachmentMaxKb:t.data});return d(n)?n:(Fe({attachmentMaxKb:t.data}),E({mode:y.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))};import wd from"chalk";var Z=e=>wd.dim(e),be=e=>wd.hex(v.primary)(e),Ie=({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,b)=>zr(f)-zr(b)).slice(0,r).map(f=>qr(f)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""};var pt={None:"none",Invalid:"invalid",Valid:"valid"};var Pn=140,Wp=["BOARD","TICKET","SWIMLANE"],Md=()=>{let e=g().selectedNode;if(!e?.context)return F({message:Z("Missing target context")});if(Wp.includes(e.context))return V();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===xe(t?.parentNodeId??"","comments"))return V()}return F({message:Z("Command not available in this context")})},re="<ENTER> to confirm",V=(e="",t=[])=>({message:Z(e),validity:pt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:pt.Invalid,message:e,completionWordList:t}),go=e=>e.length===0,Pd=(e,t)=>{let n=Le(g().breadCrumb,"BOARD");if(d(n))return F({message:be("Command is not applicable in this context")});let r=Xr(n.value.id);return d(r)?F({message:be(`Unable to ${t}: board id is not a valid ULID`)}):ld({date:e,horizonDate:r.value})?null:F({message:be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},fo=e=>` ${Ld.hex("#000").bgHex(le(e))(` ${e} `)} `,Ks=({modifier:e})=>{let t="confirm";return e===t?V(re):F({message:go(e)?Z("if you are certain, enter ")+qr(t):"",completionWordList:[t]})},jp=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:Z(n)}):V():F({message:go(r)?t:"",completionWordList:[...e]}),un=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>go(n)&&go(r)?F({message:e,completionWordList:[]}):V(t??re),Vp=({modifier:e,inputString:t})=>{let n=ie(x.CONFIG);if(!n.includes(e))return F({message:Ie({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ne.EDITOR:{let r=[...fd];return t.trim()?r.includes(t.trim())?V(re):F({message:Ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:Ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?V(re):F({message:Ie({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.USERNAME:return t.trim()?V(re):F({message:be("Enter a user name. Saved in ")+Ld.bgBlack("~/.epiq-global/config.json")});case ne.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?V(re):F({message:Ie({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ne.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=ad(o);return F({message:Ie({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return V(re)}case ne.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<cr||o>lr){let s=Ie({prefix:" examples: ",wordList:Hs,minLengthForHints:0,inputString:t});return F({message:be(`provide a size cap in KB (${cr}-${lr}). current: ${r??mt} KB.`)+s,completionWordList:Hs})}return V(re)}case ne.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=rd(t);if(!t.trim()||o===null||o<An){let s=Ie({prefix:" examples: ",wordList:$s,minLengthForHints:0,inputString:t});return F({message:be(`provide duration above ${An}ms. current duration: ${r}ms.`)+s,completionWordList:$s})}return V(re)}default:return F({message:be("Unknown config option"),completionWordList:n})}},Kp=({modifier:e,inputString:t})=>{let n=ie(x.EDIT);if(!n.length)return F({message:be("Command not available in this context")});if(!n.includes(e)){let r=Ie({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||be("Unknown edit option"),completionWordList:n})}switch(e){case $e.COMMENT:return t.trim()?V(re):F({message:Z("write a comment...")});case $e.TITLE:return V(re);case $e.DESCRIPTION:{let{preferredEditor:r}=K();return r?V(Z("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:be("Unknown edit option"),completionWordList:n})}},Gp=({modifier:e})=>{let t=ie(x.YANK);return t.length?t.includes(e)?V(re+Z(" and copy to clipboard")):F({message:Ie({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):F({message:be("Nothing selected to copy from")})},zp={[x.EXPORT]:()=>V(re+Z(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return V(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=cn(r);if(!r||!o)return F(n);let s=Pd(o,"peek");return s||V(re)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=uo(e.modifier,e.inputString),r={message:Z("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=cn(t);if(!t||!o)return F(r);let s=Pd(o,"replay");return s||(n&&lo(n)===null?F({message:be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):V("<ENTER> to replay board history",n?pd:[]))},[x.EXIT]:()=>V(re+Z(" and exit the application")),[x.INIT]:()=>V(re),[x.PALETTE]:()=>V(re),[x.FILTER]:e=>{if(e.modifier==="clear")return V(re);let t=s=>ie(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:Ie({wordList:ie(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ie(x.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:Ie({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):V():F({message:Ie({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=ie(x.NONE);return F({message:Ie({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>jp({list:ie(x.NEW),hint:Ie({wordList:ie(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>V(re),[x.EDIT]:Kp,[x.COMMENT]:e=>{let t=un({hint:Z(`write a comment (max ${Pn} char)...`),onOk:Z(`(${e.inputString.length}/${Pn})`)})(e);return t.validity===pt.Invalid?t:e.inputString.length>Pn?V(be("max input exceeded")):t},[x.CONFIG]:Vp,[x.YANK]:Gp,[x.DELETE]:e=>{let t=Md();return t.validity==="invalid"?t:Ks(e)},[x.CLOSE_ISSUE]:e=>Ks(e),[x.RE_OPEN_ISSUE]:e=>Ks(e),[x.MOVE]:e=>{let t=Md();return t.validity==="invalid"?t:un({hint:Ie({prefix:"hey hacker! These commands are blocked for you... ",wordList:ie(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(fo).join("");return un({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[x.UNTAG]:e=>{let t=ao();if(d(t))return F({message:be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(fo).slice(0,10);return n.length?un({hint:Z(" ... ")+n.join("")})(e):F({message:be("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=I.getExistingAssignees().map(fo).slice(0,10);return un({hint:Z("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=co();if(d(t))return F({message:be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(fo).slice(0,10);return n.length?un({hint:Z("remove assignee... ")+n.join("")})(e):F({message:be("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>V(re),[x.COFFEE]:e=>{let{modifier:t}=e,n=ie(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:Z("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):un({hint:Ie({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},kd=Object.fromEntries(Object.entries(zp).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var yo=["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 qp=3,Yp=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"]),Xp=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},Jp=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=qp&&!Yp.has(t)&&!/^\d+$/.test(t)),Qp=e=>{let t=new Map;for(let s of Xp(e))for(let i of Jp(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=yo.filter(s=>!r.has(s));return[...n,...o]},Dd=yo,Fd=-1,Bd=()=>{let e=Je();if(d(e))return yo;let t=e.value,n=t.eventLog.length;return n!==Fd&&(Dd=Qp(t),Fd=n),Dd};var Ud=e=>Object.values(x).includes(e),Od=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=kd[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?ie(n):m?Bd():[],{mode:f}=g(),b=f===y.COMMAND_LINE?i??"":"",N=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:b,autoCompletion:t?va(e,N):{hint:"",hints:[],remainder:"",overlap:0}}};var _d=e=>{let t=e.trimStart(),n=ef(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=tf(e),c=Ud(r)?r:null,u=c!==null,m=r!=="",p=c?ie(c)??[]:[],f=c&&p.includes(o)?o:"",b="word";n.length===0||n.length===1&&!s?b="command":(n.length===1&&s||n.length===2&&!s)&&(b="modifier");let N=s?"":i,S=Zp(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:b,inputToMatch:N,inputString:S}},Zp=(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},ef=e=>e.trim()?e.trim().split(/\s+/):[],tf=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as nf}from"react";var Ln=e=>e===Gs||e===":",Gs=" ",Ae={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:pt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},zs=new Set,$d=()=>{for(let e of zs)e()},qs=e=>(zs.add(e),()=>zs.delete(e)),ft=e=>{let n=e(Ae),r=_d(n.value),o=n.cursorPosition===n.value.length;Ae={...n,commandMeta:Od(r,o)},$d()},ur=({message:e,status:t})=>{let n=structuredClone(Ae);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ae=n,$d(),l(e,null)},Ys=e=>{ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Xs=e=>{ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ln(n[o-1]);)o--;for(;o>0&&!Ln(n[o-1]);)o--}else{for(;o<n.length&&!Ln(n[o]);)o++;for(;o<n.length&&Ln(n[o]);)o++}return{...t,cursorPosition:o}})},Hd=()=>{ft(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}})},Wd=()=>{ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ln(t[r-1]);)r--;for(;r>0&&!Ln(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},vo=e=>{ft(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,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},jd=()=>{ft(e=>({...e,commandIsPending:!0}))},W=e=>{ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Vd=({addToHistory:e=!0})=>{ft(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Kd=()=>{ft(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}})},Gd=()=>{ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Y=()=>Ae,zd=()=>nf(qs,Y,Y),qd=()=>{let[e,...t]=Ae.value.split(Gs);return t.join(Gs).trim()};var h={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 rf(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function of(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function sf(e,t,n){let r=g().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 Yd(e,t){let n=Y();if(e.sequence==="?"&&t!==y.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return h.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===y.COMMAND_LINE)return la(e,n.value);if(t===y.PALETTE)return ua(e,n.value);let r=rf(e)||of(e);if(r)return af(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"y":return h.Yank;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return K().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function af(e,t){let n=t===y.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return sf(g().contextNode.childRenderAxis,e,n)}var ho=e=>{let{context:t}=g().contextNode;if(!t)return w.None;switch(e){case x.EXIT:return w.Exit;case x.EXPORT:return w.Export;case x.COFFEE:return w.Coffee;case x.INIT:return w.Init;case x.DELETE:return w.Delete;case x.EDIT:return w.Edit;case x.COMMENT:return w.Comment;case x.HELP:return w.ViewHelp;case x.RE_OPEN_ISSUE:return w.ReopenIssue;case x.CLOSE_ISSUE:return w.CloseIssue;case x.TAG:return w.TagTicket;case x.UNTAG:return w.UntagTicket;case x.ASSIGN:return w.AssignUserToTicket;case x.UNASSIGN:return w.UnassignUserFromTicket;case x.NEW:return w.NewItem;case x.FILTER:return w.Filter;case x.MOVE:return w.Move;case x.PEEK:return w.Peek;case x.REPLAY:return w.Replay;case x.CONFIG:return w.Config;case x.YANK:return w.Yank;case x.SYNC:return w.Sync;default:return w.None}},w={Exit:"exit",Init:"init",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",Coffee:"coffee"};import{ulid as we}from"ulid";import gc from"node:fs";import Jf from"node:path";import Qf from"react";import{Box as Yf}from"ink";import No from"react";import Cf from"chalk";import{Box as Qs,Text as Nf}from"ink";import gt from"react";import{Text as Xd}from"ink";import Jd,{useEffect as Qd,useState as df}from"react";var Zd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=H(),r=Zd[n]??Zd.default,[o,s]=df(0);if(Qd(()=>{s(0)},[r]),Qd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Jd.createElement(Xd,null,t);let i=r[o]??r[0]??t;return Jd.createElement(Xd,{color:v.accent,dimColor:o===1},i)};import{Box as Js,Text as cf}from"ink";import xo from"react";var et=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),f=p+c,b=e.slice(p,f),N=e.length>c,S=s,R=N?Math.max(1,Math.floor(c/e.length*S)):S,M=Math.max(0,S-R),U=Math.max(1,e.length-c),j=N?Math.floor(p/U*M):0;return xo.createElement(Js,{flexDirection:"row",height:s,width:"100%"},xo.createElement(Js,{flexDirection:"column",flexGrow:1,height:s},b),xo.createElement(Js,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((D,z)=>xo.createElement(cf,{key:z,color:N&&z>=j&&z<j+R?v.accent:v.secondary},N?"\u2502":" "))))};import{Box as Fn,Text as Io}from"ink";import tt from"react";import{Text as lf}from"ink";import uf from"react";var mf=e=>e.toLowerCase().trim(),pf=(e,t=In)=>{let n=mf(e);return t[n]?t[n]:tr(n)},Ht=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return uf.createElement(lf,{underline:t,color:pf(n.name)},"@"+n.name)};import{Text as ff}from"ink";import gf from"react";var kn=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return gf.createElement(ff,{underline:t,backgroundColor:le(n.name),color:v.secondary}," "+n.name+" ")};import{useEffect as yf,useState as vf}from"react";var hf=80,ec=1400,bo=new Set,mr=null,xf=e=>(bo.add(e),mr||(mr=setInterval(()=>{for(let t of bo)t()},hf)),()=>{bo.delete(e),bo.size===0&&mr&&(clearInterval(mr),mr=null)}),bf=()=>{let e=Date.now()%ec/ec;return e<.5?e*2:(1-e)*2},Dn=e=>{let[,t]=vf(0);return yf(()=>{if(e)return xf(()=>t(n=>n+1))},[e]),Gr(bf())};var If=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),nn(e.slice(r).trim(),t)]},tc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Dn(r),s=e-4,[i,c]=If(lt(t.title),s),u=c?null:nn(lt(t.props.description),s)||null,m=_t(t),p=$t(t);return tt.createElement(Fn,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?v.accent:v.secondary,justifyContent:"space-between"},tt.createElement(Fn,{paddingLeft:1,flexDirection:"column"},tt.createElement(Io,{color:v.primary},i),c&&tt.createElement(Io,{color:v.primary},c),u&&tt.createElement(Io,{color:v.secondary2,dimColor:!0},u)),tt.createElement(Fn,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},tt.createElement(Fn,{flexDirection:"row"},m.map(f=>tt.createElement(Fn,{paddingRight:1,key:f.id},tt.createElement(kn,{key:f.id,id:f.id}))),p.map(f=>tt.createElement(Fn,{paddingRight:1,key:f.id},tt.createElement(Ht,{key:f.id,id:f.id})))),tt.createElement(Io,{wrap:"truncate",color:v.secondary2,dimColor:!0},Ue(t.id))))};import{Box as mn,Text as pr}from"ink";import We from"react";var Ef=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,nc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=Dn(r),c=(t.props.tags??[]).map(D=>I.getTag(D)).filter(D=>!!D),u=(t.props.assignees??[]).map(D=>I.getContributor(D)).filter(D=>!!D),m=1,p=c.length*(1+m),f=u.length*(2+m),b=c.map(D=>We.createElement(mn,{key:D.id,paddingRight:m},We.createElement(pr,{color:le(D.name)},"\u25A0"))),N=u.map(D=>We.createElement(mn,{key:D.id,paddingRight:m},We.createElement(pr,{color:tr(D.name)},"@"+D.name.at(0)))),S=r?i:n?v.accent:s===y.MOVE?v.secondary:v.primary,R=4,M=I.getCommentsByIssue(t.id),U=M.length?String(M.length).length+2+m:0,j=M.length?We.createElement(mn,{paddingRight:m},We.createElement(pr,{color:v.accent},"[",M.length,"]")):null;return We.createElement(mn,{borderBottom:!0,justifyContent:"space-between"},We.createElement(mn,null,We.createElement(mn,{width:R},n?We.createElement(Re,{isSelected:n}):We.createElement(pr,{color:"gray",dimColor:!0},o+1)),We.createElement(pr,{wrap:"truncate",color:S},Ef(t.title,e-p-f-U-18))),We.createElement(mn,null,b,N,j))};var Sf=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=H(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,b=f?.has(e.id)??!1,N=Dn(b),S=`${e.title} ${Cf.hex(v.secondary2).dim("("+p.length+")")}`,R=3,M=o?1:5,U=s&&i===-1,j=n-(U?7:5),D=r-R-(o?2:1),z=gt.createElement(Qs,{borderStyle:"round",borderColor:v.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},gt.createElement(Re,{isSelected:t}),gt.createElement(Nf,{bold:!0,color:b?N:t?v.accent:v.primary},S," ",e.readonly?"\u{1F512}":"")),$=(P,O)=>{let Ge=s&&i===O;if(!A(P))return null;let Ne=f?.has(P.id)??!1;return o?gt.createElement(nc,{key:P.id,index:O,width:n,ticket:P,isSelected:Ge,isFlashing:Ne,mode:c}):gt.createElement(tc,{key:P.id,width:j,ticket:P,isSelected:Ge,isFlashing:Ne})};return gt.createElement(Qs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?v.accent:v.secondary,paddingRight:1,paddingLeft:1,height:r},z,gt.createElement(Qs,{padding:o?1:0},p.length>0&>.createElement(et,{selectedIndex:i,height:D,itemHeight:M},p.map($)),U&>.createElement(Re,{isSelected:!0})))},rc=gt.memo(Sf);import{Box as pn,Text as oi}from"ink";import Ee,{useMemo as fr}from"react";var oc=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},sc=(e,t,n)=>Q.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 Bn,Text as St}from"ink";import Te,{useEffect as Af,useMemo as Rf,useRef as Tf}from"react";import{decodeTime as Zs}from"ulid";var wf=e=>xe(e,"attachments"),Mf=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Zs(t.id)-Zs(n.id)),ic=e=>{for(let t of e)I.deleteNode(t.id)},Pf=(e,t,n)=>Q.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Lf=(e,t)=>{let n=I.getNode(wf(e.id));if(!n||!Oe(n))return[];let r=t.map((o,s)=>Pf(o,s,n.id)).map(o=>I.createNode(o)).filter(te).map(({value:o})=>o).filter(Oe);return t.length>0&&g().selectedIndex<0&&T.navigate({contextNode:n,selectedIndex:0}),r},kf=e=>`${Math.max(1,Math.round(e/1024))} KB`;function ac({ticket:e,width:t,height:n}){let r=Rf(()=>Mf(e),[e]),o=Tf([]);Af(()=>(ic(o.current),o.current=Lf(e,r),()=>{ic(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Te.createElement(Bn,{flexDirection:"column",width:t,height:n,padding:1},Te.createElement(St,{color:v.primary},"No attachments yet."),Te.createElement(Bn,{paddingTop:1},Te.createElement(St,{color:v.primary},"Attach images from the browser GUI"),Te.createElement(St,{color:v.accent}," epiq gui "),Te.createElement(St,{color:v.primary},"by dropping or pasting them."))):Te.createElement(Bn,{flexDirection:"column",width:t,height:n},Te.createElement(Bn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:v.secondary,borderStyle:"single",paddingBottom:1},Te.createElement(St,{color:v.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Te.createElement(et,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,b=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Te.createElement(Bn,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Te.createElement(St,{color:v.accent},f?"\u276F ":" "),Te.createElement(Bn,{paddingLeft:1},Te.createElement(St,{color:v.secondary2},`#${p+1} `),Te.createElement(St,{color:f?v.accent:v.primary},b),Te.createElement(St,{color:v.secondary2}," "+kf(m.bytes)+" "+Cn(Zs(m.id)))))})))}import{Box as Wt,Text as At}from"ink";import fe,{useEffect as Df,useMemo as Ff,useRef as Bf}from"react";import{decodeTime as ei}from"ulid";var Uf=e=>xe(e,"comments"),Of=e=>I.getCommentsByIssue(e.id).sort((t,n)=>ei(t.id)-ei(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),dc=e=>{for(let t of e)I.deleteNode(t.id)},_f=(e,t)=>{let n=I.getNode(Uf(e.id));if(!n||!Oe(n))return[];let r=t.map((o,s)=>sc(o,s,n.id)).map(I.createNode).filter(te).map(({value:o})=>o).filter(Zn);return t.length>0&&g().selectedIndex<0&&T.navigate({contextNode:n,selectedIndex:0}),r},$f=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function cc({ticket:e,width:t,height:n}){let r=Ff(()=>Of(e),[e]),o=Bf([]);Df(()=>(dc(o.current),o.current=_f(e,r),()=>{dc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?fe.createElement(Wt,{flexDirection:"column",width:t,height:n,padding:1},fe.createElement(At,{color:v.primary},"No comments yet."),fe.createElement(Wt,{paddingTop:1},fe.createElement(At,{color:v.primary},"Use"),fe.createElement(At,{color:v.accent}," :comment "),fe.createElement(At,{color:v.primary},"to add the first one."))):fe.createElement(Wt,{flexDirection:"column",width:t,height:n},fe.createElement(Wt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:v.secondary,borderStyle:"single",paddingBottom:1},fe.createElement(At,{color:v.secondary2},"Comments (",r.length,") ")),fe.createElement(et,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return fe.createElement(Wt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:v.secondary,borderStyle:"single"},fe.createElement(Wt,{flexDirection:"row",paddingBottom:1},fe.createElement(At,{color:v.accent},f?"\u276F ":" "),fe.createElement(Wt,{paddingLeft:1},fe.createElement(At,{color:v.secondary2},`#${p+1} `),fe.createElement(Ht,{id:m.authorId}),fe.createElement(At,{color:v.secondary2}," "+Cn(ei(m.id))))),fe.createElement(Wt,{paddingLeft:3,paddingBottom:1},fe.createElement(At,{color:v.primary},$f(m.md,u))))})))}import{Box as Eo,Text as Hf}from"ink";import Rt from"react";var lc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=H(),{title:o}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,i=s&&A(s)?o===J.ASSIGNEES?s.props.assignees??[]:o===J.TAGS?s.props.tags??[]:[]:[];return Rt.createElement(Eo,{alignItems:"center",paddingTop:1},Rt.createElement(Eo,{minWidth:12},Rt.createElement(Re,{isSelected:n}),Rt.createElement(Hf,{color:n?v.accent:v.secondary2},o,":")),Rt.createElement(Eo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return Rt.createElement(Eo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Rt.createElement(Re,{isSelected:m}),o===J.ASSIGNEES?Rt.createElement(Ht,{isSelected:m,id:c}):o===J.TAGS?Rt.createElement(kn,{isSelected:m,id:c}):null)})))};import{Box as Co,Text as ti}from"ink";import Tt,{useEffect as Wf,useMemo as uc}from"react";var jf="\u2029",mc=(e,t)=>`${e}::inline-line::${t}`,ni=new Map,pc=e=>{let t=ni.get(e)??[];ni.delete(e);for(let n of t)I.deleteNode(n)},Vf=(e,t)=>{pc(e);let n=[];t.forEach((r,o)=>{let s=_e(BigInt(o+1));if(!te(s))return;let i=I.createNode(Q.text({id:mc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),ni.set(e,n)},ri=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=H(),u=uc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=uc(()=>u.join("\0"),[u]);Wf(()=>(Vf(e,u),()=>{pc(e)}),[e,m]);let p=b=>String(b).replace(/\r?\n/g,""),f=u.map((b,N)=>{let S=c.id===e&&i===N;return Tt.createElement(Co,{key:mc(e,N)},Tt.createElement(ti,{color:S?v.primary:v.secondary2,dimColor:!S},`${N+1} `.padStart(5,"\xA0")),Tt.createElement(ti,{backgroundColor:S?"gray":void 0},p(b.length?nn(b,s-10):jf)))});return Tt.createElement(Co,{flexDirection:"column",paddingTop:1},Tt.createElement(Co,null,Tt.createElement(Re,{isSelected:o}),Tt.createElement(ti,{color:o?v.accent:v.secondary2},t)),Tt.createElement(Co,{flexDirection:"row",borderStyle:"round",borderColor:v.secondary,paddingLeft:1,marginLeft:1},Tt.createElement(et,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var Kf=e=>xe(e,"description"),Gf=e=>xe(e,"comments"),zf=e=>xe(e,"history"),qf=e=>xe(e,"attachments"),fc=({ticket:e,height:t})=>{let n=fr(()=>oc(e),[e]),{selectedIndex:r,contextNode:o}=H(),s=process.stdout.columns||120,i=fr(()=>Kf(e.id),[e.id]),c=fr(()=>Gf(e.id),[e.id]),u=fr(()=>zf(e.id),[e.id]),m=fr(()=>qf(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,f=o.id===e.id,b=o.id===c||o.parentNodeId===c,N=o.id===u||o.parentNodeId===u,S=o.id===m||o.parentNodeId===m,R=G(e.id);if(b){let O=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(cc,{ticket:e,width:s,height:O}))}if(S){let O=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(ac,{ticket:e,width:s,height:O}))}if(N){let P=I.getNode(u),O=P&&Oe(P)?P.props.value??"":"",Ne=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},P?Ee.createElement(ri,{id:P.id,label:"Event log",text:O,selected:!1,maxWidth:s,height:Ne}):null)}let M=R.reduce((P,O)=>Qn(O)||O.id===c||O.id===m||O.id===u?P+1:P,0),U=2,j=3,D=M,z=t-j-D-U,$=(P,O)=>P.id===i?Ee.createElement(ri,{key:P.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:O,maxWidth:s,height:z}):Qn(P)?Ee.createElement(lc,{key:P.id,parent:P,selected:O,selectedIndex:r}):P.id===c?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(oi,{backgroundColor:v.secondary,color:O?v.accent:v.primary},` Comments (${n}) \u203A\u203A `)):P.id===m?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(oi,{backgroundColor:v.secondary,color:O?v.accent:v.primary},` Attachments (${p}) \u203A\u203A `)):P.id===u?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(oi,{backgroundColor:v.secondary,color:O?v.accent:v.primary}," History \u203A\u203A ")):null;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((P,O)=>$(P,f&&r===O)))};var Xf=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===L.TICKET||u===L.FIELD_LIST||u===L.FIELD,p=u===L.BOARD||u===L.SWIMLANE,f=u===L.TICKET?t:r.find(M=>M.context===L.TICKET),b=Math.floor(c/3),N=Math.floor(c/Math.max(e.length,1)),S=Math.min(N,b),R=s==="dense";return No.createElement(Yf,{flexDirection:"row",height:i},p&&e.map((M,U)=>{let j=t.id===M.id,D=j?n:-1,z=t.context===L.BOARD&&n===U;return No.createElement(rc,{key:M.id,height:i,width:S,swimlane:M,isSelected:z,isDense:R,isFocused:j,listSelectedIndex:D,mode:o})}),m&&f&&No.createElement(fc,{height:i,ticket:f}))},So=No.memo(Xf);import{render as Zf}from"ink";import{Writable as eg}from"node:stream";var gr=e=>String(e).padStart(2,"0"),tg=e=>{let t=e.getUTCFullYear(),n=gr(e.getUTCMonth()+1),r=gr(e.getUTCDate()),o=gr(e.getUTCHours()),s=gr(e.getUTCMinutes()),i=gr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},ng=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",rg=async(e,{width:t,height:n})=>{let r="",o=new eg({write(i,c,u){let m=og(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Zf(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},og=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),yc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),i=r.find(U=>U.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await rg(Qf.createElement(So,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(U=>U!==void 0&&Dt(U)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=Lr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,b=tg(f),N=`board_${ng(i.title)}_${b}.md`,S=Di(p.value);gc.mkdirSync(S,{recursive:!0});let R=Jf.join(S,N),M=`# Board - ${i.title}
|
|
47
47
|
Date: ${f.toISOString()}
|
|
48
48
|
|
|
49
49
|
\`\`\`text
|
|
50
50
|
${m}
|
|
51
51
|
\`\`\`
|
|
52
|
-
`;return
|
|
52
|
+
`;return gc.writeFileSync(R,M,"utf8"),l("Exported board layout",R)};var Ao=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};import{useSyncExternalStore as eR}from"react";var Ro,sg=new Set,vc=()=>{for(let e of sg)e()};var jt=()=>{if(!Ro)throw new Error("Ui state not initialized. Call initUiState() first.");return Ro};var hc=(e={})=>(Ro=e,vc(),l("UX state initialized",null)),ig=e=>{let t=jt();return Ro=e(t),vc(),l("UX state updated",null)},Vt=e=>ig(t=>({...t,...e}));import{spawn as ag}from"node:child_process";function yr(e){let t=process.platform,o=ag(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}import{ulid as si}from"ulid";import{spawnSync as dg}from"node:child_process";import cg from"node:os";import xc from"node:path";import{ulid as lg}from"ulid";function ug(){let{preferredEditor:e}=K(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function mg(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function bc(e){let t=xc.join(cg.tmpdir(),"epiq");He.mkDir(t);let n=xc.join(t,lg());He.writeToFile(n,e??"");let r=ug();for(let o of r){let s=mg(o,n),i=dg(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=He.readFile(n);if(c==null)return a("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return a("Unable to open editor")}var Ic=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(e.modifier===$e.DESCRIPTION)return fg();if(r&&Zn(r))return pg(e);if(e.modifier===$e.TITLE){let o=se();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await at();return d(c)?c:B([{id:si(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},pg=async e=>{let t=se();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=G(n.id)[r];if(!o||!Zn(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=g().nodes[s];if(!i||!A(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=I.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await at();if(d(p))return p;let f=p.value;return B([{id:si(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],f)},fg=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let t=await at();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=Le([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!A(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=G(i.id).find(f=>f.title===J.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=bc(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:si(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import yg from"node:fs";import Cc from"node:path";import ii from"node:fs";import gg from"node:path";var Ec=async e=>{let t=gg.join(e,".gitignore"),n=ii.existsSync(t)?ii.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
53
53
|
`).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
54
54
|
`);return n=n.trimEnd()+`
|
|
55
55
|
|
|
56
56
|
${c}
|
|
57
|
-
`,
|
|
58
|
-
`));let ce=Je();if(d(ce))return ee(16,ce.message);let{rootNodeId:$n,nodes:Hn}=ce.value,Mi=Hn[$n];return Mi?(T.navigate({contextNode:Mi,selectedIndex:0}),E({hasProjectDefinition:!0,mode:y.DEFAULT}),l(O,null)):ee(16,"Unable to resolve initialized root node")};import{ulid as hg}from"ulid";import{ulid as vg}from"ulid";var Nc=null,Kt=()=>structuredClone(Nc),vr=e=>{Nc=e},Sc=()=>{let{contextNode:e,selectedIndex:t}=g(),r=q(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},ii=({id:e,parentId:t,position:n={at:"end"}})=>{let r=q(t).filter(o=>o.id!==e);return to(r,n)},Ac=({id:e,parentId:t,position:n={at:"end"}})=>{let r=se();if(d(r))return a("Unable to resolve user ID");let o=ii({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:vg(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Rc=e=>{vr(e);let t=Bt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function ai(e){let t=Sc();if(d(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=q(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=Ac({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Rc(u.value)}function di(e){let t=Sc();if(d(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=q(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Ac({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Rc(i.value)}var Tc=()=>{let e=Kt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return a("Move parent not found");let o=q(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(T.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},To=(e,t="Moved preview")=>{if(d(e))return e;let n=Tc();return d(n)?n:(E({mode:y.MOVE}),l(t,null))},wc=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=Y().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=q(n.id)[r];if(!o)return E({mode:y.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=q(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=ii({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(vr({id:hg(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:y.MOVE}),l("Move initialized",null))}if(t==="next")return To(di(1));if(t==="previous")return To(di(-1));if(t==="to-next")return To(ai(1));if(t==="to-previous")return To(ai(-1));if(t==="confirm"){let s=Kt();if(!s)return a("No pending move to confirm");let i=await at();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=Tc();return d(u)?u:(vr(null),E({mode:y.DEFAULT}),l("Moved item",null))}return t==="cancel"?(vr(null),E({mode:y.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Mo}from"ulid";import{monotonicFactory as xg,ulid as bg}from"ulid";var Ig=xg(),wo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Ig();return l("Created issue events",[{id:bg(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Mc=async(e,t)=>{let n=se();if(d(n))return a("Unable to resolve user ID");let r=await at();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:c}=g(),u=m=>{let p=B([m],o);if(d(p))return p;let f=I.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let b=I.getNode(f.parentNodeId);return b?(T.navigate({contextNode:b,selectedIndex:I.getSiblings(f.parentNodeId).findIndex(({id:N})=>N===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return a("Workspace not found");let f=Sn(p.id,n.value,o);return d(f)?f:u({id:Mo(),action:"add.board",payload:{id:Mo(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Le(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Sn(m.value.id,n.value,o);return d(p)?p:u({id:Mo(),action:"add.swimlane",payload:{id:Mo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=G(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let j=Le(s,"SWIMLANE");return d(j)?null:j.value})();if(!p)return a("Unable to add issue in this context");let f=Sn(p.id,n.value,o);if(d(f))return f;let b=wo({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(b))return b;let N=b.value,S=B([...N],o);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let U=N.find(j=>j.action==="add.issue")?.payload.id;return U?(T.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:j})=>j===U)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var Po=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Oa(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Gt();if(d(u))return u;let p=Ut(i).filter(d);if(p.length>0)return Gt(),E(o),a(p.map(b=>b.message).join(", "));let f=g().nodes[e];return f?(T.navigate({contextNode:f,selectedIndex:r}),l("",{unappliedEvents:c})):(Gt(),E(o),a("Board did not exist at that date"))};var Eg=20,Cg=16,Ng=150,Lo=null,ko=null;var fn=()=>{Lo!==null&&(clearInterval(Lo),Lo=null),ko!==null&&(clearTimeout(ko),ko=null)},Pc=()=>{fn(),E({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Sg=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)},Lc=({events:e,startTime:t,durationMs:n})=>{fn();let r=e.length,o=e.map(f=>Nn(f)??t),s=o[r-1]??Date.now(),i=Sg(o),c=Math.max(1,Math.round(n*Eg/1e3)),u=Math.max(Math.round(n/c),Cg),m=0,p=0;E({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Lo=setInterval(()=>{m++;let f=m/c,b=[],N;for(;p<r&&i[p]<=f;){let R=e[p],M=Bt(R);if(d(M)){Pc();return}b.push(...Ts(R)),N=R,p++}if(p>=r||m>=c){for(;p<r;p++){let M=Bt(e[p]);if(d(M))break}let R=g().replay;E({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),fn(),ko=setTimeout(Pc,Ng);return}let S=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?Nn(N)??S?.currentTime??t:S?.currentTime??t,currentLabel:N?Pa(N):S?.currentLabel??"",flashNodeIds:N?[...new Set(b)]:S?.flashNodeIds??[]}})},u)};var kc=async()=>{let e=Le(g().breadCrumb,"BOARD");if(d(e))return e;let t=await dt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=Y().commandMeta;if(fn(),r==="now"){let c=Et(n.value);if(d(c))return a(c.message);let u=Gt();if(d(u))return u;let p=Ut(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(E({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=g().eventLog.at(-1),u=Nn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=g().unappliedEvents.at(0),u=Nn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=cn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Po({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(E({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var Dc=async()=>{let e=Le(g().breadCrumb,"BOARD");if(d(e))return e;let t=await dt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=Y().commandMeta,{dateInput:s,durationInput:i}=uo(r,o);if(fn(),g().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=cn(s);if(!c)return a("Invalid replay date");let u=i?lo(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=Po({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:b}=f.value;return b.length===0?(Gt(),E(p),l("Nothing to replay from that point",!0)):(Lc({events:b,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Rg from"zod";var Fc=()=>{let e=Y().commandMeta.inputString,t=Rg.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=Ze({autoSyncDebounceMs:t.data});return d(n)?n:(Fe({autoSyncIntervalMs:t.data}),E({mode:y.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Bc=()=>{let e=Y().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=ad(e),n=Ze({autoSync:t});return d(n)?n:(Fe({autoSync:t}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var Uc=()=>{let e=Y().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Ze({logLevel:e});return d(n)?n:(Fe({logLevel:e}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))};import{spawn as Tg}from"node:child_process";var wg=()=>{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"]}}},Oc=async e=>new Promise(t=>{let{command:n,args:r}=wg();try{let o=Tg(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("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 hr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Oc(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},_c=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=ir({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case pe.REF:return hr(Ue(o.id),"ref");case pe.TITLE:return hr(o.title,"title");case pe.DESCRIPTION:return r?hr(r.props?.description??"","description"):a("No issue in scope");case pe.TAGS:{if(!r)return a("No issue in scope");let s=_t(r).map(({name:i})=>i);return hr(s.join(", "),"tags")}case pe.ASSIGNEES:{if(!r)return a("No issue in scope");let s=$t(r).map(({name:i})=>i);return hr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var $c=async()=>{W(""),E({mode:y.DEFAULT});let e=Je();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await oo();return d(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Mg=e=>e.action==="add.issue.comment",Hc=e=>Object.values(g().tags).find(t=>t.name===e),Wc=e=>Object.values(g().contributors).find(t=>t.name===e),wt=async()=>{let e=await at();return d(e)?e:l("Resolved persist root",e.value)},Do=[{systemOnly:!0,intent:w.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:wc},{intent:w.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await wt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=A(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!A(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Mg).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:we(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:we(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Y().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>ie(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return he(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),l("Filter updated",null)}},{intent:w.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Vt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:y.HELP}),l("Viewing help",null)}},{intent:w.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!A(r))return a("Cannot close in this context");let o=g().nodes[me];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await wt();if(d(s))return s;let i=s.value,c=sn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:we(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):It(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=g().nodes[me];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!A(s))return a("Target node is not issue");let c=Ao(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await wt();if(d(m))return m;let p=m.value,f=sn(u.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let b=B([{id:we(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return d(b)?b:l("Issue reopened",null)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Cc},{intent:w.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:Mc,onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=zd();if(!o)return a("Provide a title");let s=await wt();return d(s)?s:B([{id:we(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Hc(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid untag target");let i=It(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await wt();return d(m)?m:B([{id:we(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=g();if(!o)return a("Invalid tag target");let s=It(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!A(i))return a("Target node is not issue");let c=await wt();if(d(c))return c;let u=Hc(r),m=u?.id??we();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:we(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:we(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=g(),i=G(s.id)[o];if(!i)return a("Invalid assign target");let c=It(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!A(u))return a("Target node is not issue");let m=await wt();if(d(m))return m;let p=Wc(r),f=p?.id??we();return(u.props.assignees??[]).includes(f)?a("Assignee already assigned"):B([...p?[]:[{id:we(),action:"create.contributor",payload:{id:f,name:r},...e.value}],{id:we(),action:"add.issue.assignee",payload:{id:u.id,assignee:f},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=Wc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid unassign target");let i=It(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await wt();return d(m)?m:B([{id:we(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>Pn)return a(`Cannot exceed ${Pn} characters`);let r=se();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),i=Le([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):It(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!A(m))return a("Target node is not issue");let p=await wt();return d(p)?p:B([{id:we(),action:"add.issue.comment",payload:{id:we(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:$c},{intent:w.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:kc},{intent:w.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:Dc},{intent:w.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await gc();return d(e)?e:(E({mode:y.DEFAULT}),l("Export successful",!0))}},{intent:w.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(T.exit(),l("Exit successful",!0))},{intent:w.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>bc(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>_c(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ne.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??we();if(!i||!c)return a("Unable to resolve user name or id");let u=Ze({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(Fe({userName:i,userId:c}),E({mode:y.DEFAULT}),l(`Username set to "${i}"`,null))}case ne.EDITOR:{if(!n)return a("No editor provided");let r=Ze({preferredEditor:n});return d(r)?r:(Fe({preferredEditor:n}),E({mode:y.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ne.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Ze({viewMode:n});return d(r)?r:(Fe({viewMode:n}),E({mode:y.DEFAULT}),l(`View set to "${n}"`,null))}case ne.AUTOSYNC:return Bc();case ne.LOG_LEVEL:return Uc();case ne.SYNC_DEBOUNCE_MS:return Fc();case ne.ATTACHMENT_MAX_KB:return Rd();default:return a("Unknown config command")}}},{intent:w.Coffee,description:"Sponsor the development of Epiq!",mode:y.COMMAND_LINE,action:()=>{let e=Y().commandMeta.modifier;return e==="custom"?yr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):yr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),W(""),l("Thanks you!",null)}}];var Pg=new Set(["peek","replay","filter","view-help","yank"]),yt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Y();if(!t)return a("No command to confirm");if(!e&&n===pt.Invalid)return a("Invalid command");let s=ho(t);Wd();let{readOnly:i}=g();if(i&&!Pg.has(s))return ur({status:Pt.Fail,message:"Command not available in readonly state",value:null});let c=Do.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return ur({status:Pt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return ur({status:Pt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?ur(u):(jd({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&io(),u)};var Fo=[{intent:h.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:y.COMMAND_LINE}),W("move cancel"),yt({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:y.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:y.COMMAND_LINE}),W("move start"),yt({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:y.MOVE,action:()=>(E({mode:y.COMMAND_LINE}),W("move confirm"),yt({isForceExecutedBySystem:!0}))}],Bo=[{intent:h.MovePreviousItem,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move next"),yt({isForceExecutedBySystem:!0})):a("No pending move")}],jc=[{intent:h.MoveToNextContainer,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move to-next"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move to-previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")}];var Vc={[L.WORKSPACE]:[...Fo,...Bo],[L.BOARD]:[...Fo,...Bo],[L.SWIMLANE]:[...Fo,...Bo,...jc],[L.TICKET]:[],[L.FIELD]:[],[L.FIELD_LIST]:[],[L.TEXT]:[],[L.COMMENT]:[]};import Lg from"node:fs";import kg from"node:path";var Kc=e=>{let t=Ye(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=Mn(e.hash,e.ext),o=kg.join(Kn(n.value),r);return Lg.existsSync(o)?(yr(o),l(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var Gc=()=>{W("");let{pendingNavTarget:e}=jt();E({mode:y.DEFAULT}),e&&T.navigate(e),Vt({pendingNavTarget:void 0})},zc=[{intent:h.ExitCommandLine,mode:y.HELP,action:()=>(Gc(),l("Exiting help",null))},{intent:h.Exit,mode:y.HELP,action:()=>(Gc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:y.HELP,action:()=>(T.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:y.HELP,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:y.HELP,action:()=>(T.navigateToNextContainer(),l("Navigating to next help container",null))}];var Dg=e=>{E({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=jt();t&&T.navigate(t),Vt({pendingNavTarget:void 0}),W(`${e} `)},qc=()=>{W("");let{pendingNavTarget:e}=jt();e&&T.navigate(e),Vt({pendingNavTarget:void 0}),E({mode:y.DEFAULT})},Yc=[{intent:h.InitCommandPalette,mode:y.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{W("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Vt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:y.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!kt(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?(Dg(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:y.PALETTE,action:()=>(qc(),l("Exiting palette",null))},{intent:h.Exit,mode:y.PALETTE,action:()=>(qc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:y.PALETTE,action:()=>(T.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:y.PALETTE,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:y.PALETTE,action:()=>(T.navigateToNextContainer(),l("Navigating to next container",null))}];var Xc=[...zc,...Yc,{intent:h.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:y.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:y.COMMAND_LINE}),W(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!q(e?.id??"")?.length){let r=e?I.getAttachment(e.id):void 0;if(r)return Kc(r);if(e?.title===J.DESCRIPTION)return E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===J.ASSIGNEES)return E({mode:y.COMMAND_LINE}),W(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===J.TAGS)return E({mode:y.COMMAND_LINE}),W(`${x.TAG} `),l("Propose command",!0);if(t.title===J.DESCRIPTION&&e?.context==="TEXT")return E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Propose command",!0)}return T.enterChildNode(),l("Entering context",null)}},{intent:h.Yank,mode:y.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===J.DESCRIPTION?pe.DESCRIPTION:e?.title===J.TAGS?pe.TAGS:e?.title===J.ASSIGNEES?pe.ASSIGNEES:pe.REF,r=ie(x.YANK).includes(t)?t:pe.REF;return E({mode:y.COMMAND_LINE}),W(`${x.YANK} ${r}`),l("Propose command",!0)}},{intent:h.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:y.DEFAULT,description:"[e] edit description",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(T.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:y.DEFAULT,action:()=>(T.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:y.DEFAULT,action:()=>(T.navigateToNextContainer(),l("Navigating to next container",null))}];var Fg=500,Bg=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Jc=e=>{let t=Bg(e);t&&vo(n=>(n+t).slice(0,Fg))};var Ug=[y.COMMAND_LINE,y.PALETTE],Og=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(qs(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(qs(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Ys("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Ys("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(vo((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(Jc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>($d(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(Hd(),l("Erasing input word",null))}],Qc=[{intent:h.Confirm,mode:y.COMMAND_LINE,action:()=>(yt(),l("Executing command",null))},{intent:h.ViewHelp,mode:y.DEFAULT,action:()=>(E({mode:y.HELP}),l("Viewing help",null))},...Ug.flatMap(Og),{intent:h.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(E({mode:y.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Vd(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Kd(),l("Getting next command from history",null))}];import tl from"chalk";var Uo=tl.dim.hex(v.secondary2)(": for command line"),Zc="q to exit",el=`${tl.hex(v.accent)("m")} to confirm`,ci={[L.WORKSPACE]:[Uo],[L.BOARD]:[Uo],[L.BOARD+y.COMMAND_LINE]:[Uo],[L.SWIMLANE]:[Uo],[L.TICKET+y.HELP]:[Zc],[L.SWIMLANE+y.HELP]:[Zc],[L.TICKET]:[],[L.FIELD]:[],[L.SWIMLANE+y.MOVE]:[el],[L.TICKET+y.MOVE]:[el]};var xr=e=>e.trim().toLocaleLowerCase(),_g=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},$g=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},nl=(e,t)=>{let n=xr(t.value);if(!n)return!0;switch(t.target){case"title":return xr(e.title??"").includes(n);case"description":return xr(e.props.description??"").includes(n);case"tag":return _g(e).map(xr).some(o=>o.includes(n));case"assignee":return $g(e).map(xr).some(o=>o.includes(n));case"ref":return ba(e.id,t.value);default:return!0}};function rl(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var ol=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 gn,li,ui=new Set,sl=()=>{for(let e of ui)e()},Wg=e=>(ui.add(e),()=>ui.delete(e));function il(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 c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=rl(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=ci[p+n]??ci[p]??[],b=[...Xc,...Vc[p]??[],...Qc],N=ol(b),S=jg(o,s),R=S[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:b,actionIndex:N,selectedNode:R,renderedChildrenIndex:S})}var g=()=>{if(!gn)throw new Error("State not initialized. Call initWorkspaceState() first.");return gn},Je=()=>gn?l("Retrieved state",gn):a("State not initialized. Call initWorkspaceState() first.");function nr(e){li=e;let t=Ye(process.cwd()),n=!1;if(!d(t)){let s=Lt(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.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=il(r);return d(o)?o:(gn=o.value,sl(),l("State initialized",null))}function he(e){let t=g(),n=e(t),r=il(n);return d(r)?a(r.message??"Unable to update state"):(gn=r.value,sl(),l("State updated",null))}var E=e=>he(t=>({...t,...e}));var H=()=>Hg(Wg,g,g),jg=(e,t)=>{let n={};for(let r of Object.values(e))A(r)&&t.length>0&&!t.every(o=>nl(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},G=e=>g()?.renderedChildrenIndex[e]??[],Gt=()=>li?nr(li):a("Cannot reset state: no initial workspace found"),Rn=()=>gn!==void 0;var mi=e=>{Rn()&&(E({syncStatus:e}),tn({type:"sync-status",payload:e}))},Oo=(e="Syncing...")=>{mi({status:"syncing",msg:e})},_o=(e="Synced")=>{mi({status:"synced",msg:e})},pi=e=>{mi({status:"failed",msg:e})},Qe=e=>(pi(e),a(e));import{decodeTime as JL}from"ulid";var Vg=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=X("getRepoRootDir",await dt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=X("getStateBranchRoot",Pe({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=X("ensureInitialCommit",await ta(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=X("bootstrapStateBranchStorage",await oa({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=X("hasInProgressGitOperation(stateBranchRoot)",await Fr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.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 m=X("ensureStateBranchLayout",Qi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Kg=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=X("stageStateBranchOwnEventFile",await Wr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=X("stageStateBranchMediaFiles",await na({stateBranchRoot:t}));if(d(o))return a(o.message);let s=X("hasStagedChanges(after stage)",await Ki(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=X("createStateBranchSyncCommit",await ra({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),l("Committed own event file",{createdCommit:!0,commitSha:i.value}))},so=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");Oo();let n=X("ensureSyncReady",await Vg({cwd:e,ensureUpstream:!0}));if(d(n))return Qe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=X("isDetachedHead(stateBranchRoot)",await Gi(o));if(d(i))return Qe(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Qe("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=X("getStateBranch",hn(r));if(d(f))return Qe(f.message);let b=f.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:o});let N=X("commitOwnEventFileToStateBranch",await Kg({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(N))return Qe(N.message);c=N.value.createdCommit,u=N.value.commitSha;let S=X("pullBranchRebaseIfPresent",await vs({cwd:o,branch:b}));if(d(S))return Qe(S.message);if(m=S.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let R=X("pushStateBranch",await Jn({stateBranchRoot:o,repoRoot:r}));if(d(R)&&Vi(R.message)){let M=X("pullBranchRebaseIfPresent(retry)",await vs({cwd:o,branch:b}));if(d(M))return Qe(M.message);m=m||M.value,R=X("pushStateBranch(retry)",await Jn({stateBranchRoot:o,repoRoot:r}))}if(d(R))return Qe(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let R=X("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(d(R))return Qe(R.message);u=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return _o(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var fi=()=>{let e=wn();return d(e)?mt:e.value.attachmentMaxKb??mt},gi=e=>{let t=Ye(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},Me=async e=>{let t=gi(e);if(d(t))return t;let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=vn(),o=await en({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await _({cwd:n.value,args:["pull","--ff-only"]});d(s)&&oe.info(3,s.message);let i=Et(n.value);if(d(i))return a(i.message);let c=an(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},ke=()=>{let e=wn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=Je();return d(e)?a(e.message):e},dl=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:le(t.name)})),cl=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:le(t.name)}));var ll=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(A).filter(o=>e.includeClosed||o.parentNodeId!==me).map(o=>({id:o.id,ref:Ue(o.id),title:lt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===me,readonly:!!o.readonly,tags:dl(o),assignees:cl(o)}));return l("Listed issues",r)},ul=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=Sn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=wo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},ml=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=sn(me,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:ge(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:me,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},pl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Target node is not issue");if(o.parentNodeId!==me)return a("Issue is not closed");let s=Ao(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===me)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=sn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:ge(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},fl=async e=>{let t=gi(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=Pe({repoRoot:t.value});if(d(r))return r;let o=Et(r.value);if(d(o))return o;let s=an(o.value);if(d(s))return s;let i=sn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:ge(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},$o=async(e={})=>{Oo();let t=gi(e.repoRoot);if(d(t))return a("Sync failed");let n=ke();if(d(n))return n;let r=await so({cwd:t.value,ownEventFileName:on(n.value)});return d(r)?(pi(r.message),r):(_o(),l("Synced",r.value))};var vt=async(e={})=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(f=>Vr(f)&&!f.isDeleted),s=new Map,i=new Map;for(let f of r)if(!f.isDeleted){if(Dt(f)&&f.parentNodeId){let b=s.get(f.parentNodeId)??[];b.push(f),s.set(f.parentNodeId,b)}if(A(f)&&f.parentNodeId){let b=i.get(f.parentNodeId)??[];b.push(f),i.set(f.parentNodeId,b)}}let c=wn();if(d(c))return c;let u={};for(let f of r.filter(A))f.isDeleted||(u[f.id]=I.getCommentsByIssue(f.id).map(b=>{let N=I.getContributor(b.authorId);return{id:b.id,issueId:b.issue,body:b.md,author:{id:b.authorId,name:N?.name??"Unknown",color:le(N?.name??b.authorId)},createdAt:al(b.id)}}));let m=new Map;for(let f of n.value.eventLog)f.action==="add.issue.attachment"&&m.set(f.payload.id,f.payload.author);let p={};for(let f of r.filter(A))f.isDeleted||(p[f.id]=I.getAttachmentsByIssue(f.id).map(b=>({id:b.id,issueId:b.issue,name:b.name,fileName:Mn(b.hash,b.ext),bytes:b.bytes,createdAt:al(b.id),canDelete:m.get(b.id)===c.value.userId})));return l("Retrieved Epiq GUI state",{boards:o.sort((f,b)=>f.rank.localeCompare(b.rank)).map(f=>({id:f.id,ref:Ue(f.id),title:f.title,swimlanes:(s.get(f.id)??[]).sort((b,N)=>b.rank.localeCompare(N.rank)).map(b=>({id:b.id,title:b.title,readonly:!!b.readonly,issues:(i.get(b.id)??[]).sort((N,S)=>N.rank.localeCompare(S.rank)).map(N=>({id:N.id,ref:Ue(N.id),title:lt(N.title),description:N.props.description??"",readonly:!!N.readonly,tags:dl(N),assignees:cl(N),parentNodeId:N.parentNodeId,isClosed:N.parentNodeId===me})),parentNodeId:b.parentNodeId}))})),tags:Object.values(n.value.tags).map(f=>({...f,color:le(f.name)})),contributors:Object.values(n.value.contributors).map(f=>({...f,color:le(f.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:le(c.value.userName??"")},commentsByIssueId:u,attachmentsByIssueId:p,attachmentMaxKb:fi()})},gl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:ge(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},yl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=lt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:ge(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},vl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=lt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??ge(),u=[...i?[]:[{id:ge(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:ge(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},hl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(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:ge(),...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):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},xl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=lt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??ge(),u=[...i?[]:[{id:ge(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:ge(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},bl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(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:ge(),...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):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Ho=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(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");let i=ge(),c={id:ge(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},Wo=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();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(!A(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 l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:ge(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Il=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=Sd(t.value.stateBranchRoot,s,fi());if(d(i))return i;let c=lt(e.name??"").trim()||"image",u=ge(),m={id:ge(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);return d(p)?a(p.message):l("Added issue attachment",{id:u,issueId:e.issueId,fileName:Mn(i.value.hash,i.value.ext),bytes:i.value.bytes})},El=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();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(!A(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 l("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:ge(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Cl=async e=>{let t=await Me(e.repoRoot);return d(t)?t:Ad(t.value.stateBranchRoot,e.fileName,fi())};var Nl=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=ar();if(d(p))return oe.error(p.message);let{autoSync:f,userName:b,preferredEditor:N}=p.value;return!!(f&&b&&N)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await $o({repoRoot:e.repoRoot}),tn({type:"state",payload:await vt({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=ar();if(d(p))return oe.error(p.message);let{autoSyncDebounceMs:f}=p.value;i()&&(t=setTimeout(()=>{c(),m()},f??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as Gg}from"ws";var Ve=(e,t)=>{e.send(JSON.stringify(t))},br=async(e,t)=>Ve(e,{type:"state",payload:await vt({repoRoot:t})}),ht=async(e,t,n,r,o)=>{if(Ve(e,{type:r,payload:o}),d(o))return Ve(e,{type:"failed",payload:o.message});n(),br(e,t)},Sl=(e,t,{onStateChanged:n})=>{new Gg({server:e,path:"/ws"}).on("connection",o=>{sa(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return br(o,t);if(c==="sync"){let u=await $o({repoRoot:t});return Ve(o,{type:"sync:result",payload:u}),n(),br(o,t)}if(c==="issue:comment:add"){let u=await Ho({repoRoot:t,...i.payload});return ht(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await Wo({repoRoot:t,...i.payload});return Ve(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Ve(o,{type:"failed",payload:u.message}):(n(),br(o,t))}if(c==="issue:edit:description"){let u=await gl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await yl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await vl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await hl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await xl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await bl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Ve(o,{type:"issues",payload:await ll({repoRoot:t})});if(c==="issues:create"){let u=await ul({...i.payload,repoRoot:t});return Ve(o,{type:"issues:create:result",payload:u}),d(u)?tn({type:"failed",payload:u.message}):(tn({type:"issue:created",payload:u.value}),n(),br(o,t))}if(c==="issues:move"){if(!i.payload.position)return Ve(o,{type:"error",message:"Missing move position"});let u=await fl({...i.payload,repoRoot:t});return ht(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Ve(o,{type:"error",message:"Missing issueId"});let u=await ml({repoRoot:t,issueId:i.payload.issueId});return ht(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Ve(o,{type:"error",message:"Missing issueId"});let u=await pl({repoRoot:t,issueId:i.payload.issueId});return ht(o,t,n,"issue:reopen:result",u)}return Ve(o,{type:"error",message:"Unknown message type"})}catch(i){return Ve(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Yg=yn.dirname(qg(import.meta.url)),Xg=process.env.IS_LOCAL==="true"?yn.resolve(process.cwd(),"dist/gui"):yn.join(Yg,"gui"),ye=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Al=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+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),Jg=2*1024*1024,Qg={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},Zg=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",Rl=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=yn.resolve(Xg),o=yn.resolve(r,n),s=yn.relative(r,o);if(s.startsWith("..")||yn.isAbsolute(s))return ye(t,403,{isError:!0,message:"Forbidden"});try{let i=await Tl(o);return t.writeHead(200,{"content-type":Zg(o)}),t.end(i)}catch{return ye(t,404,{isError:!0,message:`Not found: ${n}`})}},ey=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),wl=async e=>{let t=zg.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return ye(s,200,await vt({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Al(o);if(!c.issueId||!c.body?.trim())return ye(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Ho({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?ye(s,400,u):ye(s,200,await vt({repoRoot:e.repoRoot}))}catch(c){return ye(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await Al(o,Jg);if(!c.issueId||!c.dataBase64)return ye(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let u=await Il({repoRoot:e.repoRoot,issueId:c.issueId,name:c.name??"",dataBase64:c.dataBase64});return d(u)?ye(s,400,{isError:!0,message:u.message}):ye(s,200,await vt({repoRoot:e.repoRoot}))}catch(c){return ye(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));if(!c)return ye(s,400,{isError:!0,message:"Missing attachment id"});let u=await El({repoRoot:e.repoRoot,attachmentId:c});return d(u)?ye(s,400,{isError:!0,message:u.message}):ye(s,200,await vt({repoRoot:e.repoRoot}))}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),u=await Cl({repoRoot:e.repoRoot,fileName:c});if(d(u))return ye(s,404,{isError:!0,message:u.message});try{let m=await Tl(u.value.filePath);return s.writeHead(200,{"content-type":Qg[u.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return ye(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return ye(s,400,{isError:!0,message:"Missing comment id"});let u=await Wo({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?ye(s,400,u):ye(s,200,await vt({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?Rl("/",s):Rl(i.pathname,s)});try{await ey(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Nl({repoRoot:e.repoRoot});Sl(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Ml=async e=>{let t=await wl({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${ty.cyan(n)}`),Li(n),l("Started GUI",{url:n})};import{Box as Jt}from"ink";import ae from"react";import{Box as yi,Text as Ir}from"ink";import ot,{useEffect as ny,useMemo as ry}from"react";import{ulid as oy}from"ulid";var Pl=({text:e,match:t,color:n,highlightColor:r=v.secondary,dimColor:o=!1})=>{if(!t)return ot.createElement(Ir,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?ot.createElement(Ir,{color:n,dimColor:o},e):ot.createElement(Ir,{color:n,dimColor:o},e.slice(0,c),ot.createElement(Ir,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Ll=oy(),sy=e=>`${e}`,iy=e=>{let{pendingNavTarget:t}=jt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(ie(x.NONE,{breadCrumb:n,contextNode:r,readOnly:g().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=ho(i),u=Do.find(m=>m.intent===c);return{command:i,description:u?.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,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},ay=e=>Q.text({id:Ll,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),dy=(e,t,n)=>Q.text({id:sy(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),vi=[],cy=e=>{kl();let t=I.createNode(ay(g().rootNodeId));d(t)||!kt(t.value)||(vi=[t.value,...e.map((n,r)=>dy(n,r,Ll)).map(I.createNode).filter(te).map(({value:n})=>n).filter(kt)],T.navigate({contextNode:t.value,selectedIndex:0}))},kl=()=>{let e=vi.map(t=>t.id);vi=[];for(let t of e)I.deleteNode(t)};function Dl({width:e,height:t}){let r=Gd().value.trim().toLowerCase(),o=ry(()=>iy(r),[r]);ny(()=>(cy(o),()=>{kl()}),[o]);let s=g().selectedIndex;return ot.createElement(yi,{flexDirection:"column",width:e,height:t-2},ot.createElement(et,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?v.accent:v.secondary2,p=i.isAvailable?"":"[unavailable] ";return ot.createElement(yi,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:v.secondary,borderStyle:"single"},ot.createElement(Ir,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",ot.createElement(Pl,{text:ua(i.command),match:r,color:m,dimColor:!i.isAvailable})),ot.createElement(yi,{paddingLeft:2},ot.createElement(Pl,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?v.primary:v.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Ay}from"ink";import Ko from"react";import Cr from"chalk";import{Box as hi,Text as Fl}from"ink";import Er,{useEffect as ly,useMemo as uy,useState as my}from"react";var Bl=Cr.hex(v.secondary),py=Cr.inverse,fy=Cr.inverse.hex(v.secondary2),gy={hint:"",hints:[],overlap:0,remainder:""},Ol=({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}},yy=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=le(t);return{bg:r=>Cr.bgHex(n).black(r),bgCursor:r=>Cr.bgHex(n).inverse.black(r)}}return Rs(t)},vy=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Ol({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}},Ul=()=>({value:Ae.value,cursorPosition:Ae.cursorPosition,commandIsPending:Ae.commandIsPending,autoCompletion:Ae.commandMeta.autoCompletion??gy,infoMessage:Ae.commandMeta.infoMessage,validationStatus:Ae.commandMeta.validity,command:Ae.commandMeta.command,inputString:Ae.commandMeta.inputString,modifier:Ae.commandMeta.modifier}),hy=(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,_l=({width:e,mode:t})=>{let[n,r]=my(Ul());ly(()=>{let S=()=>{let M=Ul();r(U=>hy(U,M)?U:M)},R=zs(S);return S(),()=>{R()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p,validationStatus:f}=n,b=c&&f===pt.Invalid,N=uy(()=>{let S=Math.max(0,Math.min(s,o.length)),R=Ol({value:o,command:m}),M=vy({value:o,command:m,modifier:p}),U=m?Rs(m):null,j=yy({command:m,modifier:p}),D=(ue,ce)=>{let $n=R&&ce>=R.start&&ce<R.end,Hn=M&&ce>=M.start&&ce<M.end;return $n&&U?U.fg(ue):Hn&&j?j.bg(ue):ue},z=(ue,ce)=>{let $n=R&&ce>=R.start&&ce<R.end,Hn=M&&ce>=M.start&&ce<M.end;return $n&&U?U.fgCursor(ue):Hn&&j?j.bgCursor(ue):py(ue)},$=o.slice(0,S),P=o[S]??" ",O=S<o.length?o.slice(S+1):"",Ge=Array.from($).map((ue,ce)=>D(ue,ce)).join(""),Ne=z(P,S),ze=Array.from(O).map((ue,ce)=>D(ue,S+1+ce)).join("");if(u.hint){let ue=u.hint[u.overlap]??P;Ne=fy(ue),ze=Bl(u.remainder.slice(1)+O)}return Bl(t===y.PALETTE?"?":":")+Ge+Ne+ze},[o,s,u,m,p]);return Er.createElement(hi,{flexDirection:"column",justifyContent:"flex-start"},Er.createElement(hi,{flexDirection:"column",paddingX:1,borderColor:v.secondary,borderStyle:"round",width:e},Er.createElement(hi,null,Er.createElement(Fl,null,N),i&&Er.createElement(Fl,{wrap:"truncate",color:b?v.red:v.secondary2},` ${i} `))))};import{Box as xy,Text as by}from"ink";import $l from"react";var Iy=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Hl=({width:e,availableHints:t})=>{let n=Iy(t,e).join(" | ");return $l.createElement(xy,{width:e,borderStyle:"round",borderColor:v.secondary,paddingX:1},$l.createElement(by,{color:v.secondary2},n.length?n:"\xA0"))};import{Box as Ey,Text as jo}from"ink";import Nr,{useEffect as Cy,useRef as Un,useState as Ny}from"react";var Sy=40,Vo=.3,xi="\u2500",Wl=1,jl=16,Vl=({width:e})=>{let{replay:t}=H(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Wl,[c,u]=Ny(0),m=Un(r);m.current=r;let p=Un(0),f=Un(0),b=Un(0),N=Un(0),S=Un(0);if(Cy(()=>{if(!n){p.current=0,b.current=0,N.current=0,S.current=0,u(0);return}p.current=m.current,f.current=Date.now(),b.current=m.current;let D=setInterval(()=>{let z=Date.now(),$=m.current;if($!==b.current){let ze=$-b.current,ue=z-f.current;if(ze<0)N.current=0,S.current=0;else if(ze>0&&ue>0){let ce=ze/ue;N.current=N.current===0?ce:N.current*(1-Vo)+ce*Vo,S.current=S.current===0?ze:S.current*(1-Vo)+ze*Vo}p.current=$,f.current=z,b.current=$}let P=z-f.current,O=Math.min(S.current,N.current*P),Ge=Math.min(1,p.current+O),Ne=Math.round(Ge*i);u(ze=>ze===Ne?ze:Ne)},Sy);return()=>clearInterval(D)},[n,i]),!t)return null;let R=D=>{let z=s>1?D/(s-1):0,$=Math.round(z*(jl-1))/(jl-1);return Gr($)},M=Math.min(s,Math.floor(c/Wl)),U=[];for(let D=0;D<M;D++){let z=R(D),$=U[U.length-1];$&&$.color===z?$.text+=xi:U.push({text:xi,color:z})}let j=xi.repeat(Math.max(0,s-M));return Nr.createElement(Ey,{width:e,borderStyle:"round",borderColor:v.secondary,paddingX:1,columnGap:1},Nr.createElement(jo,{color:v.secondary2},"\u25B6"),Nr.createElement(jo,null,U.map((D,z)=>Nr.createElement(jo,{key:z,color:D.color},D.text)),Nr.createElement(jo,{color:v.secondary,dimColor:!0},j)))};var Sr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=H(),o=t===y.COMMAND_LINE||t===y.PALETTE;return Ko.createElement(Ay,null,o?Ko.createElement(_l,{width:e,mode:t}):r==="replay"?Ko.createElement(Vl,{width:e}):Ko.createElement(Hl,{width:e,mode:t,availableHints:n}))};import{Box as zt,Text as On}from"ink";import De,{useEffect as Ry,useMemo as Ty}from"react";import{ulid as Kl}from"ulid";var zo=Kl(),wy=()=>[...new Set([...g().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),My=e=>Q.text({id:zo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Py=(e,t,n)=>Q.text({id:Kl(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Go=[],Gl=()=>{let e=Go.filter(n=>n.id!==zo).map(n=>n.id),t=Go.filter(n=>n.id===zo).map(n=>n.id);Go=[];for(let n of[...e,...t])I.deleteNode(n)},Ly=e=>{Gl();let t=I.createNode(My(g().rootNodeId));if(d(t)||!kt(t.value))return logger.error("Could not attach help nodes");Go=[t.value,...e.map((n,r)=>Py(n,r,zo)).map(I.createNode).filter(te).map(({value:n})=>n).filter(kt)],T.navigate({contextNode:t.value,selectedIndex:0})},zl=({width:e,height:t})=>{let n=Ty(()=>wy(),[]);Ry(()=>(Ly(n),()=>{Gl()}),[n]);let r=g().selectedIndex;return De.createElement(zt,{flexDirection:"column",marginTop:3,borderColor:v.secondary,borderStyle:"round",width:e,height:t-2},De.createElement(zt,{paddingX:1,justifyContent:"center"},De.createElement(On,{color:v.accent},"Help"),De.createElement(On,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),De.createElement(zt,{paddingX:1,marginTop:1},De.createElement(zt,{width:20,justifyContent:"flex-end"},De.createElement(On,{color:v.secondary},"Key(s)")),De.createElement(zt,{flexGrow:1,width:40,paddingLeft:2},De.createElement(On,{color:v.secondary},"Action"))),De.createElement(et,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return De.createElement(zt,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},De.createElement(zt,{width:20,justifyContent:"flex-end"},De.createElement(On,{color:v.accent},o)),De.createElement(zt,{flexGrow:1,width:40,paddingLeft:2},De.createElement(On,{color:c?v.primary:v.secondary2},s)))})))};import ky from"chalk";import{Box as qo,Text as Mt}from"ink";import Ke from"react";var ql=({width:e,height:t})=>Ke.createElement(qo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:v.secondary,rowGap:1},Ke.createElement(Mt,{color:v.accent,bold:!0},"Initialize project"),Ke.createElement(Mt,null,`This folder is not an ${ky.hex(v.accent)("epiq")} project yet.`),Ke.createElement(Mt,{color:v.primary},"To start tracking issues here, we need to initialize a new",Ke.createElement(Mt,{color:v.primary,backgroundColor:v.secondary}," .epiq/project.json "),"file in this repository."),Ke.createElement(qo,{marginTop:1,flexDirection:"column"},Ke.createElement(qo,null,Ke.createElement(Mt,{color:v.accent}," "),Ke.createElement(Mt,{color:v.primary},"Type "),Ke.createElement(Mt,{backgroundColor:v.secondary}," :init "))),Ke.createElement(qo,{marginTop:1},Ke.createElement(Mt,{color:v.secondary2},"This will create, commit and push "),Ke.createElement(Mt,{color:v.primary,backgroundColor:v.secondary}," .epiq/project.json ")));import{Box as Yo,Text as xt}from"ink";import Ce from"react";var Dy=({isDone:e,command:t,value:n})=>Ce.createElement(Yo,null,Ce.createElement(xt,{color:v.accent,dimColor:e},e?" \u2714 ":" "),Ce.createElement(xt,{dimColor:e},"Type "),Ce.createElement(xt,{backgroundColor:v.secondary,dimColor:e}," "+t+" "),n!==void 0&&Ce.createElement(Ce.Fragment,null,Ce.createElement(xt,{dimColor:e}," "),Ce.createElement(xt,{color:v.secondary,dimColor:e},"<"+n+">"))),Fy=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function bi({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Ot(),u=[{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:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(f=>!f.done),p=m===-1?void 0:u[m];return Ce.createElement(Yo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:v.secondary,rowGap:1},Ce.createElement(xt,{color:v.accent,bold:!0},"Welcome! \u{1F539}"),Ce.createElement(xt,null,"Let's get you started - it's a breeze."),Ce.createElement(xt,{color:v.secondary2},"Remember - you can always search available commands by typing:",Ce.createElement(xt,{color:v.accent}," ? ")),p&&Ce.createElement(xt,{color:v.secondary2},p.message),Ce.createElement(Yo,{flexDirection:"column"},u.map((f,b)=>m===-1||b<=m?Ce.createElement(Yo,{key:f.key,marginBottom:1},Ce.createElement(Dy,{isDone:f.done,command:f.command,value:f.done?Fy(f.value):void 0})):null)))}import es from"chalk";import{Box as Rr,Text as _n}from"ink";import ve from"react";import{Box as Xo,Text as Yl}from"ink";import qt from"react";import By from"chalk";var Uy=e=>(I.getTag(e)?.name??"").length+3,Oy=e=>(I.getContributor(e)?.name??"").length+3,Xl=({width:e})=>{let{viewMode:t}=K(),n=H(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=It(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],b=m?.parentNodeId?!Ns(o.id,m.parentNodeId)&&t==="dense":!1,N=r.map(($,P)=>{let O=P===r.length-1,Ge=q($.id),Ne=O?Ge?.[s]?.title:void 0;return`${P?" / ":""}${$.title??""}${Ne?` \u25B8 ${Ne}`:""}`}).join(""),S=m?I.getCommentsByIssue(m.id):[],R=S.length?String(S.length).length+11:0,M=b?p.reduce(($,P)=>$+Uy(P),0)+f.reduce(($,P)=>$+Oy(P),0)+R:0,U=c?.id!=null&&!(t==="wide"&&A(c)),j=Math.max(0,e-M),D=N.substring(0,j)+(U?By.hex(v.secondary2).dim(` ${Ue(c.id)}`):""),z=b?[...p.map($=>qt.createElement(Xo,{key:`tag-${$}`,paddingLeft:1},qt.createElement(kn,{id:$}))),...f.map($=>qt.createElement(Xo,{key:`assignee-${$}`,paddingLeft:1},qt.createElement(Ht,{id:$}))),S.length?qt.createElement(Xo,{key:"comments",paddingLeft:1},qt.createElement(Yl,{color:v.accent},"[",S.length," comment",S.length===1?"":"s","]")):null]:[];return qt.createElement(Xo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},qt.createElement(Yl,{color:v.secondary2},D),z)};import{Box as _y,Text as Jl}from"ink";import Jo from"react";var $y=({filters:e})=>Jo.createElement(_y,{columnGap:1},Jo.createElement(Jl,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Jo.createElement(Jl,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ql=Jo.memo($y);import{Box as Hy,Text as Qo}from"ink";import Ar from"react";function Zl(){let{eventLog:e,unappliedEvents:t}=H(),n=e.at(-1)?.id,r=Xr(n??""),o=te(r)?Yr(r.value):"INVALID DATE";return Ar.createElement(Hy,{paddingLeft:1},Ar.createElement(Qo,{backgroundColor:v.accent,color:v.secondary}," Readonly "),Ar.createElement(Qo,{color:v.accent}," "+t.length+" edits ago at "+o+"."),Ar.createElement(Qo,{color:v.accent}," Resume with "),Ar.createElement(Qo,{backgroundColor:v.accent,color:v.secondary}," ",":peek now"," "))}import{Box as Wy,Text as Ii}from"ink";import Zo from"react";function eu(){let{replay:e}=H();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Zo.createElement(Wy,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Zo.createElement(Ii,{backgroundColor:v.accent,color:v.secondary}," \u25B6 REPLAY "),Zo.createElement(Ii,{color:v.secondary2},Yr(new Date(r))),Zo.createElement(Ii,{color:v.accent},`${t}/${n} edits`))}import Ei from"chalk";import{Box as jy,Text as tu}from"ink";import Ci,{useEffect as Vy,useState as Ky}from"react";var Gy=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],zy=150,nu=12,qy=.36,ru=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)}},Yy=({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)}`},Xy=(e,t,n)=>{let r=ru(e),o=ru(t);return Yy({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Jy=(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 Xy(s,i,o)};function ou({syncStatus:e,autoSync:t}){let[n,r]=Ky(0);Vy(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*qy)+1)/2,p=Math.round(m*(nu-1));r(f=>f===p?f:p)},zy);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:v.secondary2,failed:v.yellow,pending:v.secondary2,syncing:Jy(Gy,n/(nu-1))??""}[e.status];return Ci.createElement(jy,null,Ci.createElement(tu,null,Ei.hex(v.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Ci.createElement(tu,null,Ei.hex(i)("\u25CF")+Ei.hex(v.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import cu from"chalk";import{Text as lu}from"ink";import uu,{useEffect as tv,useState as nv}from"react";var Yt="1.3.1";import Ni from"chalk";var Qy="https://registry.npmjs.org/epiq/latest",Si=null,su=0,Zy=1e3*60*60*24,iu=e=>e.replace(/^v/,""),ev=(e,t)=>{let n=iu(e).split(".").map(Number),r=iu(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},au=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Si&&Date.now()-su<Zy)return Si;try{let t=await fetch(Qy);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?ev(r,e)>0:!1};return Si=o,su=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},du=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Ni.hex(v.accent).dim(s):Ni.hex(v.secondary).dim(s)).join(Ni.hex(v.secondary2).dim("."))};function mu(){let[e,t]=nv({current:Yt,latest:null,updateAvailable:!1});return tv(()=>{let n=!0;return au(Yt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?uu.createElement(lu,{dimColor:!0,color:v.secondary2},Yt+" "):uu.createElement(lu,null,cu.hex(v.secondary2).dim(Yt),cu.hex(v.accent).dim(" \u2197 "),du(Yt,e.latest))}function Tr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=H(),{userName:i,preferredEditor:c,autoSync:u}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",b=s?nn(s.currentLabel,Math.max(0,p)):"";return ve.createElement(Rr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?ve.createElement(Rr,{paddingLeft:1},ve.createElement(_n,{color:v.secondary2},b)):f?ve.createElement(_n,null," "):o===y.PALETTE?ve.createElement(Rr,null,ve.createElement(_n,{color:v.accent},"Command Palette"),ve.createElement(_n,{dimColor:!0,color:v.secondary2}," ","- search, select and press enter")):ve.createElement(Rr,{paddingLeft:1},e.length>0?ve.createElement(Ql,{filters:e}):ve.createElement(Xl,{width:p})),n==="live"?ve.createElement(Rr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},ve.createElement(ou,{autoSync:!!u,syncStatus:r}),ve.createElement(_n,null,es.hex(v.secondary2).dim("Mode: ")+es.hex(v.secondary2).dim(o.padEnd(8," "))," "),ve.createElement(pu,{icon:"@",value:i}),ve.createElement(pu,{icon:"\u276F",value:c}),ve.createElement(mu,null)):"",n==="peek"?ve.createElement(Zl,null):"",n==="replay"?ve.createElement(eu,null):"")}function pu({icon:e,value:t}){return ve.createElement(_n,null,es.dim(e)+es.hex(v.accent)(` ${t??"-"} `))}import{Box as rv,Text as ov}from"ink";import wr from"react";import{Box as ts,Text as Ai}from"ink";import Xt from"react";function Ri(){let e=H(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?G(t?.id):[];return Xt.createElement(ts,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:v.secondary,width:s},Xt.createElement(ts,{padding:1,paddingTop:0,paddingBottom:0},Xt.createElement(Ai,null,"Select a board:")),Xt.createElement(ts,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,f=G(c.id).flatMap(({id:b})=>q(b)).length;return Xt.createElement(ts,{key:c.id??u},Xt.createElement(Ai,{color:m?v.accent:v.secondary2},Xt.createElement(Re,{isSelected:m})),Xt.createElement(Ai,{color:m?v.accent:v.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var sv=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=H(),u=n.find(({context:b})=>b==="BOARD"),f=s-1-3;return wr.createElement(rv,{flexDirection:"row"},e.context==="WORKSPACE"?wr.createElement(Ri,null):u?wr.createElement(So,{height:f,width:i,swimlanes:(c[u.id]??[]).filter(b=>b!==void 0&&Dt(b)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):wr.createElement(ov,null))},fu=wr.memo(sv);import{useEffect as iv}from"react";var av=e=>{iv(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=g();u==="default"&&!c&&io(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},gu=({autoSync:e})=>(av(e),null);function Ti({width:e,height:t}){let n=H(),{autoSync:r,viewMode:o}=va(),s=n.filters;if(n.mode===y.HELP)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(zl,{width:e,height:t}));if(n.mode===y.PALETTE)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{filters:s}),ae.createElement(Dl,{width:e,height:t-2}),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Ot(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{hideBreadCrumb:!0,filters:s}),ae.createElement(bi,{height:t,width:e})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{hideBreadCrumb:!0,filters:s}),ae.createElement(ql,{height:t,width:e})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Le(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,f=G(p).length,b=3,N=Math.floor(e/b),S=Math.floor(e/Math.max(f,1));e=Math.min(S,N)*Math.max(f,b)}return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(gu,{autoSync:r}),ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{filters:s}),ae.createElement(fu,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import dv from"readline";var ns,rs,bt,cv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.Yank,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),lv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp,h.Yank]),yu=async e=>{if(e.ctrl&&e.name==="c")return T.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=g(),s=qd(e,n);if(!s||r&&!cv.has(s)||o==="replay"&&n===y.DEFAULT&&lv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},uv=()=>async function(t,n){n.name!=="escape"&&(bt&&(clearTimeout(bt),bt=void 0),await yu(n))},mv=()=>async function(t){if(t.length===1&&t[0]===27){bt&&clearTimeout(bt),bt=setTimeout(()=>{yu({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),bt=void 0},25);return}bt&&(clearTimeout(bt),bt=void 0)};function vu(){ns&&process.stdin.removeListener("keypress",ns),rs&&process.stdin.removeListener("data",rs),ns=uv(),rs=mv(),dv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",rs),process.stdin.on("keypress",ns)}async function hu(){try{let e=wn();te(e)&&Fe(e.value);let t=Ye(process.cwd()),n=[];if(te(t)){let s=Pe({repoRoot:t.value});if(d(s))return dn(3,s.message);let i=vn(),c=await en({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return dn(3,c.message);let u=await _({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=Et(s.value);if(d(m))return dn(3,m.message);n=m.value}let r=an(n);if(d(r))return dn(4,r.message);E({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=wi();return d(o)?dn(6,o.message):(vu(),l("Booted Epiq",void 0))}catch(e){return dn(0,ro(e))}}vc();var yv=`${Qt.bold("Epiq CLI")}
|
|
57
|
+
`,ii.writeFileSync(t,n,"utf8"),oe.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var vg=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},ee=(e,t)=>a(`[${e}] ${t}`),Nc=async()=>{W("");let e=vn(),t=await dt(process.cwd());if(d(t))return ee(1,t.message);let n=t.value,r=await Fr(n);if(d(r))return ee(2,r.message);if(r.value)return ee(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await vg(n);if(d(o))return ee(2.5,o.message);if(o.value)return ee(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(ls(n))return ee(4,"Epiq project already initialized");let s=Ot();if(!s.isSetupDone||!s.userName)return ee(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=K(),c=i.userName,u=i.userId;if(!u||!c)return ee(5,"Missing Epiq user id");let m=e.stateBranch,p=await Ur({repoRoot:n,branch:m});if(d(p))return ee(6,p.message);if(p.value)return ee(6,`State branch already exists: ${m}`);let f=await Is({repoRoot:n,stateBranchName:m});if(d(f))return ee(6,f.message);let b=$r();if(d(b))return ee(7,b.message);let N=Cc.join(_r(),e.projectId),S=await en({repoRoot:n,stateBranchRoot:N,stateBranchName:m});if(d(S))return ee(8,S.message);let R=Cc.join(N,".epiq");yg.mkdirSync(R,{recursive:!0});let M=td({userId:u,userName:c});if(d(M))return ee(9,M.message);for(let as of M.value){let Li=eo({event:as,rootDir:N});if(d(Li))return ee(9,Li.message)}let U=await Wr({stateBranchRoot:N,eventFileName:on({userId:u,userName:c})});if(d(U))return ee(10,U.message);let j=await xn({cwd:N,message:"[epiq:init]"});if(d(j))return ee(10,j.message);let D=await Ec(n);if(d(D))return ee(11,D.message);let z=Ui({repoRoot:n,fileContents:e});if(d(z))return ee(12,z.message);let $=await de.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d($))return ee(13,$.message);let P=await de.commit({cwd:n,message:"[epiq:init-project]"});if(d(P))return ee(13,P.message);let O="Project initialized!",Ge=await _({cwd:n,args:["push","-u","origin","HEAD"]});d(Ge)&&(O+=` Warn: [init:14] ${Ge.message}`);let Ne=await Jn({repoRoot:n,stateBranchRoot:N});d(Ne)&&(O+=` Warn: [init:15] ${Ne.message}`);let ue=Ut(M.value).filter(d);if(ue.length>0)return ee(16,ue.map(as=>as.message).join(`
|
|
58
|
+
`));let ce=Je();if(d(ce))return ee(16,ce.message);let{rootNodeId:$n,nodes:Hn}=ce.value,Pi=Hn[$n];return Pi?(T.navigate({contextNode:Pi,selectedIndex:0}),E({hasProjectDefinition:!0,mode:y.DEFAULT}),l(O,null)):ee(16,"Unable to resolve initialized root node")};import{ulid as xg}from"ulid";import{ulid as hg}from"ulid";var Sc=null,Kt=()=>structuredClone(Sc),vr=e=>{Sc=e},Ac=()=>{let{contextNode:e,selectedIndex:t}=g(),r=q(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},ai=({id:e,parentId:t,position:n={at:"end"}})=>{let r=q(t).filter(o=>o.id!==e);return to(r,n)},Rc=({id:e,parentId:t,position:n={at:"end"}})=>{let r=se();if(d(r))return a("Unable to resolve user ID");let o=ai({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:hg(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Tc=e=>{vr(e);let t=Bt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function di(e){let t=Ac();if(d(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=q(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=Rc({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Tc(u.value)}function ci(e){let t=Ac();if(d(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=q(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Rc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Tc(i.value)}var wc=()=>{let e=Kt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return a("Move parent not found");let o=q(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(T.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},To=(e,t="Moved preview")=>{if(d(e))return e;let n=wc();return d(n)?n:(E({mode:y.MOVE}),l(t,null))},Mc=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=Y().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=q(n.id)[r];if(!o)return E({mode:y.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=q(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=ai({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(vr({id:xg(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:y.MOVE}),l("Move initialized",null))}if(t==="next")return To(ci(1));if(t==="previous")return To(ci(-1));if(t==="to-next")return To(di(1));if(t==="to-previous")return To(di(-1));if(t==="confirm"){let s=Kt();if(!s)return a("No pending move to confirm");let i=await at();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=wc();return d(u)?u:(vr(null),E({mode:y.DEFAULT}),l("Moved item",null))}return t==="cancel"?(vr(null),E({mode:y.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Mo}from"ulid";import{monotonicFactory as bg,ulid as Ig}from"ulid";var Eg=bg(),wo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Eg();return l("Created issue events",[{id:Ig(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Pc=async(e,t)=>{let n=se();if(d(n))return a("Unable to resolve user ID");let r=await at();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:c}=g(),u=m=>{let p=B([m],o);if(d(p))return p;let f=I.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let b=I.getNode(f.parentNodeId);return b?(T.navigate({contextNode:b,selectedIndex:I.getSiblings(f.parentNodeId).findIndex(({id:N})=>N===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return a("Workspace not found");let f=Sn(p.id,n.value,o);return d(f)?f:u({id:Mo(),action:"add.board",payload:{id:Mo(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Le(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Sn(m.value.id,n.value,o);return d(p)?p:u({id:Mo(),action:"add.swimlane",payload:{id:Mo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=G(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let j=Le(s,"SWIMLANE");return d(j)?null:j.value})();if(!p)return a("Unable to add issue in this context");let f=Sn(p.id,n.value,o);if(d(f))return f;let b=wo({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(b))return b;let N=b.value,S=B([...N],o);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let U=N.find(j=>j.action==="add.issue")?.payload.id;return U?(T.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:j})=>j===U)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var Po=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=_a(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Gt();if(d(u))return u;let p=Ut(i).filter(d);if(p.length>0)return Gt(),E(o),a(p.map(b=>b.message).join(", "));let f=g().nodes[e];return f?(T.navigate({contextNode:f,selectedIndex:r}),l("",{unappliedEvents:c})):(Gt(),E(o),a("Board did not exist at that date"))};var Cg=20,Ng=16,Sg=150,Lo=null,ko=null;var fn=()=>{Lo!==null&&(clearInterval(Lo),Lo=null),ko!==null&&(clearTimeout(ko),ko=null)},Lc=()=>{fn(),E({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Ag=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)},kc=({events:e,startTime:t,durationMs:n})=>{fn();let r=e.length,o=e.map(f=>Nn(f)??t),s=o[r-1]??Date.now(),i=Ag(o),c=Math.max(1,Math.round(n*Cg/1e3)),u=Math.max(Math.round(n/c),Ng),m=0,p=0;E({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Lo=setInterval(()=>{m++;let f=m/c,b=[],N;for(;p<r&&i[p]<=f;){let R=e[p],M=Bt(R);if(d(M)){Lc();return}b.push(...ws(R)),N=R,p++}if(p>=r||m>=c){for(;p<r;p++){let M=Bt(e[p]);if(d(M))break}let R=g().replay;E({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),fn(),ko=setTimeout(Lc,Sg);return}let S=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?Nn(N)??S?.currentTime??t:S?.currentTime??t,currentLabel:N?La(N):S?.currentLabel??"",flashNodeIds:N?[...new Set(b)]:S?.flashNodeIds??[]}})},u)};var Dc=async()=>{let e=Le(g().breadCrumb,"BOARD");if(d(e))return e;let t=await dt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=Y().commandMeta;if(fn(),r==="now"){let c=Et(n.value);if(d(c))return a(c.message);let u=Gt();if(d(u))return u;let p=Ut(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(E({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=g().eventLog.at(-1),u=Nn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=g().unappliedEvents.at(0),u=Nn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=cn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Po({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(E({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var Fc=async()=>{let e=Le(g().breadCrumb,"BOARD");if(d(e))return e;let t=await dt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=Y().commandMeta,{dateInput:s,durationInput:i}=uo(r,o);if(fn(),g().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=cn(s);if(!c)return a("Invalid replay date");let u=i?lo(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=Po({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:b}=f.value;return b.length===0?(Gt(),E(p),l("Nothing to replay from that point",!0)):(kc({events:b,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Tg from"zod";var Bc=()=>{let e=Y().commandMeta.inputString,t=Tg.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=Ze({autoSyncDebounceMs:t.data});return d(n)?n:(Fe({autoSyncIntervalMs:t.data}),E({mode:y.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Uc=()=>{let e=Y().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=dd(e),n=Ze({autoSync:t});return d(n)?n:(Fe({autoSync:t}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var Oc=()=>{let e=Y().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Ze({logLevel:e});return d(n)?n:(Fe({logLevel:e}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))};import{spawn as wg}from"node:child_process";var Mg=()=>{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"]}}},_c=async e=>new Promise(t=>{let{command:n,args:r}=Mg();try{let o=wg(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("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 hr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await _c(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},$c=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=ir({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case pe.REF:return hr(Ue(o.id),"ref");case pe.TITLE:return hr(o.title,"title");case pe.DESCRIPTION:return r?hr(r.props?.description??"","description"):a("No issue in scope");case pe.TAGS:{if(!r)return a("No issue in scope");let s=_t(r).map(({name:i})=>i);return hr(s.join(", "),"tags")}case pe.ASSIGNEES:{if(!r)return a("No issue in scope");let s=$t(r).map(({name:i})=>i);return hr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var Hc=async()=>{W(""),E({mode:y.DEFAULT});let e=Je();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await oo();return d(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Pg=e=>e.action==="add.issue.comment",Wc=e=>Object.values(g().tags).find(t=>t.name===e),jc=e=>Object.values(g().contributors).find(t=>t.name===e),wt=async()=>{let e=await at();return d(e)?e:l("Resolved persist root",e.value)},Do=[{systemOnly:!0,intent:w.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:Mc},{intent:w.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await wt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=A(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!A(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Pg).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:we(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:we(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Y().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>ie(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return he(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),l("Filter updated",null)}},{intent:w.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Vt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:y.HELP}),l("Viewing help",null)}},{intent:w.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!A(r))return a("Cannot close in this context");let o=g().nodes[me];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await wt();if(d(s))return s;let i=s.value,c=sn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:we(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):It(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=g().nodes[me];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!A(s))return a("Target node is not issue");let c=Ao(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await wt();if(d(m))return m;let p=m.value,f=sn(u.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let b=B([{id:we(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return d(b)?b:l("Issue reopened",null)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Nc},{intent:w.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:Pc,onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=qd();if(!o)return a("Provide a title");let s=await wt();return d(s)?s:B([{id:we(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Wc(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid untag target");let i=It(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await wt();return d(m)?m:B([{id:we(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=g();if(!o)return a("Invalid tag target");let s=It(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!A(i))return a("Target node is not issue");let c=await wt();if(d(c))return c;let u=Wc(r),m=u?.id??we();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:we(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:we(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=g(),i=G(s.id)[o];if(!i)return a("Invalid assign target");let c=It(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!A(u))return a("Target node is not issue");let m=await wt();if(d(m))return m;let p=jc(r),f=p?.id??we();return(u.props.assignees??[]).includes(f)?a("Assignee already assigned"):B([...p?[]:[{id:we(),action:"create.contributor",payload:{id:f,name:r},...e.value}],{id:we(),action:"add.issue.assignee",payload:{id:u.id,assignee:f},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=jc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid unassign target");let i=It(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await wt();return d(m)?m:B([{id:we(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>Pn)return a(`Cannot exceed ${Pn} characters`);let r=se();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),i=Le([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):It(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!A(m))return a("Target node is not issue");let p=await wt();return d(p)?p:B([{id:we(),action:"add.issue.comment",payload:{id:we(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:Hc},{intent:w.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:Dc},{intent:w.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:Fc},{intent:w.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await yc();return d(e)?e:(E({mode:y.DEFAULT}),l("Export successful",!0))}},{intent:w.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(T.exit(),l("Exit successful",!0))},{intent:w.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>Ic(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>$c(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ne.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??we();if(!i||!c)return a("Unable to resolve user name or id");let u=Ze({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(Fe({userName:i,userId:c}),E({mode:y.DEFAULT}),l(`Username set to "${i}"`,null))}case ne.EDITOR:{if(!n)return a("No editor provided");let r=Ze({preferredEditor:n});return d(r)?r:(Fe({preferredEditor:n}),E({mode:y.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ne.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Ze({viewMode:n});return d(r)?r:(Fe({viewMode:n}),E({mode:y.DEFAULT}),l(`View set to "${n}"`,null))}case ne.AUTOSYNC:return Uc();case ne.LOG_LEVEL:return Oc();case ne.SYNC_DEBOUNCE_MS:return Bc();case ne.ATTACHMENT_MAX_KB:return Td();default:return a("Unknown config command")}}},{intent:w.Coffee,description:"Sponsor the development of Epiq!",mode:y.COMMAND_LINE,action:()=>{let e=Y().commandMeta.modifier;return e==="custom"?yr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):yr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),W(""),l("Thanks you!",null)}}];var Lg=new Set(["peek","replay","filter","view-help","yank"]),yt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Y();if(!t)return a("No command to confirm");if(!e&&n===pt.Invalid)return a("Invalid command");let s=ho(t);jd();let{readOnly:i}=g();if(i&&!Lg.has(s))return ur({status:Pt.Fail,message:"Command not available in readonly state",value:null});let c=Do.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return ur({status:Pt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return ur({status:Pt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?ur(u):(Vd({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&io(),u)};var Fo=[{intent:h.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:y.COMMAND_LINE}),W("move cancel"),yt({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:y.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:y.COMMAND_LINE}),W("move start"),yt({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:y.MOVE,action:()=>(E({mode:y.COMMAND_LINE}),W("move confirm"),yt({isForceExecutedBySystem:!0}))}],Bo=[{intent:h.MovePreviousItem,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move next"),yt({isForceExecutedBySystem:!0})):a("No pending move")}],Vc=[{intent:h.MoveToNextContainer,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move to-next"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move to-previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")}];var Kc={[L.WORKSPACE]:[...Fo,...Bo],[L.BOARD]:[...Fo,...Bo],[L.SWIMLANE]:[...Fo,...Bo,...Vc],[L.TICKET]:[],[L.FIELD]:[],[L.FIELD_LIST]:[],[L.TEXT]:[],[L.COMMENT]:[]};import kg from"node:fs";import Dg from"node:path";var Gc=e=>{let t=Ye(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=Mn(e.hash,e.ext),o=Dg.join(Kn(n.value),r);return kg.existsSync(o)?(yr(o),l(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var zc=()=>{W("");let{pendingNavTarget:e}=jt();E({mode:y.DEFAULT}),e&&T.navigate(e),Vt({pendingNavTarget:void 0})},qc=[{intent:h.ExitCommandLine,mode:y.HELP,action:()=>(zc(),l("Exiting help",null))},{intent:h.Exit,mode:y.HELP,action:()=>(zc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:y.HELP,action:()=>(T.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:y.HELP,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:y.HELP,action:()=>(T.navigateToNextContainer(),l("Navigating to next help container",null))}];var Fg=e=>{E({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=jt();t&&T.navigate(t),Vt({pendingNavTarget:void 0}),W(`${e} `)},Yc=()=>{W("");let{pendingNavTarget:e}=jt();e&&T.navigate(e),Vt({pendingNavTarget:void 0}),E({mode:y.DEFAULT})},Xc=[{intent:h.InitCommandPalette,mode:y.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{W("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Vt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:y.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!kt(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?(Fg(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:y.PALETTE,action:()=>(Yc(),l("Exiting palette",null))},{intent:h.Exit,mode:y.PALETTE,action:()=>(Yc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:y.PALETTE,action:()=>(T.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:y.PALETTE,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:y.PALETTE,action:()=>(T.navigateToNextContainer(),l("Navigating to next container",null))}];var Jc=[...qc,...Xc,{intent:h.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:y.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:y.COMMAND_LINE}),W(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!q(e?.id??"")?.length){let r=e?I.getAttachment(e.id):void 0;if(r)return Gc(r);if(e?.title===J.DESCRIPTION)return E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===J.ASSIGNEES)return E({mode:y.COMMAND_LINE}),W(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===J.TAGS)return E({mode:y.COMMAND_LINE}),W(`${x.TAG} `),l("Propose command",!0);if(t.title===J.DESCRIPTION&&e?.context==="TEXT")return E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Propose command",!0)}return T.enterChildNode(),l("Entering context",null)}},{intent:h.Yank,mode:y.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===J.DESCRIPTION?pe.DESCRIPTION:e?.title===J.TAGS?pe.TAGS:e?.title===J.ASSIGNEES?pe.ASSIGNEES:pe.REF,r=ie(x.YANK).includes(t)?t:pe.REF;return E({mode:y.COMMAND_LINE}),W(`${x.YANK} ${r}`),l("Propose command",!0)}},{intent:h.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:y.DEFAULT,description:"[e] edit description",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(T.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:y.DEFAULT,action:()=>(T.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:y.DEFAULT,action:()=>(T.navigateToNextContainer(),l("Navigating to next container",null))}];var Bg=500,Ug=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Qc=e=>{let t=Ug(e);t&&vo(n=>(n+t).slice(0,Bg))};var Og=[y.COMMAND_LINE,y.PALETTE],_g=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(Ys(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(Ys(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Xs("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Xs("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(vo((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(Qc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(Hd(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(Wd(),l("Erasing input word",null))}],Zc=[{intent:h.Confirm,mode:y.COMMAND_LINE,action:()=>(yt(),l("Executing command",null))},{intent:h.ViewHelp,mode:y.DEFAULT,action:()=>(E({mode:y.HELP}),l("Viewing help",null))},...Og.flatMap(_g),{intent:h.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(E({mode:y.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Kd(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Gd(),l("Getting next command from history",null))}];import nl from"chalk";var Uo=nl.dim.hex(v.secondary2)(": for command line"),el="q to exit",tl=`${nl.hex(v.accent)("m")} to confirm`,li={[L.WORKSPACE]:[Uo],[L.BOARD]:[Uo],[L.BOARD+y.COMMAND_LINE]:[Uo],[L.SWIMLANE]:[Uo],[L.TICKET+y.HELP]:[el],[L.SWIMLANE+y.HELP]:[el],[L.TICKET]:[],[L.FIELD]:[],[L.SWIMLANE+y.MOVE]:[tl],[L.TICKET+y.MOVE]:[tl]};var xr=e=>e.trim().toLocaleLowerCase(),$g=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Hg=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},rl=(e,t)=>{let n=xr(t.value);if(!n)return!0;switch(t.target){case"title":return xr(e.title??"").includes(n);case"description":return xr(e.props.description??"").includes(n);case"tag":return $g(e).map(xr).some(o=>o.includes(n));case"assignee":return Hg(e).map(xr).some(o=>o.includes(n));case"ref":return Ia(e.id,t.value);default:return!0}};function ol(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var sl=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 gn,ui,mi=new Set,il=()=>{for(let e of mi)e()},jg=e=>(mi.add(e),()=>mi.delete(e));function al(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 c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=ol(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=li[p+n]??li[p]??[],b=[...Jc,...Kc[p]??[],...Zc],N=sl(b),S=Vg(o,s),R=S[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:b,actionIndex:N,selectedNode:R,renderedChildrenIndex:S})}var g=()=>{if(!gn)throw new Error("State not initialized. Call initWorkspaceState() first.");return gn},Je=()=>gn?l("Retrieved state",gn):a("State not initialized. Call initWorkspaceState() first.");function nr(e){ui=e;let t=Ye(process.cwd()),n=!1;if(!d(t)){let s=Lt(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.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=al(r);return d(o)?o:(gn=o.value,il(),l("State initialized",null))}function he(e){let t=g(),n=e(t),r=al(n);return d(r)?a(r.message??"Unable to update state"):(gn=r.value,il(),l("State updated",null))}var E=e=>he(t=>({...t,...e}));var H=()=>Wg(jg,g,g),Vg=(e,t)=>{let n={};for(let r of Object.values(e))A(r)&&t.length>0&&!t.every(o=>rl(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},G=e=>g()?.renderedChildrenIndex[e]??[],Gt=()=>ui?nr(ui):a("Cannot reset state: no initial workspace found"),Rn=()=>gn!==void 0;var pi=e=>{Rn()&&(E({syncStatus:e}),tn({type:"sync-status",payload:e}))},Oo=(e="Syncing...")=>{pi({status:"syncing",msg:e})},_o=(e="Synced")=>{pi({status:"synced",msg:e})},fi=e=>{pi({status:"failed",msg:e})},Qe=e=>(fi(e),a(e));import{decodeTime as ZL}from"ulid";var Kg=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=X("getRepoRootDir",await dt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=X("getStateBranchRoot",Pe({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=X("ensureInitialCommit",await na(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=X("bootstrapStateBranchStorage",await sa({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=X("hasInProgressGitOperation(stateBranchRoot)",await Fr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.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 m=X("ensureStateBranchLayout",Zi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Gg=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=X("stageStateBranchOwnEventFile",await Wr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=X("stageStateBranchMediaFiles",await ra({stateBranchRoot:t}));if(d(o))return a(o.message);let s=X("hasStagedChanges(after stage)",await Gi(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=X("createStateBranchSyncCommit",await oa({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),l("Committed own event file",{createdCommit:!0,commitSha:i.value}))},so=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");Oo();let n=X("ensureSyncReady",await Kg({cwd:e,ensureUpstream:!0}));if(d(n))return Qe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=X("isDetachedHead(stateBranchRoot)",await zi(o));if(d(i))return Qe(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Qe("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=X("getStateBranch",hn(r));if(d(f))return Qe(f.message);let b=f.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:o});let N=X("commitOwnEventFileToStateBranch",await Gg({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(N))return Qe(N.message);c=N.value.createdCommit,u=N.value.commitSha;let S=X("pullBranchRebaseIfPresent",await hs({cwd:o,branch:b}));if(d(S))return Qe(S.message);if(m=S.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let R=X("pushStateBranch",await Jn({stateBranchRoot:o,repoRoot:r}));if(d(R)&&Ki(R.message)){let M=X("pullBranchRebaseIfPresent(retry)",await hs({cwd:o,branch:b}));if(d(M))return Qe(M.message);m=m||M.value,R=X("pushStateBranch(retry)",await Jn({stateBranchRoot:o,repoRoot:r}))}if(d(R))return Qe(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let R=X("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(d(R))return Qe(R.message);u=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return _o(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var gi=()=>{let e=wn();return d(e)?mt:e.value.attachmentMaxKb??mt},yi=e=>{let t=Ye(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},Me=async e=>{let t=yi(e);if(d(t))return t;let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=vn(),o=await en({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await _({cwd:n.value,args:["pull","--ff-only"]});d(s)&&oe.info(3,s.message);let i=Et(n.value);if(d(i))return a(i.message);let c=an(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},ke=()=>{let e=wn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=Je();return d(e)?a(e.message):e},cl=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:le(t.name)})),ll=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:le(t.name)}));var ul=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(A).filter(o=>e.includeClosed||o.parentNodeId!==me).map(o=>({id:o.id,ref:Ue(o.id),title:lt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===me,readonly:!!o.readonly,tags:cl(o),assignees:ll(o)}));return l("Listed issues",r)},ml=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=Sn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=wo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},pl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=sn(me,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:ge(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:me,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},fl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Target node is not issue");if(o.parentNodeId!==me)return a("Issue is not closed");let s=Ao(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===me)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=sn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:ge(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},gl=async e=>{let t=yi(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=Pe({repoRoot:t.value});if(d(r))return r;let o=Et(r.value);if(d(o))return o;let s=an(o.value);if(d(s))return s;let i=sn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:ge(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},$o=async(e={})=>{Oo();let t=yi(e.repoRoot);if(d(t))return a("Sync failed");let n=ke();if(d(n))return n;let r=await so({cwd:t.value,ownEventFileName:on(n.value)});return d(r)?(fi(r.message),r):(_o(),l("Synced",r.value))};var vt=async(e={})=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(f=>Vr(f)&&!f.isDeleted),s=new Map,i=new Map;for(let f of r)if(!f.isDeleted){if(Dt(f)&&f.parentNodeId){let b=s.get(f.parentNodeId)??[];b.push(f),s.set(f.parentNodeId,b)}if(A(f)&&f.parentNodeId){let b=i.get(f.parentNodeId)??[];b.push(f),i.set(f.parentNodeId,b)}}let c=wn();if(d(c))return c;let u={};for(let f of r.filter(A))f.isDeleted||(u[f.id]=I.getCommentsByIssue(f.id).map(b=>{let N=I.getContributor(b.authorId);return{id:b.id,issueId:b.issue,body:b.md,author:{id:b.authorId,name:N?.name??"Unknown",color:le(N?.name??b.authorId)},createdAt:dl(b.id)}}));let m=new Map;for(let f of n.value.eventLog)f.action==="add.issue.attachment"&&m.set(f.payload.id,f.payload.author);let p={};for(let f of r.filter(A))f.isDeleted||(p[f.id]=I.getAttachmentsByIssue(f.id).map(b=>({id:b.id,issueId:b.issue,name:b.name,fileName:Mn(b.hash,b.ext),bytes:b.bytes,createdAt:dl(b.id),canDelete:m.get(b.id)===c.value.userId})));return l("Retrieved Epiq GUI state",{boards:o.sort((f,b)=>f.rank.localeCompare(b.rank)).map(f=>({id:f.id,ref:Ue(f.id),title:f.title,swimlanes:(s.get(f.id)??[]).sort((b,N)=>b.rank.localeCompare(N.rank)).map(b=>({id:b.id,title:b.title,readonly:!!b.readonly,issues:(i.get(b.id)??[]).sort((N,S)=>N.rank.localeCompare(S.rank)).map(N=>({id:N.id,ref:Ue(N.id),title:lt(N.title),description:N.props.description??"",readonly:!!N.readonly,tags:cl(N),assignees:ll(N),parentNodeId:N.parentNodeId,isClosed:N.parentNodeId===me})),parentNodeId:b.parentNodeId}))})),tags:Object.values(n.value.tags).map(f=>({...f,color:le(f.name)})),contributors:Object.values(n.value.contributors).map(f=>({...f,color:le(f.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:le(c.value.userName??"")},commentsByIssueId:u,attachmentsByIssueId:p,attachmentMaxKb:gi()})},yl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:ge(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},vl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=lt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:ge(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},hl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=lt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??ge(),u=[...i?[]:[{id:ge(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:ge(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},xl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(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:ge(),...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):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},bl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=lt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??ge(),u=[...i?[]:[{id:ge(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:ge(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Il=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(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:ge(),...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):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Ho=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(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");let i=ge(),c={id:ge(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},Wo=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();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(!A(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 l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:ge(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},El=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=Ad(t.value.stateBranchRoot,s,gi());if(d(i))return i;let c=lt(e.name??"").trim()||"image",u=ge(),m={id:ge(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);return d(p)?a(p.message):l("Added issue attachment",{id:u,issueId:e.issueId,fileName:Mn(i.value.hash,i.value.ext),bytes:i.value.bytes})},Cl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();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(!A(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 l("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:ge(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Nl=async e=>{let t=await Me(e.repoRoot);return d(t)?t:Rd(t.value.stateBranchRoot,e.fileName,gi())};var Sl=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=ar();if(d(p))return oe.error(p.message);let{autoSync:f,userName:b,preferredEditor:N}=p.value;return!!(f&&b&&N)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await $o({repoRoot:e.repoRoot}),tn({type:"state",payload:await vt({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=ar();if(d(p))return oe.error(p.message);let{autoSyncDebounceMs:f}=p.value;i()&&(t=setTimeout(()=>{c(),m()},f??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as zg}from"ws";var Ve=(e,t)=>{e.send(JSON.stringify(t))},br=async(e,t)=>Ve(e,{type:"state",payload:await vt({repoRoot:t})}),ht=async(e,t,n,r,o)=>{if(Ve(e,{type:r,payload:o}),d(o))return Ve(e,{type:"failed",payload:o.message});n(),br(e,t)},Al=(e,t,{onStateChanged:n})=>{new zg({server:e,path:"/ws"}).on("connection",o=>{ia(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return br(o,t);if(c==="sync"){let u=await $o({repoRoot:t});return Ve(o,{type:"sync:result",payload:u}),n(),br(o,t)}if(c==="issue:comment:add"){let u=await Ho({repoRoot:t,...i.payload});return ht(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await Wo({repoRoot:t,...i.payload});return Ve(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Ve(o,{type:"failed",payload:u.message}):(n(),br(o,t))}if(c==="issue:edit:description"){let u=await yl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await vl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await hl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await xl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await bl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Il({repoRoot:t,...i.payload});return ht(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Ve(o,{type:"issues",payload:await ul({repoRoot:t})});if(c==="issues:create"){let u=await ml({...i.payload,repoRoot:t});return Ve(o,{type:"issues:create:result",payload:u}),d(u)?tn({type:"failed",payload:u.message}):(tn({type:"issue:created",payload:u.value}),n(),br(o,t))}if(c==="issues:move"){if(!i.payload.position)return Ve(o,{type:"error",message:"Missing move position"});let u=await gl({...i.payload,repoRoot:t});return ht(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Ve(o,{type:"error",message:"Missing issueId"});let u=await pl({repoRoot:t,issueId:i.payload.issueId});return ht(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Ve(o,{type:"error",message:"Missing issueId"});let u=await fl({repoRoot:t,issueId:i.payload.issueId});return ht(o,t,n,"issue:reopen:result",u)}return Ve(o,{type:"error",message:"Unknown message type"})}catch(i){return Ve(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Xg=yn.dirname(Yg(import.meta.url)),Jg=process.env.IS_LOCAL==="true"?yn.resolve(process.cwd(),"dist/gui"):yn.join(Xg,"gui"),jo,Qg=async()=>(jo===void 0&&(jo=await import("node:sea").catch(()=>null)),jo?.isSea()?jo:null),ye=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Rl=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+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),Zg=2*1024*1024,ey={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},ty=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",Tl=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=yn.resolve(Jg),o=yn.resolve(r,n),s=yn.relative(r,o);if(s.startsWith("..")||yn.isAbsolute(s))return ye(t,403,{isError:!0,message:"Forbidden"});let i=await Qg();try{let c=i?Buffer.from(i.getAsset(`gui/${s}`)):await wl(o);return t.writeHead(200,{"content-type":ty(o)}),t.end(c)}catch{return ye(t,404,{isError:!0,message:`Not found: ${n}`})}},ny=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Ml=async e=>{let t=qg.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return ye(s,200,await vt({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Rl(o);if(!c.issueId||!c.body?.trim())return ye(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Ho({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?ye(s,400,u):ye(s,200,await vt({repoRoot:e.repoRoot}))}catch(c){return ye(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await Rl(o,Zg);if(!c.issueId||!c.dataBase64)return ye(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let u=await El({repoRoot:e.repoRoot,issueId:c.issueId,name:c.name??"",dataBase64:c.dataBase64});return d(u)?ye(s,400,{isError:!0,message:u.message}):ye(s,200,await vt({repoRoot:e.repoRoot}))}catch(c){return ye(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));if(!c)return ye(s,400,{isError:!0,message:"Missing attachment id"});let u=await Cl({repoRoot:e.repoRoot,attachmentId:c});return d(u)?ye(s,400,{isError:!0,message:u.message}):ye(s,200,await vt({repoRoot:e.repoRoot}))}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),u=await Nl({repoRoot:e.repoRoot,fileName:c});if(d(u))return ye(s,404,{isError:!0,message:u.message});try{let m=await wl(u.value.filePath);return s.writeHead(200,{"content-type":ey[u.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return ye(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return ye(s,400,{isError:!0,message:"Missing comment id"});let u=await Wo({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?ye(s,400,u):ye(s,200,await vt({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?Tl("/",s):Tl(i.pathname,s)});try{await ny(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Sl({repoRoot:e.repoRoot});Al(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Pl=async e=>{let t=await Ml({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${ry.cyan(n)}`),ki(n),l("Started GUI",{url:n})};import{Box as Jt}from"ink";import ae from"react";import{Box as vi,Text as Ir}from"ink";import ot,{useEffect as oy,useMemo as sy}from"react";import{ulid as iy}from"ulid";var Ll=({text:e,match:t,color:n,highlightColor:r=v.secondary,dimColor:o=!1})=>{if(!t)return ot.createElement(Ir,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?ot.createElement(Ir,{color:n,dimColor:o},e):ot.createElement(Ir,{color:n,dimColor:o},e.slice(0,c),ot.createElement(Ir,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},kl=iy(),ay=e=>`${e}`,dy=e=>{let{pendingNavTarget:t}=jt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(ie(x.NONE,{breadCrumb:n,contextNode:r,readOnly:g().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=ho(i),u=Do.find(m=>m.intent===c);return{command:i,description:u?.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,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},cy=e=>Q.text({id:kl,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),ly=(e,t,n)=>Q.text({id:ay(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),hi=[],uy=e=>{Dl();let t=I.createNode(cy(g().rootNodeId));d(t)||!kt(t.value)||(hi=[t.value,...e.map((n,r)=>ly(n,r,kl)).map(I.createNode).filter(te).map(({value:n})=>n).filter(kt)],T.navigate({contextNode:t.value,selectedIndex:0}))},Dl=()=>{let e=hi.map(t=>t.id);hi=[];for(let t of e)I.deleteNode(t)};function Fl({width:e,height:t}){let r=zd().value.trim().toLowerCase(),o=sy(()=>dy(r),[r]);oy(()=>(uy(o),()=>{Dl()}),[o]);let s=g().selectedIndex;return ot.createElement(vi,{flexDirection:"column",width:e,height:t-2},ot.createElement(et,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?v.accent:v.secondary2,p=i.isAvailable?"":"[unavailable] ";return ot.createElement(vi,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:v.secondary,borderStyle:"single"},ot.createElement(Ir,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",ot.createElement(Ll,{text:ma(i.command),match:r,color:m,dimColor:!i.isAvailable})),ot.createElement(vi,{paddingLeft:2},ot.createElement(Ll,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?v.primary:v.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Ty}from"ink";import Go from"react";import Cr from"chalk";import{Box as xi,Text as Bl}from"ink";import Er,{useEffect as my,useMemo as py,useState as fy}from"react";var Ul=Cr.hex(v.secondary),gy=Cr.inverse,yy=Cr.inverse.hex(v.secondary2),vy={hint:"",hints:[],overlap:0,remainder:""},_l=({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}},hy=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=le(t);return{bg:r=>Cr.bgHex(n).black(r),bgCursor:r=>Cr.bgHex(n).inverse.black(r)}}return Ts(t)},xy=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=_l({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}},Ol=()=>({value:Ae.value,cursorPosition:Ae.cursorPosition,commandIsPending:Ae.commandIsPending,autoCompletion:Ae.commandMeta.autoCompletion??vy,infoMessage:Ae.commandMeta.infoMessage,validationStatus:Ae.commandMeta.validity,command:Ae.commandMeta.command,inputString:Ae.commandMeta.inputString,modifier:Ae.commandMeta.modifier}),by=(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,$l=({width:e,mode:t})=>{let[n,r]=fy(Ol());my(()=>{let S=()=>{let M=Ol();r(U=>by(U,M)?U:M)},R=qs(S);return S(),()=>{R()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p,validationStatus:f}=n,b=c&&f===pt.Invalid,N=py(()=>{let S=Math.max(0,Math.min(s,o.length)),R=_l({value:o,command:m}),M=xy({value:o,command:m,modifier:p}),U=m?Ts(m):null,j=hy({command:m,modifier:p}),D=(ue,ce)=>{let $n=R&&ce>=R.start&&ce<R.end,Hn=M&&ce>=M.start&&ce<M.end;return $n&&U?U.fg(ue):Hn&&j?j.bg(ue):ue},z=(ue,ce)=>{let $n=R&&ce>=R.start&&ce<R.end,Hn=M&&ce>=M.start&&ce<M.end;return $n&&U?U.fgCursor(ue):Hn&&j?j.bgCursor(ue):gy(ue)},$=o.slice(0,S),P=o[S]??" ",O=S<o.length?o.slice(S+1):"",Ge=Array.from($).map((ue,ce)=>D(ue,ce)).join(""),Ne=z(P,S),ze=Array.from(O).map((ue,ce)=>D(ue,S+1+ce)).join("");if(u.hint){let ue=u.hint[u.overlap]??P;Ne=yy(ue),ze=Ul(u.remainder.slice(1)+O)}return Ul(t===y.PALETTE?"?":":")+Ge+Ne+ze},[o,s,u,m,p]);return Er.createElement(xi,{flexDirection:"column",justifyContent:"flex-start"},Er.createElement(xi,{flexDirection:"column",paddingX:1,borderColor:v.secondary,borderStyle:"round",width:e},Er.createElement(xi,null,Er.createElement(Bl,null,N),i&&Er.createElement(Bl,{wrap:"truncate",color:b?v.red:v.secondary2},` ${i} `))))};import{Box as Iy,Text as Ey}from"ink";import Hl from"react";var Cy=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Wl=({width:e,availableHints:t})=>{let n=Cy(t,e).join(" | ");return Hl.createElement(Iy,{width:e,borderStyle:"round",borderColor:v.secondary,paddingX:1},Hl.createElement(Ey,{color:v.secondary2},n.length?n:"\xA0"))};import{Box as Ny,Text as Vo}from"ink";import Nr,{useEffect as Sy,useRef as Un,useState as Ay}from"react";var Ry=40,Ko=.3,bi="\u2500",jl=1,Vl=16,Kl=({width:e})=>{let{replay:t}=H(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*jl,[c,u]=Ay(0),m=Un(r);m.current=r;let p=Un(0),f=Un(0),b=Un(0),N=Un(0),S=Un(0);if(Sy(()=>{if(!n){p.current=0,b.current=0,N.current=0,S.current=0,u(0);return}p.current=m.current,f.current=Date.now(),b.current=m.current;let D=setInterval(()=>{let z=Date.now(),$=m.current;if($!==b.current){let ze=$-b.current,ue=z-f.current;if(ze<0)N.current=0,S.current=0;else if(ze>0&&ue>0){let ce=ze/ue;N.current=N.current===0?ce:N.current*(1-Ko)+ce*Ko,S.current=S.current===0?ze:S.current*(1-Ko)+ze*Ko}p.current=$,f.current=z,b.current=$}let P=z-f.current,O=Math.min(S.current,N.current*P),Ge=Math.min(1,p.current+O),Ne=Math.round(Ge*i);u(ze=>ze===Ne?ze:Ne)},Ry);return()=>clearInterval(D)},[n,i]),!t)return null;let R=D=>{let z=s>1?D/(s-1):0,$=Math.round(z*(Vl-1))/(Vl-1);return Gr($)},M=Math.min(s,Math.floor(c/jl)),U=[];for(let D=0;D<M;D++){let z=R(D),$=U[U.length-1];$&&$.color===z?$.text+=bi:U.push({text:bi,color:z})}let j=bi.repeat(Math.max(0,s-M));return Nr.createElement(Ny,{width:e,borderStyle:"round",borderColor:v.secondary,paddingX:1,columnGap:1},Nr.createElement(Vo,{color:v.secondary2},"\u25B6"),Nr.createElement(Vo,null,U.map((D,z)=>Nr.createElement(Vo,{key:z,color:D.color},D.text)),Nr.createElement(Vo,{color:v.secondary,dimColor:!0},j)))};var Sr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=H(),o=t===y.COMMAND_LINE||t===y.PALETTE;return Go.createElement(Ty,null,o?Go.createElement($l,{width:e,mode:t}):r==="replay"?Go.createElement(Kl,{width:e}):Go.createElement(Wl,{width:e,mode:t,availableHints:n}))};import{Box as zt,Text as On}from"ink";import De,{useEffect as wy,useMemo as My}from"react";import{ulid as Gl}from"ulid";var qo=Gl(),Py=()=>[...new Set([...g().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Ly=e=>Q.text({id:qo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),ky=(e,t,n)=>Q.text({id:Gl(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),zo=[],zl=()=>{let e=zo.filter(n=>n.id!==qo).map(n=>n.id),t=zo.filter(n=>n.id===qo).map(n=>n.id);zo=[];for(let n of[...e,...t])I.deleteNode(n)},Dy=e=>{zl();let t=I.createNode(Ly(g().rootNodeId));if(d(t)||!kt(t.value))return logger.error("Could not attach help nodes");zo=[t.value,...e.map((n,r)=>ky(n,r,qo)).map(I.createNode).filter(te).map(({value:n})=>n).filter(kt)],T.navigate({contextNode:t.value,selectedIndex:0})},ql=({width:e,height:t})=>{let n=My(()=>Py(),[]);wy(()=>(Dy(n),()=>{zl()}),[n]);let r=g().selectedIndex;return De.createElement(zt,{flexDirection:"column",marginTop:3,borderColor:v.secondary,borderStyle:"round",width:e,height:t-2},De.createElement(zt,{paddingX:1,justifyContent:"center"},De.createElement(On,{color:v.accent},"Help"),De.createElement(On,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),De.createElement(zt,{paddingX:1,marginTop:1},De.createElement(zt,{width:20,justifyContent:"flex-end"},De.createElement(On,{color:v.secondary},"Key(s)")),De.createElement(zt,{flexGrow:1,width:40,paddingLeft:2},De.createElement(On,{color:v.secondary},"Action"))),De.createElement(et,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return De.createElement(zt,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},De.createElement(zt,{width:20,justifyContent:"flex-end"},De.createElement(On,{color:v.accent},o)),De.createElement(zt,{flexGrow:1,width:40,paddingLeft:2},De.createElement(On,{color:c?v.primary:v.secondary2},s)))})))};import Fy from"chalk";import{Box as Yo,Text as Mt}from"ink";import Ke from"react";var Yl=({width:e,height:t})=>Ke.createElement(Yo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:v.secondary,rowGap:1},Ke.createElement(Mt,{color:v.accent,bold:!0},"Initialize project"),Ke.createElement(Mt,null,`This folder is not an ${Fy.hex(v.accent)("epiq")} project yet.`),Ke.createElement(Mt,{color:v.primary},"To start tracking issues here, we need to initialize a new",Ke.createElement(Mt,{color:v.primary,backgroundColor:v.secondary}," .epiq/project.json "),"file in this repository."),Ke.createElement(Yo,{marginTop:1,flexDirection:"column"},Ke.createElement(Yo,null,Ke.createElement(Mt,{color:v.accent}," "),Ke.createElement(Mt,{color:v.primary},"Type "),Ke.createElement(Mt,{backgroundColor:v.secondary}," :init "))),Ke.createElement(Yo,{marginTop:1},Ke.createElement(Mt,{color:v.secondary2},"This will create, commit and push "),Ke.createElement(Mt,{color:v.primary,backgroundColor:v.secondary}," .epiq/project.json ")));import{Box as Xo,Text as xt}from"ink";import Ce from"react";var By=({isDone:e,command:t,value:n})=>Ce.createElement(Xo,null,Ce.createElement(xt,{color:v.accent,dimColor:e},e?" \u2714 ":" "),Ce.createElement(xt,{dimColor:e},"Type "),Ce.createElement(xt,{backgroundColor:v.secondary,dimColor:e}," "+t+" "),n!==void 0&&Ce.createElement(Ce.Fragment,null,Ce.createElement(xt,{dimColor:e}," "),Ce.createElement(xt,{color:v.secondary,dimColor:e},"<"+n+">"))),Uy=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Ii({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Ot(),u=[{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:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(f=>!f.done),p=m===-1?void 0:u[m];return Ce.createElement(Xo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:v.secondary,rowGap:1},Ce.createElement(xt,{color:v.accent,bold:!0},"Welcome! \u{1F539}"),Ce.createElement(xt,null,"Let's get you started - it's a breeze."),Ce.createElement(xt,{color:v.secondary2},"Remember - you can always search available commands by typing:",Ce.createElement(xt,{color:v.accent}," ? ")),p&&Ce.createElement(xt,{color:v.secondary2},p.message),Ce.createElement(Xo,{flexDirection:"column"},u.map((f,b)=>m===-1||b<=m?Ce.createElement(Xo,{key:f.key,marginBottom:1},Ce.createElement(By,{isDone:f.done,command:f.command,value:f.done?Uy(f.value):void 0})):null)))}import ts from"chalk";import{Box as Rr,Text as _n}from"ink";import ve from"react";import{Box as Jo,Text as Xl}from"ink";import qt from"react";import Oy from"chalk";var _y=e=>(I.getTag(e)?.name??"").length+3,$y=e=>(I.getContributor(e)?.name??"").length+3,Jl=({width:e})=>{let{viewMode:t}=K(),n=H(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=It(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],b=m?.parentNodeId?!Ss(o.id,m.parentNodeId)&&t==="dense":!1,N=r.map(($,P)=>{let O=P===r.length-1,Ge=q($.id),Ne=O?Ge?.[s]?.title:void 0;return`${P?" / ":""}${$.title??""}${Ne?` \u25B8 ${Ne}`:""}`}).join(""),S=m?I.getCommentsByIssue(m.id):[],R=S.length?String(S.length).length+11:0,M=b?p.reduce(($,P)=>$+_y(P),0)+f.reduce(($,P)=>$+$y(P),0)+R:0,U=c?.id!=null&&!(t==="wide"&&A(c)),j=Math.max(0,e-M),D=N.substring(0,j)+(U?Oy.hex(v.secondary2).dim(` ${Ue(c.id)}`):""),z=b?[...p.map($=>qt.createElement(Jo,{key:`tag-${$}`,paddingLeft:1},qt.createElement(kn,{id:$}))),...f.map($=>qt.createElement(Jo,{key:`assignee-${$}`,paddingLeft:1},qt.createElement(Ht,{id:$}))),S.length?qt.createElement(Jo,{key:"comments",paddingLeft:1},qt.createElement(Xl,{color:v.accent},"[",S.length," comment",S.length===1?"":"s","]")):null]:[];return qt.createElement(Jo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},qt.createElement(Xl,{color:v.secondary2},D),z)};import{Box as Hy,Text as Ql}from"ink";import Qo from"react";var Wy=({filters:e})=>Qo.createElement(Hy,{columnGap:1},Qo.createElement(Ql,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Qo.createElement(Ql,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Zl=Qo.memo(Wy);import{Box as jy,Text as Zo}from"ink";import Ar from"react";function eu(){let{eventLog:e,unappliedEvents:t}=H(),n=e.at(-1)?.id,r=Xr(n??""),o=te(r)?Yr(r.value):"INVALID DATE";return Ar.createElement(jy,{paddingLeft:1},Ar.createElement(Zo,{backgroundColor:v.accent,color:v.secondary}," Readonly "),Ar.createElement(Zo,{color:v.accent}," "+t.length+" edits ago at "+o+"."),Ar.createElement(Zo,{color:v.accent}," Resume with "),Ar.createElement(Zo,{backgroundColor:v.accent,color:v.secondary}," ",":peek now"," "))}import{Box as Vy,Text as Ei}from"ink";import es from"react";function tu(){let{replay:e}=H();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return es.createElement(Vy,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},es.createElement(Ei,{backgroundColor:v.accent,color:v.secondary}," \u25B6 REPLAY "),es.createElement(Ei,{color:v.secondary2},Yr(new Date(r))),es.createElement(Ei,{color:v.accent},`${t}/${n} edits`))}import Ci from"chalk";import{Box as Ky,Text as nu}from"ink";import Ni,{useEffect as Gy,useState as zy}from"react";var qy=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Yy=150,ru=12,Xy=.36,ou=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)}},Jy=({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)}`},Qy=(e,t,n)=>{let r=ou(e),o=ou(t);return Jy({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Zy=(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 Qy(s,i,o)};function su({syncStatus:e,autoSync:t}){let[n,r]=zy(0);Gy(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Xy)+1)/2,p=Math.round(m*(ru-1));r(f=>f===p?f:p)},Yy);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:v.secondary2,failed:v.yellow,pending:v.secondary2,syncing:Zy(qy,n/(ru-1))??""}[e.status];return Ni.createElement(Ky,null,Ni.createElement(nu,null,Ci.hex(v.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Ni.createElement(nu,null,Ci.hex(i)("\u25CF")+Ci.hex(v.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import lu from"chalk";import{Text as uu}from"ink";import mu,{useEffect as rv,useState as ov}from"react";var Yt="1.3.3";import Si from"chalk";var ev="https://registry.npmjs.org/epiq/latest",Ai=null,iu=0,tv=1e3*60*60*24,au=e=>e.replace(/^v/,""),nv=(e,t)=>{let n=au(e).split(".").map(Number),r=au(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},du=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Ai&&Date.now()-iu<tv)return Ai;try{let t=await fetch(ev);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?nv(r,e)>0:!1};return Ai=o,iu=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},cu=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Si.hex(v.accent).dim(s):Si.hex(v.secondary).dim(s)).join(Si.hex(v.secondary2).dim("."))};function pu(){let[e,t]=ov({current:Yt,latest:null,updateAvailable:!1});return rv(()=>{let n=!0;return du(Yt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?mu.createElement(uu,{dimColor:!0,color:v.secondary2},Yt+" "):mu.createElement(uu,null,lu.hex(v.secondary2).dim(Yt),lu.hex(v.accent).dim(" \u2197 "),cu(Yt,e.latest))}function Tr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=H(),{userName:i,preferredEditor:c,autoSync:u}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",b=s?nn(s.currentLabel,Math.max(0,p)):"";return ve.createElement(Rr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?ve.createElement(Rr,{paddingLeft:1},ve.createElement(_n,{color:v.secondary2},b)):f?ve.createElement(_n,null," "):o===y.PALETTE?ve.createElement(Rr,null,ve.createElement(_n,{color:v.accent},"Command Palette"),ve.createElement(_n,{dimColor:!0,color:v.secondary2}," ","- search, select and press enter")):ve.createElement(Rr,{paddingLeft:1},e.length>0?ve.createElement(Zl,{filters:e}):ve.createElement(Jl,{width:p})),n==="live"?ve.createElement(Rr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},ve.createElement(su,{autoSync:!!u,syncStatus:r}),ve.createElement(_n,null,ts.hex(v.secondary2).dim("Mode: ")+ts.hex(v.secondary2).dim(o.padEnd(8," "))," "),ve.createElement(fu,{icon:"@",value:i}),ve.createElement(fu,{icon:"\u276F",value:c}),ve.createElement(pu,null)):"",n==="peek"?ve.createElement(eu,null):"",n==="replay"?ve.createElement(tu,null):"")}function fu({icon:e,value:t}){return ve.createElement(_n,null,ts.dim(e)+ts.hex(v.accent)(` ${t??"-"} `))}import{Box as sv,Text as iv}from"ink";import wr from"react";import{Box as ns,Text as Ri}from"ink";import Xt from"react";function Ti(){let e=H(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?G(t?.id):[];return Xt.createElement(ns,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:v.secondary,width:s},Xt.createElement(ns,{padding:1,paddingTop:0,paddingBottom:0},Xt.createElement(Ri,null,"Select a board:")),Xt.createElement(ns,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,f=G(c.id).flatMap(({id:b})=>q(b)).length;return Xt.createElement(ns,{key:c.id??u},Xt.createElement(Ri,{color:m?v.accent:v.secondary2},Xt.createElement(Re,{isSelected:m})),Xt.createElement(Ri,{color:m?v.accent:v.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var av=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=H(),u=n.find(({context:b})=>b==="BOARD"),f=s-1-3;return wr.createElement(sv,{flexDirection:"row"},e.context==="WORKSPACE"?wr.createElement(Ti,null):u?wr.createElement(So,{height:f,width:i,swimlanes:(c[u.id]??[]).filter(b=>b!==void 0&&Dt(b)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):wr.createElement(iv,null))},gu=wr.memo(av);import{useEffect as dv}from"react";var cv=e=>{dv(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=g();u==="default"&&!c&&io(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},yu=({autoSync:e})=>(cv(e),null);function wi({width:e,height:t}){let n=H(),{autoSync:r,viewMode:o}=ha(),s=n.filters;if(n.mode===y.HELP)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(ql,{width:e,height:t}));if(n.mode===y.PALETTE)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{filters:s}),ae.createElement(Fl,{width:e,height:t-2}),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Ot(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{hideBreadCrumb:!0,filters:s}),ae.createElement(Ii,{height:t,width:e})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{hideBreadCrumb:!0,filters:s}),ae.createElement(Yl,{height:t,width:e})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Le(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,f=G(p).length,b=3,N=Math.floor(e/b),S=Math.floor(e/Math.max(f,1));e=Math.min(S,N)*Math.max(f,b)}return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(yu,{autoSync:r}),ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{filters:s}),ae.createElement(gu,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import lv from"readline";var rs,os,bt,uv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.Yank,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),mv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp,h.Yank]),vu=async e=>{if(e.ctrl&&e.name==="c")return T.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=g(),s=Yd(e,n);if(!s||r&&!uv.has(s)||o==="replay"&&n===y.DEFAULT&&mv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},pv=()=>async function(t,n){n.name!=="escape"&&(bt&&(clearTimeout(bt),bt=void 0),await vu(n))},fv=()=>async function(t){if(t.length===1&&t[0]===27){bt&&clearTimeout(bt),bt=setTimeout(()=>{vu({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),bt=void 0},25);return}bt&&(clearTimeout(bt),bt=void 0)};function hu(){rs&&process.stdin.removeListener("keypress",rs),os&&process.stdin.removeListener("data",os),rs=pv(),os=fv(),lv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",os),process.stdin.on("keypress",rs)}async function xu(){try{let e=wn();te(e)&&Fe(e.value);let t=Ye(process.cwd()),n=[];if(te(t)){let s=Pe({repoRoot:t.value});if(d(s))return dn(3,s.message);let i=vn(),c=await en({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return dn(3,c.message);let u=await _({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=Et(s.value);if(d(m))return dn(3,m.message);n=m.value}let r=an(n);if(d(r))return dn(4,r.message);E({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=Mi();return d(o)?dn(6,o.message):(hu(),l("Booted Epiq",void 0))}catch(e){return dn(0,ro(e))}}hc();var hv=`${Qt.bold("Epiq CLI")}
|
|
59
59
|
|
|
60
60
|
${Qt.dim("Boot in directory:")}
|
|
61
61
|
${Qt.cyan("$ epiq")}
|
|
62
62
|
|
|
63
63
|
${Qt.dim("Launch GUI:")}
|
|
64
64
|
${Qt.cyan("$ epiq gui")}
|
|
65
|
-
`,
|
|
66
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
67
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
65
|
+
`,xv=yv(hv,{importMeta:import.meta,version:Yt,flags:{init:{type:"boolean",default:!1}}}),ss=xv.input[0];ss&&ss!=="gui"&&(console.error(Qt.red(`Unknown command: ${ss}`)),process.exit(1));var bu=process.stdout.columns||120,Iu=process.stdout.rows||20,is=null,bv=e=>{try{return is?(is.rerender(e),l("Rerendered app",void 0)):(is=gv(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${ro(t)}`)}},Mi=()=>bv(vv.createElement(wi,{width:bu,height:Iu}));process.stdout.on("resize",()=>{if(bu=process.stdout.columns||120,Iu=process.stdout.rows||20,!is)return;let e=Mi();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(ss==="gui"){let e=await Pl({repoRoot:process.cwd()});d(e)&&(console.error(Qt.red(`Failed to start Epiq GUI:
|
|
66
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await xu();d(e)&&(logger.info(e.message),console.error(Qt.red(`Failed to boot Epiq:
|
|
67
|
+
${e.message}`)),process.exitCode=1)}export{Mi as renderApp};
|