epiq 0.7.4 → 0.7.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +1 -1
- package/dist/index.js +42 -42
- package/dist/mcp.js +43 -43
- package/package.json +1 -1
- package/readme.md +41 -15
package/dist/mcp.js
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"utf8"),c("Created project.json",null)}catch(r){return i(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});var
|
|
2
|
+
var zc=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Gc=(e,t)=>{for(var n in t)zc(e,n,{get:t[n],enumerable:!0})};var ct,i,c,a,ht,E=y(()=>{"use strict";ct={None:"none",Success:"success",Fail:"fail"},i=e=>({status:ct.Fail,message:e,value:null}),c=(e,t)=>({status:ct.Success,message:e,value:t}),a=e=>e.status==="fail",ht=e=>e.status==="success"});import un from"node:fs";import et from"node:path";var Zp,tt,Pe,qn,Kc,zn,Gn,mn,As,Yc,dr,Kn,lt,Ts,He,le=y(()=>{"use strict";E();It();Zp=process.env.IS_LOCAL==="true",tt=".epiq",Pe=".epiq-global",qn="events",Kc="project.json",zn=e=>et.join(e,tt),Gn=e=>et.join(zn(e),Kc),mn=e=>et.join(zn(e),qn),As=e=>et.join(e,tt),Yc=e=>{let t=et.join(e,tt);return un.existsSync(t)&&un.statSync(t).isDirectory()},dr=e=>{let t=Gn(e);return un.existsSync(t)&&un.statSync(t).isFile()},Kn=e=>{let t=et.resolve(e);for(;;){if(Yc(t))return c("Resolved closest .epiq root",t);let n=et.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},lt=e=>{let t=et.resolve(e);for(;;){if(dr(t))return c("Resolved closest epiq project root",t);let n=et.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},Ts=e=>{let t=mn(e);try{return un.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},He=async()=>{let e=await ut(process.cwd());if(a(e))return e;let t=nt({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import pn from"node:fs";import{ulid as Xc}from"ulid";import{z as Yn}from"zod";var Jc,Qc,Xn,mt,ws,Ms,bt=y(()=>{"use strict";E();le();Jc="__epiq_state__",Qc=Yn.object({projectId:Yn.string().min(1),stateBranch:Yn.string().min(1),createdAt:Yn.iso.datetime()}),Xn=()=>({projectId:Xc(),stateBranch:Jc,createdAt:new Date().toISOString()}),mt=e=>{let t=Gn(e);if(!pn.existsSync(t))return i("Missing .epiq/project.json");try{let n=pn.readFileSync(t,"utf8"),o=JSON.parse(n),r=Qc.safeParse(o);return r.success?c("Read project.json",r.data):i(`Invalid .epiq/project.json: ${r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return i(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},ws=e=>{let t=mt(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Ms=({repoRoot:e,fileContents:t})=>{let n=zn(e),o=Gn(e);try{if(pn.mkdirSync(n,{recursive:!0}),pn.existsSync(o)){let r=mt(e);return a(r)?i(r.message):c("Project already initialized",null)}return pn.writeFileSync(o,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),c("Created project.json",null)}catch(r){return i(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});var cr,ks=y(()=>{"use strict";E();cr=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let d=o(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return r.clear=()=>n.clear(),r}});import gn from"fs";import pr from"path";import Zc from"util";function tl(){let e=Ds();if(!e||!gn.existsSync(e))return;let n=gn.readFileSync(e,"utf8").split(`
|
|
4
4
|
`);if(n[n.length-1]===""&&n.pop(),n.length<=Ls)return;let o=n.slice(-Ls).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;gn.writeFileSync(e,o,"utf8")}function
|
|
7
|
-
`;gn.mkdirSync(
|
|
8
|
-
`);u(n?{stdout:d,stderr:
|
|
9
|
-
`)))}),r.on("close",
|
|
10
|
-
`)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:x}))})}),
|
|
11
|
-
${n.message}`);let o=await
|
|
12
|
-
${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},
|
|
13
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
14
|
-
${r.message}`);let s=await
|
|
15
|
-
${s.message}`):c("Pulled with rebase",!0)}
|
|
16
|
-
`+e.message);let t=yn(
|
|
17
|
-
`+t.message):c("Ensured epiq storage",!0)},
|
|
6
|
+
`;gn.writeFileSync(e,o,"utf8")}function ur(e,t,n=!1){let o=Ds();if(!o)return;let r=Zc.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
|
|
7
|
+
`;gn.mkdirSync(pr.dirname(o),{recursive:!0}),gn.appendFileSync(o,l,"utf8"),lr++,lr>=el&&(lr=0,tl())}var Ls,el,lr,Ps,Ds,mr,ue,fn=y(()=>{"use strict";E();le();Ls=1e3,el=50,lr=0,Ps=()=>process.env.EPIQ_MCP==="true",Ds=()=>{let e=process.cwd(),t=Kn(e);return a(t)?Ps()?pr.join(process.cwd(),".epiq-mcp.log"):void 0:pr.join(t.value,tt,"log","epiq.log")};mr=()=>Ps()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ue={info(...e){let t=mr();(t==="info"||t==="debug")&&ur("[Info]",e,!1)},debug(...e){mr()==="debug"&&ur("[Debug]",e,!0)},error(...e){let t=mr();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;ur("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=ue});var ne,Jn=y(()=>{"use strict";Nt();ne={stage:({cwd:e,pathspec:t})=>j({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>j({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>j({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>j({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>j({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:o=!1})=>{let r=t&&n?["push",...o?["-u"]:[],t,n]:["push"];return j({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>j({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>j({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>j({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>j({args:["worktree","prune"],cwd:e})}});var _t,De,Qn=y(()=>{"use strict";bt();E();le();_t=e=>{let t=lt(e);if(a(t))return i("Unable to resolve epiq project root");let n=mt(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},De="origin"});import{spawn as nl}from"node:child_process";import Zn from"node:fs";import vn from"node:path";var Fs,ol,Us,j,Ve,jt,rl,sl,eo,gr,to,no,Os,Bs,fr,oo,_s,js,il,vr,$s,Ws,Nt=y(()=>{"use strict";E();Jn();Qn();Fs=1e4,ol={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Us=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Zn.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:p,exitCode:1});return}o(i(p));return}let r=nl("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:ol}),s=!1,d="",l="",u=p=>{s||(s=!0,clearTimeout(m),o(p))},m=setTimeout(()=>{r.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Fs}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},Fs);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",p=>{d+=p}),r.stderr.on("data",p=>{l+=p}),r.on("error",p=>{if(n){u({stdout:d,stderr:p.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
9
|
+
`)))}),r.on("close",p=>{let x=p??1;if(n){u({stdout:d,stderr:l,exitCode:x});return}if(x!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
+
`)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:x}))})}),j=({args:e,cwd:t})=>Us({args:e,cwd:t,allowFail:!1}),Ve=({args:e,cwd:t})=>Us({args:e,cwd:t,allowFail:!0}),jt=async({cwd:e,message:t})=>{let n=await ne.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
|
|
11
|
+
${n.message}`);let o=await j({args:["rev-parse","HEAD"],cwd:e});return a(o)?i(`Commit created, but failed to read HEAD SHA
|
|
12
|
+
${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},rl=async e=>{let t=await j({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",vn.isAbsolute(n)?n:vn.resolve(e,n))},sl=async e=>{let t=await rl(e);if(a(t))return i(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(o))if(Zn.existsSync(vn.join(n,s)))return c("Checked for in-progress Git operation",d);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(r))if(Zn.existsSync(vn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},eo=async e=>{let t=await sl(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},gr=async({repoRoot:e})=>{let n=(await Ve({args:["remote","get-url",De],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},to=async({repoRoot:e,branch:t})=>{let n=await Ve({args:["ls-remote","--heads",De,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${De}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},no=async({repoRoot:e,branch:t})=>{let n=await Ve({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},Os=e=>{try{return Zn.realpathSync.native(e)}catch{return vn.resolve(e)}},Bs=async({repoRoot:e,worktreeRoot:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=Os(t),r=n.value.stdout.split(`
|
|
13
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Os).includes(o);return c("Checked worktree registration",r)},fr=async e=>{let t=await Ve({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},oo=async e=>{let t=await j({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},_s=async e=>{let t=await j({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},js=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),il=async e=>(await Ve({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),vr=async({cwd:e,branch:t})=>{let n=await to({repoRoot:e,branch:t});if(a(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let o=await il(e);if(a(o))return i(o.message);let r=await ne.fetch({cwd:e,remote:De,branch:t});if(a(r))return i(`Failed to fetch ${t}
|
|
14
|
+
${r.message}`);let s=await ne.pullRebase({cwd:e,remote:De,branch:t});return a(s)?i(`Failed during pull --rebase
|
|
15
|
+
${s.message}`):c("Pulled with rebase",!0)},$s=async e=>{let t=await Ve({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):i(t.stderr.trim()||"Unable to inspect staged changes")},Ws=async e=>{let t=await oo(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import yr from"node:fs";import al from"node:os";import qe from"node:path";var Vs,xr,qs,ro,nt,dl,Hs,yn,so,zs,Gs,Ks,ut,Wg,It=y(()=>{"use strict";bt();E();le();ks();fn();Nt();Vs="4b825dc642cb6eb9a060e54bf8d69288fbee4904",xr=e=>qe.join(tt,qn,e),qs=()=>qe.join(al.homedir(),Pe),ro=()=>qe.join(qs(),"worktrees"),nt=({repoRoot:e})=>{let t=ws(e);return a(t)?i(t.message):c("Resolved state branch root",qe.join(ro(),t.value))},dl=e=>qe.join(e,tt),Hs=e=>qe.join(dl(e),qn),yn=e=>{try{return yr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},so=()=>{let e=yn(qs());if(a(e))return i(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=yn(ro());return a(t)?i(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):c("Ensured epiq storage",!0)},zs=e=>{yr.existsSync(e)&&(ue.debug("[sync] remove path",e),yr.rmSync(e,{recursive:!0,force:!0}))},Gs=(e,t)=>{for(let n of[Hs(e),Hs(t)]){let o=yn(n);if(a(o))return i(o.message)}return c("Ensured state branch",void 0)},Ks=async e=>{let t=await j({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
|
|
18
18
|
`+t.message);let o=t.value.stdout.trim().split(`
|
|
19
|
-
`).filter(Boolean).filter(d=>d!==tt);if(o.length===0)return c("State branch is storage-only",!1);let r=await
|
|
20
|
-
${r.message}`);let s=await jt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},ut=
|
|
21
|
-
${n.message}`);let o=n.value.stdout.trim(),r=await
|
|
22
|
-
${r.message}`):c("Created state branch",!0)},
|
|
23
|
-
`+n.message);let o=n.value,r=o?await
|
|
24
|
-
`+r.message);let s=r.value;if(o&&s){let l=await
|
|
25
|
-
${l.message}`)}let d=await
|
|
26
|
-
`+d.message);if(d.value)return c("Local state branch already exists",!1);if(s){let l=await
|
|
27
|
-
${l.message}`):c("Created local state branch from remote",!0)}return
|
|
28
|
-
`),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return c("Found worktree for branch",r)}return c("No worktree found for branch",null)},
|
|
29
|
-
`+o.message);$t.existsSync(t)&&!$t.existsSync(xn.join(t,".git"))&&(ue.info("Removing broken state branch worktree path"),
|
|
30
|
-
${r.message}`):c("Created state branch worktree",!0)},hn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await
|
|
31
|
-
${u.message}`)}if(s&&!$t.existsSync(s)){ue.info("Pruning stale state branch worktree");let u=await
|
|
32
|
-
${u.message}`)}let d=await
|
|
33
|
-
${u.message}`)}return
|
|
34
|
-
${r.message}`):c("Checked out state branch",!0)},
|
|
35
|
-
${l.message}`);let u=await
|
|
36
|
-
${u.message}`):c("Configured state branch upstream",!0)},
|
|
37
|
-
${r.message}`):c("Staged state branch event file",void 0)},
|
|
38
|
-
`+n.message):jt({cwd:t,message:n.value})},In=async({repoRoot:e,stateBranchRoot:t})=>{let n=await
|
|
39
|
-
${s.message}`):c("Pushed state branch",!0)},Js=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=_t(e);if(a(r))return r;let s=r.value,d=[ro(),await sl({repoRoot:e,stateBranchName:s}),await hn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await dl({stateBranchRoot:t,stateBranchName:s}),await Gs(t),n?await cl({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);o=o||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import{WebSocket as ll}from"ws";var ul,Qs,Zs=y(()=>{"use strict";ul=new Set,Qs=e=>{let t=JSON.stringify(e);for(let n of ul)n.readyState===ll.OPEN&&n.send(t)}});function yr(e){return e.context===w.WORKSPACE}function M(e){return e.context===w.TICKET}function ei(e){return e.context===w.TEXT}function Ve(e){return e.context===w.FIELD}function Nn(e){return e.context===w.FIELD_LIST}var w,En,xr,bn,te=y(()=>{"use strict";w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};En=e=>e.context===w.SWIMLANE,xr=e=>e.context===w.BOARD,bn=e=>e.context===w.COMMENT});var f,J=y(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ti=y(()=>{"use strict";bt()});function ao(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var co,Ct,Wt=y(()=>{"use strict";co=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ct=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var ni,oi,ri=y(()=>{"use strict";ni=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},oi=(e,t)=>t?e.get(t)??[]:[]});var si,ml,ii,ai=y(()=>{"use strict";Wt();ri();si=new WeakMap,ml=e=>{let t=si.get(e);return t||(t=ni(e),si.set(e,t)),t},ii=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return oi(ml(e),o).filter(s=>ao(o,s)>=n)}});var pl,di,gl,ci=y(()=>{"use strict";Wt();ai();pl={hint:"",hints:[],overlap:0,remainder:""},di=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return pl;let r=ii({wordList:o,inputToMatch:e,overlapThreshold:1});return gl(t,r)},gl=(e,t)=>{let n=t[0]??"",o=ao(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,g=(l&&d?r:n)+(l&&d?":":" "),x=g.slice(o);return{hint:g,hints:t,overlap:o,remainder:x}}});import{useSyncExternalStore as sf}from"react";var lo,fl,vl,Q,qe,Ee=y(()=>{"use strict";lo={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},fl=new Set,vl=()=>{for(let e of fl)e()},Q=()=>lo,qe=e=>(lo={...lo,...e},vl(),lo)});function li(e){return!e||!xl.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Fe(e,t=Ht){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function be(e,t){if(!e&&!t)return Fe(ze/2n,Ht);let n=e?li(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?li(t):c("Resolved upper bound",ze);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return Fe(ze/2n,Ht);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):Fe(d,Ht)}function ui(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=ze*BigInt(o+1)/(t+1n),s=Fe(r,Ht);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var Ht,yl,ze,xl,Vt=y(()=>{"use strict";C();Ht=24n,yl=Ht*4n,ze=(1n<<yl)-1n,xl=/^[0-9a-f]+$/});import{ulid as hl}from"ulid";var hr,mi=y(()=>{"use strict";C();Ge();Vt();hr=(e,t)=>{let n=K(e),o=ui(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let d=n[s],l=o.value[s];if(!d||!l)return i("Unable to assign rebalance rank");r[d.id]=l}return c("Created rebalance event",{id:hl(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Rt,Il,St,I,ie=y(()=>{"use strict";te();C();L();Ge();Rt=(e,t)=>{let{nodes:n}=p(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return c("Resolved ancestor node",o);let r=o.parentNodeId?n[o.parentNodeId]:void 0;for(;r;){if(r.context===t)return c("Resolved ancestor node",r);r=r.parentNodeId?n[r.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},Il=(e,t)=>{let{nodes:n}=p(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},St=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:i("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let o={...n,userId:t},r=ge(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):c("Linked contributor to user",o)},deleteNode(e){ge(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!M(t))return i("Can only comment on issues");let n=ge(o=>({...o,comments:{...o.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return i("Unable to edit comment, missing issue");if(!M(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=ge(d=>({...d,comments:{...d.comments??{},[e]:r}}));return a(s)?i("Unable to edit comment"):c("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=ge(r=>({...r,comments:{...r.comments??{},[e]:n}}));return a(o)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return p().comments?.[e]},getCommentsByIssue(e){return Object.values(p().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=p(),o=n[e];if(!o)return i("Edit target node not found");let r=St(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let o=St(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),c("Renamed node",r)},getExistingTags(){let{tags:e}=p();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=p();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return K(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=p(),r=this.getNode(e),s=this.getNode(t);if(!r)return i("Node not found");if(!s)return i("Target parent not found");if(o===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=St(r,"move");if(d)return d;if(Il(t,e))return i("Cannot move node into its own descendant");let l={...r,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=p(),r=this.getNode(e);if(!r)return i("Node not found");if(o===e)return i("Cannot delete root node");let s=new Set,d=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let g of K(m.id))d(g.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(N({nodes:l}),c("Successfully tomb stoned",r)):i("Unable to delete undefined")},createContributor(e){let t=ge(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!o)return i("Unable to assign contributor, missing target");let r=St(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!o)return i("Unable to unassign, missing target");let r=St(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let r=St(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!o)return i("Unable to remove tag, missing target");let r=St(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=ge(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=ge(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},o=ge(r=>({...r,nodes:{...r.nodes,[e]:n}}));return a(o)?i(o.message):c("Locked node",n)},updateNode(e){let t=ge(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return p().contributors[e]},getTag(e){return p().tags[e]},getNode(e){return p().nodes[e]},getSiblings(e){return K(e)}}});var ne,qt=y(()=>{"use strict";ne={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"}});var fe,zt=y(()=>{"use strict";te();fe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:w.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:w.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:w.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var ve,S,Ce=y(()=>{"use strict";ve={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"},S={accent:ve.cyan,accent2:ve.magenta,primary:ve.white,secondary:ve.grayDark,secondary2:ve.grayLight,gray:ve.gray,green:ve.green,yellow:ve.yellow,red:ve.red}});var h,Gt,uo=y(()=>{"use strict";Ce();h={red:ve.red,yellow:ve.yellow,green:ve.green,blue:ve.blue,magenta:ve.magenta,cyan:ve.cyan},Gt={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan}});import pi from"chalk";var Nr,gi,Ir,fi,Nl,El,bl,Cl,Sl,Cn,Se,Rl,mo,Al,Tl,po,pt=y(()=>{"use strict";uo();Nr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},gi=(e,t,n)=>Math.max(t,Math.min(n,e)),Ir=(e,t,n)=>e+(t-e)*n,fi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Nl=e=>e.toLowerCase().trim(),El=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,g=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,g=l):d>=3&&d<4?(m=l,g=s):d>=4&&d<5?(u=l,g=s):(u=s,g=l);let x=r-s/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((g+x)*255)]},bl=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Cl=(e,t,n)=>{let o=gi(n,0,1);return[Math.round(Ir(e[0],t[0],o)),Math.round(Ir(e[1],t[1],o)),Math.round(Ir(e[2],t[2],o))]},Sl=(e,t,n)=>Cl(e,t,n),Cn=e=>{let n=fi(e)%360,o=El(n,Nr.stringColor.saturation,Nr.stringColor.lightness);return bl(o)},Se=(e,t=Gt)=>{let n=Nl(e);return n&&t[n]?t[n]:Cn(n)},Rl=e=>{let t=Nr.gradient.stops,n=gi(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),d=r-s;return Sl(t[s],t[s+1],d)},mo=e=>fi(e.toLowerCase().trim())/4294967295,Al=e=>{let t=mo(e);return Rl(t)},Tl=e=>{let[t,n,o]=Al(e);return{normal:r=>pi.bgRgb(t,n,o).black(r),cursor:r=>pi.bgRgb(t,n,o).white.bold(r)}},po=e=>Tl(e).normal(` ${e} `)});import{decodeTime as vi}from"ulid";var go,yi,Er,Sn=y(()=>{"use strict";C();go=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"},yi=e=>{try{return c("Decoded date",new Date(vi(e)))}catch(t){return i("Decoding failed + "+t.message)}},Er=e=>{if(!e?.id)return null;try{return vi(e.id)}catch{return null}}});import At from"chalk";import xi from"string-width";import{decodeTime as wl}from"ulid";var Ml,Ll,Pl,kl,Dl,Fl,Ol,Ul,Bl,hi,Ii=y(()=>{"use strict";ie();L();pt();Sn();Ml=(e,t)=>e+" ".repeat(Math.max(0,t-xi(e))),Ll=(e,t)=>" ".repeat(Math.max(0,t-xi(e)))+e,Pl=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),kl=(e,t)=>t?e<t?"up":e>t?"down":null:null,Dl=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?At.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=kl(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Fl=e=>{switch(e.action){case"add.issue.tag":{let t=p().tags[e.payload.tag];return t?At.bgHex(Se(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=p().tags[e.payload.tag];return t?At.bgHex(Se(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=p().contributors[e.payload.assignee];return t?At.hex(Se(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=p().contributors[e.payload.assignee];return t?At.hex(Se(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:""}"`;default:return""}},Ol=e=>{let t=go(wl(e));return At.gray(Ll(t,8))},Ul=12,Bl=e=>Ml(`${e}`,Ul),hi=(e,t)=>{let n=Ol(e.id),o=Bl(e.userName),r=At.dim("\u203A"),s=e.action==="move.node"?Dl(e,t):[Pl(e.action),Fl(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as _l}from"node:crypto";var jl,$l,Re,Rn=y(()=>{"use strict";jl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$l=e=>{let t=_l("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=jl[Number(n>>s&31n)]}return o},Re=(e,t)=>$l(`${e}:virtual:${t}`)});var Wl,Hl,Vl,ql,zl,br,Ni,Ei,Gl,bi=y(()=>{"use strict";Ii();te();C();qt();ie();zt();L();Vt();Rn();Wl=e=>Re(e,"comments"),Hl=e=>Re(e,"description"),Vl=e=>Re(e,"assignees"),ql=e=>Re(e,"tags"),zl=e=>Re(e,"history"),br=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=I.getNode(e);if(!l){let g=I.createNode({...fe.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(g)?g:c("Virtual field created",void 0)}if(!Ve(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==o||l.props.value!==r||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=I.updateNode({...l,title:t,parentNodeId:n,rank:o,props:{...l.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},Ni=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...fe.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!Nn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==o||d.readonly!==r||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=I.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Ei=e=>{let t=Fe(ze/4n),n=Fe(ze/2n),o=Fe(ze*3n/4n),r=Fe(ze*7n/8n),s=Fe(ze*13n/16n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;let d=br({id:Hl(e.id),name:ne.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let l=Ni({id:Vl(e.id),name:ne.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(l))return l;let u=Ni({id:ql(e.id),name:ne.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(u))return u;let m=br({id:Wl(e.id),name:ne.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(m))return m;let g=br({id:zl(e.id),name:ne.HISTORY,parentNodeId:e.id,rank:s.value,value:Gl(e),readonly:!0,childRenderAxis:"vertical"});return a(g)?g:c("Ticket virtual nodes materialized",void 0)},Gl=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>hi(o,n.get(o.action)??[])).join(`
|
|
40
|
-
`)}});var Kl,me,fo,An=y(()=>{"use strict";Kl=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[me,fo]=Kl});function Tn(e,t=!1){let n=nu[e.action](e);if(a(n))return n;let o=tu(e,t);return o||n}var D,Ci,Yl,Xl,Jl,Ql,Zl,eu,tu,nu,Tt,Kt=y(()=>{"use strict";te();C();qt();ie();zt();L();bi();An();D=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ci=e=>{let t=I.getNode(e);if(!t||!M(t)||t.isDeleted)return null;let n=Ei(t);return a(n)?n:null},Yl=e=>{for(let t of e){let n=Ci(t);if(n)return n;let o=p().nodes[t]?.parentNodeId;if(!o)continue;let r=Ci(o);if(r)return r}return null},Xl=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Jl=e=>{let t=[e],n=p().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ql=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Jl(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[]}},Zl=e=>{ge(t=>({...t,eventLog:[...t.eventLog,e]}))},eu=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):c("Valid user",null)},tu=(e,t)=>{let n=eu(e);if(a(n))return n;let o=[...new Set(Ql(e))];t||(o.forEach(s=>Xl(s,e)),Zl(e));let r=Yl(o);return r||null},nu={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=fe.workspace(t,n,o),s=wn(r);if(a(s))return D(s.message,e);let d=I.createNode(r);return a(d)?D(d.message??"Failed to initialize workspace",e):yr(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=I.createNode(fe.workspace(t,n,o));return a(r)?D(r.message??"Failed to add workspace",e):yr(r.value)?c("Added workspace",{action:e.action,result:r.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(fe.board(t,n,o,r));return a(s)?D(s.message??"Unable to create board",e):xr(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(fe.swimlane(t,n,o,r));return a(s)?D(s.message??"Unable to create swimlane",e):En(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(fe.ticket(t,n,o,r));return a(s)?D(s.message??"Unable to create issue",e):M(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,d=I.createNode(fe.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(ne.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):Ve(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return D(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?D(r.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=I.createTag({id:t,name:n});return a(o)?D(o.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=I.createContributor({id:t,name:n});return a(o)?D(o.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.tag(t,n);return a(o)?D(o.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.untag(t,n);return a(o)?D(o.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.assign(t,n);return a(o)?D(o.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.unassign(t,n);return a(o)?D(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?D(r.message??"Failed to move node",e):c("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=I.editValue(t,n);return a(o)?D(o.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return D("Unable to locate issue",e);if(!M(r))return D("Can only close issues",e);let s=I.getNode(me);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?D(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return D("Unable to locate issue",e);if(!M(r))return D("Can only reopen issues",e);let s=I.getNode(me);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return D("Reopen parent no longer exists",e);let l=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(l)?D(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=I.getNode(o);if(!s)return D(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return D(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return D(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=I.createComment({id:t,issue:n,authorId:o,authorName:I.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return a(s)?D(s.message??"Unable to add comment",e):c("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=I.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?D(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=I.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?D(r.message??"Unable to delete comment",e):c("Comment 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 a(n)?D(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};Tt=e=>e.map(t=>Tn(t))});import vo from"node:fs";import Sr from"node:path";import{decodeTime as ou}from"ulid";import{z as Cr}from"zod";function Ar(e){let t=mn(e);if(!vo.existsSync(t))return c("No events found",[]);let n=vo.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>Sr.join(t,r)),o=[];for(let r of n){let s=lu(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",uu(o))}function wt(e){let t=Ar(e);return a(t)?i(t.message):Rr(t.value)}function Si(e,t){let n=Ar(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=mu(n.value,t),s=Rr(o);if(a(s))return i(s.message);let d=Rr(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Ri(e=process.cwd()){let t=Ar(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var ru,su,iu,au,du,cu,Rr,lu,uu,mu,Mn=y(()=>{"use strict";C();le();je();ru=Cr.object({userId:Cr.string().min(1).default("unknown"),userName:Cr.string().min(1).default("unknown")}),su=e=>{let[t,n]=Sr.basename(e,".jsonl").split("."),o=ru.safeParse({userId:t,userName:n});return o.success?c("Parsed event file actor",o.data):i(`Invalid event file name ${Sr.basename(e)}: ${o.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},iu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},au=(e,t)=>t in e,du=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),cu=e=>{let{userId:t,userName:n,...o}=e,r=iu(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?au(o,s)?c("Decoded persisted event",du({id:d,action:s,payload:o[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},Rr=e=>{let t=[];for(let n of e){let o=cu(n);if(a(o))return i(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${o.message}`);t.push(o.value)}return c("Decoded reconstructed events",t)},lu=e=>{if(!vo.existsSync(e))return c("Event file missing",[]);let t=su(e);if(a(t))return i(t.message);let n=vo.readFileSync(e,"utf8"),o=[];for(let r of n.split(`
|
|
41
|
-
`)){let s=r.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=
|
|
42
|
-
`,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let o=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var Li,
|
|
19
|
+
`).filter(Boolean).filter(d=>d!==tt);if(o.length===0)return c("State branch is storage-only",!1);let r=await j({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return i(`Failed to clean storage branch
|
|
20
|
+
${r.message}`);let s=await jt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},ut=cr(async(e=process.cwd())=>{let t=await j({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>qe.resolve(e)),Wg=cr(async e=>{let t=await j({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),o=qe.isAbsolute(n)?n:qe.join(e,n);return c("Resolved git dir",o)},e=>qe.resolve(e))});import $t from"node:fs";import xn from"node:path";var Xs,Ys,cl,hr,ll,ul,ml,hn,pl,gl,io,Js,In,Qs,ao=y(()=>{"use strict";E();fn();Jn();Qn();It();Nt();Xs=async e=>{if((await Ve({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ue.info("Creating initial commit");let n=await ne.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},Ys=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",cl=async e=>{let t=await oo(e);if(a(t))return i(t.message);let n=await _s(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Ys(t.value)}:sha:${Ys(n.value)}]`)},hr=async({repoRoot:e,stateBranchName:t})=>{ue.info(`Creating ${t}`);let n=await j({args:["commit-tree",Vs,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
|
|
21
|
+
${n.message}`);let o=n.value.stdout.trim(),r=await j({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return a(r)?i(`Failed to create ${t}
|
|
22
|
+
${r.message}`):c("Created state branch",!0)},ll=async({repoRoot:e,stateBranchName:t})=>{let n=await gr({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
|
|
23
|
+
`+n.message);let o=n.value,r=o?await to({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(r))return i(`Ensure local state branch failed
|
|
24
|
+
`+r.message);let s=r.value;if(o&&s){let l=await ne.fetch({cwd:e,remote:De,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
|
|
25
|
+
${l.message}`)}let d=await no({repoRoot:e,branch:t});if(a(d))return i(`Ensure local state branch failed
|
|
26
|
+
`+d.message);if(d.value)return c("Local state branch already exists",!1);if(s){let l=await j({args:["branch","--track",t,`${De}/${t}`],cwd:e});return a(l)?i(`Failed to create local ${t} from remote
|
|
27
|
+
${l.message}`):c("Created local state branch from remote",!0)}return hr({repoRoot:e,stateBranchName:t})},ul=async({repoRoot:e,branch:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=n.value.stdout.split(`
|
|
28
|
+
`),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return c("Found worktree for branch",r)}return c("No worktree found for branch",null)},ml=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=yn(xn.dirname(t));if(a(o))return i(`Failed to create state branch worktree
|
|
29
|
+
`+o.message);$t.existsSync(t)&&!$t.existsSync(xn.join(t,".git"))&&(ue.info("Removing broken state branch worktree path"),zs(t)),ue.info("Creating state branch worktree");let r=await ne.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(r)?i(`Failed to create state branch worktree
|
|
30
|
+
${r.message}`):c("Created state branch worktree",!0)},hn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await ul({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=xn.resolve(t),s=o.value?xn.resolve(o.value):null;if(s&&s===r&&$t.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==r){ue.info("Moving state branch worktree to expected location");let u=await ne.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
|
|
31
|
+
${u.message}`)}if(s&&!$t.existsSync(s)){ue.info("Pruning stale state branch worktree");let u=await ne.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
32
|
+
${u.message}`)}let d=await Bs({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=$t.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){ue.info("Pruning missing registered state branch worktree");let u=await ne.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
33
|
+
${u.message}`)}return ml({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},pl=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await oo(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Ve({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ue.info("Aborted stale state branch rebase");let r=await ne.checkout({cwd:e,branch:t});return a(r)?i(`Failed to checkout ${t}
|
|
34
|
+
${r.message}`):c("Checked out state branch",!0)},gl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await fr(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await gr({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return c("No remote available for state branch upstream",!1);let r=_t(e);if(a(r))return r;let s=r.value,d=await to({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);ue.info(`Configuring ${s} upstream`);let l=await ne.fetch({cwd:t,remote:De,branch:s});if(a(l))return i(`Failed to fetch ${s}
|
|
35
|
+
${l.message}`);let u=await ne.setUpstream({cwd:t,branch:s,upstream:`${De}/${s}`});return a(u)?i(`Failed to set state branch upstream
|
|
36
|
+
${u.message}`):c("Configured state branch upstream",!0)},io=async({stateBranchRoot:e,eventFileName:t})=>{let n=xr(t),o=xn.join(e,n);if(!$t.existsSync(o))return c("No event file to stage",void 0);let r=await ne.stage({cwd:e,pathspec:[n]});return a(r)?i(`Failed to stage state branch event file
|
|
37
|
+
${r.message}`):c("Staged state branch event file",void 0)},Js=async({repoRoot:e,stateBranchRoot:t})=>{let n=await cl(e);return a(n)?i(`Create state branch sync commit failed
|
|
38
|
+
`+n.message):jt({cwd:t,message:n.value})},In=async({repoRoot:e,stateBranchRoot:t})=>{let n=await fr(t);if(a(n))return i(n.message);let o=_t(e);if(a(o))return o;let r=o.value,s=n.value?await ne.push({cwd:t}):await ne.push({cwd:t,remote:De,branch:r,setUpstream:!0});return a(s)?i(`Failed during state branch push
|
|
39
|
+
${s.message}`):c("Pushed state branch",!0)},Qs=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=_t(e);if(a(r))return r;let s=r.value,d=[so(),await ll({repoRoot:e,stateBranchName:s}),await hn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await pl({stateBranchRoot:t,stateBranchName:s}),await Ks(t),n?await gl({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);o=o||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import{WebSocket as fl}from"ws";var vl,Zs,ei=y(()=>{"use strict";vl=new Set,Zs=e=>{let t=JSON.stringify(e);for(let n of vl)n.readyState===fl.OPEN&&n.send(t)}});function Ir(e){return e.context===w.WORKSPACE}function A(e){return e.context===w.TICKET}function ti(e){return e.context===w.TEXT}function ze(e){return e.context===w.FIELD}function bn(e){return e.context===w.FIELD_LIST}var w,Nn,br,En,Q=y(()=>{"use strict";w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Nn=e=>e.context===w.SWIMLANE,br=e=>e.context===w.BOARD,En=e=>e.context===w.COMMENT});var f,Z=y(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ni=y(()=>{"use strict";Et()});function co(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var lo,Ct,Wt=y(()=>{"use strict";lo=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ct=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var oi,ri,si=y(()=>{"use strict";oi=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},ri=(e,t)=>t?e.get(t)??[]:[]});var ii,yl,ai,di=y(()=>{"use strict";Wt();si();ii=new WeakMap,yl=e=>{let t=ii.get(e);return t||(t=oi(e),ii.set(e,t)),t},ai=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return ri(yl(e),o).filter(s=>co(o,s)>=n)}});var xl,ci,hl,li=y(()=>{"use strict";Wt();di();xl={hint:"",hints:[],overlap:0,remainder:""},ci=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return xl;let r=ai({wordList:o,inputToMatch:e,overlapThreshold:1});return hl(t,r)},hl=(e,t)=>{let n=t[0]??"",o=co(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,p=(l&&d?r:n)+(l&&d?":":" "),x=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:x}}});import{useSyncExternalStore as yf}from"react";var uo,Il,bl,ee,Ge,Ne=y(()=>{"use strict";uo={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Il=new Set,bl=()=>{for(let e of Il)e()},ee=()=>uo,Ge=e=>(uo={...uo,...e},bl(),uo)});function ui(e){return!e||!El.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Fe(e,t=Ht){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ee(e,t){if(!e&&!t)return Fe(Ke/2n,Ht);let n=e?ui(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?ui(t):c("Resolved upper bound",Ke);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return Fe(Ke/2n,Ht);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):Fe(d,Ht)}function mi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=Ke*BigInt(o+1)/(t+1n),s=Fe(r,Ht);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var Ht,Nl,Ke,El,Vt=y(()=>{"use strict";E();Ht=24n,Nl=Ht*4n,Ke=(1n<<Nl)-1n,El=/^[0-9a-f]+$/});import{ulid as Cl}from"ulid";var Nr,pi=y(()=>{"use strict";E();Ye();Vt();Nr=(e,t)=>{let n=Y(e),o=mi(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let d=n[s],l=o.value[s];if(!d||!l)return i("Unable to assign rebalance rank");r[d.id]=l}return c("Created rebalance event",{id:Cl(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Rt,Sl,St,I,ie=y(()=>{"use strict";Q();E();M();Ye();Rt=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return c("Resolved ancestor node",o);let r=o.parentNodeId?n[o.parentNodeId]:void 0;for(;r;){if(r.context===t)return c("Resolved ancestor node",r);r=r.parentNodeId?n[r.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},Sl=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},St=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:i("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let o={...n,userId:t},r=ge(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):c("Linked contributor to user",o)},deleteNode(e){ge(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!A(t))return i("Can only comment on issues");let n=ge(o=>({...o,comments:{...o.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return i("Unable to edit comment, missing issue");if(!A(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=ge(d=>({...d,comments:{...d.comments??{},[e]:r}}));return a(s)?i("Unable to edit comment"):c("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=ge(r=>({...r,comments:{...r.comments??{},[e]:n}}));return a(o)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return i("Edit target node not found");let r=St(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let o=St(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),c("Renamed node",r)},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 Y(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return i("Node not found");if(!s)return i("Target parent not found");if(o===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=St(r,"move");if(d)return d;if(Sl(t,e))return i("Cannot move node into its own descendant");let l={...r,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return i("Node not found");if(o===e)return i("Cannot delete root node");let s=new Set,d=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of Y(m.id))d(p.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(b({nodes:l}),c("Successfully tomb stoned",r)):i("Unable to delete undefined")},createContributor(e){let t=ge(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!o)return i("Unable to assign contributor, missing target");let r=St(o,"edit");if(r)return r;if(!A(o))return i("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!o)return i("Unable to unassign, missing target");let r=St(o,"edit");if(r)return r;if(!A(o))return i("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let r=St(o,"edit");if(r)return r;if(!A(o))return i("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!o)return i("Unable to remove tag, missing target");let r=St(o,"edit");if(r)return r;if(!A(o))return i("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=ge(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=ge(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},o=ge(r=>({...r,nodes:{...r.nodes,[e]:n}}));return a(o)?i(o.message):c("Locked node",n)},updateNode(e){let t=ge(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return Y(e)}}});var oe,qt=y(()=>{"use strict";oe={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"}});var fe,zt=y(()=>{"use strict";Q();fe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:w.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:w.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:w.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var ve,S,Ce=y(()=>{"use strict";ve={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"},S={accent:ve.cyan,accent2:ve.magenta,primary:ve.white,secondary:ve.grayDark,secondary2:ve.grayLight,gray:ve.gray,green:ve.green,yellow:ve.yellow,red:ve.red}});var h,Gt,mo=y(()=>{"use strict";Ce();h={red:ve.red,yellow:ve.yellow,green:ve.green,blue:ve.blue,magenta:ve.magenta,cyan:ve.cyan},Gt={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan}});import gi from"chalk";var Cr,fi,Er,vi,Rl,Al,Tl,wl,Ml,Cn,Se,kl,po,Ll,Pl,go,pt=y(()=>{"use strict";mo();Cr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},fi=(e,t,n)=>Math.max(t,Math.min(n,e)),Er=(e,t,n)=>e+(t-e)*n,vi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Rl=e=>e.toLowerCase().trim(),Al=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let x=r-s/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((p+x)*255)]},Tl=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,wl=(e,t,n)=>{let o=fi(n,0,1);return[Math.round(Er(e[0],t[0],o)),Math.round(Er(e[1],t[1],o)),Math.round(Er(e[2],t[2],o))]},Ml=(e,t,n)=>wl(e,t,n),Cn=e=>{let n=vi(e)%360,o=Al(n,Cr.stringColor.saturation,Cr.stringColor.lightness);return Tl(o)},Se=(e,t=Gt)=>{let n=Rl(e);return n&&t[n]?t[n]:Cn(n)},kl=e=>{let t=Cr.gradient.stops,n=fi(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),d=r-s;return Ml(t[s],t[s+1],d)},po=e=>vi(e.toLowerCase().trim())/4294967295,Ll=e=>{let t=po(e);return kl(t)},Pl=e=>{let[t,n,o]=Ll(e);return{normal:r=>gi.bgRgb(t,n,o).black(r),cursor:r=>gi.bgRgb(t,n,o).white.bold(r)}},go=e=>Pl(e).normal(` ${e} `)});import{decodeTime as yi}from"ulid";var fo,xi,Sr,Sn=y(()=>{"use strict";E();fo=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"},xi=e=>{try{return c("Decoded date",new Date(yi(e)))}catch(t){return i("Decoding failed + "+t.message)}},Sr=e=>{if(!e?.id)return null;try{return yi(e.id)}catch{return null}}});import At from"chalk";import hi from"string-width";import{decodeTime as Dl}from"ulid";var Fl,Ol,Ul,Bl,_l,jl,$l,Wl,Hl,Ii,bi=y(()=>{"use strict";ie();M();pt();Sn();Fl=(e,t)=>e+" ".repeat(Math.max(0,t-hi(e))),Ol=(e,t)=>" ".repeat(Math.max(0,t-hi(e)))+e,Ul=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Bl=(e,t)=>t?e<t?"up":e>t?"down":null:null,_l=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?At.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=Bl(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},jl=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?At.bgHex(Se(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?At.bgHex(Se(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?At.hex(Se(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?At.hex(Se(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:""}"`;default:return""}},$l=e=>{let t=fo(Dl(e));return At.gray(Ol(t,8))},Wl=12,Hl=e=>Fl(`${e}`,Wl),Ii=(e,t)=>{let n=$l(e.id),o=Hl(e.userName),r=At.dim("\u203A"),s=e.action==="move.node"?_l(e,t):[Ul(e.action),jl(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as Vl}from"node:crypto";var ql,zl,Re,Rn=y(()=>{"use strict";ql="0123456789ABCDEFGHJKMNPQRSTVWXYZ",zl=e=>{let t=Vl("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=ql[Number(n>>s&31n)]}return o},Re=(e,t)=>zl(`${e}:virtual:${t}`)});var Gl,Kl,Yl,Xl,Jl,Rr,Ni,Ei,Ql,Ci=y(()=>{"use strict";bi();Q();E();qt();ie();zt();M();Vt();Rn();Gl=e=>Re(e,"comments"),Kl=e=>Re(e,"description"),Yl=e=>Re(e,"assignees"),Xl=e=>Re(e,"tags"),Jl=e=>Re(e,"history"),Rr=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=I.getNode(e);if(!l){let p=I.createNode({...fe.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!ze(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==o||l.props.value!==r||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=I.updateNode({...l,title:t,parentNodeId:n,rank:o,props:{...l.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},Ni=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...fe.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!bn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==o||d.readonly!==r||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=I.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Ei=e=>{let t=Fe(Ke/4n),n=Fe(Ke/2n),o=Fe(Ke*3n/4n),r=Fe(Ke*7n/8n),s=Fe(Ke*13n/16n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;let d=Rr({id:Kl(e.id),name:oe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let l=Ni({id:Yl(e.id),name:oe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(l))return l;let u=Ni({id:Xl(e.id),name:oe.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(u))return u;let m=Rr({id:Gl(e.id),name:oe.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(m))return m;let p=Rr({id:Jl(e.id),name:oe.HISTORY,parentNodeId:e.id,rank:s.value,value:Ql(e),readonly:!0,childRenderAxis:"vertical"});return a(p)?p:c("Ticket virtual nodes materialized",void 0)},Ql=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>Ii(o,n.get(o.action)??[])).join(`
|
|
40
|
+
`)}});var Zl,ae,vo,Kt=y(()=>{"use strict";Zl=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ae,vo]=Zl});function An(e,t=!1){let n=au[e.action](e);if(a(n))return n;let o=iu(e,t);return o||n}var F,Si,eu,tu,nu,ou,ru,su,iu,au,Tt,Yt=y(()=>{"use strict";Q();E();qt();ie();zt();M();Ci();Kt();F=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Si=e=>{let t=I.getNode(e);if(!t||!A(t)||t.isDeleted)return null;let n=Ei(t);return a(n)?n:null},eu=e=>{for(let t of e){let n=Si(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=Si(o);if(r)return r}return null},tu=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},nu=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},ou=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return nu(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[]}},ru=e=>{ge(t=>({...t,eventLog:[...t.eventLog,e]}))},su=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?F("Invalid user ID format",e):c("Valid user",null)},iu=(e,t)=>{let n=su(e);if(a(n))return n;let o=[...new Set(ou(e))];t||(o.forEach(s=>tu(s,e)),ru(e));let r=eu(o);return r||null},au={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=fe.workspace(t,n,o),s=Tn(r);if(a(s))return F(s.message,e);let d=I.createNode(r);return a(d)?F(d.message??"Failed to initialize workspace",e):Ir(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=I.createNode(fe.workspace(t,n,o));return a(r)?F(r.message??"Failed to add workspace",e):Ir(r.value)?c("Added workspace",{action:e.action,result:r.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(fe.board(t,n,o,r));return a(s)?F(s.message??"Unable to create board",e):br(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(fe.swimlane(t,n,o,r));return a(s)?F(s.message??"Unable to create swimlane",e):Nn(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(fe.ticket(t,n,o,r));return a(s)?F(s.message??"Unable to create issue",e):A(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,d=I.createNode(fe.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(oe.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?F(d.message??`Unable to create field: ${n}`,e):ze(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return F(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?F(r.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(n)?F(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=I.createTag({id:t,name:n});return a(o)?F(o.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=I.createContributor({id:t,name:n});return a(o)?F(o.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.tag(t,n);return a(o)?F(o.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.untag(t,n);return a(o)?F(o.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.assign(t,n);return a(o)?F(o.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.unassign(t,n);return a(o)?F(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?F(r.message??"Failed to move node",e):c("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=I.editValue(t,n);return a(o)?F(o.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return F("Unable to locate issue",e);if(!A(r))return F("Can only close issues",e);let s=I.getNode(ae);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?F(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return F("Unable to locate issue",e);if(!A(r))return F("Can only reopen issues",e);let s=I.getNode(ae);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return F("Reopen parent no longer exists",e);let l=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(l)?F(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return a(n)?F(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=I.getNode(o);if(!s)return F(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return F(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return F(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=I.createComment({id:t,issue:n,authorId:o,authorName:I.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return a(s)?F(s.message??"Unable to add comment",e):c("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=I.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?F(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=I.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?F(r.message??"Unable to delete comment",e):c("Comment 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 a(n)?F(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};Tt=e=>e.map(t=>An(t))});import yo from"node:fs";import Tr from"node:path";import{decodeTime as du}from"ulid";import{z as Ar}from"zod";function Mr(e){let t=mn(e);if(!yo.existsSync(t))return c("No events found",[]);let n=yo.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>Tr.join(t,r)),o=[];for(let r of n){let s=fu(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",vu(o))}function wt(e){let t=Mr(e);return a(t)?i(t.message):wr(t.value)}function Ri(e,t){let n=Mr(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=yu(n.value,t),s=wr(o);if(a(s))return i(s.message);let d=wr(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Ai(e=process.cwd()){let t=Mr(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var cu,lu,uu,mu,pu,gu,wr,fu,vu,yu,wn=y(()=>{"use strict";E();le();je();cu=Ar.object({userId:Ar.string().min(1).default("unknown"),userName:Ar.string().min(1).default("unknown")}),lu=e=>{let[t,n]=Tr.basename(e,".jsonl").split("."),o=cu.safeParse({userId:t,userName:n});return o.success?c("Parsed event file actor",o.data):i(`Invalid event file name ${Tr.basename(e)}: ${o.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},uu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},mu=(e,t)=>t in e,pu=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),gu=e=>{let{userId:t,userName:n,...o}=e,r=uu(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?mu(o,s)?c("Decoded persisted event",pu({id:d,action:s,payload:o[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},wr=e=>{let t=[];for(let n of e){let o=gu(n);if(a(o))return i(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${o.message}`);t.push(o.value)}return c("Decoded reconstructed events",t)},fu=e=>{if(!yo.existsSync(e))return c("Event file missing",[]);let t=lu(e);if(a(t))return i(t.message);let n=yo.readFileSync(e,"utf8"),o=[];for(let r of n.split(`
|
|
41
|
+
`)){let s=r.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=kr(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);o.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",o)};vu=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],x=m.id[1]??null;t.set(p,m);let C=n.get(x)??[];C.push(m),n.set(x,C)}for(let m of n.values())m.sort((p,x)=>p.id[0].localeCompare(x.id[0]));let o=[],r=new Set,s=m=>{let p=m.id[0];if(r.has(p))return;o.push(m),r.add(p);let x=n.get(p)??[];for(let C of x)s(C)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],x=m.id[1]??null;return!r.has(p)&&x!==null&&!t.has(x)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return o},yu=(e,t)=>{let n=new Set,o=[],r=[];for(let s of e){let d=s.id[0],l=s.id[1],u=!1;try{u=du(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),r.push(s)):o.push(s)}return{appliedEvents:o,unappliedEvents:r}}});var Ti,wi=y(()=>{"use strict";Ti=e=>({action:e.action,payload:e.payload})});import xu from"node:fs";import hu from"node:path";import{decodeTime as Iu,monotonicFactory as bu}from"ulid";import{z as Mn}from"zod";function xo({event:e,rootDir:t}){try{let n=Ts(t);if(a(n))return n;let o=Ru(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=Ai(t);if(a(r))return i(r.message);let s=r.value?Mi(Math.max(Date.now(),Iu(r.value)+1)):Mi(),d=Au(Ti(e),[s,r.value]);return a(d)?i(d.message):(xu.appendFileSync(o.value,`${JSON.stringify(d.value)}
|
|
42
|
+
`,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let o=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var Li,Mi,Nu,Eu,kr,ki,Cu,Su,X,Mt,Ru,Au,je=y(()=>{"use strict";E();Ne();le();wn();wi();Li=1,Mi=bu(),Nu=Mn.tuple([Mn.string().min(1),Mn.string().min(1).nullable()]),Eu=Mn.looseObject({v:Mn.literal(Li),id:Nu}),kr=e=>{let t=Eu.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ki=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Cu=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Su=e=>e.trim().length>0&&e.length<=80,X=()=>{let{userName:e,userId:t}=ee();return e?t?Cu(t)?Su(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},Mt=({userId:e,userName:t})=>`${ki(e)}.${ki(t)}.jsonl`,Ru=(e,{userId:t,userName:n})=>{let o=Mt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=hu.join(mn(e),o);return c("Successfully resolved event log path",s)},Au=(e,t)=>{let n={[e.action]:e.payload,v:Li,id:t};return kr(n)}});import{ulid as Tu}from"ulid";function Pi(e,t){let n=An(e);if(n.status!==ct.Success)return n;let o=xo({event:e,rootDir:t});return a(o)?o:n}function U(e,t){if(e.length===0||!e[0])return i("No events provided");let n=wu(e[0],t);if(a(n))return n;let o=e.map(s=>Pi(s,t)),r=o.filter(a);return r.length>0?i("Materialize and persist failed: "+r.map(s=>s.message).join(", ")):c("Materialization succeeded",o.map(s=>s.value))}var wu,kt=y(()=>{"use strict";E();ie();Yt();je();wu=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(I.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:Tu(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=Pi(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var Di,ho,Y,Fi,Oi,Lt,Xt,Ye=y(()=>{"use strict";pi();kt();E();M();Vt();Di=e=>ho(Y(e),{at:"end"}),ho=(e,t={at:"end"})=>{let n=o=>a(o)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ee(void 0,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ee(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ee(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=Fi(e,t.sibling);if(o<0)return i("Sibling not found");let r=o>0?e[o-1]:void 0,s=e[o];return s?n(Ee(r?.rank,s.rank)):i("Sibling not found")}case"after":{let o=Fi(e,t.sibling);if(o<0)return i("Sibling not found");let r=e[o],s=o<e.length-1?e[o+1]:void 0;return r?n(Ee(r.rank,s?.rank)):i("Sibling not found")}}},Y=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Fi=(e,t)=>e.findIndex(n=>n.id===t),Oi=(e,t,n={at:"end"})=>ho(Y(t).filter(o=>o.id!==e),n),Lt=(e,t,n,o,r)=>{let s=Oi(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=Nr(e,o);if(a(d))return d;let l=U([d.value],r);if(a(l))return l;let u=Oi(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},Xt=(e,t,n)=>{let o=Di(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=Nr(e,t);if(a(r))return r;let s=U([r.value],n);if(a(s))return s;let d=Di(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var L,Ui,Bi,Oe=y(()=>{"use strict";M();L={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=z(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||L.navigate({contextNode:r,selectedIndex:z(r.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 o=z(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;L.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ui(1),navigateToPreviousItem:()=>Ui(-1),navigateToNextContainer:()=>Bi(1),navigateToPreviousContainer:()=>Bi(-1),navigate:({contextNode:e,selectedIndex:t})=>{b({contextNodeId:e.id,selectedIndex:t})}},Ui=e=>{let{selectedIndex:t,contextNode:n}=g(),o=z(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;L.navigate({selectedIndex:s,contextNode:n})},Bi=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=z(r.id),d=s.findIndex(C=>C.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=z(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),x=u.length?p:-1;L.navigate({contextNode:l,selectedIndex:x})}});var ji,$i,Mu,Io,Wi,_i,ku,Hi,Vi=y(()=>{"use strict";Q();E();Ye();M();Oe();ji=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),$i=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Mu=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&ze(t)&&t.childRenderAxis==="vertical"},Io=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=Y(o.id);return L.navigate({contextNode:o,selectedIndex:ji(t,r.length)}),!0},Wi=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Io(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=Y(r.id).findIndex(l=>l.id===n.id);return d>=0?(L.navigate({contextNode:r,selectedIndex:d}),!0):Wi(r.id)},_i=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Wi(n))return!0;n=t[n]?.parentNodeId}return!1},ku=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Hi=e=>{let{nodes:t,rootNodeId:n}=g();if(Mu(e.contextNodeId)&&Io(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(ku(e.selectedNodeId)&&e.selectedNodeId&&_i(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Io(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Io(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(_i(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return i("Unable to restore navigation");let r=Y(o.id);return L.navigate({contextNode:o,selectedIndex:ji(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as Lu,ulid as ot}from"ulid";function Pu(){let e=Ue();if(a(e))return i("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[o]=z(n.id),[r]=o?z(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return c("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?c("Resolved boot nav target",{contextNode:o,selectedIndex:0}):n?c("Resolved boot nav target",{contextNode:n,selectedIndex:0}):c("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function Du(){let e=Pu();return a(e)?e:L.navigate(e.value)}function qi({userId:e,userName:t}){let n=kn(),o=kn(),r=kn(),s=kn(),d=kn(),l=Ee(void 0,void 0);if(a(l))return l;let u=Ee(void 0,void 0);if(a(u))return u;let m=Ee(u.value,void 0);if(a(m))return m;let p=Ee(void 0,void 0);if(a(p))return p;let x=Ee(p.value,void 0);if(a(x))return x;let C=Ee(x.value,void 0);if(a(C))return C;let T=Ee(void 0,void 0);return a(T)?T:c("Created default events",[{id:ot(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:ot(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:ot(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:ot(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:x.value}},{id:ot(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:C.value}},{id:ot(),userId:e,userName:t,action:"add.board",payload:{id:vo,name:"Closed",parent:n,rank:m.value}},{id:ot(),userId:e,userName:t,action:"add.swimlane",payload:{id:ae,name:"Closed",parent:vo,rank:T.value}},{id:ot(),userId:e,userName:t,action:"lock.node",payload:{id:vo}},{id:ot(),userId:e,userName:t,action:"lock.node",payload:{id:ae}}])}function Ln(e){if(!e.length){let o=fe.workspace("temporary-uninitialized-workspace","Workspace","a0"),r=Tn(o);return a(r)?r:(b({hasProjectDefinition:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(o=>o.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Tt(e).filter(a);return n.length>0?i(`Materializing failed:
|
|
43
43
|
${n.map(o=>o.message).join(`
|
|
44
|
-
`)}`):(wu(),N({hasProjectDefinition:!0}),c("State booted successfully",null))}var Pn,Io=y(()=>{"use strict";Oe();J();C();zt();L();Vt();Kt();An();Pn=Au()});var q,wr=y(()=>{"use strict";C();q=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Ye,No,Mu,qi,Mr=y(()=>{"use strict";Hi();Io();Mn();je();J();C();L();Eo();wr();Lr();Ye=null,No=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Ye,currentStatus:p().syncStatus?.status,currentMessage:p().syncStatus?.msg}),Ye)return logger.debug("[sync] syncAndReloadState joining existing promise"),Ye;logger.debug("[sync] syncAndReloadState creating promise"),Ye=Mu();try{let e=await Ye;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:p().syncStatus?.status,statusMessageAfterResolve:p().syncStatus?.msg}),a(e)&&p().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Ye||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:p().syncStatus?.status,statusMessageBeforeClear:p().syncStatus?.msg}),Ye=null}},Mu=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:p().mode,syncStatus:p().syncStatus});let e=qi();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:p().mode,message:e.message,syncStatus:p().syncStatus}),e;if(Ye)return Ye;logger.debug("[sync] syncAndReloadState:start");let t=q("resolveActorId",X());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:p().syncStatus});let n=Mt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=q("syncEpiqWithRemote",await bo({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:p().syncStatus}),Ue(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=q("loadMergedEvents",wt(r));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(s),message:(a(s),s.message),count:a(s)?void 0:s.value.length}),a(s))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:p().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=qi();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:p().mode,message:d.message,syncStatus:p().syncStatus}),d;let l=ji();if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,selectedNodeId:p().selectedNode?.id,contextNodeId:p().contextNode?.id,selectedNodeIsVirtual:p().selectedNode?.isVirtual,contextNodeIsVirtual:p().contextNode?.isVirtual}),!p().selectedNode?.isVirtual&&!p().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let m=q("bootStateFromEventLog",kn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(m),message:(a(m),m.message)}),a(m))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:p().syncStatus}),i(`Unable to boot synced state. ${m.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:p().selectedNode?.isVirtual,contextNodeIsVirtual:p().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),logger.debug("[sync] restoreNavigationAnchor:start");let u=q("restoreNavigationAnchor",Wi(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(u),message:a(u)?u.message:"Navigation restored",selectedNodeId:p().selectedNode?.id,contextNodeId:p().contextNode?.id}),a(u)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:p().syncStatus}),u):(N({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:p().syncStatus}),c("Synced",!0))},qi=()=>p().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:p().mode,syncStatus:p().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var Xt,zi,Gi,Pr,kr,Dn,Dr,Lu,Ki,Pu,Yi,Co=y(()=>{"use strict";C();Ee();L();Mr();Xt=3e3,zi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Xt?null:t},Gi=0,kr=!1,Dn=!1,Dr=()=>{if(kr)return!0;let e=Ke();return a(e)?!1:e.value.syncStatus.status==="syncing"},Lu=()=>{let e=Q().autoSyncIntervalMs??1e4,t=Date.now()-Gi;return Math.max(0,e-t)},Ki=()=>{Pr||(Pr=setTimeout(async()=>{if(Pr=void 0,!!Jt()){if(Dr()){Dn=!0;return}Dn=!1,await Pu()}},Lu()))},Pu=async()=>{if(p().readOnly||p().timeMode==="peek")return i("Cannot auto-sync while peeking");if(!Jt())return i("Cannot auto-sync before state is initialized");if(Dr())return Dn=!0,i("Sync already in progress");kr=!0,Gi=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await No()}finally{kr=!1,Dn&&Ki()}},Yi=()=>{Jt()&&(Dn=!0,!Dr()&&Ki())}});var So,Xi,Ji,Qi,Fn=y(()=>{"use strict";C();Nt();Ee();le();So=()=>{let e=Q(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},Xi=()=>{let e=lt(process.cwd());if(a(e))return!1;let t=mt(e.value);return ht(t)},Ji=e=>e===!0?"on":e===!1?"off":null,Qi=e=>e==="on"?!0:e==="off"?!1:null});var ku,Du,Fr,Or,Ro,Ao,To=y(()=>{"use strict";te();C();ie();L();ku=e=>e.props.tags??[],Du=e=>e.props.assignees??[],Fr=e=>ku(e).map(t=>I.getTag(t)).filter(t=>!!t),Or=e=>Du(e).map(t=>I.getContributor(t)).filter(t=>!!t),Ro=()=>{let{breadCrumb:e,selectedNode:t}=p(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!M(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Fr(n))},Ao=()=>{let{breadCrumb:e,selectedNode:t}=p(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!M(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Or(n))}});var v,kt=y(()=>{"use strict";v={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var Fu,Ou,Uu,Bu,_u,wo,Zi,ju,ea,Mo=y(()=>{"use strict";Fu=/^(\d+)(h|d|w|mo|y)$/,Ou=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Uu=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},Bu=(e,t=new Date)=>{let n=e.match(Fu);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(r){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},_u=e=>{let t=e.match(Ou);if(!t)return null;let[,n,o,r,s,d]=t,l=Number(n),u=Number(o),m=Number(r),g=s?Number(s):0,x=d?Number(d):0;return Uu({year:l,month:u,day:m,hour:g,minute:x})?new Date(l,u-1,m,g,x):null},wo=e=>{let t=e.trim().toLowerCase();return Bu(t)??_u(t)},Zi=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ju=[{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}],ea=(e=ju)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var $u,oe,Xe,Wu,Hu,Br,Dt,Lo,Ur,ta,Vu,qu,zu,pe,Qt=y(()=>{"use strict";Co();Fn();ie();L();uo();To();kt();Mo();$u=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},Xe={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Wu=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.LOG_LEVEL],Hu=[Xe.TITLE,Xe.DESCRIPTION,Xe.COMMENT],Br=[String(Xt),"5000","15000","30000","60000"],Dt=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG],Lo=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Ur=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],ta=[v.FILTER,v.PEEK],Vu={WORKSPACE:[...Dt,...Lo],BOARD:[...ta,...Dt,...Lo],SWIMLANE:[...ta,...Dt,...Lo],TICKET:[...Dt,...Lo,...Ur],FIELD:[...Dt,...Ur],FIELD_LIST:[...Dt,...Ur],TEXT:[...Dt],COMMENT:[v.EDIT,v.DELETE]},qu=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],zu=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=So();if(!o)return[v.HELP,v.CONFIG];if(!Xi())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.EXPORT,v.CONFIG];let r=e?.context,s=r&&$u.includes(r);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Vu[l]:[]))].filter(l=>l===v.MOVE?!1:l===v.EDIT||l===v.DELETE?s:!0)},pe=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=p())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:zu({breadCrumb:r,readOnly:o,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...ea(),"now","prev","next"],[v.EDIT]:[...Hu],[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","clear"],[v.TAG]:[...new Set([...Object.keys(Gt),...I.getExistingTags()])],[v.UNTAG]:[...Ro()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...Ao()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:I.getExistingAssignees(),[v.NEW]:qu(s),[v.CONFIG]:[...Wu],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var na,oa=y(()=>{"use strict";na=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var Be,Zt=y(()=>{"use strict";C();Be=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});import ra from"chalk";var Z,Ie,ye,sa=y(()=>{"use strict";pt();Ce();Z=e=>ra.dim(e),Ie=e=>ra.hex(S.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let g=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,b)=>mo(x)-mo(b)).slice(0,o).map(x=>po(x)).join(" ");return g?`${Z(e)}${g}${Z(n)}`:""}});var gt,Po=y(()=>{"use strict";gt={None:"none",Invalid:"invalid",Valid:"valid"}});import aa from"chalk";var en,Gu,ia,re,H,_,Do,ko,_r,Ku,Ft,Yu,Xu,Ju,da,jr=y(()=>{"use strict";Co();Fn();oa();Sn();Zt();C();ie();de();Ee();L();pt();To();Rn();sa();kt();Po();Qt();Mo();en=140,Gu=["BOARD","TICKET","SWIMLANE"],ia=()=>{let e=p().selectedNode;if(!e?.context)return _({message:Z("Missing target context")});if(Gu.includes(e.context))return H();if(e.parentNodeId){let t=p().nodes[e.parentNodeId];if(t?.id===Re(t?.parentNodeId??"","comments"))return H()}return _({message:Z("Command not available in this context")})},re="<ENTER> to confirm",H=(e="",t=[])=>({message:Z(e),validity:gt.Valid,completionWordList:t}),_=({message:e,completionWordList:t=[]})=>({validity:gt.Invalid,message:e,completionWordList:t}),Do=e=>e.length===0,ko=e=>` ${aa.hex("#000").bgHex(Se(e))(` ${e} `)} `,_r=({modifier:e})=>{let t="confirm";return e===t?H(re):_({message:Do(e)?Z("if you are certain, enter ")+po(t):"",completionWordList:[t]})},Ku=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?_({message:Z(n)}):H():_({message:Do(o)?t:"",completionWordList:[...e]}),Ft=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Do(n)&&Do(o)?_({message:e,completionWordList:[]}):H(t??re),Yu=({modifier:e,inputString:t})=>{let n=pe(v.CONFIG);if(!n.includes(e))return _({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let o=[...na];return t.trim()?o.includes(t.trim())?H(re):_({message:ye({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):_({message:ye({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?H(re):_({message:ye({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.USERNAME:return t.trim()?H(re):_({message:Ie("Enter a user name. Saved in ")+aa.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?H(re):_({message:ye({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case oe.AUTOSYNC:{let o=["on","off"],r=Q().autoSync;if(!o.includes(t.trim())){let s=Ji(r);return _({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return H(re)}case oe.SYNC_DEBOUNCE_MS:{let o=Q().autoSyncIntervalMs,r=zi(t);if(!t.trim()||r===null||r<Xt){let s=ye({prefix:" examples: ",wordList:Br,minLengthForHints:0,inputString:t});return _({message:Ie(`provide duration above ${Xt}ms. current duration: ${o}ms.`)+s,completionWordList:Br})}return H(re)}default:return _({message:Ie("Unknown config option"),completionWordList:n})}},Xu=({modifier:e,inputString:t})=>{let n=pe(v.EDIT);if(!n.includes(e)){let d=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return _({message:d||Ie("Unknown edit option"),completionWordList:n})}let{breadCrumb:o,selectedNode:r}=p(),s=Be([...o,r],"TICKET");if(a(s))return _({message:Ie("Command not available in this context")});switch(e){case Xe.COMMENT:return t||tn(()=>"hahah"),H(re);case Xe.TITLE:return H(re);case Xe.DESCRIPTION:{let{preferredEditor:d}=Q();return d?H(Z("<ENTER> to edit in ")+d):_({message:"No editor selected"})}default:return _({message:Ie("Unknown edit option"),completionWordList:n})}},Ju={[v.EXPORT]:()=>H(re+Z(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return H(re);let o=wo(t);if(!t||!o)return _(n);let r=Be(p().breadCrumb,"BOARD");if(a(r))return _({message:Ie("Command is not applicable in this context")});let s=yi(r.value.id);return a(s)?_({message:Ie("Unable to peek: board id is not a valid ULID")}):Zi({date:o,horizonDate:s.value})?H(re):_({message:Ie(`nothing to peek before ${s.value.toISOString().slice(0,16).replace("T"," ")}`)})},[v.EXIT]:()=>H(re+Z(" and exit the application")),[v.INIT]:()=>H(re),[v.PALETTE]:()=>H(re),[v.FILTER]:e=>{if(e.modifier==="clear")return H();let t=s=>pe(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return _({message:ye({wordList:pe(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:pe(v.FILTER)});let n=Object.values(p().tags).map(s=>s.name),o=Object.values(p().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?_({message:ye({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString}),completionWordList:r}):H():_({message:ye({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString}),completionWordList:r})},[v.NONE]:e=>{let t=pe(v.NONE);return _({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Ku({list:pe(v.NEW),hint:ye({wordList:pe(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>H(re),[v.EDIT]:Xu,[v.COMMENT]:e=>{let t=Ft({hint:Z(`write a comment (max ${en} char)...`),onOk:Z(`(${e.inputString.length}/${en})`)})(e);return t.validity===gt.Invalid?t:e.inputString.length>en?H(Ie("max input exceeded")):t},[v.CONFIG]:Yu,[v.DELETE]:e=>{let t=ia();return t.validity==="invalid"?t:_r(e)},[v.CLOSE_ISSUE]:e=>_r(e),[v.RE_OPEN_ISSUE]:e=>_r(e),[v.MOVE]:e=>{let t=ia();return t.validity==="invalid"?t:Ft({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:pe(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(ko).join("");return Ft({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[v.UNTAG]:e=>{let t=Ro();if(a(t))return _({message:Ie("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(ko).slice(0,10);return n.length?Ft({hint:Z(" ... ")+n.join("")})(e):_({message:Ie("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=I.getExistingAssignees().map(ko).slice(0,10);return Ft({hint:Z("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=Ao();if(a(t))return _({message:Ie("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(ko).slice(0,10);return n.length?Ft({hint:Z("remove assignee... ")+n.join("")})(e):_({message:Ie("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>H(re),[v.COFFEE]:e=>{let{modifier:t}=e,n=pe(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?_({message:Z("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):Ft({hint:ye({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},da=Object.fromEntries(Object.entries(Ju).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var ca,la=y(()=>{"use strict";ca=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"]});var ua,ma,$r=y(()=>{"use strict";ci();Qt();kt();jr();la();L();J();ua=e=>Object.values(v).includes(e),ma=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=da[n].validate(n,o,s),m=r==="command"||r==="modifier"?pe(n):ca,{mode:g}=p(),x=g===f.COMMAND_LINE?d??"":"",b=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?di(e,b):{hint:"",hints:[],remainder:"",overlap:0}}}});var pa,Qu,Zu,em,ga=y(()=>{"use strict";$r();Qt();pa=e=>{let t=e.trimStart(),n=Zu(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=em(e),l=ua(o)?o:null,u=l!==null,m=o!=="",g=l?pe(l)??[]:[],x=l&&g.includes(r)?r:"",b="word";n.length===0||n.length===1&&!s?b="command":(n.length===1&&s||n.length===2&&!s)&&(b="modifier");let T=s?"":d,R=Qu(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:x,target:b,inputToMatch:T,inputString:R}},Qu=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},Zu=e=>e.trim()?e.trim().split(/\s+/):[],em=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as xh}from"react";var nn,Wr,on,tm,fa,Je,On,Hr,Vr,va,ya,tn,xa,$,ha,Ia,Na,se,Ea,de=y(()=>{"use strict";$r();ga();C();Po();nn=e=>e===Wr||e===":",Wr=" ",on={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:gt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},tm=new Set,fa=()=>{for(let e of tm)e()},Je=e=>{let n=e(on),o=pa(n.value),r=n.cursorPosition===n.value.length;on={...n,commandMeta:ma(o,r)},fa()},On=({message:e,status:t})=>{let n=structuredClone(on);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,on=n,fa(),c(e,null)},Hr=e=>{Je(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Vr=e=>{Je(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&nn(n[r-1]);)r--;for(;r>0&&!nn(n[r-1]);)r--}else{for(;r<n.length&&!nn(n[r]);)r++;for(;r<n.length&&nn(n[r]);)r++}return{...t,cursorPosition:r}})},va=()=>{Je(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}})},ya=()=>{Je(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&nn(t[o-1]);)o--;for(;o>0&&!nn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},tn=e=>{Je(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),d=s+r,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},xa=()=>{Je(e=>({...e,commandIsPending:!0}))},$=e=>{Je(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},ha=({addToHistory:e=!0})=>{Je(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ia=()=>{Je(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}})},Na=()=>{Je(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},se=()=>on,Ea=()=>{let[e,...t]=on.value.split(Wr);return t.join(Wr).trim()}});var A,bt=y(()=>{"use strict";J();ti();L();de();Ee();A={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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var ba,P,qr=y(()=>{"use strict";L();kt();ba=e=>{let{context:t}=p().contextNode;if(!t)return P.None;switch(e){case v.EXIT:return P.Exit;case v.EXPORT:return P.Export;case v.COFFEE:return P.Coffee;case v.INIT:return P.Init;case v.DELETE:return P.Delete;case v.EDIT:return P.Edit;case v.COMMENT:return P.Comment;case v.HELP:return P.ViewHelp;case v.RE_OPEN_ISSUE:return P.ReopenIssue;case v.CLOSE_ISSUE:return P.CloseIssue;case v.TAG:return P.TagTicket;case v.UNTAG:return P.UntagTicket;case v.ASSIGN:return P.AssignUserToTicket;case v.UNASSIGN:return P.UnassignUserFromTicket;case v.NEW:return P.NewItem;case v.FILTER:return P.Filter;case v.MOVE:return P.Move;case v.PEEK:return P.Peek;case v.CONFIG:return P.Config;case v.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",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{Text as Ca}from"ink";import Sa,{useEffect as Ra,useState as nm}from"react";var Aa,Ae,rn=y(()=>{"use strict";L();Ce();Aa={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ae=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=_e(),o=Aa[n]??Aa.default,[r,s]=nm(0);if(Ra(()=>{s(0)},[o]),Ra(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return Sa.createElement(Ca,null,t);let d=o[r]??o[0]??t;return Sa.createElement(Ca,{color:S.accent,dimColor:r===1},d)}});import{Box as zr,Text as om}from"ink";import Fo from"react";var sn,Oo=y(()=>{"use strict";Ce();sn=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,scrollByOne:r=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(o)),l=Math.max(1,Math.floor(s/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),g=r?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),x=g+l,b=e.slice(g,x),T=e.length>l,R=s,F=T?Math.max(1,Math.floor(l/e.length*R)):R,j=Math.max(0,R-F),O=Math.max(1,e.length-l),Y=T?Math.floor(g/O*j):0;return Fo.createElement(zr,{flexDirection:"row",height:s,width:"100%"},Fo.createElement(zr,{flexDirection:"column",flexGrow:1,height:s},b),Fo.createElement(zr,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((W,V)=>Fo.createElement(om,{key:V,color:T&&V>=Y&&V<Y+F?S.accent:S.secondary},T?"\u2502":" "))))}});import{Text as rm}from"ink";import sm from"react";var im,am,an,Uo=y(()=>{"use strict";uo();pt();ie();im=e=>e.toLowerCase().trim(),am=(e,t=Gt)=>{let n=im(e);return t[n]?t[n]:Cn(n)},an=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return sm.createElement(rm,{underline:t,color:am(n.name)},"@"+n.name)}});import{Text as dm}from"ink";import cm from"react";var Bo,Gr=y(()=>{"use strict";ie();Ce();pt();Bo=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return cm.createElement(dm,{underline:t,backgroundColor:Se(n.name),color:S.secondary}," "+n.name+" ")}});import{Box as _o,Text as lm}from"ink";import Ot from"react";var Ta,wa=y(()=>{"use strict";Ce();Wt();To();Uo();Gr();Ta=({width:e,ticket:t,isSelected:n})=>{let o=e-14,r=co(Ct(t.title),o),s=Fr(t),d=Or(t);return Ot.createElement(_o,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?S.accent:S.secondary,justifyContent:"space-between"},Ot.createElement(_o,{borderBottom:!0},Ot.createElement(_o,{paddingLeft:1,flexDirection:"column"},Ot.createElement(lm,{color:S.primary},r))),Ot.createElement(_o,{flexDirection:"row",paddingLeft:1},s.map(l=>Ot.createElement(Bo,{key:l.id,id:l.id})),d.map(l=>Ot.createElement(an,{key:l.id,id:l.id}))))}});import{Box as Ut,Text as Un}from"ink";import Te from"react";var um,Ma,La=y(()=>{"use strict";J();ie();Ce();pt();rn();um=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ma=({width:e,ticket:t,isSelected:n,index:o,mode:r})=>{let s=(t.props.tags??[]).map(O=>I.getTag(O)).filter(O=>!!O),d=(t.props.assignees??[]).map(O=>I.getContributor(O)).filter(O=>!!O),l=1,u=s.length*(1+l),m=d.length*(2+l),g=s.map(O=>Te.createElement(Ut,{key:O.id,paddingRight:l},Te.createElement(Un,{color:Se(O.name)},"\u25A0"))),x=d.map(O=>Te.createElement(Ut,{key:O.id,paddingRight:l},Te.createElement(Un,{color:Cn(O.name)},"@"+O.name.at(0)))),b=n?S.accent:r===f.MOVE?S.secondary:S.primary,T=4,R=I.getCommentsByIssue(t.id),F=R.length?String(R.length).length+2+l:0,j=R.length?Te.createElement(Ut,{paddingRight:l},Te.createElement(Un,{color:S.accent},"[",R.length,"]")):null;return Te.createElement(Ut,{borderBottom:!0,justifyContent:"space-between"},Te.createElement(Ut,null,Te.createElement(Ut,{width:T},n?Te.createElement(Ae,{isSelected:n}):Te.createElement(Un,{color:"gray",dimColor:!0},o+1)),Te.createElement(Un,{wrap:"truncate",color:b},um(t.title,e-u-m-F-18))),Te.createElement(Ut,null,g,x,j))}});import mm from"chalk";import{Box as Kr,Text as pm}from"ink";import Qe from"react";var gm,Pa,ka=y(()=>{"use strict";te();L();Ce();rn();Oo();wa();La();gm=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=_e(),m=u[e.id]??[],g=`${e.title} ${mm.hex(S.secondary2).dim("("+m.length+")")}`,x=3,b=r?1:4,T=o-x-(r?2:1),R=Qe.createElement(Kr,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Qe.createElement(Ae,{isSelected:t}),Qe.createElement(pm,{bold:!0,color:t?S.accent:S.primary},g," ",e.readonly?"\u{1F512}":"")),F=(j,O)=>{let Y=s&&d===O;return M(j)?r?Qe.createElement(Ma,{key:j.id,index:O,width:n,ticket:j,isSelected:Y,mode:l}):Qe.createElement(Ta,{key:j.id,width:n,ticket:j,isSelected:Y}):null};return Qe.createElement(Kr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:1,paddingLeft:1,height:o},R,Qe.createElement(Kr,{padding:r?1:0},m.length>0&&Qe.createElement(sn,{selectedIndex:d,height:T,itemHeight:b},m.map(F)),Qe.createElement(Ae,{isSelected:s&&d===-1})))},Pa=Qe.memo(gm)});import{Box as jo,Text as fm}from"ink";import rt from"react";var Da,Fa=y(()=>{"use strict";te();ie();qt();L();Ce();Uo();rn();Gr();Da=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=_e(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&M(s)?r===ne.ASSIGNEES?s.props.assignees??[]:r===ne.TAGS?s.props.tags??[]:[]:[];return rt.createElement(jo,{alignItems:"center",paddingTop:1},rt.createElement(jo,{minWidth:12},rt.createElement(Ae,{isSelected:n}),rt.createElement(fm,{color:n?S.accent:S.secondary2},r,":")),rt.createElement(jo,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return rt.createElement(jo,{key:`${r}-${l}`,paddingRight:2,minHeight:1},rt.createElement(Ae,{isSelected:m}),r===ne.ASSIGNEES?rt.createElement(an,{isSelected:m,id:l}):r===ne.TAGS?rt.createElement(Bo,{isSelected:m,id:l}):null)})))}});import{Box as $o,Text as Yr}from"ink";import st,{useEffect as vm,useMemo as Oa}from"react";var ym,Ua,Xr,Ba,xm,Jr,_a=y(()=>{"use strict";ie();C();zt();L();Ce();Wt();rn();Oo();Vt();ym="\u2029",Ua=(e,t)=>`${e}::inline-line::${t}`,Xr=new Map,Ba=e=>{let t=Xr.get(e)??[];Xr.delete(e);for(let n of t)I.deleteNode(n)},xm=(e,t)=>{Ba(e);let n=[];t.forEach((o,r)=>{let s=Fe(BigInt(r+1));if(!ht(s))return;let d=I.createNode(fe.text({id:Ua(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));ht(d)&&n.push(d.value.id)}),Xr.set(e,n)},Jr=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=_e(),u=Oa(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Oa(()=>u.join("\0"),[u]);vm(()=>(xm(e,u),()=>{Ba(e)}),[e,m]);let g=b=>String(b).replace(/\r?\n/g,""),x=u.map((b,T)=>{let R=l.id===e&&d===T;return st.createElement($o,{key:Ua(e,T)},st.createElement(Yr,{color:R?S.primary:S.secondary2,dimColor:!R},`${T+1} `.padStart(5,"\xA0")),st.createElement(Yr,{backgroundColor:R?"gray":void 0},g(b.length?co(b,s-10):ym)))});return st.createElement($o,{flexDirection:"column",paddingTop:1},st.createElement($o,null,st.createElement(Ae,{isSelected:r}),st.createElement(Yr,{color:r?S.accent:S.secondary2},t)),st.createElement($o,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1},st.createElement(sn,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},x)))}});var ja,$a,Qr=y(()=>{"use strict";zt();ja=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},$a=(e,t,n)=>fe.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 ft,Text as it}from"ink";import ae,{useEffect as hm,useMemo as Im,useRef as Nm}from"react";import{decodeTime as Zr}from"ulid";function Ha({ticket:e,width:t,height:n}){let o=Im(()=>bm(e),[e]),r=Nm([]);hm(()=>(Wa(r.current),r.current=Cm(e,o),()=>{Wa(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=_e(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?ae.createElement(ft,{flexDirection:"column",width:t,height:n,padding:1},ae.createElement(it,{color:S.primary},"No comments yet."),ae.createElement(ft,{paddingTop:1},ae.createElement(it,{color:S.primary},"Use"),ae.createElement(it,{color:S.accent}," :comment "),ae.createElement(it,{color:S.primary},"to add the first one."))):ae.createElement(ft,{flexDirection:"column",width:t,height:n},ae.createElement(ft,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},ae.createElement(it,{color:S.secondary2},"Comments (",o.length,") ")),ae.createElement(sn,{height:l,itemHeight:4,selectedIndex:s},o.map((m,g)=>{let x=g===s;return ae.createElement(ft,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},ae.createElement(ft,{flexDirection:"row",paddingBottom:1},ae.createElement(it,{color:S.accent},x?"\u276F ":" "),ae.createElement(ft,{paddingLeft:1},ae.createElement(it,{color:S.secondary2},`#${g+1} `),ae.createElement(an,{id:m.authorId}),ae.createElement(it,{color:S.secondary2}," "+go(Zr(m.id))))),ae.createElement(ft,{paddingLeft:3,paddingBottom:1},ae.createElement(it,{color:S.primary},Sm(m.md,u))))})))}var Em,bm,Wa,Cm,Sm,Va=y(()=>{"use strict";Oe();Sn();te();C();ie();L();Ce();Rn();Uo();Oo();Qr();Em=e=>Re(e,"comments"),bm=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Zr(t.id)-Zr(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Wa=e=>{for(let t of e)I.deleteNode(t.id)},Cm=(e,t)=>{let n=I.getNode(Em(e.id));if(!n||!Ve(n))return[];let o=t.map((r,s)=>$a(r,s,n.id)).map(I.createNode).filter(ht).map(({value:r})=>r).filter(bn);return t.length>0&&p().selectedIndex<0&&k.navigate({contextNode:n,selectedIndex:0}),o},Sm=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}});import{Box as Bn,Text as qa}from"ink";import we,{useMemo as Wo}from"react";var Rm,Am,Tm,za,Ga=y(()=>{"use strict";te();ie();L();Ce();Rn();rn();Fa();_a();Va();Qr();Rm=e=>Re(e,"description"),Am=e=>Re(e,"comments"),Tm=e=>Re(e,"history"),za=({ticket:e,height:t})=>{let n=Wo(()=>ja(e),[e]),{selectedIndex:o,contextNode:r}=_e(),s=process.stdout.columns||120,d=Wo(()=>Rm(e.id),[e.id]),l=Wo(()=>Am(e.id),[e.id]),u=Wo(()=>Tm(e.id),[e.id]),m=r.id===e.id,g=r.id===l||r.parentNodeId===l,x=r.id===u||r.parentNodeId===u,b=z(e.id);if(g){let V=t-3;return we.createElement(Bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(Ha,{ticket:e,width:s,height:V}))}if(x){let W=I.getNode(u),V=W&&Ve(W)?W.props.value??"":"",Hn=t-3;return we.createElement(Bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},W?we.createElement(Jr,{id:W.id,label:"Event log",text:V,selected:!1,maxWidth:s,height:Hn}):null)}let T=b.reduce((W,V)=>Nn(V)||V.id===l||V.id===u?W+1:W,0),R=2,F=3,j=T,O=t-F-j-R,Y=(W,V)=>W.id===d?we.createElement(Jr,{key:W.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,height:O}):Nn(W)?we.createElement(Da,{key:W.id,parent:W,selected:V,selectedIndex:o}):W.id===l?we.createElement(Bn,{key:W.id,paddingTop:1},we.createElement(Ae,{isSelected:V}),we.createElement(qa,{backgroundColor:S.secondary,color:V?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):W.id===u?we.createElement(Bn,{key:W.id,paddingTop:1},we.createElement(Ae,{isSelected:V}),we.createElement(qa,{backgroundColor:S.secondary,color:V?S.accent:S.primary}," History \u203A\u203A ")):null;return we.createElement(Bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},b.map((W,V)=>Y(W,m&&o===V)))}});import{Box as wm}from"ink";import Ho from"react";var Mm,Ka,Ya=y(()=>{"use strict";te();ka();Ga();Mm=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===w.TICKET||u===w.FIELD_LIST||u===w.FIELD,g=u===w.BOARD||u===w.SWIMLANE,x=u===w.TICKET?t:o.find(j=>j.context===w.TICKET),b=Math.floor(l/3),T=Math.floor(l/Math.max(e.length,1)),R=Math.min(T,b),F=s==="dense";return Ho.createElement(wm,{flexDirection:"row",height:d},g&&e.map((j,O)=>{let Y=t.id===j.id,W=Y?n:-1,V=t.context===w.BOARD&&n===O;return Ho.createElement(Pa,{key:j.id,height:d,width:R,swimlane:j,isSelected:V,isDense:F,isFocused:Y,listSelectedIndex:W,mode:r})}),m&&x&&Ho.createElement(za,{height:d,ticket:x}))},Ka=Ho.memo(Mm)});import Xa from"node:fs";import Lm from"node:path";import Pm from"react";import{render as km}from"ink";import{Writable as Dm}from"node:stream";var _n,Fm,Om,Um,Bm,Ja,Qa=y(()=>{"use strict";Ya();te();C();L();le();Ee();_n=e=>String(e).padStart(2,"0"),Fm=e=>{let t=e.getUTCFullYear(),n=_n(e.getUTCMonth()+1),o=_n(e.getUTCDate()),r=_n(e.getUTCHours()),s=_n(e.getUTCMinutes()),d=_n(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},Om=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Um=async(e,{width:t,height:n})=>{let o="",r=new Dm({write(d,l,u){let m=Bm(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=km(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},Bm=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Ja=async()=>{let{viewMode:e}=Q(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=p(),d=o.find(O=>O.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await Um(Pm.createElement(Ka,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(O=>O!==void 0&&En(O)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:l,height:u});if(!m)return i("Failed to render board export");let g=Gn(process.cwd());if(a(g))return i("Unable to export, epiq root not found");let x=new Date,b=Fm(x),T=`board_${Om(d.title)}_${b}.md`,R=Rs(g.value);Xa.mkdirSync(R,{recursive:!0});let F=Lm.join(R,T),j=`# Board - ${d.title}
|
|
44
|
+
`)}`):(Du(),b({hasProjectDefinition:!0}),c("State booted successfully",null))}var kn,bo=y(()=>{"use strict";Oe();Z();E();zt();M();Vt();Yt();Kt();kn=Lu()});var q,Lr=y(()=>{"use strict";E();q=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Xe,No,Fu,zi,Pr=y(()=>{"use strict";Vi();bo();wn();je();Z();E();M();Eo();Lr();Dr();Xe=null,No=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Xe,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Xe)return logger.debug("[sync] syncAndReloadState joining existing promise"),Xe;logger.debug("[sync] syncAndReloadState creating promise"),Xe=Fu();try{let e=await Xe;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),b({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}),Xe||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Xe=null}},Fu=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=zi();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Xe)return Xe;logger.debug("[sync] syncAndReloadState:start");let t=q("resolveActorId",X());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");b({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Mt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=q("syncEpiqWithRemote",await Co({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),b({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Be(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=q("loadMergedEvents",wt(r));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(s),message:(a(s),s.message),count:a(s)?void 0:s.value.length}),a(s))return b({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=zi();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=$i(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,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=q("bootStateFromEventLog",Ln(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return b({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`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"),b({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=q("restoreNavigationAnchor",Hi(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(m),message:a(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(m)?(b({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(b({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},zi=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),b({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var Jt,Gi,Ki,Fr,Or,Pn,Ur,Ou,Yi,Uu,Xi,So=y(()=>{"use strict";E();Ne();M();Pr();Jt=3e3,Gi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Jt?null:t},Ki=0,Or=!1,Pn=!1,Ur=()=>{if(Or)return!0;let e=Ue();return a(e)?!1:e.value.syncStatus.status==="syncing"},Ou=()=>{let e=ee().autoSyncIntervalMs??1e4,t=Date.now()-Ki;return Math.max(0,e-t)},Yi=()=>{Fr||(Fr=setTimeout(async()=>{if(Fr=void 0,!!Qt()){if(Ur()){Pn=!0;return}Pn=!1,await Uu()}},Ou()))},Uu=async()=>{if(g().readOnly||g().timeMode==="peek")return i("Cannot auto-sync while peeking");if(!Qt())return i("Cannot auto-sync before state is initialized");if(Ur())return Pn=!0,i("Sync already in progress");Or=!0,Ki=Date.now(),b({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await No()}finally{Or=!1,Pn&&Yi()}},Xi=()=>{Qt()&&(Pn=!0,!Ur()&&Yi())}});var Ro,Ji,Qi,Zi,Dn=y(()=>{"use strict";E();bt();Ne();le();Ro=()=>{let e=ee(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},Ji=()=>{let e=lt(process.cwd());if(a(e))return!1;let t=mt(e.value);return ht(t)},Qi=e=>e===!0?"on":e===!1?"off":null,Zi=e=>e==="on"?!0:e==="off"?!1:null});var Bu,_u,Fn,On,Ao,To,wo=y(()=>{"use strict";Q();E();ie();M();Bu=e=>e.props.tags??[],_u=e=>e.props.assignees??[],Fn=e=>Bu(e).map(t=>I.getTag(t)).filter(t=>!!t),On=e=>_u(e).map(t=>I.getContributor(t)).filter(t=>!!t),Ao=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!A(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Fn(n))},To=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!A(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",On(n))}});var v,Pt=y(()=>{"use strict";v={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var ju,$u,Wu,Hu,Vu,Mo,ea,qu,ta,ko=y(()=>{"use strict";ju=/^(\d+)(h|d|w|mo|y)$/,$u=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Wu=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},Hu=(e,t=new Date)=>{let n=e.match(ju);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(r){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},Vu=e=>{let t=e.match($u);if(!t)return null;let[,n,o,r,s,d]=t,l=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,x=d?Number(d):0;return Wu({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},Mo=e=>{let t=e.trim().toLowerCase();return Hu(t)??Vu(t)},ea=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,qu=[{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}],ta=(e=qu)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var zu,re,$e,Gu,Ku,_r,Dt,Lo,Br,na,Yu,Xu,Ju,oa,Qu,me,Zt=y(()=>{"use strict";So();Dn();Kt();Q();ie();M();mo();wo();Pt();ko();zu=["BOARD","TICKET","SWIMLANE","COMMENT"],re={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},$e={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Gu=[re.EDITOR,re.VIEW,re.USERNAME,re.AUTOSYNC,re.SYNC_DEBOUNCE_MS,re.LOG_LEVEL],Ku=(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[]}},_r=[String(Jt),"5000","15000","30000","60000"],Dt=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG],Lo=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Br=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],na=[v.FILTER,v.PEEK],Yu={WORKSPACE:[...Dt,...Lo],BOARD:[...na,...Dt,...Lo],SWIMLANE:[...na,...Dt,...Lo],TICKET:[...Dt,...Lo,...Br],FIELD:[...Dt,...Br],FIELD_LIST:[...Dt,...Br],TEXT:[...Dt],COMMENT:[v.EDIT,v.DELETE]},Xu=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ju=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&A(n)),oa=e=>e.parentNodeId===ae,Qu=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=Ro();if(!o)return[v.HELP,v.CONFIG];if(!Ji())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.EXPORT,v.CONFIG];let r=e?.context,s=r&&zu.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Yu[u]:[]))],l=Ju({breadCrumb:n,selectedNode:e});return d.filter(u=>u===v.MOVE?!1:u===v.EDIT||u===v.DELETE?s:u===v.UNTAG?!!(l&&Fn(l).length>0):u===v.UNASSIGN?!!(l&&On(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&oa(l)):u===v.CLOSE_ISSUE?!!(l&&!oa(l)):!0)},me=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:Qu({breadCrumb:r,readOnly:o,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...ta(),"now","prev","next"],[v.EDIT]:Ku(n?.context),[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","clear"],[v.TAG]:[...new Set([...Object.keys(Gt),...I.getExistingTags()])],[v.UNTAG]:[...Ao()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...To()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:I.getExistingAssignees(),[v.NEW]:Xu(s),[v.CONFIG]:[...Gu],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var ra,sa=y(()=>{"use strict";ra=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var We,en=y(()=>{"use strict";E();We=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});import ia from"chalk";var J,Ie,ye,aa=y(()=>{"use strict";pt();Ce();J=e=>ia.dim(e),Ie=e=>ia.hex(S.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,C)=>po(x)-po(C)).slice(0,o).map(x=>go(x)).join(" ");return p?`${J(e)}${p}${J(n)}`:""}});var gt,Po=y(()=>{"use strict";gt={None:"none",Invalid:"invalid",Valid:"valid"}});import ca from"chalk";var tn,Zu,da,te,H,_,Fo,Do,jr,em,Ft,tm,nm,om,la,$r=y(()=>{"use strict";So();Dn();sa();Sn();en();E();ie();Ne();M();pt();wo();Rn();aa();Pt();Po();Zt();ko();tn=140,Zu=["BOARD","TICKET","SWIMLANE"],da=()=>{let e=g().selectedNode;if(!e?.context)return _({message:J("Missing target context")});if(Zu.includes(e.context))return H();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Re(t?.parentNodeId??"","comments"))return H()}return _({message:J("Command not available in this context")})},te="<ENTER> to confirm",H=(e="",t=[])=>({message:J(e),validity:gt.Valid,completionWordList:t}),_=({message:e,completionWordList:t=[]})=>({validity:gt.Invalid,message:e,completionWordList:t}),Fo=e=>e.length===0,Do=e=>` ${ca.hex("#000").bgHex(Se(e))(` ${e} `)} `,jr=({modifier:e})=>{let t="confirm";return e===t?H(te):_({message:Fo(e)?J("if you are certain, enter ")+go(t):"",completionWordList:[t]})},em=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?_({message:J(n)}):H():_({message:Fo(o)?t:"",completionWordList:[...e]}),Ft=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Fo(n)&&Fo(o)?_({message:e,completionWordList:[]}):H(t??te),tm=({modifier:e,inputString:t})=>{let n=me(v.CONFIG);if(!n.includes(e))return _({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case re.EDITOR:{let o=[...ra];return t.trim()?o.includes(t.trim())?H(te):_({message:ye({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):_({message:ye({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case re.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?H(te):_({message:ye({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case re.USERNAME:return t.trim()?H(te):_({message:Ie("Enter a user name. Saved in ")+ca.bgBlack("~/.epiq-global/config.json")});case re.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?H(te):_({message:ye({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case re.AUTOSYNC:{let o=["on","off"],r=ee().autoSync;if(!o.includes(t.trim())){let s=Qi(r);return _({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return H(te)}case re.SYNC_DEBOUNCE_MS:{let o=ee().autoSyncIntervalMs,r=Gi(t);if(!t.trim()||r===null||r<Jt){let s=ye({prefix:" examples: ",wordList:_r,minLengthForHints:0,inputString:t});return _({message:Ie(`provide duration above ${Jt}ms. current duration: ${o}ms.`)+s,completionWordList:_r})}return H(te)}default:return _({message:Ie("Unknown config option"),completionWordList:n})}},nm=({modifier:e,inputString:t})=>{let n=me(v.EDIT);if(!n.length)return _({message:Ie("Command not available in this context")});if(!n.includes(e)){let o=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return _({message:o||Ie("Unknown edit option"),completionWordList:n})}switch(e){case $e.COMMENT:return t.trim()?H(te):_({message:J("write a comment...")});case $e.TITLE:return H(te);case $e.DESCRIPTION:{let{preferredEditor:o}=ee();return o?H(J("<ENTER> to edit in ")+o):_({message:"No editor selected"})}default:return _({message:Ie("Unknown edit option"),completionWordList:n})}},om={[v.EXPORT]:()=>H(te+J(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(te);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return H(te);let o=t||e.inputString,r=Mo(o);if(!o||!r)return _(n);let s=We(g().breadCrumb,"BOARD");if(a(s))return _({message:Ie("Command is not applicable in this context")});let d=xi(s.value.id);return a(d)?_({message:Ie("Unable to peek: board id is not a valid ULID")}):ea({date:r,horizonDate:d.value})?H(te):_({message:Ie(`nothing to peek before ${d.value.toISOString().slice(0,16).replace("T"," ")}`)})},[v.EXIT]:()=>H(te+J(" and exit the application")),[v.INIT]:()=>H(te),[v.PALETTE]:()=>H(te),[v.FILTER]:e=>{if(e.modifier==="clear")return H(te);let t=s=>me(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return _({message:ye({wordList:me(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:me(v.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?_({message:ye({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):H():_({message:ye({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[v.NONE]:e=>{let t=me(v.NONE);return _({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>em({list:me(v.NEW),hint:ye({wordList:me(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>H(te),[v.EDIT]:nm,[v.COMMENT]:e=>{let t=Ft({hint:J(`write a comment (max ${tn} char)...`),onOk:J(`(${e.inputString.length}/${tn})`)})(e);return t.validity===gt.Invalid?t:e.inputString.length>tn?H(Ie("max input exceeded")):t},[v.CONFIG]:tm,[v.DELETE]:e=>{let t=da();return t.validity==="invalid"?t:jr(e)},[v.CLOSE_ISSUE]:e=>jr(e),[v.RE_OPEN_ISSUE]:e=>jr(e),[v.MOVE]:e=>{let t=da();return t.validity==="invalid"?t:Ft({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:me(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Do).join("");return Ft({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[v.UNTAG]:e=>{let t=Ao();if(a(t))return _({message:Ie("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Do).slice(0,10);return n.length?Ft({hint:J(" ... ")+n.join("")})(e):_({message:Ie("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Do).slice(0,10);return Ft({hint:J("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=To();if(a(t))return _({message:Ie("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Do).slice(0,10);return n.length?Ft({hint:J("remove assignee... ")+n.join("")})(e):_({message:Ie("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>H(te),[v.COFFEE]:e=>{let{modifier:t}=e,n=me(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?_({message:J("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):Ft({hint:ye({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},la=Object.fromEntries(Object.entries(om).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var Oo,ua=y(()=>{"use strict";Oo=["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 rm,sm,im,am,dm,ma,pa,ga,fa=y(()=>{"use strict";E();M();ua();rm=3,sm=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"]),im=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.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},am=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=rm&&!sm.has(t)&&!/^\d+$/.test(t)),dm=e=>{let t=new Map;for(let s of im(e))for(let d of am(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),o=new Set(n),r=Oo.filter(s=>!o.has(s));return[...n,...r]},ma=Oo,pa=-1,ga=()=>{let e=Ue();if(a(e))return Oo;let t=e.value,n=t.eventLog.length;return n!==pa&&(ma=dm(t),pa=n),ma}});var va,ya,Wr=y(()=>{"use strict";li();Zt();Pt();$r();fa();M();Z();va=e=>Object.values(v).includes(e),ya=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=la[n].validate(n,o,s),m=r==="command"||r==="modifier"?me(n):ga(),{mode:p}=g(),x=p===f.COMMAND_LINE?d??"":"",C=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?ci(e,C):{hint:"",hints:[],remainder:"",overlap:0}}}});var xa,cm,lm,um,ha=y(()=>{"use strict";Wr();Zt();xa=e=>{let t=e.trimStart(),n=lm(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=um(e),l=va(o)?o:null,u=l!==null,m=o!=="",p=l?me(l)??[]:[],x=l&&p.includes(r)?r:"",C="word";n.length===0||n.length===1&&!s?C="command":(n.length===1&&s||n.length===2&&!s)&&(C="modifier");let T=s?"":d,P=cm(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:x,target:C,inputToMatch:T,inputString:P}},cm=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},lm=e=>e.trim()?e.trim().split(/\s+/):[],um=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as Oh}from"react";var nn,Hr,on,mm,Ia,Je,Un,Vr,qr,ba,Na,Uo,Ea,$,Ca,Sa,Ra,se,Aa,pe=y(()=>{"use strict";Wr();ha();E();Po();nn=e=>e===Hr||e===":",Hr=" ",on={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:gt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},mm=new Set,Ia=()=>{for(let e of mm)e()},Je=e=>{let n=e(on),o=xa(n.value),r=n.cursorPosition===n.value.length;on={...n,commandMeta:ya(o,r)},Ia()},Un=({message:e,status:t})=>{let n=structuredClone(on);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,on=n,Ia(),c(e,null)},Vr=e=>{Je(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qr=e=>{Je(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&nn(n[r-1]);)r--;for(;r>0&&!nn(n[r-1]);)r--}else{for(;r<n.length&&!nn(n[r]);)r++;for(;r<n.length&&nn(n[r]);)r++}return{...t,cursorPosition:r}})},ba=()=>{Je(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}})},Na=()=>{Je(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&nn(t[o-1]);)o--;for(;o>0&&!nn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Uo=e=>{Je(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),d=s+r,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Ea=()=>{Je(e=>({...e,commandIsPending:!0}))},$=e=>{Je(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ca=({addToHistory:e=!0})=>{Je(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Sa=()=>{Je(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}})},Ra=()=>{Je(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},se=()=>on,Aa=()=>{let[e,...t]=on.value.split(Hr);return t.join(Hr).trim()}});var R,Et=y(()=>{"use strict";Z();ni();M();pe();Ne();R={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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Ta,k,zr=y(()=>{"use strict";M();Pt();Ta=e=>{let{context:t}=g().contextNode;if(!t)return k.None;switch(e){case v.EXIT:return k.Exit;case v.EXPORT:return k.Export;case v.COFFEE:return k.Coffee;case v.INIT:return k.Init;case v.DELETE:return k.Delete;case v.EDIT:return k.Edit;case v.COMMENT:return k.Comment;case v.HELP:return k.ViewHelp;case v.RE_OPEN_ISSUE:return k.ReopenIssue;case v.CLOSE_ISSUE:return k.CloseIssue;case v.TAG:return k.TagTicket;case v.UNTAG:return k.UntagTicket;case v.ASSIGN:return k.AssignUserToTicket;case v.UNASSIGN:return k.UnassignUserFromTicket;case v.NEW:return k.NewItem;case v.FILTER:return k.Filter;case v.MOVE:return k.Move;case v.PEEK:return k.Peek;case v.CONFIG:return k.Config;case v.SYNC:return k.Sync;default:return k.None}},k={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",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{Text as wa}from"ink";import Ma,{useEffect as ka,useState as pm}from"react";var La,Ae,rn=y(()=>{"use strict";M();Ce();La={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ae=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=_e(),o=La[n]??La.default,[r,s]=pm(0);if(ka(()=>{s(0)},[o]),ka(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return Ma.createElement(wa,null,t);let d=o[r]??o[0]??t;return Ma.createElement(wa,{color:S.accent,dimColor:r===1},d)}});import{Box as Gr,Text as gm}from"ink";import Bo from"react";var sn,_o=y(()=>{"use strict";Ce();sn=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,scrollByOne:r=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(o)),l=Math.max(1,Math.floor(s/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=r?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),x=p+l,C=e.slice(p,x),T=e.length>l,P=s,D=T?Math.max(1,Math.floor(l/e.length*P)):P,O=Math.max(0,P-D),B=Math.max(1,e.length-l),K=T?Math.floor(p/B*O):0;return Bo.createElement(Gr,{flexDirection:"row",height:s,width:"100%"},Bo.createElement(Gr,{flexDirection:"column",flexGrow:1,height:s},C),Bo.createElement(Gr,{flexDirection:"column",width:1,height:P},Array.from({length:P}).map((W,V)=>Bo.createElement(gm,{key:V,color:T&&V>=K&&V<K+D?S.accent:S.secondary},T?"\u2502":" "))))}});import{Text as fm}from"ink";import vm from"react";var ym,xm,an,jo=y(()=>{"use strict";mo();pt();ie();ym=e=>e.toLowerCase().trim(),xm=(e,t=Gt)=>{let n=ym(e);return t[n]?t[n]:Cn(n)},an=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return vm.createElement(fm,{underline:t,color:xm(n.name)},"@"+n.name)}});import{Text as hm}from"ink";import Im from"react";var $o,Kr=y(()=>{"use strict";ie();Ce();pt();$o=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return Im.createElement(hm,{underline:t,backgroundColor:Se(n.name),color:S.secondary}," "+n.name+" ")}});import{Box as Wo,Text as bm}from"ink";import Ot from"react";var Pa,Da=y(()=>{"use strict";Ce();Wt();wo();jo();Kr();Pa=({width:e,ticket:t,isSelected:n})=>{let o=e-14,r=lo(Ct(t.title),o),s=Fn(t),d=On(t);return Ot.createElement(Wo,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?S.accent:S.secondary,justifyContent:"space-between"},Ot.createElement(Wo,{borderBottom:!0},Ot.createElement(Wo,{paddingLeft:1,flexDirection:"column"},Ot.createElement(bm,{color:S.primary},r))),Ot.createElement(Wo,{flexDirection:"row",paddingLeft:1},s.map(l=>Ot.createElement($o,{key:l.id,id:l.id})),d.map(l=>Ot.createElement(an,{key:l.id,id:l.id}))))}});import{Box as Ut,Text as Bn}from"ink";import Te from"react";var Nm,Fa,Oa=y(()=>{"use strict";Z();ie();Ce();pt();rn();Nm=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Fa=({width:e,ticket:t,isSelected:n,index:o,mode:r})=>{let s=(t.props.tags??[]).map(B=>I.getTag(B)).filter(B=>!!B),d=(t.props.assignees??[]).map(B=>I.getContributor(B)).filter(B=>!!B),l=1,u=s.length*(1+l),m=d.length*(2+l),p=s.map(B=>Te.createElement(Ut,{key:B.id,paddingRight:l},Te.createElement(Bn,{color:Se(B.name)},"\u25A0"))),x=d.map(B=>Te.createElement(Ut,{key:B.id,paddingRight:l},Te.createElement(Bn,{color:Cn(B.name)},"@"+B.name.at(0)))),C=n?S.accent:r===f.MOVE?S.secondary:S.primary,T=4,P=I.getCommentsByIssue(t.id),D=P.length?String(P.length).length+2+l:0,O=P.length?Te.createElement(Ut,{paddingRight:l},Te.createElement(Bn,{color:S.accent},"[",P.length,"]")):null;return Te.createElement(Ut,{borderBottom:!0,justifyContent:"space-between"},Te.createElement(Ut,null,Te.createElement(Ut,{width:T},n?Te.createElement(Ae,{isSelected:n}):Te.createElement(Bn,{color:"gray",dimColor:!0},o+1)),Te.createElement(Bn,{wrap:"truncate",color:C},Nm(t.title,e-u-m-D-18))),Te.createElement(Ut,null,p,x,O))}});import Em from"chalk";import{Box as Yr,Text as Cm}from"ink";import Qe from"react";var Sm,Ua,Ba=y(()=>{"use strict";Q();M();Ce();rn();_o();Da();Oa();Sm=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=_e(),m=u[e.id]??[],p=`${e.title} ${Em.hex(S.secondary2).dim("("+m.length+")")}`,x=3,C=r?1:4,T=o-x-(r?2:1),P=Qe.createElement(Yr,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Qe.createElement(Ae,{isSelected:t}),Qe.createElement(Cm,{bold:!0,color:t?S.accent:S.primary},p," ",e.readonly?"\u{1F512}":"")),D=(O,B)=>{let K=s&&d===B;return A(O)?r?Qe.createElement(Fa,{key:O.id,index:B,width:n,ticket:O,isSelected:K,mode:l}):Qe.createElement(Pa,{key:O.id,width:n,ticket:O,isSelected:K}):null};return Qe.createElement(Yr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:1,paddingLeft:1,height:o},P,Qe.createElement(Yr,{padding:r?1:0},m.length>0&&Qe.createElement(sn,{selectedIndex:d,height:T,itemHeight:C},m.map(D)),Qe.createElement(Ae,{isSelected:s&&d===-1})))},Ua=Qe.memo(Sm)});import{Box as Ho,Text as Rm}from"ink";import rt from"react";var _a,ja=y(()=>{"use strict";Q();ie();qt();M();Ce();jo();rn();Kr();_a=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=_e(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&A(s)?r===oe.ASSIGNEES?s.props.assignees??[]:r===oe.TAGS?s.props.tags??[]:[]:[];return rt.createElement(Ho,{alignItems:"center",paddingTop:1},rt.createElement(Ho,{minWidth:12},rt.createElement(Ae,{isSelected:n}),rt.createElement(Rm,{color:n?S.accent:S.secondary2},r,":")),rt.createElement(Ho,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return rt.createElement(Ho,{key:`${r}-${l}`,paddingRight:2,minHeight:1},rt.createElement(Ae,{isSelected:m}),r===oe.ASSIGNEES?rt.createElement(an,{isSelected:m,id:l}):r===oe.TAGS?rt.createElement($o,{isSelected:m,id:l}):null)})))}});import{Box as Vo,Text as Xr}from"ink";import st,{useEffect as Am,useMemo as $a}from"react";var Tm,Wa,Jr,Ha,wm,Qr,Va=y(()=>{"use strict";ie();E();zt();M();Ce();Wt();rn();_o();Vt();Tm="\u2029",Wa=(e,t)=>`${e}::inline-line::${t}`,Jr=new Map,Ha=e=>{let t=Jr.get(e)??[];Jr.delete(e);for(let n of t)I.deleteNode(n)},wm=(e,t)=>{Ha(e);let n=[];t.forEach((o,r)=>{let s=Fe(BigInt(r+1));if(!ht(s))return;let d=I.createNode(fe.text({id:Wa(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));ht(d)&&n.push(d.value.id)}),Jr.set(e,n)},Qr=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=_e(),u=$a(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=$a(()=>u.join("\0"),[u]);Am(()=>(wm(e,u),()=>{Ha(e)}),[e,m]);let p=C=>String(C).replace(/\r?\n/g,""),x=u.map((C,T)=>{let P=l.id===e&&d===T;return st.createElement(Vo,{key:Wa(e,T)},st.createElement(Xr,{color:P?S.primary:S.secondary2,dimColor:!P},`${T+1} `.padStart(5,"\xA0")),st.createElement(Xr,{backgroundColor:P?"gray":void 0},p(C.length?lo(C,s-10):Tm)))});return st.createElement(Vo,{flexDirection:"column",paddingTop:1},st.createElement(Vo,null,st.createElement(Ae,{isSelected:r}),st.createElement(Xr,{color:r?S.accent:S.secondary2},t)),st.createElement(Vo,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1},st.createElement(sn,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},x)))}});var qa,za,Zr=y(()=>{"use strict";zt();qa=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},za=(e,t,n)=>fe.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 ft,Text as it}from"ink";import de,{useEffect as Mm,useMemo as km,useRef as Lm}from"react";import{decodeTime as es}from"ulid";function Ka({ticket:e,width:t,height:n}){let o=km(()=>Dm(e),[e]),r=Lm([]);Mm(()=>(Ga(r.current),r.current=Fm(e,o),()=>{Ga(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=_e(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?de.createElement(ft,{flexDirection:"column",width:t,height:n,padding:1},de.createElement(it,{color:S.primary},"No comments yet."),de.createElement(ft,{paddingTop:1},de.createElement(it,{color:S.primary},"Use"),de.createElement(it,{color:S.accent}," :comment "),de.createElement(it,{color:S.primary},"to add the first one."))):de.createElement(ft,{flexDirection:"column",width:t,height:n},de.createElement(ft,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},de.createElement(it,{color:S.secondary2},"Comments (",o.length,") ")),de.createElement(sn,{height:l,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let x=p===s;return de.createElement(ft,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},de.createElement(ft,{flexDirection:"row",paddingBottom:1},de.createElement(it,{color:S.accent},x?"\u276F ":" "),de.createElement(ft,{paddingLeft:1},de.createElement(it,{color:S.secondary2},`#${p+1} `),de.createElement(an,{id:m.authorId}),de.createElement(it,{color:S.secondary2}," "+fo(es(m.id))))),de.createElement(ft,{paddingLeft:3,paddingBottom:1},de.createElement(it,{color:S.primary},Om(m.md,u))))})))}var Pm,Dm,Ga,Fm,Om,Ya=y(()=>{"use strict";Oe();Sn();Q();E();ie();M();Ce();Rn();jo();_o();Zr();Pm=e=>Re(e,"comments"),Dm=e=>I.getCommentsByIssue(e.id).sort((t,n)=>es(t.id)-es(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Ga=e=>{for(let t of e)I.deleteNode(t.id)},Fm=(e,t)=>{let n=I.getNode(Pm(e.id));if(!n||!ze(n))return[];let o=t.map((r,s)=>za(r,s,n.id)).map(I.createNode).filter(ht).map(({value:r})=>r).filter(En);return t.length>0&&g().selectedIndex<0&&L.navigate({contextNode:n,selectedIndex:0}),o},Om=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}});import{Box as _n,Text as Xa}from"ink";import we,{useMemo as qo}from"react";var Um,Bm,_m,Ja,Qa=y(()=>{"use strict";Q();ie();M();Ce();Rn();rn();ja();Va();Ya();Zr();Um=e=>Re(e,"description"),Bm=e=>Re(e,"comments"),_m=e=>Re(e,"history"),Ja=({ticket:e,height:t})=>{let n=qo(()=>qa(e),[e]),{selectedIndex:o,contextNode:r}=_e(),s=process.stdout.columns||120,d=qo(()=>Um(e.id),[e.id]),l=qo(()=>Bm(e.id),[e.id]),u=qo(()=>_m(e.id),[e.id]),m=r.id===e.id,p=r.id===l||r.parentNodeId===l,x=r.id===u||r.parentNodeId===u,C=z(e.id);if(p){let V=t-3;return we.createElement(_n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(Ka,{ticket:e,width:s,height:V}))}if(x){let W=I.getNode(u),V=W&&ze(W)?W.props.value??"":"",Vn=t-3;return we.createElement(_n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},W?we.createElement(Qr,{id:W.id,label:"Event log",text:V,selected:!1,maxWidth:s,height:Vn}):null)}let T=C.reduce((W,V)=>bn(V)||V.id===l||V.id===u?W+1:W,0),P=2,D=3,O=T,B=t-D-O-P,K=(W,V)=>W.id===d?we.createElement(Qr,{key:W.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,height:B}):bn(W)?we.createElement(_a,{key:W.id,parent:W,selected:V,selectedIndex:o}):W.id===l?we.createElement(_n,{key:W.id,paddingTop:1},we.createElement(Ae,{isSelected:V}),we.createElement(Xa,{backgroundColor:S.secondary,color:V?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):W.id===u?we.createElement(_n,{key:W.id,paddingTop:1},we.createElement(Ae,{isSelected:V}),we.createElement(Xa,{backgroundColor:S.secondary,color:V?S.accent:S.primary}," History \u203A\u203A ")):null;return we.createElement(_n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C.map((W,V)=>K(W,m&&o===V)))}});import{Box as jm}from"ink";import zo from"react";var $m,Za,ed=y(()=>{"use strict";Q();Ba();Qa();$m=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===w.TICKET||u===w.FIELD_LIST||u===w.FIELD,p=u===w.BOARD||u===w.SWIMLANE,x=u===w.TICKET?t:o.find(O=>O.context===w.TICKET),C=Math.floor(l/3),T=Math.floor(l/Math.max(e.length,1)),P=Math.min(T,C),D=s==="dense";return zo.createElement(jm,{flexDirection:"row",height:d},p&&e.map((O,B)=>{let K=t.id===O.id,W=K?n:-1,V=t.context===w.BOARD&&n===B;return zo.createElement(Ua,{key:O.id,height:d,width:P,swimlane:O,isSelected:V,isDense:D,isFocused:K,listSelectedIndex:W,mode:r})}),m&&x&&zo.createElement(Ja,{height:d,ticket:x}))},Za=zo.memo($m)});import td from"node:fs";import Wm from"node:path";import Hm from"react";import{render as Vm}from"ink";import{Writable as qm}from"node:stream";var jn,zm,Gm,Km,Ym,nd,od=y(()=>{"use strict";ed();Q();E();M();le();Ne();jn=e=>String(e).padStart(2,"0"),zm=e=>{let t=e.getUTCFullYear(),n=jn(e.getUTCMonth()+1),o=jn(e.getUTCDate()),r=jn(e.getUTCHours()),s=jn(e.getUTCMinutes()),d=jn(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},Gm=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Km=async(e,{width:t,height:n})=>{let o="",r=new qm({write(d,l,u){let m=Ym(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=Vm(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},Ym=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),nd=async()=>{let{viewMode:e}=ee(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(B=>B.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await Km(Hm.createElement(Za,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(B=>B!==void 0&&Nn(B)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=Kn(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let x=new Date,C=zm(x),T=`board_${Gm(d.title)}_${C}.md`,P=As(p.value);td.mkdirSync(P,{recursive:!0});let D=Wm.join(P,T),O=`# Board - ${d.title}
|
|
45
45
|
Date: ${x.toISOString()}
|
|
46
46
|
|
|
47
47
|
\`\`\`text
|
|
48
48
|
${m}
|
|
49
49
|
\`\`\`
|
|
50
|
-
`;return
|
|
51
|
-
`),c("Config written",null)}catch{return i(`Unable to write ~/${
|
|
50
|
+
`;return td.writeFileSync(D,O,"utf8"),c("Exported board layout",D)}});import{accessSync as Xm,copyFileSync as Jm,existsSync as Go,mkdirSync as rd,readdirSync as sd,readFileSync as Qm,renameSync as Zm,rmSync as ep,statSync as id,unlinkSync as tp,writeFileSync as np}from"node:fs";import dn from"node:path";var ts,Me,ns=y(()=>{"use strict";ts=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Me={writeToFile:(e,t)=>{try{let n=dn.dirname(e);Go(n)||rd(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);np(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Qm(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Me.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 Go(e)&&id(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Xm(e),!0}catch{return!1}},mkDir:e=>rd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=dn.parse(t);for(;;){let o=dn.join(t,e);try{if(Go(o)&&id(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=dn.dirname(t)}return null},readFirstJSON(e){try{if(!Me.dirExists(e))return null;let t=sd(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=dn.join(e,t);return Me.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Me.dirExists(e)?sd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{tp(e)}catch(t){(!ts(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{ep(e,{recursive:!0,force:!0})}catch(t){(!ts(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(dn.dirname(t)),!n?.overwrite&&Go(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Zm(e,t)}catch(o){if(ts(o)&&o.code==="EXDEV"){Jm(e,t),this.rmFile(e);return}throw o}}}});import op from"node:os";import ad from"node:path";import{z as vt}from"zod";var rp,dd,sp,cd,os,rs,ip,ld,ud,at,md,cn=y(()=>{"use strict";le();E();ns();rp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},dd=vt.object({logLevel:vt.enum(["info","error","debug"]),preferredEditor:vt.string().optional(),userName:vt.string().optional(),userId:vt.string().optional(),autoSync:vt.boolean().nullable().optional(),autoSyncDebounceMs:vt.number().optional(),viewMode:vt.enum(["dense","wide"]).optional()}).partial(),sp="config.json",cd=()=>ad.join(op.homedir(),Pe),os=()=>ad.join(cd(),sp),rs=()=>{try{return Me.mkDir(cd()),c(`Ensured ~/${Pe} exists`,null)}catch{return i(`Unable to create ~/${Pe}`)}},ip=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Pe}/config.json JSON`)}let n=dd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Pe}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},ld=()=>{let e=rs();if(a(e))return i(e.message);let t=os(),n=Me.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):ip(n)},ud=e=>{let t=rs();if(a(t))return i(t.message);let n=dd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=os();try{return Me.writeToFile(o,JSON.stringify(n.data,null,2)+`
|
|
51
|
+
`),c("Config written",null)}catch{return i(`Unable to write ~/${Pe}/config.json`)}},at=e=>{let t=ld();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return ud(n)},md=()=>{let e=os(),t=rs();if(a(t))return i(`Unable to create ~/${Pe}`);if(!(Me.readFile(e)!==null)){let p=ud(rp);if(a(p))throw new Error(`Unable to create ~/${Pe}/config.json`)}let o=ld();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,logLevel:m}=o.value;return!s||!d?i(`User name or ID not configured in ~/${Pe}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:r??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))}});var Ko,ss=y(()=>{"use strict";Ko=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];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 PN}from"react";var is,ap,dp,ln,cp,yt,Yo=y(()=>{"use strict";E();ap=new Set,dp=()=>{for(let e of ap)e()},ln=()=>{if(!is)throw new Error("Ui state not initialized. Call initUiState() first.");return is},cp=e=>{let t=ln();return is=e(t),dp(),c("UX state updated",null)},yt=e=>cp(t=>({...t,...e}))});import{spawn as lp}from"node:child_process";function as(e){let t=process.platform,r=lp(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var pd=y(()=>{"use strict"});import{spawnSync as up}from"node:child_process";import mp from"node:os";import gd from"node:path";import{ulid as pp}from"ulid";function gp(){let{preferredEditor:e}=ee(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function fp(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function fd(e){let t=gd.join(mp.tmpdir(),"epiq");Me.mkDir(t);let n=gd.join(t,pp());Me.writeToFile(n,e??"");let o=gp();for(let r of o){let s=fp(r,n),d=up(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=Me.readFile(n);if(l==null)return i("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return i("Unable to open editor")}var vd=y(()=>{"use strict";E();Ne();ns()});import{ulid as ds}from"ulid";var yd,vp,yp,xd=y(()=>{"use strict";vd();kt();je();en();Q();E();qt();ie();M();le();Zt();yd=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=z(t.id)[n];if(o&&En(o))return vp(e);if(e.modifier===$e.DESCRIPTION)return yp();if(e.modifier===$e.TITLE){let r=X();if(a(r))return i("Unable to resolve user ID");let s=o;if(!s)return i("Missing node");if(s.readonly)return i("Cannot rename readonly node");let d=e.inputString.trim();if(!d)return i("Provide a title");let l=await He();return a(l)?l:U([{id:ds(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},vp=async e=>{let t=X();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=z(n.id)[o];if(!r||!En(r))return i("Select a comment first");if(r.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=g().nodes[s];if(!d||!A(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=r.id.split(":").at(0)??"",u=I.getComment(l);if(!u||u.deleted)return i("Unable to resolve comment");if(u.issue!==d.id)return i("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return i("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return i("Provide a comment");let p=await He();if(a(p))return p;let x=p.value;return U([{id:ds(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],x)},yp=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let t=await He();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=We([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!A(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=z(d.id).find(x=>x.title===oe.DESCRIPTION);if(!l)return i("No target found");if(l.readonly)return i("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return i("Selected field is not editable text");let m=fd(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):U([{id:ds(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import cs from"node:fs";import xp from"node:path";var hd,Id=y(()=>{"use strict";E();fn();hd=async e=>{let t=xp.join(e,".gitignore"),n=cs.existsSync(t)?cs.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
|
|
52
52
|
`).map(u=>u.trim()),s=o.filter(u=>!r.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
53
53
|
`);return n=n.trimEnd()+`
|
|
54
54
|
|
|
55
55
|
${l}
|
|
56
|
-
`,
|
|
57
|
-
`));let or=Ke();if(a(or))return G(16,or.message);let{rootNodeId:_c,nodes:jc}=or.value,Cs=jc[_c];return Cs?(k.navigate({contextNode:Cs,selectedIndex:0}),N({hasProjectDefinition:!0,mode:f.DEFAULT}),c(nr,null)):G(16,"Unable to resolve initialized root node")}});import{ulid as lp}from"ulid";function ls(e){let t=Id();if(a(t))return t;let{contextNode:n,nodes:o}=p();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=K(r.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=Nd({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Ed(u.value)}function us(e){let t=Id();if(a(t))return t;let{contextNode:n,selectedIndex:o}=p(),s=K(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Nd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Ed(d.value)}var hd,xt,jn,Id,cs,Nd,Ed,ms=y(()=>{"use strict";Kt();je();C();Ge();L();hd=null,xt=()=>structuredClone(hd),jn=e=>{hd=e},Id=()=>{let{contextNode:e,selectedIndex:t}=p(),o=K(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},cs=({id:e,parentId:t,position:n={at:"end"}})=>{let o=K(t).filter(r=>r.id!==e);return xo(o,n)},Nd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=X();if(a(o))return i("Unable to resolve user ID");let r=cs({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:lp(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Ed=e=>{jn(e);let t=Tn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as up}from"ulid";var bd,Go,Cd,Sd=y(()=>{"use strict";Oe();ms();Lt();je();J();C();Ge();de();L();le();bd=()=>{let e=xt();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=p().nodes[n];if(!o)return i("Move parent not found");let r=K(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(k.navigate({contextNode:o,selectedIndex:r}),c("Synchronized navigation to moved node",null))},Go=(e,t="Moved preview")=>{if(a(e))return e;let n=bd();return a(n)?n:(N({mode:f.MOVE}),c(t,null))},Cd=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=se().commandMeta,{contextNode:n,selectedIndex:o}=p(),r=K(n.id)[o];if(!r)return N({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(r.readonly)return i("Target node is read-only");if(o===-1)return i("No item selected");if(!r.parentNodeId)return i("Target has no parent");let s=K(r.parentNodeId),d=s.findIndex(({id:x})=>x===r.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},g=cs({parentId:r.parentNodeId,id:r.id,position:m});return a(g)?g:(jn({id:up(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:g.value.rank},...e.value}),N({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return Go(us(1));if(t==="previous")return Go(us(-1));if(t==="to-next")return Go(ls(1));if(t==="to-previous")return Go(ls(-1));if(t==="confirm"){let s=xt();if(!s)return i("No pending move to confirm");let d=await $e();if(a(d))return d;let l=U([s],d.value);if(a(l))return l;let u=bd();return a(u)?u:(jn(null),N({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(jn(null),N({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as mp,ulid as pp}from"ulid";var gp,Ko,ps=y(()=>{"use strict";C();gp=mp(),Ko=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=gp();return c("Created issue events",[{id:pp(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Yo}from"ulid";var Rd,Ad=y(()=>{"use strict";Oe();ps();Lt();je();Zt();C();ie();Ge();L();le();Rd=async(e,t)=>{let n=X();if(a(n))return i("Unable to resolve user ID");let o=await $e();if(a(o))return o;let r=o.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=p(),u=m=>{let g=U([m],r);if(a(g))return g;let x=I.getNode(g.value[0].result.id);if(!x)return i("Created node not found");if(!x.parentNodeId)return g;let b=I.getNode(x.parentNodeId);return b?(k.navigate({contextNode:b,selectedIndex:I.getSiblings(x.parentNodeId).findIndex(({id:T})=>T===x.id)}),g):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=p(),g=I.getNode(m);if(!g)return i("Workspace not found");let x=Yt(g.id,n.value,r);return a(x)?x:u({id:Yo(),action:"add.board",payload:{id:Yo(),name:t.inputString,parent:g.id,rank:x.value},...n.value})}if(t.modifier==="swimlane"){let m=Be(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let g=Yt(m.value.id,n.value,r);return a(g)?g:u({id:Yo(),action:"add.swimlane",payload:{id:Yo(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=z(d.id)[l],g=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let Y=Be(s,"SWIMLANE");return a(Y)?null:Y.value})();if(!g)return i("Unable to add issue in this context");let x=Yt(g.id,n.value,r);if(a(x))return x;let b=Ko({name:t.inputString,parent:g.id,rank:x.value,user:n.value});if(a(b))return b;let T=b.value,R=U([...T],r);if(a(R))return R;if(!R.value[0])return i("Issue creation failed");let O=T.find(Y=>Y.action==="add.issue")?.payload.id;return O?(k.navigate({contextNode:g,selectedIndex:I.getSiblings(g.id).findIndex(({id:Y})=>Y===O)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Td,wd=y(()=>{"use strict";It();Oe();Sn();Mn();Kt();J();Zt();C();de();L();Mo();Td=async()=>{let e=Be(p().breadCrumb,"BOARD");if(a(e))return e;let t=await ut(process.cwd());if(a(t))return i("Unable to locate repo root");let n=nt({repoRoot:t.value});if(a(n))throw new Error(n.message);let{modifier:o}=se().commandMeta;if(o==="now"){let R=wt(n.value);if(a(R))return i(R.message);let F=$n();if(a(F))return F;let O=Tt(R.value).filter(a);return O.length>0?i(O.map(Y=>Y.message).join(", ")):(N({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let r;if(o==="prev"){let R=p().eventLog.at(-1),F=Er(R);if(F===null)return i("No previous event to peek");r=F}else if(o==="next"){let R=p().unappliedEvents.at(0),F=Er(R);if(F===null)return i("No next event to peek");r=F+1}else{let R=wo(o);if(!R)return i("Invalid peek date");r=R.getTime()}let s=p(),d=e.value.id,l=Si(n.value,r);if(a(l))return i(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=$n();if(a(g))return g;let b=Tt(u).filter(a);if(b.length>0)return $n(),N(s),i(b.map(R=>R.message).join(", "));let T=p().nodes[d];return T?(k.navigate({contextNode:T,selectedIndex:0}),N({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):($n(),N(s),i("Board did not exist at peek date"))}});import fp from"zod";var Md,Ld=y(()=>{"use strict";cn();J();C();de();Ee();L();Md=()=>{let e=se().commandMeta.inputString,t=fp.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=at({autoSyncDebounceMs:t.data});return a(n)?n:(qe({autoSyncIntervalMs:t.data}),N({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var Pd,kd=y(()=>{"use strict";Fn();cn();J();C();de();Ee();L();Pd=()=>{let e=se().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Qi(e),n=at({autoSync:t});return a(n)?n:(qe({autoSync:t}),N({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var Dd,Fd=y(()=>{"use strict";cn();J();C();de();Ee();L();Dd=()=>{let e=se().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=at({logLevel:e});return a(n)?n:(qe({logLevel:e}),N({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var Od,Ud=y(()=>{"use strict";Mr();J();C();de();L();Od=async()=>{$(""),N({mode:f.DEFAULT});let e=Ke();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await No();return a(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as xe}from"ulid";var vp,Bd,_d,dt,jd,$d=y(()=>{"use strict";Qa();Oe();cn();Lt();je();rs();An();J();Zt();te();C();ie();Ge();de();Ee();L();zo();le();dd();kt();qr();Qt();jr();pd();xd();Sd();Ad();wd();Ld();kd();Fd();Ud();vp=e=>e.action==="add.issue.comment",Bd=e=>Object.values(p().tags).find(t=>t.name===e),_d=e=>Object.values(p().contributors).find(t=>t.name===e),dt=async()=>{let e=await $e();return a(e)?e:c("Resolved persist root",e.value)},jd=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Cd},{intent:P.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=z(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await dt();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=M(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=p().nodes[d];if(!l||!M(l))return i("Unable to resolve comment issue");let u=l.log?.filter(vp).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):U([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return U([{id:xe(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=se().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>pe(v.FILTER).map(l=>l.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return ge(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=p();return yt({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),N({mode:f.HELP}),c("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=z(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!M(o))return i("Cannot close in this context");let r=p().nodes[me];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await dt();if(a(s))return s;let d=s.value,l=Pt(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=U([{id:xe(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=z(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?c("Resolved ticket",o):Rt(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=p().nodes[me];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!M(s))return i("Target node is not issue");let l=qo(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=p().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await dt();if(a(m))return m;let g=m.value,x=Pt(u.id,s.id,{at:"end"},e.value,g);if(a(x))return x;let b=U([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:x.value},...e.value}],g);return a(b)?b:c("Issue reopened",null)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:yd},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Rd,onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=z(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Ea();if(!r)return i("Provide a title");let s=await dt();return a(s)?s:U([{id:xe(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=Bd(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=p();if(!s)return i("Invalid untag target");let d=Rt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!M(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await dt();return a(m)?m:U([{id:xe(),action:"remove.issue.tag",payload:{id:l.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=p();if(!r)return i("Invalid tag target");let s=Rt(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!M(d))return i("Target node is not issue");let l=await dt();if(a(l))return l;let u=Bd(o),m=u?.id??xe();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):U([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let{selectedIndex:r,contextNode:s}=p(),d=z(s.id)[r];if(!d)return i("Invalid assign target");let l=Rt(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.value;if(!M(u))return i("Target node is not issue");let m=await dt();if(a(m))return m;let g=_d(o),x=g?.id??xe();return(u.props.assignees??[]).includes(x)?i("Assignee already assigned"):U([...g?[]:[{id:xe(),action:"create.contributor",payload:{id:x,name:o},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:x},...e.value}],m.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let r=_d(o);if(!r)return i(`Assignee "${o}" does not exist`);let{selectedNode:s}=p();if(!s)return i("Invalid unassign target");let d=Rt(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.value;if(!M(l))return i("Target node is not issue");if(!(l.props.assignees??[]).includes(r.id))return i(`Issue is not assigned to "${o}"`);let m=await dt();return a(m)?m:U([{id:xe(),action:"remove.issue.assignee",payload:{id:l.id,assignee:r.id},...e.value}],m.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>en)return i(`Cannot exceed ${en} characters`);let o=X();if(a(o))return i("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=p(),d=Be([...r,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Rt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!M(m))return i("Target node is not issue");let g=await dt();return a(g)?g:U([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:o.value.userId,md:n},...o.value}],g.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:Od},{intent:P.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Td},{intent:P.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Ja();return a(e)?e:(N({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(k.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>md(t),onSuccess:()=>N({mode:f.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case oe.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=Q(),d=n||s,l=o??xe();if(!d||!l)return i("Unable to resolve user name or id");let u=at({userName:d,userId:l,preferredEditor:r??""});return a(u)?u:(qe({userName:d,userId:l}),N({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case oe.EDITOR:{if(!n)return i("No editor provided");let o=at({preferredEditor:n});return a(o)?o:(qe({preferredEditor:n}),N({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case oe.VIEW:return n!=="wide"&&n!=="dense"?i("Invalid view mode"):(qe({viewMode:n}),c(`View set to "${n}"`,null));case oe.AUTOSYNC:return Pd();case oe.LOG_LEVEL:return Dd();case oe.SYNC_DEBOUNCE_MS:return Md();default:return i("Unknown config command")}}},{intent:P.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=se().commandMeta.modifier;return e==="custom"?is("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):is(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),$(""),c("Thanks you!",null)}}]});var yp,Ze,gs=y(()=>{"use strict";Co();Po();qr();$d();C();de();Ee();L();yp=new Set(["peek","filter","view-help"]),Ze=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=se();if(!t)return i("No command to confirm");if(!e&&n===gt.Invalid)return i("Invalid command");let s=ba(t);xa();let{readOnly:d}=p();if(d&&!yp.has(s))return On({status:ct.Fail,message:"Command not available in readonly state",value:null});let l=jd.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return On({status:ct.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return On({status:ct.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?On(u):(ha({addToHistory:!e}),l.onSuccess?.(),Q().autoSync&&Yi(),u)}});var Xo,Jo,Wd,Hd=y(()=>{"use strict";C();J();L();bt();gs();ms();de();Xo=[{intent:A.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:f.COMMAND_LINE}),$("move cancel"),Ze({isForceExecutedBySystem:!0}))},{intent:A.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(N({mode:f.COMMAND_LINE}),$("move start"),Ze({isForceExecutedBySystem:!0}))},{intent:A.ConfirmMove,mode:f.MOVE,action:()=>(N({mode:f.COMMAND_LINE}),$("move confirm"),Ze({isForceExecutedBySystem:!0}))}],Jo=[{intent:A.MovePreviousItem,mode:f.MOVE,action:()=>xt()?(N({mode:f.COMMAND_LINE}),$("move previous"),Ze({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveNextItem,mode:f.MOVE,action:()=>xt()?(N({mode:f.COMMAND_LINE}),$("move next"),Ze({isForceExecutedBySystem:!0})):i("No pending move")}],Wd=[{intent:A.MoveToNextContainer,mode:f.MOVE,action:()=>xt()?(N({mode:f.COMMAND_LINE}),$("move to-next"),Ze({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveToPreviousContainer,mode:f.MOVE,action:()=>xt()?(N({mode:f.COMMAND_LINE}),$("move to-previous"),Ze({isForceExecutedBySystem:!0})):i("No pending move")}]});var Vd,qd=y(()=>{"use strict";te();Hd();Vd={[w.WORKSPACE]:[...Xo,...Jo],[w.BOARD]:[...Xo,...Jo],[w.SWIMLANE]:[...Xo,...Jo,...Wd],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[],[w.COMMENT]:[]}});var zd,Gd,Kd=y(()=>{"use strict";J();C();de();L();zo();bt();Oe();zd=()=>{$("");let{pendingNavTarget:e}=ln();N({mode:f.DEFAULT}),e&&k.navigate(e),yt({pendingNavTarget:void 0})},Gd=[{intent:A.ExitCommandLine,mode:f.HELP,action:()=>(zd(),c("Exiting help",null))},{intent:A.Exit,mode:f.HELP,action:()=>(zd(),c("Closed help",null))},{intent:A.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(k.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:A.NavNextItem,mode:f.HELP,action:()=>(k.navigateToNextItem(),c("Navigating to next help item",null))},{intent:A.NavToPreviousContainer,mode:f.HELP,action:()=>(k.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:A.NavToNextContainer,mode:f.HELP,action:()=>(k.navigateToNextContainer(),c("Navigating to next help container",null))}]});var xp,Yd,Xd,Jd=y(()=>{"use strict";J();te();C();de();L();zo();bt();Oe();xp=e=>{N({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=ln();t&&k.navigate(t),yt({pendingNavTarget:void 0}),$(`${e} `)},Yd=()=>{$("");let{pendingNavTarget:e}=ln();e&&k.navigate(e),yt({pendingNavTarget:void 0}),N({mode:f.DEFAULT})},Xd=[{intent:A.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{$("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=p();return yt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),N({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:A.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=p();if(!e||!ei(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(xp(t),c("Selected command",t)):c("No command selected",null)}},{intent:A.ExitCommandLine,mode:f.PALETTE,action:()=>(Yd(),c("Exiting palette",null))},{intent:A.Exit,mode:f.PALETTE,action:()=>(Yd(),c("Closed command palette",null))},{intent:A.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(k.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.PALETTE,action:()=>(k.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.PALETTE,action:()=>(k.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.PALETTE,action:()=>(k.navigateToNextContainer(),c("Navigating to next container",null))}]});var Qd,Zd=y(()=>{"use strict";kt();J();C();qt();Ge();de();L();bt();Kd();Jd();Oe();Qd=[...Gd,...Xd,{intent:A.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.NEW} `),c("Adding new item",null))},{intent:A.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.DELETE} `),c("Deleting item",null))},{intent:A.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(N({mode:f.COMMAND_LINE}),$(""),c("Entering command line mode",null))},{intent:A.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=p();if(!K(e?.id??"")?.length){if(e?.title===ne.DESCRIPTION)return N({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===ne.ASSIGNEES)return N({mode:f.COMMAND_LINE}),$(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===ne.TAGS)return N({mode:f.COMMAND_LINE}),$(`${v.TAG} `),c("Propose command",!0);if(t.title===ne.DESCRIPTION&&e?.context==="TEXT")return N({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0)}return k.enterChildNode(),c("Entering context",null)}},{intent:A.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.EDIT} title ${p().selectedNode?.title}`),c("Exiting context",null))},{intent:A.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Exiting context",null))},{intent:A.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(k.enterParentNode(),c("Exiting context",null))},{intent:A.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(k.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.DEFAULT,action:()=>(k.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(k.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.DEFAULT,action:()=>(k.navigateToNextContainer(),c("Navigating to next container",null))}]});var hp,Ip,ec,tc=y(()=>{"use strict";de();hp=500,Ip=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ec=e=>{let t=Ip(e);t&&tn(n=>(n+t).slice(0,hp))}});var Np,Ep,nc,oc=y(()=>{"use strict";tc();J();C();de();L();bt();gs();Np=[f.COMMAND_LINE,f.PALETTE],Ep=e=>[{intent:A.MoveCursorLeft,mode:e,action:()=>(Hr(-1),c("Moving cursor left",null))},{intent:A.MoveCursorRight,mode:e,action:()=>(Hr(1),c("Moving cursor right",null))},{intent:A.MoveCursorLeftOfWord,mode:e,action:()=>(Vr("left"),c("Moving cursor left of word",null))},{intent:A.MoveCursorRightOfWord,mode:e,action:()=>(Vr("right"),c("Moving cursor right of word",null))},{intent:A.AutoCompleteCommand,mode:e,action:()=>(tn((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=p().selectedNode?.title??""),o+r}),c("Auto-completing command",null))},{intent:A.CaptureInput,mode:e,action:(t,{sequence:n})=>(ec(n??""),c("Capturing input",null))},{intent:A.EraseInput,mode:e,action:()=>(va(),c("Erasing input",null))},{intent:A.EraseInputWord,mode:e,action:()=>(ya(),c("Erasing input word",null))}],nc=[{intent:A.Confirm,mode:f.COMMAND_LINE,action:()=>(Ze(),c("Executing command",null))},{intent:A.ViewHelp,mode:f.DEFAULT,action:()=>(N({mode:f.HELP}),c("Viewing help",null))},...Np.flatMap(Ep),{intent:A.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(N({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:A.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Ia(),c("Getting last command from history",null))},{intent:A.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Na(),c("Getting next command from history",null))}]});import ic from"chalk";var Qo,rc,sc,fs,ac=y(()=>{"use strict";J();te();Ce();Qo=ic.dim.hex(S.secondary2)(": for command line"),rc="q to exit",sc=`${ic.hex(S.accent)("m")} to confirm`,fs={[w.WORKSPACE]:[Qo],[w.BOARD]:[Qo],[w.BOARD+f.COMMAND_LINE]:[Qo],[w.SWIMLANE]:[Qo],[w.TICKET+f.HELP]:[rc],[w.SWIMLANE+f.HELP]:[rc],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+f.MOVE]:[sc],[w.TICKET+f.MOVE]:[sc]}});var Wn,bp,Cp,dc,cc=y(()=>{"use strict";L();Wn=e=>e.trim().toLocaleLowerCase(),bp=e=>{let{tags:t}=p();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Cp=e=>{let{contributors:t}=p();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},dc=(e,t)=>{let n=Wn(t.value);if(!n)return!0;switch(t.target){case"title":return Wn(e.title??"").includes(n);case"description":return Wn(e.props.description??"").includes(n);case"tag":return bp(e).map(Wn).some(r=>r.includes(n));case"assignee":return Cp(e).map(Wn).some(r=>r.includes(n));default:return!0}}});function lc(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=o;for(;s&&(r.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=r[r.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),c("Breadcrumb built",r))}var uc=y(()=>{"use strict";C()});var mc,pc=y(()=>{"use strict";mc=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as Sp}from"react";function fc(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!o)return i("derive(): rootNode is missing");if(!r[o])return i("derive(): unable to find root node");let l=r[t];if(!l)return i("Unable to derive state, contextNode not found");let u=lc(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,x=fs[g+n]??fs[g]??[],b=[...Qd,...Vd[g]??[],...nc],T=mc(b),R=Ap(r,s),F=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:x,availableActions:b,actionIndex:T,selectedNode:F,renderedChildrenIndex:R})}function wn(e){vs=e;let t=lt(process.cwd()),n=!1;if(!a(t)){let s=mt(t.value);if(a(s))return i(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},r=fc(o);return a(r)?r:(Bt=r.value,gc(),c("State initialized",null))}function ge(e){let t=p(),n=e(t),o=fc(n);return a(o)?i(o.message??"Unable to update state"):(Bt=o.value,gc(),c("State updated",null))}var Bt,vs,ys,gc,Rp,p,Ke,N,_e,Ap,z,$n,Jt,L=y(()=>{"use strict";qd();Zd();oc();ac();Nt();J();te();C();le();cc();uc();pc();ys=new Set,gc=()=>{for(let e of ys)e()},Rp=e=>(ys.add(e),()=>ys.delete(e));p=()=>{if(!Bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Bt},Ke=()=>Bt?c("Retrieved state",Bt):i("State not initialized. Call initWorkspaceState() first.");N=e=>ge(t=>({...t,...e})),_e=()=>Sp(Rp,p,p),Ap=(e,t)=>{let n={};for(let o of Object.values(e))M(o)&&t.length>0&&!t.every(r=>dc(o,r))||!o.parentNodeId||o.isDeleted||((!o.parentNodeId||!n[o.parentNodeId])&&(n[o.parentNodeId]=[]),n[o.parentNodeId].push(o));for(let o of Object.keys(n))n[o].sort((r,s)=>{let d=e[r.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},z=e=>p()?.renderedChildrenIndex[e]??[],$n=()=>vs?wn(vs):i("Cannot reset state: no initial workspace found"),Jt=()=>Bt!==void 0});var xs,Zo,er,hs,Ue,Eo=y(()=>{"use strict";Zs();C();L();xs=e=>{Jt()&&(N({syncStatus:e}),Qs({type:"sync-status",payload:e}))},Zo=(e="Syncing...")=>{xs({status:"syncing",msg:e})},er=(e="Synced")=>{xs({status:"synced",msg:e})},hs=e=>{xs({status:"failed",msg:e})},Ue=e=>(hs(e),i(e))});import{decodeTime as vA}from"ulid";var vc=y(()=>{"use strict";C()});var Tp,wp,bo,Lr=y(()=>{"use strict";C();Eo();wr();Jn();It();Et();io();vc();Tp=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=q("getRepoRootDir",await ut(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=q("getStateBranchRoot",nt({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=q("ensureInitialCommit",await Ys(o));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let l=q("bootstrapStateBranchStorage",await Js({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(l))return i(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=q("hasInProgressGitOperation(stateBranchRoot)",await Zn(s));if(a(u))return i(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"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let m=q("ensureStateBranchLayout",zs(o,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}))},wp=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 o=q("stageStateBranchOwnEventFile",await so({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=q("hasStagedChanges(after stage)",await js(t));if(a(r))return i(r.message);if(logger.debug("[sync] state branch change check after stage result",{changed:r.value}),!r.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=q("createStateBranchSyncCommit",await Xs({repoRoot:e,stateBranchRoot:t}));return a(s)?i(s.message):(logger.debug("[sync] created sync commit",s.value),c("Committed own event file",{createdCommit:!0,commitSha:s.value}))},bo=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}),i("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}),i("Own event file must end with .jsonl");Zo();let n=q("ensureSyncReady",await Tp({cwd:e,ensureUpstream:!0}));if(a(n))return Ue(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=q("isDetachedHead(stateBranchRoot)",await $s(r));if(a(d))return Ue(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ue("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,x=q("getStateBranch",_t(o));if(a(x))return Ue(x.message);let b=x.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:r});let T=q("commitOwnEventFileToStateBranch",await wp({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(T))return Ue(T.message);l=T.value.createdCommit,u=T.value.commitSha;let R=q("pullBranchRebaseIfPresent",await pr({cwd:r,branch:b}));if(a(R))return Ue(R.message);if(m=R.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let F=q("pushStateBranch",await In({stateBranchRoot:r,repoRoot:o}));if(a(F)&&_s(F.message)){let j=q("pullBranchRebaseIfPresent(retry)",await pr({cwd:r,branch:b}));if(a(j))return Ue(j.message);m=m||j.value,F=q("pushStateBranch(retry)",await In({stateBranchRoot:r,repoRoot:o}))}if(a(F))return Ue(F.message);g=F.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let F=q("git rev-parse HEAD",await B({args:["rev-parse","HEAD"],cwd:r}));if(a(F))return Ue(F.message);u=F.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return er(g?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:l,commitSha:u,pulled:m,pushed:g,bootstrapped:s})}});import{decodeTime as FA,ulid as he}from"ulid";var Is,Ne,Le,Pe,Mp,Lp,yc,xc,hc,Ic,Nc,Ec,bc,Cc,Sc,Rc,Ac,Tc,wc,Mc,Lc,Pc,kc,Dc=y(()=>{"use strict";It();Et();io();Lr();cn();ps();Io();Mn();Lt();je();rs();An();te();C();Nt();ie();Ge();L();Eo();le();pt();Wt();fn();Is=e=>{let t=lt(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},Ne=async e=>{let t=Is(e);if(a(t))return t;let n=nt({repoRoot:t.value});if(a(n))return i(n.message);let o=Yn(),r=await hn({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:o.stateBranch});if(a(r))return i(r.message);let s=await B({cwd:n.value,args:["pull","--ff-only"]});a(s)&&ue.info(3,s.message);let d=wt(n.value);if(a(d))return i(d.message);let l=kn(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},Le=()=>{let e=ad();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},Pe=()=>{let e=Ke();return a(e)?i(e.message):e},Mp=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Se(t.name)})),Lp=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Se(t.name)})),yc=async(e={})=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},xc=async(e={})=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===me,readonly:!!r.readonly}));return c("Listed swimlanes",o)},hc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(M).filter(r=>e.includeClosed||r.parentNodeId!==me).map(r=>({id:r.id,title:Ct(r.title),description:r.props.description??"",parentNodeId:r.parentNodeId,isClosed:r.parentNodeId===me,readonly:!!r.readonly,tags:Mp(r),assignees:Lp(r)}));return c("Listed issues",o)},Ic=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Yt(e.parentId,n.value,t.value.stateBranchRoot);if(a(o))return o;let r=Ko({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(a(r))return r;let s=r.value,d=U([...s],t.value.stateBranchRoot);if(a(d))return i(d.message);let l=s.find(u=>u.action==="add.issue")?.payload.id;return l?c("Created issue",{id:l,title:e.title,parentId:e.parentId}):i("Unable to determine created issue id")},Nc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pt(me,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:he(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:me,rank:o.value}},s=U([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},Ec=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Target node is not issue");if(r.parentNodeId!==me)return i("Issue is not closed");let s=qo(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===me)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Pt(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:he(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:l.value}},m=U([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:r.id,parentId:d.id})},bc=async e=>{let t=Is(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=nt({repoRoot:t.value});if(a(o))return o;let r=wt(o.value);if(a(r))return r;let s=kn(r.value);if(a(s))return s;let d=Pt(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:he(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=U([l],o.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},Cc=async(e={})=>{Zo();let t=Is(e.repoRoot);if(a(t))return i("Sync failed");let n=Le();if(a(n))return n;let o=await bo({cwd:t.value,ownEventFileName:Mt(n.value)});return a(o)?(hs(o.message),o):(er(),c("Synced",o.value))},Sc=async(e={})=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Pe();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},Rc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=r.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:he(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=U([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},Ac=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=Ct(e.title);if(!s.trim())return i("Issue title cannot be empty");if(r.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:he(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=U([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},Tc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Tag target must be an issue");if(r.readonly)return i("Cannot tag readonly issue");let s=Ct(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(o.value.tags).find(g=>g.name===s),l=d?.id??he(),u=[...d?[]:[{id:he(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:he(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=U(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},wc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Untag target must be an issue");if(r.readonly)return i("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return i("Tag not found");let s={id:he(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=U([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Mc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Assign target must be an issue");if(r.readonly)return i("Cannot assign readonly issue");let s=Ct(e.assigneeName).trim();if(!s)return i("Assignee name cannot be empty");let d=Object.values(o.value.contributors).find(g=>g.name===s),l=d?.id??he(),u=[...d?[]:[{id:he(),...n.value,action:"create.contributor",payload:{id:l,name:s}}],{id:he(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:l}}],m=U(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue assignee",{id:e.issueId,assignee:{id:l,name:s}})},Lc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Unassign target must be an issue");if(r.readonly)return i("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:he(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=U([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Pc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Comment target must be an issue");if(r.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");let d=he(),l={id:he(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=U([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},kc=async e=>{let t=await Ne(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Pe();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!M(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let l={id:he(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=U([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})}});var Uc={};Wc(Uc,{createMcpServer:()=>Fc,resultJson:()=>ce,startMcpServer:()=>Oc});import{McpServer as Pp}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as kp}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as E}from"zod";var ce,Fc,Oc,Bc=y(async()=>{"use strict";C();Dc();ce=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Fc=()=>{let e=new Pp({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:E.object({repoRoot:E.string().optional()})},async t=>ce(await Sc(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:E.object({repoRoot:E.string().optional(),includeClosed:E.boolean().optional()})},async t=>ce(await hc(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:E.object({repoRoot:E.string().optional()})},async t=>ce(await yc(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:E.object({repoRoot:E.string().optional(),boardId:E.string().optional()})},async t=>ce(await xc(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:E.object({title:E.string().min(1),parentId:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Ic(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),description:E.string(),repoRoot:E.string().optional()})},async t=>ce(await Rc(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),title:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Ac(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:E.object({issueId:E.string().min(1),tagName:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Tc(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),tagId:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await wc(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue, creating the contributor if they do not exist",inputSchema:E.object({issueId:E.string().min(1),assigneeName:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Mc(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),assigneeId:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Lc(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),body:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Pc(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:E.object({commentId:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await kc(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:E.object({issueId:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Ec(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),repoRoot:E.string().optional()})},async t=>ce(await Nc(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:E.object({issueId:E.string().min(1),parentId:E.string().min(1),position:E.discriminatedUnion("at",[E.object({at:E.literal("start")}),E.object({at:E.literal("end")}),E.object({at:E.literal("before"),sibling:E.string().min(1)}),E.object({at:E.literal("after"),sibling:E.string().min(1)})]).optional(),repoRoot:E.string().optional()})},async t=>ce(await bc(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:E.object({repoRoot:E.string().optional()})},async t=>ce(await Cc(t))),e},Oc=async()=>{let e=Fc(),t=new kp;await e.connect(t)};await Oc()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Bc().then(()=>Uc);
|
|
56
|
+
`,cs.writeFileSync(t,n,"utf8"),ue.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import hp from"node:fs";import bd from"node:path";var Ip,G,Nd,Ed=y(()=>{"use strict";Id();Jn();It();Nt();ao();Oe();Dn();bo();Yt();je();Z();E();bt();pe();Ne();M();le();Ip=async e=>{let t=await j({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},G=(e,t)=>i(`[${e}] ${t}`),Nd=async()=>{$("");let e=Xn(),t=await ut(process.cwd());if(a(t))return G(1,t.message);let n=t.value,o=await eo(n);if(a(o))return G(2,o.message);if(o.value)return G(2,`Cannot initialize Epiq while a git operation is in progress: ${o.value}`);let r=await Ip(n);if(a(r))return G(2.5,r.message);if(r.value)return G(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(dr(n))return G(4,"Epiq project already initialized");let s=Ro();if(!s.isSetupDone||!s.userName)return G(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ee(),l=d.userName,u=d.userId;if(!u||!l)return G(5,"Missing Epiq user id");let m=e.stateBranch,p=await no({repoRoot:n,branch:m});if(a(p))return G(6,p.message);if(p.value)return G(6,`State branch already exists: ${m}`);let x=await hr({repoRoot:n,stateBranchName:m});if(a(x))return G(6,x.message);let C=so();if(a(C))return G(7,C.message);let T=bd.join(ro(),e.projectId),P=await hn({repoRoot:n,stateBranchRoot:T,stateBranchName:m});if(a(P))return G(8,P.message);let D=bd.join(T,".epiq");hp.mkdirSync(D,{recursive:!0});let O=qi({userId:u,userName:l});if(a(O))return G(9,O.message);for(let ar of O.value){let Rs=xo({event:ar,rootDir:T});if(a(Rs))return G(9,Rs.message)}let B=await io({stateBranchRoot:T,eventFileName:Mt({userId:u,userName:l})});if(a(B))return G(10,B.message);let K=await jt({cwd:T,message:"[epiq:init]"});if(a(K))return G(10,K.message);let W=await hd(n);if(a(W))return G(11,W.message);let V=Ms({repoRoot:n,fileContents:e});if(a(V))return G(12,V.message);let rr=await ne.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(rr))return G(13,rr.message);let Vn=await ne.commit({cwd:n,message:"[epiq:init-project]"});if(a(Vn))return G(13,Vn.message);let sr="Project initialized!",Ns=await j({cwd:n,args:["push","-u","origin","HEAD"]});a(Ns)&&(sr+=` Warn: [init:14] ${Ns.message}`);let Es=await In({repoRoot:n,stateBranchRoot:T});a(Es)&&(sr+=` Warn: [init:15] ${Es.message}`);let Cs=Tt(O.value).filter(a);if(Cs.length>0)return G(16,Cs.map(ar=>ar.message).join(`
|
|
57
|
+
`));let ir=Ue();if(a(ir))return G(16,ir.message);let{rootNodeId:Vc,nodes:qc}=ir.value,Ss=qc[Vc];return Ss?(L.navigate({contextNode:Ss,selectedIndex:0}),b({hasProjectDefinition:!0,mode:f.DEFAULT}),c(sr,null)):G(16,"Unable to resolve initialized root node")}});import{ulid as bp}from"ulid";function us(e){let t=Sd();if(a(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=Y(r.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=Rd({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Ad(u.value)}function ms(e){let t=Sd();if(a(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=Y(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Rd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Ad(d.value)}var Cd,xt,$n,Sd,ls,Rd,Ad,ps=y(()=>{"use strict";Yt();je();E();Ye();M();Cd=null,xt=()=>structuredClone(Cd),$n=e=>{Cd=e},Sd=()=>{let{contextNode:e,selectedIndex:t}=g(),o=Y(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},ls=({id:e,parentId:t,position:n={at:"end"}})=>{let o=Y(t).filter(r=>r.id!==e);return ho(o,n)},Rd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=X();if(a(o))return i("Unable to resolve user ID");let r=ls({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:bp(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Ad=e=>{$n(e);let t=An(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Np}from"ulid";var Td,Xo,wd,Md=y(()=>{"use strict";Oe();ps();kt();je();Z();E();Ye();pe();M();le();Td=()=>{let e=xt();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return i("Move parent not found");let r=Y(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(L.navigate({contextNode:o,selectedIndex:r}),c("Synchronized navigation to moved node",null))},Xo=(e,t="Moved preview")=>{if(a(e))return e;let n=Td();return a(n)?n:(b({mode:f.MOVE}),c(t,null))},wd=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=se().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=Y(n.id)[o];if(!r)return b({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(r.readonly)return i("Target node is read-only");if(o===-1)return i("No item selected");if(!r.parentNodeId)return i("Target has no parent");let s=Y(r.parentNodeId),d=s.findIndex(({id:x})=>x===r.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=ls({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:($n({id:Np(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),b({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return Xo(ms(1));if(t==="previous")return Xo(ms(-1));if(t==="to-next")return Xo(us(1));if(t==="to-previous")return Xo(us(-1));if(t==="confirm"){let s=xt();if(!s)return i("No pending move to confirm");let d=await He();if(a(d))return d;let l=U([s],d.value);if(a(l))return l;let u=Td();return a(u)?u:($n(null),b({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?($n(null),b({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Ep,ulid as Cp}from"ulid";var Sp,Jo,gs=y(()=>{"use strict";E();Sp=Ep(),Jo=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=Sp();return c("Created issue events",[{id:Cp(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Qo}from"ulid";var kd,Ld=y(()=>{"use strict";Oe();gs();kt();je();en();E();ie();Ye();M();le();kd=async(e,t)=>{let n=X();if(a(n))return i("Unable to resolve user ID");let o=await He();if(a(o))return o;let r=o.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=U([m],r);if(a(p))return p;let x=I.getNode(p.value[0].result.id);if(!x)return i("Created node not found");if(!x.parentNodeId)return p;let C=I.getNode(x.parentNodeId);return C?(L.navigate({contextNode:C,selectedIndex:I.getSiblings(x.parentNodeId).findIndex(({id:T})=>T===x.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return i("Workspace not found");let x=Xt(p.id,n.value,r);return a(x)?x:u({id:Qo(),action:"add.board",payload:{id:Qo(),name:t.inputString,parent:p.id,rank:x.value},...n.value})}if(t.modifier==="swimlane"){let m=We(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=Xt(m.value.id,n.value,r);return a(p)?p:u({id:Qo(),action:"add.swimlane",payload:{id:Qo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=z(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let K=We(s,"SWIMLANE");return a(K)?null:K.value})();if(!p)return i("Unable to add issue in this context");let x=Xt(p.id,n.value,r);if(a(x))return x;let C=Jo({name:t.inputString,parent:p.id,rank:x.value,user:n.value});if(a(C))return C;let T=C.value,P=U([...T],r);if(a(P))return P;if(!P.value[0])return i("Issue creation failed");let B=T.find(K=>K.action==="add.issue")?.payload.id;return B?(L.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:K})=>K===B)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Pd,Dd=y(()=>{"use strict";It();Oe();Sn();wn();Yt();Z();en();E();pe();M();ko();Pd=async()=>{let e=We(g().breadCrumb,"BOARD");if(a(e))return e;let t=await ut(process.cwd());if(a(t))return i("Unable to locate repo root");let n=nt({repoRoot:t.value});if(a(n))throw new Error(n.message);let{modifier:o,inputString:r}=se().commandMeta;if(o==="now"){let D=wt(n.value);if(a(D))return i(D.message);let O=Wn();if(a(O))return O;let K=Tt(D.value).filter(a);return K.length>0?i(K.map(W=>W.message).join(", ")):(b({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let s;if(o==="prev"){let D=g().eventLog.at(-1),O=Sr(D);if(O===null)return i("No previous event to peek");s=O}else if(o==="next"){let D=g().unappliedEvents.at(0),O=Sr(D);if(O===null)return i("No next event to peek");s=O+1}else{let D=Mo(o||r);if(!D)return i("Invalid peek date");s=D.getTime()}let d=g(),l=e.value.id,u=Ri(n.value,s);if(a(u))return i(u.message);let{appliedEvents:m,unappliedEvents:p}=u.value,x=Wn();if(a(x))return x;let T=Tt(m).filter(a);if(T.length>0)return Wn(),b(d),i(T.map(D=>D.message).join(", "));let P=g().nodes[l];return P?(L.navigate({contextNode:P,selectedIndex:0}),b({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:p}),c("Peeking",!0)):(Wn(),b(d),i("Board did not exist at peek date"))}});import Rp from"zod";var Fd,Od=y(()=>{"use strict";cn();Z();E();pe();Ne();M();Fd=()=>{let e=se().commandMeta.inputString,t=Rp.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=at({autoSyncDebounceMs:t.data});return a(n)?n:(Ge({autoSyncIntervalMs:t.data}),b({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var Ud,Bd=y(()=>{"use strict";Dn();cn();Z();E();pe();Ne();M();Ud=()=>{let e=se().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Zi(e),n=at({autoSync:t});return a(n)?n:(Ge({autoSync:t}),b({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var _d,jd=y(()=>{"use strict";cn();Z();E();pe();Ne();M();_d=()=>{let e=se().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=at({logLevel:e});return a(n)?n:(Ge({logLevel:e}),b({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var $d,Wd=y(()=>{"use strict";Pr();Z();E();pe();M();$d=async()=>{$(""),b({mode:f.DEFAULT});let e=Ue();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");b({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await No();return a(t)?(b({syncStatus:{msg:t.message,status:"failed"}}),t):(b({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as xe}from"ulid";var Ap,Hd,Vd,dt,qd,zd=y(()=>{"use strict";od();Oe();cn();kt();je();ss();Kt();Z();en();Q();E();ie();Ye();pe();Ne();M();Yo();le();pd();Pt();zr();Zt();$r();xd();Ed();Md();Ld();Dd();Od();Bd();jd();Wd();Ap=e=>e.action==="add.issue.comment",Hd=e=>Object.values(g().tags).find(t=>t.name===e),Vd=e=>Object.values(g().contributors).find(t=>t.name===e),dt=async()=>{let e=await He();return a(e)?e:c("Resolved persist root",e.value)},qd=[{systemOnly:!0,intent:k.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:wd},{intent:k.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=z(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await dt();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=A(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!A(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Ap).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):U([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return U([{id:xe(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=se().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>me(v.FILTER).map(l=>l.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return ge(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:k.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return yt({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),b({mode:f.HELP}),c("Viewing help",null)}},{intent:k.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=z(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!A(o))return i("Cannot close in this context");let r=g().nodes[ae];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await dt();if(a(s))return s;let d=s.value,l=Lt(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=U([{id:xe(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=z(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?c("Resolved ticket",o):Rt(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[ae];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!A(s))return i("Target node is not issue");let l=Ko(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await dt();if(a(m))return m;let p=m.value,x=Lt(u.id,s.id,{at:"end"},e.value,p);if(a(x))return x;let C=U([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:x.value},...e.value}],p);return a(C)?C:c("Issue reopened",null)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:Nd},{intent:k.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:kd,onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.Rename,description:"itle] Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=z(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Aa();if(!r)return i("Provide a title");let s=await dt();return a(s)?s:U([{id:xe(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=Hd(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Rt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!A(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await dt();return a(m)?m:U([{id:xe(),action:"remove.issue.tag",payload:{id:l.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=g();if(!r)return i("Invalid tag target");let s=Rt(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!A(d))return i("Target node is not issue");let l=await dt();if(a(l))return l;let u=Hd(o),m=u?.id??xe();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):U([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let{selectedIndex:r,contextNode:s}=g(),d=z(s.id)[r];if(!d)return i("Invalid assign target");let l=Rt(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.value;if(!A(u))return i("Target node is not issue");let m=await dt();if(a(m))return m;let p=Vd(o),x=p?.id??xe();return(u.props.assignees??[]).includes(x)?i("Assignee already assigned"):U([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:x,name:o},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:x},...e.value}],m.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let r=Vd(o);if(!r)return i(`Assignee "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid unassign target");let d=Rt(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.value;if(!A(l))return i("Target node is not issue");if(!(l.props.assignees??[]).includes(r.id))return i(`Issue is not assigned to "${o}"`);let m=await dt();return a(m)?m:U([{id:xe(),action:"remove.issue.assignee",payload:{id:l.id,assignee:r.id},...e.value}],m.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>tn)return i(`Cannot exceed ${tn} characters`);let o=X();if(a(o))return i("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=g(),d=We([...r,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Rt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!A(m))return i("Target node is not issue");let p=await dt();return a(p)?p:U([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:o.value.userId,md:n},...o.value}],p.value)},onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:$d},{intent:k.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Pd},{intent:k.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await nd();return a(e)?e:(b({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:k.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(L.exit(),c("Exit successful",!0))},{intent:k.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>yd(t),onSuccess:()=>b({mode:f.DEFAULT})},{intent:k.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case re.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=ee(),d=n||s,l=o??xe();if(!d||!l)return i("Unable to resolve user name or id");let u=at({userName:d,userId:l,preferredEditor:r??""});return a(u)?u:(Ge({userName:d,userId:l}),b({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case re.EDITOR:{if(!n)return i("No editor provided");let o=at({preferredEditor:n});return a(o)?o:(Ge({preferredEditor:n}),b({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case re.VIEW:return n!=="wide"&&n!=="dense"?i("Invalid view mode"):(Ge({viewMode:n}),c(`View set to "${n}"`,null));case re.AUTOSYNC:return Ud();case re.LOG_LEVEL:return _d();case re.SYNC_DEBOUNCE_MS:return Fd();default:return i("Unknown config command")}}},{intent:k.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=se().commandMeta.modifier;return e==="custom"?as("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):as(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),$(""),c("Thanks you!",null)}}]});var Tp,Ze,fs=y(()=>{"use strict";So();Po();zr();zd();E();pe();Ne();M();Tp=new Set(["peek","filter","view-help"]),Ze=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=se();if(!t)return i("No command to confirm");if(!e&&n===gt.Invalid)return i("Invalid command");let s=Ta(t);Ea();let{readOnly:d}=g();if(d&&!Tp.has(s))return Un({status:ct.Fail,message:"Command not available in readonly state",value:null});let l=qd.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Un({status:ct.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return Un({status:ct.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?Un(u):(Ca({addToHistory:!e}),l.onSuccess?.(),ee().autoSync&&Xi(),u)}});var Zo,er,Gd,Kd=y(()=>{"use strict";E();Z();M();Et();fs();ps();pe();Zo=[{intent:R.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(b({mode:f.COMMAND_LINE}),$("move cancel"),Ze({isForceExecutedBySystem:!0}))},{intent:R.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(b({mode:f.COMMAND_LINE}),$("move start"),Ze({isForceExecutedBySystem:!0}))},{intent:R.ConfirmMove,mode:f.MOVE,action:()=>(b({mode:f.COMMAND_LINE}),$("move confirm"),Ze({isForceExecutedBySystem:!0}))}],er=[{intent:R.MovePreviousItem,mode:f.MOVE,action:()=>xt()?(b({mode:f.COMMAND_LINE}),$("move previous"),Ze({isForceExecutedBySystem:!0})):i("No pending move")},{intent:R.MoveNextItem,mode:f.MOVE,action:()=>xt()?(b({mode:f.COMMAND_LINE}),$("move next"),Ze({isForceExecutedBySystem:!0})):i("No pending move")}],Gd=[{intent:R.MoveToNextContainer,mode:f.MOVE,action:()=>xt()?(b({mode:f.COMMAND_LINE}),$("move to-next"),Ze({isForceExecutedBySystem:!0})):i("No pending move")},{intent:R.MoveToPreviousContainer,mode:f.MOVE,action:()=>xt()?(b({mode:f.COMMAND_LINE}),$("move to-previous"),Ze({isForceExecutedBySystem:!0})):i("No pending move")}]});var Yd,Xd=y(()=>{"use strict";Q();Kd();Yd={[w.WORKSPACE]:[...Zo,...er],[w.BOARD]:[...Zo,...er],[w.SWIMLANE]:[...Zo,...er,...Gd],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[],[w.COMMENT]:[]}});var Jd,Qd,Zd=y(()=>{"use strict";Z();E();pe();M();Yo();Et();Oe();Jd=()=>{$("");let{pendingNavTarget:e}=ln();b({mode:f.DEFAULT}),e&&L.navigate(e),yt({pendingNavTarget:void 0})},Qd=[{intent:R.ExitCommandLine,mode:f.HELP,action:()=>(Jd(),c("Exiting help",null))},{intent:R.Exit,mode:f.HELP,action:()=>(Jd(),c("Closed help",null))},{intent:R.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:R.NavNextItem,mode:f.HELP,action:()=>(L.navigateToNextItem(),c("Navigating to next help item",null))},{intent:R.NavToPreviousContainer,mode:f.HELP,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:R.NavToNextContainer,mode:f.HELP,action:()=>(L.navigateToNextContainer(),c("Navigating to next help container",null))}]});var wp,ec,tc,nc=y(()=>{"use strict";Z();Q();E();pe();M();Yo();Et();Oe();wp=e=>{b({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=ln();t&&L.navigate(t),yt({pendingNavTarget:void 0}),$(`${e} `)},ec=()=>{$("");let{pendingNavTarget:e}=ln();e&&L.navigate(e),yt({pendingNavTarget:void 0}),b({mode:f.DEFAULT})},tc=[{intent:R.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{$("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return yt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),b({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:R.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!ti(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(wp(t),c("Selected command",t)):c("No command selected",null)}},{intent:R.ExitCommandLine,mode:f.PALETTE,action:()=>(ec(),c("Exiting palette",null))},{intent:R.Exit,mode:f.PALETTE,action:()=>(ec(),c("Closed command palette",null))},{intent:R.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:R.NavNextItem,mode:f.PALETTE,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:R.NavToPreviousContainer,mode:f.PALETTE,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:R.NavToNextContainer,mode:f.PALETTE,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))}]});var oc,rc=y(()=>{"use strict";Pt();Z();E();qt();Ye();pe();M();Et();Zd();nc();Oe();oc=[...Qd,...tc,{intent:R.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(b({mode:f.COMMAND_LINE}),$(`${v.NEW} `),c("Adding new item",null))},{intent:R.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(b({mode:f.COMMAND_LINE}),$(`${v.DELETE} `),c("Deleting item",null))},{intent:R.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(b({mode:f.COMMAND_LINE}),$(""),c("Entering command line mode",null))},{intent:R.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!Y(e?.id??"")?.length){if(e?.title===oe.DESCRIPTION)return b({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===oe.ASSIGNEES)return b({mode:f.COMMAND_LINE}),$(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===oe.TAGS)return b({mode:f.COMMAND_LINE}),$(`${v.TAG} `),c("Propose command",!0);if(t.title===oe.DESCRIPTION&&e?.context==="TEXT")return b({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0)}return L.enterChildNode(),c("Entering context",null)}},{intent:R.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(b({mode:f.COMMAND_LINE}),$(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:R.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(b({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Exiting context",null))},{intent:R.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),c("Exiting context",null))},{intent:R.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:R.NavNextItem,mode:f.DEFAULT,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:R.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:R.NavToNextContainer,mode:f.DEFAULT,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))}]});var Mp,kp,sc,ic=y(()=>{"use strict";pe();Mp=500,kp=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),sc=e=>{let t=kp(e);t&&Uo(n=>(n+t).slice(0,Mp))}});var Lp,Pp,ac,dc=y(()=>{"use strict";ic();Z();E();pe();M();Et();fs();Lp=[f.COMMAND_LINE,f.PALETTE],Pp=e=>[{intent:R.MoveCursorLeft,mode:e,action:()=>(Vr(-1),c("Moving cursor left",null))},{intent:R.MoveCursorRight,mode:e,action:()=>(Vr(1),c("Moving cursor right",null))},{intent:R.MoveCursorLeftOfWord,mode:e,action:()=>(qr("left"),c("Moving cursor left of word",null))},{intent:R.MoveCursorRightOfWord,mode:e,action:()=>(qr("right"),c("Moving cursor right of word",null))},{intent:R.AutoCompleteCommand,mode:e,action:()=>(Uo((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),c("Auto-completing command",null))},{intent:R.CaptureInput,mode:e,action:(t,{sequence:n})=>(sc(n??""),c("Capturing input",null))},{intent:R.EraseInput,mode:e,action:()=>(ba(),c("Erasing input",null))},{intent:R.EraseInputWord,mode:e,action:()=>(Na(),c("Erasing input word",null))}],ac=[{intent:R.Confirm,mode:f.COMMAND_LINE,action:()=>(Ze(),c("Executing command",null))},{intent:R.ViewHelp,mode:f.DEFAULT,action:()=>(b({mode:f.HELP}),c("Viewing help",null))},...Lp.flatMap(Pp),{intent:R.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(b({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:R.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Sa(),c("Getting last command from history",null))},{intent:R.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Ra(),c("Getting next command from history",null))}]});import uc from"chalk";var tr,cc,lc,vs,mc=y(()=>{"use strict";Z();Q();Ce();tr=uc.dim.hex(S.secondary2)(": for command line"),cc="q to exit",lc=`${uc.hex(S.accent)("m")} to confirm`,vs={[w.WORKSPACE]:[tr],[w.BOARD]:[tr],[w.BOARD+f.COMMAND_LINE]:[tr],[w.SWIMLANE]:[tr],[w.TICKET+f.HELP]:[cc],[w.SWIMLANE+f.HELP]:[cc],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+f.MOVE]:[lc],[w.TICKET+f.MOVE]:[lc]}});var Hn,Dp,Fp,pc,gc=y(()=>{"use strict";M();Hn=e=>e.trim().toLocaleLowerCase(),Dp=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Fp=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},pc=(e,t)=>{let n=Hn(t.value);if(!n)return!0;switch(t.target){case"title":return Hn(e.title??"").includes(n);case"description":return Hn(e.props.description??"").includes(n);case"tag":return Dp(e).map(Hn).some(r=>r.includes(n));case"assignee":return Fp(e).map(Hn).some(r=>r.includes(n));default:return!0}}});function fc(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=o;for(;s&&(r.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=r[r.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),c("Breadcrumb built",r))}var vc=y(()=>{"use strict";E()});var yc,xc=y(()=>{"use strict";yc=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as Op}from"react";function Ic(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!o)return i("derive(): rootNode is missing");if(!r[o])return i("derive(): unable to find root node");let l=r[t];if(!l)return i("Unable to derive state, contextNode not found");let u=fc(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=vs[p+n]??vs[p]??[],C=[...oc,...Yd[p]??[],...ac],T=yc(C),P=Bp(r,s),D=P[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:x,availableActions:C,actionIndex:T,selectedNode:D,renderedChildrenIndex:P})}function Tn(e){ys=e;let t=lt(process.cwd()),n=!1;if(!a(t)){let s=mt(t.value);if(a(s))return i(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},r=Ic(o);return a(r)?r:(Bt=r.value,hc(),c("State initialized",null))}function ge(e){let t=g(),n=e(t),o=Ic(n);return a(o)?i(o.message??"Unable to update state"):(Bt=o.value,hc(),c("State updated",null))}var Bt,ys,xs,hc,Up,g,Ue,b,_e,Bp,z,Wn,Qt,M=y(()=>{"use strict";Xd();rc();dc();mc();bt();Z();Q();E();le();gc();vc();xc();xs=new Set,hc=()=>{for(let e of xs)e()},Up=e=>(xs.add(e),()=>xs.delete(e));g=()=>{if(!Bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Bt},Ue=()=>Bt?c("Retrieved state",Bt):i("State not initialized. Call initWorkspaceState() first.");b=e=>ge(t=>({...t,...e})),_e=()=>Op(Up,g,g),Bp=(e,t)=>{let n={};for(let o of Object.values(e))A(o)&&t.length>0&&!t.every(r=>pc(o,r))||!o.parentNodeId||o.isDeleted||((!o.parentNodeId||!n[o.parentNodeId])&&(n[o.parentNodeId]=[]),n[o.parentNodeId].push(o));for(let o of Object.keys(n))n[o].sort((r,s)=>{let d=e[r.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},z=e=>g()?.renderedChildrenIndex[e]??[],Wn=()=>ys?Tn(ys):i("Cannot reset state: no initial workspace found"),Qt=()=>Bt!==void 0});var hs,nr,or,Is,Be,Eo=y(()=>{"use strict";ei();E();M();hs=e=>{Qt()&&(b({syncStatus:e}),Zs({type:"sync-status",payload:e}))},nr=(e="Syncing...")=>{hs({status:"syncing",msg:e})},or=(e="Synced")=>{hs({status:"synced",msg:e})},Is=e=>{hs({status:"failed",msg:e})},Be=e=>(Is(e),i(e))});import{decodeTime as DA}from"ulid";var bc=y(()=>{"use strict";E()});var _p,jp,Co,Dr=y(()=>{"use strict";E();Eo();Lr();Qn();It();Nt();ao();bc();_p=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=q("getRepoRootDir",await ut(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=q("getStateBranchRoot",nt({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=q("ensureInitialCommit",await Xs(o));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let l=q("bootstrapStateBranchStorage",await Qs({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(l))return i(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=q("hasInProgressGitOperation(stateBranchRoot)",await eo(s));if(a(u))return i(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"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let m=q("ensureStateBranchLayout",Gs(o,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}))},jp=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 o=q("stageStateBranchOwnEventFile",await io({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=q("hasStagedChanges(after stage)",await $s(t));if(a(r))return i(r.message);if(logger.debug("[sync] state branch change check after stage result",{changed:r.value}),!r.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=q("createStateBranchSyncCommit",await Js({repoRoot:e,stateBranchRoot:t}));return a(s)?i(s.message):(logger.debug("[sync] created sync commit",s.value),c("Committed own event file",{createdCommit:!0,commitSha:s.value}))},Co=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}),i("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}),i("Own event file must end with .jsonl");nr();let n=q("ensureSyncReady",await _p({cwd:e,ensureUpstream:!0}));if(a(n))return Be(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=q("isDetachedHead(stateBranchRoot)",await Ws(r));if(a(d))return Be(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Be("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,x=q("getStateBranch",_t(o));if(a(x))return Be(x.message);let C=x.value;logger.debug("[sync] resolved state branch",{stateBranch:C,stateBranchRoot:r});let T=q("commitOwnEventFileToStateBranch",await jp({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(T))return Be(T.message);l=T.value.createdCommit,u=T.value.commitSha;let P=q("pullBranchRebaseIfPresent",await vr({cwd:r,branch:C}));if(a(P))return Be(P.message);if(m=P.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let D=q("pushStateBranch",await In({stateBranchRoot:r,repoRoot:o}));if(a(D)&&js(D.message)){let O=q("pullBranchRebaseIfPresent(retry)",await vr({cwd:r,branch:C}));if(a(O))return Be(O.message);m=m||O.value,D=q("pushStateBranch(retry)",await In({stateBranchRoot:r,repoRoot:o}))}if(a(D))return Be(D.message);p=D.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let D=q("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:r}));if(a(D))return Be(D.message);u=D.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return or(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s})}});import{decodeTime as ZA,ulid as he}from"ulid";var bs,be,ke,Le,$p,Wp,Nc,Ec,Cc,Sc,Rc,Ac,Tc,wc,Mc,kc,Lc,Pc,Dc,Fc,Oc,Uc,Bc,_c=y(()=>{"use strict";It();Nt();ao();Dr();cn();gs();bo();wn();kt();je();ss();Kt();Q();E();bt();ie();Ye();M();Eo();le();pt();Wt();fn();bs=e=>{let t=lt(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},be=async e=>{let t=bs(e);if(a(t))return t;let n=nt({repoRoot:t.value});if(a(n))return i(n.message);let o=Xn(),r=await hn({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:o.stateBranch});if(a(r))return i(r.message);let s=await j({cwd:n.value,args:["pull","--ff-only"]});a(s)&&ue.info(3,s.message);let d=wt(n.value);if(a(d))return i(d.message);let l=Ln(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},ke=()=>{let e=md();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},Le=()=>{let e=Ue();return a(e)?i(e.message):e},$p=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Se(t.name)})),Wp=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Se(t.name)})),Nc=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},Ec=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===ae,readonly:!!r.readonly}));return c("Listed swimlanes",o)},Cc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Le();if(a(n))return n;let o=Object.values(n.value.nodes).filter(A).filter(r=>e.includeClosed||r.parentNodeId!==ae).map(r=>({id:r.id,title:Ct(r.title),description:r.props.description??"",parentNodeId:r.parentNodeId,isClosed:r.parentNodeId===ae,readonly:!!r.readonly,tags:$p(r),assignees:Wp(r)}));return c("Listed issues",o)},Sc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Xt(e.parentId,n.value,t.value.stateBranchRoot);if(a(o))return o;let r=Jo({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(a(r))return r;let s=r.value,d=U([...s],t.value.stateBranchRoot);if(a(d))return i(d.message);let l=s.find(u=>u.action==="add.issue")?.payload.id;return l?c("Created issue",{id:l,title:e.title,parentId:e.parentId}):i("Unable to determine created issue id")},Rc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Lt(ae,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:he(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ae,rank:o.value}},s=U([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},Ac=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Target node is not issue");if(r.parentNodeId!==ae)return i("Issue is not closed");let s=Ko(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===ae)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Lt(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:he(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:l.value}},m=U([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:r.id,parentId:d.id})},Tc=async e=>{let t=bs(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=nt({repoRoot:t.value});if(a(o))return o;let r=wt(o.value);if(a(r))return r;let s=Ln(r.value);if(a(s))return s;let d=Lt(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:he(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=U([l],o.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},wc=async(e={})=>{nr();let t=bs(e.repoRoot);if(a(t))return i("Sync failed");let n=ke();if(a(n))return n;let o=await Co({cwd:t.value,ownEventFileName:Mt(n.value)});return a(o)?(Is(o.message),o):(or(),c("Synced",o.value))},Mc=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Le();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},kc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=r.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:he(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=U([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},Lc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=Ct(e.title);if(!s.trim())return i("Issue title cannot be empty");if(r.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:he(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=U([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},Pc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Tag target must be an issue");if(r.readonly)return i("Cannot tag readonly issue");let s=Ct(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(o.value.tags).find(p=>p.name===s),l=d?.id??he(),u=[...d?[]:[{id:he(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:he(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=U(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},Dc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Untag target must be an issue");if(r.readonly)return i("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return i("Tag not found");let s={id:he(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=U([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Fc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Assign target must be an issue");if(r.readonly)return i("Cannot assign readonly issue");let s=Ct(e.assigneeName).trim();if(!s)return i("Assignee name cannot be empty");let d=Object.values(o.value.contributors).find(p=>p.name===s),l=d?.id??he(),u=[...d?[]:[{id:he(),...n.value,action:"create.contributor",payload:{id:l,name:s}}],{id:he(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:l}}],m=U(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue assignee",{id:e.issueId,assignee:{id:l,name:s}})},Oc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Unassign target must be an issue");if(r.readonly)return i("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:he(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=U([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Uc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!A(r))return i("Comment target must be an issue");if(r.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");let d=he(),l={id:he(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=U([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},Bc=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=ke();if(a(n))return n;let o=Le();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!A(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let l={id:he(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=U([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})}});var Wc={};Gc(Wc,{createMcpServer:()=>jc,resultJson:()=>ce,startMcpServer:()=>$c});import{McpServer as Hp}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Vp}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as N}from"zod";var ce,jc,$c,Hc=y(async()=>{"use strict";E();_c();ce=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),jc=()=>{let e=new Hp({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:N.object({repoRoot:N.string().optional()})},async t=>ce(await Mc(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:N.object({repoRoot:N.string().optional(),includeClosed:N.boolean().optional()})},async t=>ce(await Cc(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:N.object({repoRoot:N.string().optional()})},async t=>ce(await Nc(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:N.object({repoRoot:N.string().optional(),boardId:N.string().optional()})},async t=>ce(await Ec(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:N.object({title:N.string().min(1),parentId:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Sc(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:N.object({issueId:N.string().min(1),description:N.string(),repoRoot:N.string().optional()})},async t=>ce(await kc(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:N.object({issueId:N.string().min(1),title:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Lc(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:N.object({issueId:N.string().min(1),tagName:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Pc(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:N.object({issueId:N.string().min(1),tagId:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Dc(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue, creating the contributor if they do not exist",inputSchema:N.object({issueId:N.string().min(1),assigneeName:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Fc(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:N.object({issueId:N.string().min(1),assigneeId:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Oc(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:N.object({issueId:N.string().min(1),body:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Uc(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:N.object({commentId:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Bc(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:N.object({issueId:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Ac(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:N.object({issueId:N.string().min(1),repoRoot:N.string().optional()})},async t=>ce(await Rc(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:N.object({issueId:N.string().min(1),parentId:N.string().min(1),position:N.discriminatedUnion("at",[N.object({at:N.literal("start")}),N.object({at:N.literal("end")}),N.object({at:N.literal("before"),sibling:N.string().min(1)}),N.object({at:N.literal("after"),sibling:N.string().min(1)})]).optional(),repoRoot:N.string().optional()})},async t=>ce(await Tc(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:N.object({repoRoot:N.string().optional()})},async t=>ce(await wc(t))),e},$c=async()=>{let e=jc(),t=new Vp;await e.connect(t)};await $c()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Hc().then(()=>Wc);
|