epiq 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +671 -218
- package/dist/index.js +53 -52
- package/dist/mcp.js +44 -43
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,66 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import Qt from"chalk";import{render as pv}from"ink";import fv from"meow";import gv from"react";import ty from"chalk";var Pt={Success:"success",Fail:"fail"},a=e=>({status:Pt.Fail,message:e,value:null}),l=(e,t)=>({status:Pt.Success,message:e,value:t}),d=e=>e.status==="fail",te=e=>e.status==="success";import{spawn as Iu}from"node:child_process";import as from"node:process";var Li=e=>{let t=as.platform==="darwin"?"open":as.platform==="win32"?"cmd":"xdg-open",n=as.platform==="win32"?["/c","start","",e]:[e];Iu(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Tl}from"node:fs/promises";import zg from"node:http";import yn from"node:path";import{fileURLToPath as qg}from"node:url";import{decodeTime as al,ulid as ge}from"ulid";import hs from"node:fs";import Fu from"node:os";import nt from"node:path";import Gn from"node:fs";import{ulid as Nu}from"ulid";import{z as kr}from"zod";import Wn from"node:fs";import st from"node:path";var Tv=process.env.IS_LOCAL==="true",it=".epiq",qe=".epiq-global",Mr="events",ds="media",Eu="project.json",jn=e=>st.join(e,it),Pr=e=>st.join(jn(e),Eu),Vn=e=>st.join(jn(e),Mr),Kn=e=>st.join(jn(e),ds),ki=e=>st.join(e,it),Cu=e=>{let t=st.join(e,it);return Wn.existsSync(t)&&Wn.statSync(t).isDirectory()},cs=e=>{let t=Pr(e);return Wn.existsSync(t)&&Wn.statSync(t).isFile()},Lr=e=>{let t=st.resolve(e);for(;;){if(Cu(t))return l("Resolved closest .epiq root",t);let n=st.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ye=e=>{let t=st.resolve(e);for(;;){if(cs(t))return l("Resolved closest epiq project root",t);let n=st.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Di=e=>{let t=Vn(e);try{return Wn.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},at=async()=>{let e=await dt(process.cwd());if(d(e))return e;let t=Pe({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var Su="__epiq_state__",Au=kr.object({projectId:kr.string().min(1),stateBranch:kr.string().min(1),createdAt:kr.iso.datetime()}),vn=()=>({projectId:Nu(),stateBranch:Su,createdAt:new Date().toISOString()}),Lt=e=>{let t=Pr(e);if(!Gn.existsSync(t))return a("Missing .epiq/project.json");try{let n=Gn.readFileSync(t,"utf8"),r=JSON.parse(n),o=Au.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Fi=e=>{let t=Lt(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},Bi=({repoRoot:e,fileContents:t})=>{let n=jn(e),r=Pr(e);try{if(Gn.mkdirSync(n,{recursive:!0}),Gn.existsSync(r)){let o=Lt(e);return d(o)?a(o.message):l("Project already initialized",null)}return Gn.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var ls=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import zn from"fs";import fs from"path";import Ru from"util";var Ui=1e3,Tu=50,us=0,Oi=()=>process.env.EPIQ_MCP==="true",_i=()=>{let e=process.cwd(),t=Lr(e);return d(t)?Oi()?fs.join(process.cwd(),".epiq-mcp.log"):void 0:fs.join(t.value,it,"log","epiq.log")};function wu(){let e=_i();if(!e||!zn.existsSync(e))return;let n=zn.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Ui)return;let r=n.slice(-Ui).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))}
|
|
9
|
-
`)))}),o.on("close",p=>{let
|
|
10
|
-
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:
|
|
11
|
-
${n.message}`);let r=await
|
|
12
|
-
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},
|
|
13
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
14
|
-
${o.message}`);let s=await
|
|
15
|
-
${s.message}`):l("Pulled with rebase",!0)},
|
|
16
|
-
`+e.message);let t=
|
|
17
|
-
`+t.message):l("Ensured epiq storage",!0)},
|
|
6
|
+
`;zn.writeFileSync(e,r,"utf8")}function ms(e,t,n=!1){let r=_i();if(!r)return;let o=Ru.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
+
`;zn.mkdirSync(fs.dirname(r),{recursive:!0}),zn.appendFileSync(r,c,"utf8"),us++,us>=Tu&&(us=0,wu())}var ps=()=>Oi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",oe={info(...e){let t=ps();(t==="info"||t==="debug")&&ms("[Info]",e,!1)},debug(...e){ps()==="debug"&&ms("[Debug]",e,!0)},error(...e){let t=ps();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;ms("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=oe;import{spawn as Mu}from"node:child_process";import Dr from"node:fs";import qn from"node:path";var de={stage:({cwd:e,pathspec:t})=>_({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>_({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>_({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>_({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return _({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})};var hn=e=>{let t=Ye(e);if(d(t))return a("Unable to resolve epiq project root");let n=Lt(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},Xe="origin";var $i=1e4,Pu={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Hi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Dr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=Mu("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Pu}),s=!1,i="",c="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${$i}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},$i);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:i,stderr:p.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
9
|
+
`)))}),o.on("close",p=>{let f=p??1;if(n){u({stdout:i,stderr:c,exitCode:f});return}if(f!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
+
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),_=({args:e,cwd:t})=>Hi({args:e,cwd:t,allowFail:!1}),ct=({args:e,cwd:t})=>Hi({args:e,cwd:t,allowFail:!0}),xn=async({cwd:e,message:t})=>{let n=await de.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
|
+
${n.message}`);let r=await _({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
12
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Lu=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",qn.isAbsolute(n)?n:qn.resolve(e,n))},ku=async e=>{let t=await Lu(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Dr.existsSync(qn.join(n,s)))return l("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(Dr.existsSync(qn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},Fr=async e=>{let t=await ku(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},gs=async({repoRoot:e})=>{let n=(await ct({args:["remote","get-url",Xe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},Br=async({repoRoot:e,branch:t})=>{let n=await ct({args:["ls-remote","--heads",Xe,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Xe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Ur=async({repoRoot:e,branch:t})=>{let n=await ct({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},Yn=e=>{try{return Dr.realpathSync.native(e)}catch{return qn.resolve(e)}},Wi=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=Yn(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Yn).includes(r);return l("Checked worktree registration",o)},ys=async e=>{let t=await ct({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Or=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},ji=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Vi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Du=async e=>(await ct({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1);var vs=async({cwd:e,branch:t})=>{let n=await Br({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await Du(e);if(d(r))return a(r.message);let o=await de.fetch({cwd:e,remote:Xe,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
14
|
+
${o.message}`);let s=await de.pullRebase({cwd:e,remote:Xe,branch:t});return d(s)?a(`Failed during pull --rebase
|
|
15
|
+
${s.message}`):l("Pulled with rebase",!0)},Ki=async e=>{let t=await ct({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?l("No staged changes",!1):t.exitCode===1?l("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var Gi=async e=>{let t=await Or(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var qi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",xs=e=>nt.join(it,Mr,e),Yi=()=>nt.join(it,ds),Xi=()=>nt.join(Fu.homedir(),qe),_r=()=>nt.join(Xi(),"worktrees"),Pe=({repoRoot:e})=>{let t=Fi(e);return d(t)?a(t.message):l("Resolved state branch root",nt.join(_r(),t.value))},Bu=e=>nt.join(e,it),zi=e=>nt.join(Bu(e),Mr);var Xn=e=>{try{return hs.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},$r=()=>{let e=Xn(Xi());if(d(e))return a(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=Xn(_r());return d(t)?a(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):l("Ensured epiq storage",!0)},Ji=e=>{hs.existsSync(e)&&(oe.debug("[sync] remove path",e),hs.rmSync(e,{recursive:!0,force:!0}))};var Qi=(e,t)=>{for(let n of[zi(e),zi(t)]){let r=Xn(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Zi=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
18
18
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
19
|
-
`).filter(Boolean).filter(i=>i!==
|
|
20
|
-
${o.message}`);let s=await
|
|
21
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
22
|
-
${o.message}`):l("Created state branch",!0)},
|
|
23
|
-
`+n.message);let r=n.value,o=r?await
|
|
24
|
-
`+o.message);let s=o.value;if(r&&s){let c=await
|
|
25
|
-
${c.message}`)}let i=await
|
|
26
|
-
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await
|
|
27
|
-
${c.message}`):l("Created local state branch from remote",!0)}return
|
|
28
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)}
|
|
29
|
-
`+r.message);
|
|
30
|
-
${o.message}`):l("Created state branch worktree",!0)},
|
|
31
|
-
${u.message}`)}if(s&&!
|
|
32
|
-
${u.message}`)}let i=await
|
|
33
|
-
${u.message}`)}return
|
|
34
|
-
${o.message}`):l("Checked out state branch",!0)},
|
|
35
|
-
${c.message}`);let u=await
|
|
36
|
-
${u.message}`):l("Configured state branch upstream",!0)},
|
|
37
|
-
${o.message}`):l("Staged state branch event file",void 0)},
|
|
38
|
-
|
|
39
|
-
${s.message}`):l("Pushed state branch",!0)},Bi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=cn(e);if(d(o))return o;let s=o.value,i=[Cr(),await Zl({repoRoot:e,stateBranchName:s}),await Gt({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await nu({stateBranchRoot:t,stateBranchName:s}),await Li(t),n?await ru({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as ou}from"ws";var Sr=new Set,Ui=e=>{Sr.add(e),e.on("close",()=>{Sr.delete(e)}),e.on("error",()=>{Sr.delete(e)})},zt=e=>{let t=JSON.stringify(e);for(let n of Sr)n.readyState===ou.OPEN&&n.send(t)};import{useSyncExternalStore as kf}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function rs(e){return e.context===P.WORKSPACE}function w(e){return e.context===P.TICKET}function St(e){return e.context===P.TEXT}function Qe(e){return e.context===P.FIELD}function Bn(e){return e.context===P.FIELD_LIST}var Nt=e=>e.context===P.SWIMLANE,Nr=e=>e.context===P.BOARD,Un=e=>e.context===P.COMMENT;var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Oi=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",_i=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",$i=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Wi=(e,t)=>{if(_i(e,e.sequence))return h.MoveCursorLeftOfWord;if($i(e,e.sequence))return h.MoveCursorRightOfWord;if(Oi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},Hi=(e,t)=>{if(_i(e,e.sequence))return h.MoveCursorLeftOfWord;if($i(e,e.sequence))return h.MoveCursorRightOfWord;if(Oi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Rr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var mn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Rt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ji=e=>e.charAt(0).toUpperCase()+e.slice(1);var Vi=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Gi=(e,t)=>t?e.get(t)??[]:[];var zi=new WeakMap,su=e=>{let t=zi.get(e);return t||(t=Vi(e),zi.set(e,t)),t};var Ki=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Gi(su(e),r).filter(s=>Rr(r,s)>=n)};var iu={hint:"",hints:[],overlap:0,remainder:""},qi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return iu;let o=Ki({wordList:r,inputToMatch:e,overlapThreshold:1});return au(t,o)},au=(e,t)=>{let n=t[0]??"",r=Rr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};import{useSyncExternalStore as du}from"react";var On={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},os=new Set,cu=()=>{for(let e of os)e()},H=()=>On,Yi=()=>du(e=>(os.add(e),()=>{os.delete(e)}),()=>On),_e=e=>(On={...On,...e},cu(),On);import{ulid as mu}from"ulid";var pn=24n,lu=pn*4n,Ze=(1n<<lu)-1n,uu=/^[0-9a-f]+$/;function Xi(e){return!e||!uu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=pn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Se(e,t){if(!e&&!t)return $e(Ze/2n,pn);let n=e?Xi(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Xi(t):l("Resolved upper bound",Ze);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return $e(Ze/2n,pn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):$e(i,pn)}function Ji(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Ze*BigInt(r+1)/(t+1n),s=$e(o,pn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var ss=(e,t)=>{let n=z(e),r=Ji(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:mu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as um}from"ulid";var pt=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},is=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Kt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),b={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){fe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!w(t))return a("Can only comment on issues");let n=fe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!w(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=fe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=fe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return a("Edit target node not found");let o=Kt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=Kt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=Kt(o,"move");if(i)return i;if(is(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of z(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(C({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=fe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=fe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return z(e)}};var se={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var et=e=>e.slice(-7).toUpperCase(),Qi=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?et(e).includes(n):!0};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:et(e)},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:et(e)},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import qt from"chalk";import sa from"string-width";import{decodeTime as hu}from"ulid";import gn from"chalk";var ge={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:ge.cyan,accent2:ge.magenta,primary:ge.white,secondary:ge.grayDark,secondary2:ge.grayLight,gray:ge.gray,green:ge.green,yellow:ge.yellow,red:ge.red};var E={red:ge.red,yellow:ge.yellow,green:ge.green,blue:ge.blue,magenta:ge.magenta,cyan:ge.cyan},fn={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var ds={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Zi=(e,t,n)=>Math.max(t,Math.min(n,e)),as=(e,t,n)=>e+(t-e)*n,ea=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},pu=e=>e.toLowerCase().trim(),fu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let v=o-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},ta=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var gu=(e,t,n)=>{let r=Zi(n,0,1);return[Math.round(as(e[0],t[0],r)),Math.round(as(e[1],t[1],r)),Math.round(as(e[2],t[2],r))]};var vu=(e,t,n)=>gu(e,t,n),_n=e=>{let n=ea(e)%360,r=fu(n,ds.stringColor.saturation,ds.stringColor.lightness);return ta(r)},ie=(e,t=fn)=>{let n=pu(e);return n&&t[n]?t[n]:_n(n)};var na=e=>{let t=ds.gradient.stops,n=Zi(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return vu(t[s],t[s+1],i)},Ar=e=>ta(na(e)),Tr=e=>ea(e.toLowerCase().trim())/4294967295,ra=e=>{let t=Tr(e);return na(t)},yu=e=>{let[t,n,r]=ra(e);return{normal:o=>gn.bgRgb(t,n,r).black(o),cursor:o=>gn.bgRgb(t,n,r).white.bold(o)}},cs=e=>{let[t,n,r]=ra(e);return{fg:o=>gn.rgb(t,n,r)(o),fgCursor:o=>gn.rgb(t,n,r).inverse(o),bg:o=>gn.bgRgb(t,n,r).black(o),bgCursor:o=>gn.bgRgb(t,n,r).white.bold(o)}},wr=e=>yu(e).normal(` ${e} `);import{decodeTime as oa}from"ulid";var Mr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Pr=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Lr=e=>{try{return l("Decoded date",new Date(oa(e)))}catch(t){return a("Decoding failed + "+t.message)}},vn=e=>{if(!e?.id)return null;try{return oa(e.id)}catch{return null}};var xu=(e,t)=>e+" ".repeat(Math.max(0,t-sa(e))),Iu=(e,t)=>" ".repeat(Math.max(0,t-sa(e)))+e,ia=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`),bu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Cu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?qt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=bu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Eu=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?qt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?qt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?qt.hex(ie(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?qt.hex(ie(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""}},Su=e=>{let t=Mr(hu(e));return qt.gray(Iu(t,8))},Nu=12,Ru=e=>xu(`${e}`,Nu),Au=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=b.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},aa=e=>[ia(e.action),Au(e)].filter(Boolean).join(" "),da=(e,t)=>{let n=Su(e.id),r=Ru(e.userName),o=qt.dim("\u203A"),s=e.action==="move.node"?Cu(e,t):[ia(e.action),Eu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Tu}from"node:crypto";var wu="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Mu=e=>{let t=Tu("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=wu[Number(n>>s&31n)]}return r},Ne=(e,t)=>Mu(`${e}:virtual:${t}`);var Pu=e=>Ne(e,"comments"),Lu=e=>Ne(e,"description"),ku=e=>Ne(e,"assignees"),Du=e=>Ne(e,"tags"),Fu=e=>Ne(e,"history"),ls=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=b.getNode(e);if(!c){let p=b.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Qe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},ca=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=b.getNode(e);if(!i){let m=b.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Bn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=b.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},la=e=>{let t=$e(Ze/4n),n=$e(Ze/2n),r=$e(Ze*3n/4n),o=$e(Ze*7n/8n),s=$e(Ze*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;let i=ls({id:Lu(e.id),name:se.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=ca({id:ku(e.id),name:se.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=ca({id:Du(e.id),name:se.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(u))return u;let m=ls({id:Pu(e.id),name:se.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=ls({id:Fu(e.id),name:se.HISTORY,parentNodeId:e.id,rank:s.value,value:Bu(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},Bu=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>da(r,n.get(r.action)??[])).join(`
|
|
40
|
-
`)};var Uu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ce,kr]=Uu;var D=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ua=e=>{let t=b.getNode(e);if(!t||!w(t)||t.isDeleted)return null;let n=la(t);return d(n)?n:null},Ou=e=>{for(let t of e){let n=ua(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ua(r);if(o)return o}return null},_u=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},$u=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},us=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 $u(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[]}},Wu=e=>{fe(t=>({...t,eventLog:[...t.eventLog,e]}))},Hu=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):l("Valid user",null)},ju=(e,t)=>{let n=Hu(e);if(d(n))return n;let r=[...new Set(us(e))];t||(r.forEach(s=>_u(s,e)),Wu(e));let o=Ou(r);return o||null},Vu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=$n(o);if(d(s))return D(s.message,e);let i=b.createNode(o);return d(i)?D(i.message??"Failed to initialize workspace",e):rs(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(Q.workspace(t,n,r));return d(o)?D(o.message??"Failed to add workspace",e):rs(o.value)?l("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.board(t,n,r,o));return d(s)?D(s.message??"Unable to create board",e):Nr(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.swimlane(t,n,r,o));return d(s)?D(s.message??"Unable to create swimlane",e):Nt(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.ticket(t,n,r,o));return d(s)?D(s.message??"Unable to create issue",e):w(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=b.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(se.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?D(i.message??`Unable to create field: ${n}`,e):Qe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?D(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return d(n)?D(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?D(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?D(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.tag(t,n);return d(r)?D(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.untag(t,n);return d(r)?D(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.assign(t,n);return d(r)?D(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.unassign(t,n);return d(r)?D(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?D(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?D(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return D("Unable to locate issue",e);if(!w(o))return D("Can only close issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let i=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?D(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return D("Unable to locate issue",e);if(!w(o))return D("Can only reopen issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return D("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?D(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?D(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=b.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let i=b.updateNode({...s,rank:o});if(d(i))return D(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=b.createComment({id:t,issue:n,authorId:r,authorName:b.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?D(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=b.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 s=b.editComment(t,r);return d(s)?D(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=b.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 o=b.deleteComment(t);return d(o)?D(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=b.linkUserId({contributorId:t,userId:e.userId});return d(n)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function At(e,t=!1){let n=Vu[e.action](e);if(d(n))return n;let r=ju(e,t);return r||n}var Tt=e=>e.map(t=>At(t));import tm from"node:fs";import nm from"node:path";import{decodeTime as rm,monotonicFactory as om}from"ulid";import{z as Wn}from"zod";import Dr from"node:fs";import ps from"node:path";import{decodeTime as Gu}from"ulid";import{z as ms}from"zod";var zu=ms.object({userId:ms.string().min(1).default("unknown"),userName:ms.string().min(1).default("unknown")}),Ku=e=>{let[t,n]=ps.basename(e,".jsonl").split("."),r=zu.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${ps.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},qu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Yu=(e,t)=>t in e,Xu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ju=e=>{let{userId:t,userName:n,...r}=e,o=qu(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Yu(r,s)?l("Decoded persisted event",Xu({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},fs=e=>{let t=[];for(let n of e){let r=Ju(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return l("Decoded reconstructed events",t)},Qu=e=>{if(!Dr.existsSync(e))return l("Event file missing",[]);let t=Ku(e);if(d(t))return a(t.message);let n=Dr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
41
|
-
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=vs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function gs(e){let t=wn(e);if(!Dr.existsSync(t))return l("No events found",[]);let n=Dr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>ps.join(t,o)),r=[];for(let o of n){let s=Qu(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",Zu(r))}function ft(e){let t=gs(e);return d(t)?a(t.message):fs(t.value)}function ma(e,t){let n=gs(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=em(n.value,t),s=fs(r);if(d(s))return a(s.message);let i=fs(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function pa(e=process.cwd()){let t=gs(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Zu=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let I=n.get(v)??[];I.push(m),n.set(v,I)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let v=n.get(p)??[];for(let I of v)s(I)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},em=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=Gu(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var fa=e=>({action:e.action,payload:e.payload});var ya=1,ga=om(),sm=Wn.tuple([Wn.string().min(1),Wn.string().min(1).nullable()]),im=Wn.looseObject({v:Wn.literal(ya),id:sm}),vs=e=>{let t=im.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},va=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",am=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),dm=e=>e.trim().length>0&&e.length<=80,Z=()=>{let{userName:e,userId:t}=H();return e?t?am(t)?dm(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},Yt=({userId:e,userName:t})=>`${va(e)}.${va(t)}.jsonl`,cm=(e,{userId:t,userName:n})=>{let r=Yt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=nm.join(wn(e),r);return l("Successfully resolved event log path",s)},lm=(e,t)=>{let n={[e.action]:e.payload,v:ya,id:t};return vs(n)};function Fr({event:e,rootDir:t}){try{let n=fi(t);if(d(n))return n;let r=cm(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=pa(t);if(d(o))return a(o.message);let s=o.value?ga(Math.max(Date.now(),rm(o.value)+1)):ga(),i=lm(fa(e),[s,o.value]);return d(i)?a(i.message):(tm.appendFileSync(r.value,`${JSON.stringify(i.value)}
|
|
42
|
-
|
|
19
|
+
`).filter(Boolean).filter(i=>i!==it);if(r.length===0)return l("State branch is storage-only",!1);let o=await _({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
20
|
+
${o.message}`);let s=await xn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},dt=ls(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>nt.resolve(e)),vh=ls(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=nt.isAbsolute(n)?n:nt.join(e,n);return l("Resolved git dir",r)},e=>nt.resolve(e));import Zt from"node:fs";import Hr from"node:path";var ta=async e=>{if((await ct({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);oe.info("Creating initial commit");let n=await de.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},ea=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Uu=async e=>{let t=await Or(e);if(d(t))return a(t.message);let n=await ji(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${ea(t.value)}:sha:${ea(n.value)}]`)},bs=async({repoRoot:e,stateBranchName:t})=>{oe.info(`Creating ${t}`);let n=await _({args:["commit-tree",qi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
21
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await _({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
22
|
+
${o.message}`):l("Created state branch",!0)},Ou=async({repoRoot:e,stateBranchName:t})=>{let n=await gs({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
23
|
+
`+n.message);let r=n.value,o=r?await Br({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
24
|
+
`+o.message);let s=o.value;if(r&&s){let c=await de.fetch({cwd:e,remote:Xe,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
25
|
+
${c.message}`)}let i=await Ur({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
|
|
26
|
+
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await _({args:["branch","--track",t,`${Xe}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
27
|
+
${c.message}`):l("Created local state branch from remote",!0)}return bs({repoRoot:e,stateBranchName:t})},_u=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
28
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},$u=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Xn(Hr.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
29
|
+
`+r.message);Zt.existsSync(t)&&!Zt.existsSync(Hr.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),Ji(t)),oe.info("Creating state branch worktree");let o=await de.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
30
|
+
${o.message}`):l("Created state branch worktree",!0)},en=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await _u({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=Yn(t),s=r.value?Yn(r.value):null;if(s&&s===o&&Zt.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){oe.info("Moving state branch worktree to expected location");let u=await de.worktreeRemove({cwd:e,worktreeRoot:s});if(d(u))return a(`Failed to remove existing state branch worktree
|
|
31
|
+
${u.message}`)}if(s&&!Zt.existsSync(s)){oe.info("Pruning stale state branch worktree");let u=await de.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
32
|
+
${u.message}`)}let i=await Wi({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=Zt.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){oe.info("Pruning missing registered state branch worktree");let u=await de.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
33
|
+
${u.message}`)}return $u({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Hu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Or(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await ct({cwd:e,args:["rebase","--abort"]})).exitCode===0&&oe.info("Aborted stale state branch rebase");let o=await de.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
34
|
+
${o.message}`):l("Checked out state branch",!0)},Wu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ys(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await gs({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=hn(e);if(d(o))return o;let s=o.value,i=await Br({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);oe.info(`Configuring ${s} upstream`);let c=await de.fetch({cwd:t,remote:Xe,branch:s});if(d(c))return a(`Failed to fetch ${s}
|
|
35
|
+
${c.message}`);let u=await de.setUpstream({cwd:t,branch:s,upstream:`${Xe}/${s}`});return d(u)?a(`Failed to set state branch upstream
|
|
36
|
+
${u.message}`):l("Configured state branch upstream",!0)},Wr=async({stateBranchRoot:e,eventFileName:t})=>{let n=xs(t),r=Hr.join(e,n);if(!Zt.existsSync(r))return l("No event file to stage",void 0);let o=await de.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
37
|
+
${o.message}`):l("Staged state branch event file",void 0)},na=async({stateBranchRoot:e})=>{let t=Yi(),n=Hr.join(e,t);if(!Zt.existsSync(n))return l("No media directory to stage",void 0);let r=await de.stage({cwd:e,pathspec:[t]});return d(r)?a(`Failed to stage state branch media files
|
|
38
|
+
${r.message}`):l("Staged state branch media files",void 0)},ra=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Uu(e);return d(n)?a(`Create state branch sync commit failed
|
|
39
|
+
`+n.message):xn({cwd:t,message:n.value})},Jn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ys(t);if(d(n))return a(n.message);let r=hn(e);if(d(r))return r;let o=r.value,s=n.value?await de.push({cwd:t}):await de.push({cwd:t,remote:Xe,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
|
|
40
|
+
${s.message}`):l("Pushed state branch",!0)},oa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=hn(e);if(d(o))return o;let s=o.value,i=[$r(),await Ou({repoRoot:e,stateBranchName:s}),await en({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Hu({stateBranchRoot:t,stateBranchName:s}),await Zi(t),n?await Wu({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as ju}from"ws";var jr=new Set,sa=e=>{jr.add(e),e.on("close",()=>{jr.delete(e)}),e.on("error",()=>{jr.delete(e)})},tn=e=>{let t=JSON.stringify(e);for(let n of jr)n.readyState===ju.OPEN&&n.send(t)};import{useSyncExternalStore as Hg}from"react";var L={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Is(e){return e.context===L.WORKSPACE}function A(e){return e.context===L.TICKET}function kt(e){return e.context===L.TEXT}function Oe(e){return e.context===L.FIELD}function Qn(e){return e.context===L.FIELD_LIST}var Dt=e=>e.context===L.SWIMLANE,Vr=e=>e.context===L.BOARD,Zn=e=>e.context===L.COMMENT;var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var ia=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",aa=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",da=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",ca=(e,t)=>{if(aa(e,e.sequence))return h.MoveCursorLeftOfWord;if(da(e,e.sequence))return h.MoveCursorRightOfWord;if(ia(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},la=(e,t)=>{if(aa(e,e.sequence))return h.MoveCursorLeftOfWord;if(da(e,e.sequence))return h.MoveCursorRightOfWord;if(ia(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Kr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var nn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",lt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ua=e=>e.charAt(0).toUpperCase()+e.slice(1);var ma=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},pa=(e,t)=>t?e.get(t)??[]:[];var fa=new WeakMap,Vu=e=>{let t=fa.get(e);return t||(t=ma(e),fa.set(e,t)),t};var ga=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return pa(Vu(e),r).filter(s=>Kr(r,s)>=n)};var Ku={hint:"",hints:[],overlap:0,remainder:""},ya=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Ku;let o=ga({wordList:r,inputToMatch:e,overlapThreshold:1});return Gu(t,o)},Gu=(e,t)=>{let n=t[0]??"",r=Kr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{useSyncExternalStore as zu}from"react";var er={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Es=new Set,qu=()=>{for(let e of Es)e()},K=()=>er,va=()=>zu(e=>(Es.add(e),()=>{Es.delete(e)}),()=>er),Fe=e=>(er={...er,...e},qu(),er);import{ulid as Ju}from"ulid";var bn=24n,Yu=bn*4n,rt=(1n<<Yu)-1n,Xu=/^[0-9a-f]+$/;function ha(e){return!e||!Xu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function _e(e,t=bn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Be(e,t){if(!e&&!t)return _e(rt/2n,bn);let n=e?ha(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?ha(t):l("Resolved upper bound",rt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return _e(rt/2n,bn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):_e(i,bn)}function xa(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=rt*BigInt(r+1)/(t+1n),s=_e(o,bn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var Cs=(e,t)=>{let n=q(e),r=xa(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:Ju(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as Zm}from"ulid";var It=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Ns=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},rn=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=he(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){he(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!A(t))return a("Can only comment on issues");let n=he(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!A(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=he(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=he(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!A(t))return a("Can only attach to issues");let n=he(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):l("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=he(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return a("Edit target node not found");let o=rn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=rn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return q(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=rn(o,"move");if(i)return i;if(Ns(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of q(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(E({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=he(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=rn(r,"edit");if(o)return o;if(!A(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=he(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=he(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=he(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return q(e)}};var J={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var Ue=e=>e.slice(-7).toUpperCase(),ba=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Ue(e).includes(n):!0};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:L.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:Ue(e)},context:L.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:L.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:Ue(e)},context:L.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:L.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Ft from"chalk";import Ra from"string-width";import{decodeTime as rm}from"ulid";import En from"chalk";var Se={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},v={accent:Se.cyan,accent2:Se.magenta,primary:Se.white,secondary:Se.grayDark,secondary2:Se.grayLight,gray:Se.gray,green:Se.green,yellow:Se.yellow,red:Se.red};var C={red:Se.red,yellow:Se.yellow,green:Se.green,blue:Se.blue,magenta:Se.magenta,cyan:Se.cyan},In={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var As={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ia=(e,t,n)=>Math.max(t,Math.min(n,e)),Ss=(e,t,n)=>e+(t-e)*n,Ea=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Qu=e=>e.toLowerCase().trim(),Zu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Ca=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var em=(e,t,n)=>{let r=Ia(n,0,1);return[Math.round(Ss(e[0],t[0],r)),Math.round(Ss(e[1],t[1],r)),Math.round(Ss(e[2],t[2],r))]};var tm=(e,t,n)=>em(e,t,n),tr=e=>{let n=Ea(e)%360,r=Zu(n,As.stringColor.saturation,As.stringColor.lightness);return Ca(r)},le=(e,t=In)=>{let n=Qu(e);return n&&t[n]?t[n]:tr(n)};var Na=e=>{let t=As.gradient.stops,n=Ia(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return tm(t[s],t[s+1],i)},Gr=e=>Ca(Na(e)),zr=e=>Ea(e.toLowerCase().trim())/4294967295,Sa=e=>{let t=zr(e);return Na(t)},nm=e=>{let[t,n,r]=Sa(e);return{normal:o=>En.bgRgb(t,n,r).black(o),cursor:o=>En.bgRgb(t,n,r).white.bold(o)}},Rs=e=>{let[t,n,r]=Sa(e);return{fg:o=>En.rgb(t,n,r)(o),fgCursor:o=>En.rgb(t,n,r).inverse(o),bg:o=>En.bgRgb(t,n,r).black(o),bgCursor:o=>En.bgRgb(t,n,r).white.bold(o)}},qr=e=>nm(e).normal(` ${e} `);import{decodeTime as Aa}from"ulid";var Cn=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Yr=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Xr=e=>{try{return l("Decoded date",new Date(Aa(e)))}catch(t){return a("Decoding failed + "+t.message)}},Nn=e=>{if(!e?.id)return null;try{return Aa(e.id)}catch{return null}};var om=(e,t)=>e+" ".repeat(Math.max(0,t-Ra(e))),sm=(e,t)=>" ".repeat(Math.max(0,t-Ra(e)))+e,Ta=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),im=(e,t)=>t?e<t?"up":e>t?"down":null:null,am=(e,t)=>{let n=I.getNode(e.payload.parent),r=n?Ft.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=im(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},wa=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ma=e=>I.getAttachment(e)?.name??"",dm=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(le(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(le(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(le(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(le(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Ft.dim(`(${wa(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ma(e.payload.id);return t?`"${t}"`:""}default:return""}},cm=e=>{let t=Cn(rm(e));return Ft.gray(sm(t,8))},lm=12,um=e=>om(`${e}`,lm),mm=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${wa(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ma(e.payload.id);return t?`"${t}"`:""}default:return""}},Pa=e=>[Ta(e.action),mm(e)].filter(Boolean).join(" "),La=(e,t)=>{let n=cm(e.id),r=um(e.userName),o=Ft.dim("\u203A"),s=e.action==="move.node"?am(e,t):[Ta(e.action),dm(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as pm}from"node:crypto";var fm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",gm=e=>{let t=pm("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=fm[Number(n>>s&31n)]}return r},xe=(e,t)=>gm(`${e}:virtual:${t}`);var ym=e=>xe(e,"comments"),vm=e=>xe(e,"description"),hm=e=>xe(e,"assignees"),xm=e=>xe(e,"tags"),bm=e=>xe(e,"history"),Im=e=>xe(e,"attachments"),Jr=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Oe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},ka=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=I.getNode(e);if(!i){let m=I.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Qn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=I.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},Da=e=>{let t=_e(rt/4n),n=_e(rt/2n),r=_e(rt*3n/4n),o=_e(rt*7n/8n),s=_e(rt*15n/16n),i=_e(rt*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;if(d(i))return i;let c=Jr({id:vm(e.id),name:J.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let u=ka({id:hm(e.id),name:J.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(u))return u;let m=ka({id:xm(e.id),name:J.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=Jr({id:ym(e.id),name:J.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=Jr({id:Im(e.id),name:J.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let b=Jr({id:bm(e.id),name:J.HISTORY,parentNodeId:e.id,rank:i.value,value:Em(e),readonly:!0,childRenderAxis:"vertical"});return d(b)?b:l("Ticket virtual nodes materialized",void 0)},Em=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>La(r,n.get(r.action)??[])).join(`
|
|
41
|
+
`)};var Cm=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[me,Qr]=Cm;var k=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Fa=e=>{let t=I.getNode(e);if(!t||!A(t)||t.isDeleted)return null;let n=Da(t);return d(n)?n:null},Nm=e=>{for(let t of e){let n=Fa(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Fa(r);if(o)return o}return null},Sm=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Am=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ts=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return Am(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Rm=e=>{he(t=>({...t,eventLog:[...t.eventLog,e]}))},Tm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?k("Invalid user ID format",e):l("Valid user",null)},wm=(e,t)=>{let n=Tm(e);if(d(n))return n;let r=[...new Set(Ts(e))];t||(r.forEach(s=>Sm(s,e)),Rm(e));let o=Nm(r);return o||null},Mm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=nr(o);if(d(s))return k(s.message,e);let i=I.createNode(o);return d(i)?k(i.message??"Failed to initialize workspace",e):Is(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=I.createNode(Q.workspace(t,n,r));return d(o)?k(o.message??"Failed to add workspace",e):Is(o.value)?l("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.board(t,n,r,o));return d(s)?k(s.message??"Unable to create board",e):Vr(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.swimlane(t,n,r,o));return d(s)?k(s.message??"Unable to create swimlane",e):Dt(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=I.createNode(Q.ticket(t,n,r,o));return d(s)?k(s.message??"Unable to create issue",e):A(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=I.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(J.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?k(i.message??`Unable to create field: ${n}`,e):Oe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.tag(t,n);return d(r)?k(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.untag(t,n);return d(r)?k(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.assign(t,n);return d(r)?k(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=I.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!A(o))return k("Can only close issues",e);let s=I.getNode(me);if(!s)return k("Unable to locate target swimlane",e);if(n!==s.id)return k("Close target must be closed swimlane",e);let i=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?k(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return k("Unable to locate issue",e);if(!A(o))return k("Can only reopen issues",e);let s=I.getNode(me);if(!s)return k("Unable to locate closed swimlane",e);if(n===s.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=I.getNode(r);if(!s)return k(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let i=I.updateNode({...s,rank:o});if(d(i))return k(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=I.createComment({id:t,issue:n,authorId:r,authorName:I.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?k(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=I.getComment(t);if(!o)return k("Unable to locate comment",e);if(o.issue!==n)return k("Comment does not belong to issue",e);let s=I.editComment(t,r);return d(s)?k(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=I.getComment(t);if(!r)return k("Unable to locate comment",e);if(r.issue!==n)return k("Comment does not belong to issue",e);let o=I.deleteComment(t);return d(o)?k(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=I.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?k(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=I.getAttachment(t);if(!r)return k("Unable to locate attachment",e);if(r.issue!==n)return k("Attachment does not belong to issue",e);let o=I.deleteAttachment(t);return d(o)?k(o.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return d(n)?k(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Bt(e,t=!1){let n=Mm[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=wm(e,t);return o||r}var Ut=e=>e.map(t=>Bt(t));import jm from"node:fs";import Vm from"node:path";import{decodeTime as Km,monotonicFactory as Gm}from"ulid";import{z as rr}from"zod";import Zr from"node:fs";import Ms from"node:path";import{decodeTime as km}from"ulid";import{z as ws}from"zod";var Pm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"];var Lm=new Set(Pm),Ba=e=>Lm.has(e),Ua=e=>({action:e.action,payload:e.payload});var Dm=ws.object({userId:ws.string().min(1).default("unknown"),userName:ws.string().min(1).default("unknown")}),Fm=e=>{let[t,n]=Ms.basename(e,".jsonl").split("."),r=Dm.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${Ms.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Bm=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Um=(e,t)=>t in e,Om=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),_m=e=>{let{userId:t,userName:n,...r}=e,o=Bm(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Um(r,s)?l("Decoded persisted event",Om({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Ps=e=>{let t=[],n=new Map;for(let r of e){let o=_m(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!Ba(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");oe.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return l("Decoded reconstructed events",t)},$m=e=>{if(!Zr.existsSync(e))return l("Event file missing",[]);let t=Fm(e);if(d(t))return a(t.message);let n=Zr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
42
|
+
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=ks(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function Ls(e){let t=Vn(e);if(!Zr.existsSync(t))return l("No events found",[]);let n=Zr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Ms.join(t,o)),r=[];for(let o of n){let s=$m(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",Hm(r))}function Et(e){let t=Ls(e);return d(t)?a(t.message):Ps(t.value)}function Oa(e,t){let n=Ls(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=Wm(n.value,t),s=Ps(r);if(d(s))return a(s.message);let i=Ps(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function _a(e=process.cwd()){let t=Ls(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Hm=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let b=n.get(f)??[];b.push(m),n.set(f,b)}for(let m of n.values())m.sort((p,f)=>p.id[0].localeCompare(f.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let f=n.get(p)??[];for(let b of f)s(b)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return!o.has(p)&&f!==null&&!t.has(f)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},Wm=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=km(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var Wa=1,$a=Gm(),zm=rr.tuple([rr.string().min(1),rr.string().min(1).nullable()]),qm=rr.looseObject({v:rr.literal(Wa),id:zm}),ks=e=>{let t=qm.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Ha=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Ym=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Xm=e=>e.trim().length>0&&e.length<=80,se=()=>{let{userName:e,userId:t}=K();return e?t?Ym(t)?Xm(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},on=({userId:e,userName:t})=>`${Ha(e)}.${Ha(t)}.jsonl`,Jm=(e,{userId:t,userName:n})=>{let r=on({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=Vm.join(Vn(e),r);return l("Successfully resolved event log path",s)},Qm=(e,t)=>{let n={[e.action]:e.payload,v:Wa,id:t};return ks(n)};function eo({event:e,rootDir:t}){try{let n=Di(t);if(d(n))return n;let r=Jm(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=_a(t);if(d(o))return a(o.message);let s=o.value?$a(Math.max(Date.now(),Km(o.value)+1)):$a(),i=Qm(Ua(e),[s,o.value]);return d(i)?a(i.message):(jm.appendFileSync(r.value,`${JSON.stringify(i.value)}
|
|
43
|
+
`,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function ja(e,t){let n=Bt(e);if(n.status!==Pt.Success)return n;let r=eo({event:e,rootDir:t});return d(r)?r:n}function B(e,t){if(e.length===0||!e[0])return a("No events provided");let n=ep(e[0],t);if(d(n))return n;let r=e.map(s=>ja(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):l("Materialization succeeded",r.map(s=>s.value))}var ep=(e,t)=>{if(e.action==="create.contributor")return l("Contributor already being created",void 0);if(I.getContributor(e.userId))return l("Contributor exists",void 0);let n={id:Zm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=ja(n,t);return d(r)?a(r.message):l("Contributor created",void 0)};var Va=e=>to(q(e),{at:"end"}),to=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Be(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Be(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Be(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=Ka(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Be(o?.rank,s.rank)):a("Sibling not found")}case"after":{let r=Ka(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Be(o.rank,s?.rank)):a("Sibling not found")}}},q=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ka=(e,t)=>e.findIndex(n=>n.id===t),Ga=(e,t,n={at:"end"})=>to(q(t).filter(r=>r.id!==e),n),sn=(e,t,n,r,o)=>{let s=Ga(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=Cs(e,r);if(d(i))return i;let c=B([i.value],o);if(d(c))return c;let u=Ga(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},Sn=(e,t,n)=>{let r=Va(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=Cs(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=Va(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var T={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=G(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||T.navigate({contextNode:o,selectedIndex:G(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=G(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;T.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>za(1),navigateToPreviousItem:()=>za(-1),navigateToNextContainer:()=>qa(1),navigateToPreviousContainer:()=>qa(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},za=e=>{let{selectedIndex:t,contextNode:n}=g(),r=G(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;T.navigate({selectedIndex:s,contextNode:n})},qa=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=G(o.id),i=s.findIndex(b=>b.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=G(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;T.navigate({contextNode:c,selectedIndex:f})};var Xa=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ja=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},tp=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&Oe(t)&&t.childRenderAxis==="vertical"},no=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=q(r.id);return T.navigate({contextNode:r,selectedIndex:Xa(t,o.length)}),!0},Qa=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return no(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=q(o.id).findIndex(c=>c.id===n.id);return i>=0?(T.navigate({contextNode:o,selectedIndex:i}),!0):Qa(o.id)},Ya=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Qa(n))return!0;n=t[n]?.parentNodeId}return!1},np=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Za=e=>{let{nodes:t,rootNodeId:n}=g();if(tp(e.contextNodeId)&&no(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(np(e.selectedNodeId)&&e.selectedNodeId&&Ya(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(no(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&no(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Ya(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=q(r.id);return T.navigate({contextNode:r,selectedIndex:Xa(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};import{monotonicFactory as rp,ulid as Ct}from"ulid";var or=rp();function op(){let e=Je();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=G(n.id),[o]=r?G(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?l("Resolved boot nav target",{contextNode:n,selectedIndex:0}):l("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function sp(){let e=op();return d(e)?e:T.navigate(e.value)}function ed({userId:e,userName:t}){let n=or(),r=or(),o=or(),s=or(),i=or(),c=Be(void 0,void 0);if(d(c))return c;let u=Be(void 0,void 0);if(d(u))return u;let m=Be(u.value,void 0);if(d(m))return m;let p=Be(void 0,void 0);if(d(p))return p;let f=Be(p.value,void 0);if(d(f))return f;let b=Be(f.value,void 0);if(d(b))return b;let N=Be(void 0,void 0);return d(N)?N:l("Created default events",[{id:Ct(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ct(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:b.value}},{id:Ct(),userId:e,userName:t,action:"add.board",payload:{id:Qr,name:"Closed",parent:n,rank:m.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:me,name:"Closed",parent:Qr,rank:N.value}},{id:Ct(),userId:e,userName:t,action:"lock.node",payload:{id:Qr}},{id:Ct(),userId:e,userName:t,action:"lock.node",payload:{id:me}}])}function an(e){if(!e.length){let r=Q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=nr(r);return d(o)?o:(E({hasProjectDefinition:!1,mode:y.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Ut(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
43
44
|
${n.map(r=>r.message).join(`
|
|
44
|
-
`)}`):(ym(),C({hasProjectDefinition:!0}),l("State booted successfully",null))}var Qt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Or=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},K=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var tt=null,_r=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!tt,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),tt)return logger.debug("[sync] syncAndReloadState joining existing promise"),tt;logger.debug("[sync] syncAndReloadState creating promise"),tt=hm();try{let e=await tt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),d(e)&&f().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({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}),tt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),tt=null}},hm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=Ma();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(tt)return tt;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:f().syncStatus});let n=Yt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await $r({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),He(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",ft(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ma();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:i.message,syncStatus:f().syncStatus}),i;let c=Ra(),u=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=K("bootStateFromEventLog",Jt(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("restoreNavigationAnchor",Ta(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),l("Synced",!0))},Ma=()=>f().mode===g.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var hn=3e3,Pa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<hn?null:t},La=0,ys,hs=!1,jn=!1,xs=()=>{if(hs)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},xm=()=>{let e=H().autoSyncIntervalMs??1e4,t=Date.now()-La;return Math.max(0,e-t)},ka=()=>{ys||(ys=setTimeout(async()=>{if(ys=void 0,!!xn()){if(xs()){jn=!0;return}jn=!1,await Im()}},xm()))},Im=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!xn())return a("Cannot auto-sync before state is initialized");if(xs())return jn=!0,a("Sync already in progress");hs=!0,La=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await _r()}finally{hs=!1,jn&&ka()}},Wr=()=>{xn()&&(jn=!0,!xs()&&ka())};var wt=()=>{let e=H(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Da=()=>{let e=Ke(process.cwd());if(d(e))return!1;let t=Et(e.value);return te(t)},Fa=e=>e===!0?"on":e===!1?"off":null,Ba=e=>e==="on"?!0:e==="off"?!1:null;var bm=e=>e.props.tags??[],Cm=e=>e.props.assignees??[],Vn=e=>bm(e).map(t=>b.getTag(t)).filter(t=>!!t),Gn=e=>Cm(e).map(t=>b.getContributor(t)).filter(t=>!!t),Hr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Vn(n))},jr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Gn(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Em=/^(\d+)(h|d|w|mo|y)$/,Sm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Nm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Rm=(e,t=new Date)=>{let n=e.match(Em);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Am=e=>{let t=e.match(Sm);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,v=i?Number(i):0;return Nm({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Zt=e=>{let t=e.trim().toLowerCase();return Rm(t)??Am(t)};var Ua=/^(\d+)(s|m)?$/,Vr=e=>{let t=e.trim().toLowerCase().match(Ua);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Gr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Ua.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Oa=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Tm=[{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}],Is=(e=Tm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var wm=["BOARD","TICKET","SWIMLANE","COMMENT"],ae={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},we={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Mm=[ae.EDITOR,ae.VIEW,ae.USERNAME,ae.AUTOSYNC,ae.SYNC_DEBOUNCE_MS,ae.LOG_LEVEL],Pm=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[we.TITLE,we.DESCRIPTION];case"BOARD":case"SWIMLANE":return[we.TITLE];case"COMMENT":return[we.COMMENT];default:return[]}},Cs=[String(hn),"5000","15000","30000","60000"],Wa=["10s","20s","30s","45s"],en=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],zr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],bs=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],_a=[x.FILTER,x.PEEK,x.REPLAY],Lm={WORKSPACE:[...en,...zr],BOARD:[..._a,...en,...zr],SWIMLANE:[..._a,...en,...zr],TICKET:[...en,...zr,...bs],FIELD:[...en,...bs],FIELD_LIST:[...en,...bs],TEXT:[...en],COMMENT:[x.EDIT,x.DELETE]},km=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ha=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),$a=e=>e.parentNodeId===ce,Dm=({selectedNode:e,breadCrumb:t})=>{let n=Pm(e?.context);return Ha({breadCrumb:t,selectedNode:e})?n.includes(we.DESCRIPTION)?n:[...n,we.DESCRIPTION]:n},Fm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=wt();if(!r)return[x.HELP,x.CONFIG];if(!Da())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG];let o=e?.context,s=o&&wm.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Lm[u]:[]))],c=Ha({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&Vn(c).length>0):u===x.UNASSIGN?!!(c&&Gn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&$a(c)):u===x.CLOSE_ISSUE?!!(c&&!$a(c)):!0)},le=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Fm({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Is(),"now","prev","next"],[x.REPLAY]:[...Is()],[x.EDIT]:Dm({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(fn),...b.getExistingTags()])],[x.UNTAG]:[...Hr()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...jr()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:km(s),[x.CONFIG]:[...Mm],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Ka from"chalk";var ja=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")};import Va from"chalk";var J=e=>Va.dim(e),ve=e=>Va.hex(y.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(i))].sort((v,I)=>Tr(v)-Tr(I)).slice(0,r).map(v=>wr(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var Mt={None:"none",Invalid:"invalid",Valid:"valid"};var In=140,Bm=["BOARD","TICKET","SWIMLANE"],Ga=()=>{let e=f().selectedNode;if(!e?.context)return F({message:J("Missing target context")});if(Bm.includes(e.context))return j();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ne(t?.parentNodeId??"","comments"))return j()}return F({message:J("Command not available in this context")})},ne="<ENTER> to confirm",j=(e="",t=[])=>({message:J(e),validity:Mt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:Mt.Invalid,message:e,completionWordList:t}),qr=e=>e.length===0,za=(e,t)=>{let n=be(f().breadCrumb,"BOARD");if(d(n))return F({message:ve("Command is not applicable in this context")});let r=Lr(n.value.id);return d(r)?F({message:ve(`Unable to ${t}: board id is not a valid ULID`)}):Oa({date:e,horizonDate:r.value})?null:F({message:ve(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Kr=e=>` ${Ka.hex("#000").bgHex(ie(e))(` ${e} `)} `,Es=({modifier:e})=>{let t="confirm";return e===t?j(ne):F({message:qr(e)?J("if you are certain, enter ")+wr(t):"",completionWordList:[t]})},Um=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:J(n)}):j():F({message:qr(r)?t:"",completionWordList:[...e]}),tn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>qr(n)&&qr(r)?F({message:e,completionWordList:[]}):j(t??ne),Om=({modifier:e,inputString:t})=>{let n=le(x.CONFIG);if(!n.includes(e))return F({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ae.EDITOR:{let r=[...ja];return t.trim()?r.includes(t.trim())?j(ne):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ne):F({message:ye({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.USERNAME:return t.trim()?j(ne):F({message:ve("Enter a user name. Saved in ")+Ka.bgBlack("~/.epiq-global/config.json")});case ae.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?j(ne):F({message:ye({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ae.AUTOSYNC:{let r=["on","off"],o=H().autoSync;if(!r.includes(t.trim())){let s=Fa(o);return F({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ne)}case ae.SYNC_DEBOUNCE_MS:{let r=H().autoSyncIntervalMs,o=Pa(t);if(!t.trim()||o===null||o<hn){let s=ye({prefix:" examples: ",wordList:Cs,minLengthForHints:0,inputString:t});return F({message:ve(`provide duration above ${hn}ms. current duration: ${r}ms.`)+s,completionWordList:Cs})}return j(ne)}default:return F({message:ve("Unknown config option"),completionWordList:n})}},_m=({modifier:e,inputString:t})=>{let n=le(x.EDIT);if(!n.length)return F({message:ve("Command not available in this context")});if(!n.includes(e)){let r=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||ve("Unknown edit option"),completionWordList:n})}switch(e){case we.COMMENT:return t.trim()?j(ne):F({message:J("write a comment...")});case we.TITLE:return j(ne);case we.DESCRIPTION:{let{preferredEditor:r}=H();return r?j(J("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:ve("Unknown edit option"),completionWordList:n})}},$m={[x.EXPORT]:()=>j(ne+J(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return j(ne);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Zt(r);if(!r||!o)return F(n);let s=za(o,"peek");return s||j(ne)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Gr(e.modifier,e.inputString),r={message:J("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Zt(t);if(!t||!o)return F(r);let s=za(o,"replay");return s||(n&&Vr(n)===null?F({message:ve("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):j("<ENTER> to replay board history",n?Wa:[]))},[x.EXIT]:()=>j(ne+J(" and exit the application")),[x.INIT]:()=>j(ne),[x.PALETTE]:()=>j(ne),[x.FILTER]:e=>{if(e.modifier==="clear")return j(ne);let t=s=>le(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:ye({wordList:le(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:le(x.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:ye({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):j():F({message:ye({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=le(x.NONE);return F({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Um({list:le(x.NEW),hint:ye({wordList:le(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ne),[x.EDIT]:_m,[x.COMMENT]:e=>{let t=tn({hint:J(`write a comment (max ${In} char)...`),onOk:J(`(${e.inputString.length}/${In})`)})(e);return t.validity===Mt.Invalid?t:e.inputString.length>In?j(ve("max input exceeded")):t},[x.CONFIG]:Om,[x.DELETE]:e=>{let t=Ga();return t.validity==="invalid"?t:Es(e)},[x.CLOSE_ISSUE]:e=>Es(e),[x.RE_OPEN_ISSUE]:e=>Es(e),[x.MOVE]:e=>{let t=Ga();return t.validity==="invalid"?t:tn({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:le(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(Kr).join("");return tn({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Hr();if(d(t))return F({message:ve("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Kr).slice(0,10);return n.length?tn({hint:J(" ... ")+n.join("")})(e):F({message:ve("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(Kr).slice(0,10);return tn({hint:J("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=jr();if(d(t))return F({message:ve("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Kr).slice(0,10);return n.length?tn({hint:J("remove assignee... ")+n.join("")})(e):F({message:ve("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ne),[x.COFFEE]:e=>{let{modifier:t}=e,n=le(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:J("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):tn({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)}},qa=Object.fromEntries(Object.entries($m).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Yr=["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 Wm=3,Hm=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"]),jm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Vm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Wm&&!Hm.has(t)&&!/^\d+$/.test(t)),Gm=e=>{let t=new Map;for(let s of jm(e))for(let i of Vm(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=Yr.filter(s=>!r.has(s));return[...n,...o]},Ya=Yr,Xa=-1,Ja=()=>{let e=We();if(d(e))return Yr;let t=e.value,n=t.eventLog.length;return n!==Xa&&(Ya=Gm(t),Xa=n),Ya};var Qa=e=>Object.values(x).includes(e),Za=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=qa[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?le(n):m?Ja():[],{mode:v}=f(),I=v===g.COMMAND_LINE?i??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?qi(e,S):{hint:"",hints:[],remainder:"",overlap:0}}};var ed=e=>{let t=e.trimStart(),n=Km(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=qm(e),c=Qa(r)?r:null,u=c!==null,m=r!=="",p=c?le(c)??[]:[],v=c&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let S=s?"":i,N=zm(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:I,inputToMatch:S,inputString:N}},zm=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Km=e=>e.trim()?e.trim().split(/\s+/):[],qm=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Ym}from"react";var bn=e=>e===Ss||e===":",Ss=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Mt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ns=new Set,td=()=>{for(let e of Ns)e()},Rs=e=>(Ns.add(e),()=>Ns.delete(e)),nt=e=>{let n=e(he),r=ed(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:Za(r,o)},td()},zn=({message:e,status:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,td(),l(e,null)},As=e=>{nt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ts=e=>{nt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&bn(n[o-1]);)o--;for(;o>0&&!bn(n[o-1]);)o--}else{for(;o<n.length&&!bn(n[o]);)o++;for(;o<n.length&&bn(n[o]);)o++}return{...t,cursorPosition:o}})},nd=()=>{nt(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}})},rd=()=>{nt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&bn(t[r-1]);)r--;for(;r>0&&!bn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Xr=e=>{nt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},od=()=>{nt(e=>({...e,commandIsPending:!0}))},_=e=>{nt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},sd=({addToHistory:e=!0})=>{nt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},id=()=>{nt(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}})},ad=()=>{nt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>he,dd=()=>Ym(Rs,q,q),cd=()=>{let[e,...t]=he.value.split(Ss);return t.join(Ss).trim()};var h={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Xm(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Jm(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Qm(e,t,n){let r=f().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function ld(e,t){let n=q();if(e.sequence==="?"&&t!==g.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==g.COMMAND_LINE)return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return Wi(e,n.value);if(t===g.PALETTE)return Hi(e,n.value);let r=Xm(e)||Jm(e);if(r)return Zm(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return H().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function Zm(e,t){let n=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return Qm(f().contextNode.childRenderAxis,e,n)}var Jr=e=>{let{context:t}=f().contextNode;if(!t)return L.None;switch(e){case x.EXIT:return L.Exit;case x.EXPORT:return L.Export;case x.COFFEE:return L.Coffee;case x.INIT:return L.Init;case x.DELETE:return L.Delete;case x.EDIT:return L.Edit;case x.COMMENT:return L.Comment;case x.HELP:return L.ViewHelp;case x.RE_OPEN_ISSUE:return L.ReopenIssue;case x.CLOSE_ISSUE:return L.CloseIssue;case x.TAG:return L.TagTicket;case x.UNTAG:return L.UntagTicket;case x.ASSIGN:return L.AssignUserToTicket;case x.UNASSIGN:return L.UnassignUserFromTicket;case x.NEW:return L.NewItem;case x.FILTER:return L.Filter;case x.MOVE:return L.Move;case x.PEEK:return L.Peek;case x.REPLAY:return L.Replay;case x.CONFIG:return L.Config;case x.SYNC:return L.Sync;default:return L.None}},L={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as xe}from"ulid";import wd from"node:fs";import Dp from"node:path";import Fp from"react";import{Box as Lp}from"ink";import oo from"react";import gp from"chalk";import{Box as Ms,Text as vp}from"ink";import ot from"react";import{Text as ud}from"ink";import md,{useEffect as pd,useState as ep}from"react";var fd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ce=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=fd[n]??fd.default,[o,s]=ep(0);if(pd(()=>{s(0)},[r]),pd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return md.createElement(ud,null,t);let i=r[o]??r[0]??t;return md.createElement(ud,{color:y.accent,dimColor:o===1},i)};import{Box as ws,Text as tp}from"ink";import Qr from"react";var rt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,I=e.slice(p,v),S=e.length>c,N=s,T=S?Math.max(1,Math.floor(c/e.length*N)):N,k=Math.max(0,N-T),O=Math.max(1,e.length-c),V=S?Math.floor(p/O*k):0;return Qr.createElement(ws,{flexDirection:"row",height:s,width:"100%"},Qr.createElement(ws,{flexDirection:"column",flexGrow:1,height:s},I),Qr.createElement(ws,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((R,A)=>Qr.createElement(tp,{key:A,color:S&&A>=V&&A<V+T?y.accent:y.secondary},S?"\u2502":" "))))};import{Box as eo,Text as pp}from"ink";import nn from"react";import{Text as np}from"ink";import rp from"react";var op=e=>e.toLowerCase().trim(),sp=(e,t=fn)=>{let n=op(e);return t[n]?t[n]:_n(n)},Pt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return rp.createElement(np,{underline:t,color:sp(n.name)},"@"+n.name)};import{Text as ip}from"ink";import ap from"react";var Cn=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return ap.createElement(ip,{underline:t,backgroundColor:ie(n.name),color:y.secondary}," "+n.name+" ")};import{useEffect as dp,useState as cp}from"react";var lp=80,gd=1400,Zr=new Set,Kn=null,up=e=>(Zr.add(e),Kn||(Kn=setInterval(()=>{for(let t of Zr)t()},lp)),()=>{Zr.delete(e),Zr.size===0&&Kn&&(clearInterval(Kn),Kn=null)}),mp=()=>{let e=Date.now()%gd/gd;return e<.5?e*2:(1-e)*2},En=e=>{let[,t]=cp(0);return dp(()=>{if(e)return up(()=>t(n=>n+1))},[e]),Ar(mp())};var vd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=En(r),s=e-14,i=mn(Rt(t.title),s),c=Vn(t),u=Gn(t);return nn.createElement(eo,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},nn.createElement(eo,{borderBottom:!0},nn.createElement(eo,{paddingLeft:1,flexDirection:"column"},nn.createElement(pp,{color:y.primary},i))),nn.createElement(eo,{flexDirection:"row",paddingLeft:1},c.map(m=>nn.createElement(Cn,{key:m.id,id:m.id})),u.map(m=>nn.createElement(Pt,{key:m.id,id:m.id}))))};import{Box as rn,Text as qn}from"ink";import Me from"react";var fp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,yd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=En(r),c=(t.props.tags??[]).map(R=>b.getTag(R)).filter(R=>!!R),u=(t.props.assignees??[]).map(R=>b.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),v=u.length*(2+m),I=c.map(R=>Me.createElement(rn,{key:R.id,paddingRight:m},Me.createElement(qn,{color:ie(R.name)},"\u25A0"))),S=u.map(R=>Me.createElement(rn,{key:R.id,paddingRight:m},Me.createElement(qn,{color:_n(R.name)},"@"+R.name.at(0)))),N=r?i:n?y.accent:s===g.MOVE?y.secondary:y.primary,T=4,k=b.getCommentsByIssue(t.id),O=k.length?String(k.length).length+2+m:0,V=k.length?Me.createElement(rn,{paddingRight:m},Me.createElement(qn,{color:y.accent},"[",k.length,"]")):null;return Me.createElement(rn,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(rn,null,Me.createElement(rn,{width:T},n?Me.createElement(Ce,{isSelected:n}):Me.createElement(qn,{color:"gray",dimColor:!0},o+1)),Me.createElement(qn,{wrap:"truncate",color:N},fp(t.title,e-p-v-O-18))),Me.createElement(rn,null,I,S,V))};var yp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=$(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,I=v?.has(e.id)??!1,S=En(I),N=`${e.title} ${gp.hex(y.secondary2).dim("("+p.length+")")}`,T=3,k=o?1:4,O=r-T-(o?2:1),V=ot.createElement(Ms,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ot.createElement(Ce,{isSelected:t}),ot.createElement(vp,{bold:!0,color:I?S:t?y.accent:y.primary},N," ",e.readonly?"\u{1F512}":"")),R=(A,G)=>{let Re=s&&i===G;if(!w(A))return null;let Ae=v?.has(A.id)??!1;return o?ot.createElement(yd,{key:A.id,index:G,width:n,ticket:A,isSelected:Re,isFlashing:Ae,mode:c}):ot.createElement(vd,{key:A.id,width:n,ticket:A,isSelected:Re,isFlashing:Ae})};return ot.createElement(Ms,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},V,ot.createElement(Ms,{padding:o?1:0},p.length>0&&ot.createElement(rt,{selectedIndex:i,height:O,itemHeight:k},p.map(R)),ot.createElement(Ce,{isSelected:s&&i===-1})))},hd=ot.memo(yp);import{Box as Yn,Text as Ad}from"ink";import Pe,{useMemo as ro}from"react";var xd=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},Id=(e,t,n)=>Q.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as Lt,Text as vt}from"ink";import ue,{useEffect as hp,useMemo as xp,useRef as Ip}from"react";import{decodeTime as Ps}from"ulid";var bp=e=>Ne(e,"comments"),Cp=e=>b.getCommentsByIssue(e.id).sort((t,n)=>Ps(t.id)-Ps(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),bd=e=>{for(let t of e)b.deleteNode(t.id)},Ep=(e,t)=>{let n=b.getNode(bp(e.id));if(!n||!Qe(n))return[];let r=t.map((o,s)=>Id(o,s,n.id)).map(b.createNode).filter(te).map(({value:o})=>o).filter(Un);return t.length>0&&f().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Sp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Cd({ticket:e,width:t,height:n}){let r=xp(()=>Cp(e),[e]),o=Ip([]);hp(()=>(bd(o.current),o.current=Ep(e,r),()=>{bd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=$(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?ue.createElement(Lt,{flexDirection:"column",width:t,height:n,padding:1},ue.createElement(vt,{color:y.primary},"No comments yet."),ue.createElement(Lt,{paddingTop:1},ue.createElement(vt,{color:y.primary},"Use"),ue.createElement(vt,{color:y.accent}," :comment "),ue.createElement(vt,{color:y.primary},"to add the first one."))):ue.createElement(Lt,{flexDirection:"column",width:t,height:n},ue.createElement(Lt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ue.createElement(vt,{color:y.secondary2},"Comments (",r.length,") ")),ue.createElement(rt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let v=p===s;return ue.createElement(Lt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ue.createElement(Lt,{flexDirection:"row",paddingBottom:1},ue.createElement(vt,{color:y.accent},v?"\u276F ":" "),ue.createElement(Lt,{paddingLeft:1},ue.createElement(vt,{color:y.secondary2},`#${p+1} `),ue.createElement(Pt,{id:m.authorId}),ue.createElement(vt,{color:y.secondary2}," "+Mr(Ps(m.id))))),ue.createElement(Lt,{paddingLeft:3,paddingBottom:1},ue.createElement(vt,{color:y.primary},Sp(m.md,u))))})))}import{Box as to,Text as Np}from"ink";import yt from"react";var Ed=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=$(),{title:o}=t,s=t.parentNodeId?b.getNode(t.parentNodeId):void 0,i=s&&w(s)?o===se.ASSIGNEES?s.props.assignees??[]:o===se.TAGS?s.props.tags??[]:[]:[];return yt.createElement(to,{alignItems:"center",paddingTop:1},yt.createElement(to,{minWidth:12},yt.createElement(Ce,{isSelected:n}),yt.createElement(Np,{color:n?y.accent:y.secondary2},o,":")),yt.createElement(to,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return yt.createElement(to,{key:`${o}-${c}`,paddingRight:2,minHeight:1},yt.createElement(Ce,{isSelected:m}),o===se.ASSIGNEES?yt.createElement(Pt,{isSelected:m,id:c}):o===se.TAGS?yt.createElement(Cn,{isSelected:m,id:c}):null)})))};import{Box as no,Text as Ls}from"ink";import ht,{useEffect as Rp,useMemo as Sd}from"react";var Ap="\u2029",Nd=(e,t)=>`${e}::inline-line::${t}`,ks=new Map,Rd=e=>{let t=ks.get(e)??[];ks.delete(e);for(let n of t)b.deleteNode(n)},Tp=(e,t)=>{Rd(e);let n=[];t.forEach((r,o)=>{let s=$e(BigInt(o+1));if(!te(s))return;let i=b.createNode(Q.text({id:Nd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),ks.set(e,n)},Ds=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=$(),u=Sd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Sd(()=>u.join("\0"),[u]);Rp(()=>(Tp(e,u),()=>{Rd(e)}),[e,m]);let p=I=>String(I).replace(/\r?\n/g,""),v=u.map((I,S)=>{let N=c.id===e&&i===S;return ht.createElement(no,{key:Nd(e,S)},ht.createElement(Ls,{color:N?y.primary:y.secondary2,dimColor:!N},`${S+1} `.padStart(5,"\xA0")),ht.createElement(Ls,{backgroundColor:N?"gray":void 0},p(I.length?mn(I,s-10):Ap)))});return ht.createElement(no,{flexDirection:"column",paddingTop:1},ht.createElement(no,null,ht.createElement(Ce,{isSelected:o}),ht.createElement(Ls,{color:o?y.accent:y.secondary2},t)),ht.createElement(no,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},ht.createElement(rt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},v)))};var wp=e=>Ne(e,"description"),Mp=e=>Ne(e,"comments"),Pp=e=>Ne(e,"history"),Td=({ticket:e,height:t})=>{let n=ro(()=>xd(e),[e]),{selectedIndex:r,contextNode:o}=$(),s=process.stdout.columns||120,i=ro(()=>wp(e.id),[e.id]),c=ro(()=>Mp(e.id),[e.id]),u=ro(()=>Pp(e.id),[e.id]),m=o.id===e.id,p=o.id===c||o.parentNodeId===c,v=o.id===u||o.parentNodeId===u,I=W(e.id);if(p){let A=t-3;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Cd,{ticket:e,width:s,height:A}))}if(v){let R=b.getNode(u),A=R&&Qe(R)?R.props.value??"":"",Re=t-3;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?Pe.createElement(Ds,{id:R.id,label:"Event log",text:A,selected:!1,maxWidth:s,height:Re}):null)}let S=I.reduce((R,A)=>Bn(A)||A.id===c||A.id===u?R+1:R,0),N=2,T=3,k=S,O=t-T-k-N,V=(R,A)=>R.id===i?Pe.createElement(Ds,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:A,maxWidth:s,height:O}):Bn(R)?Pe.createElement(Ed,{key:R.id,parent:R,selected:A,selectedIndex:r}):R.id===c?Pe.createElement(Yn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Ad,{backgroundColor:y.secondary,color:A?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):R.id===u?Pe.createElement(Yn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Ad,{backgroundColor:y.secondary,color:A?y.accent:y.primary}," History \u203A\u203A ")):null;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((R,A)=>V(R,m&&r===A)))};var kp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:r.find(k=>k.context===P.TICKET),I=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),N=Math.min(S,I),T=s==="dense";return oo.createElement(Lp,{flexDirection:"row",height:i},p&&e.map((k,O)=>{let V=t.id===k.id,R=V?n:-1,A=t.context===P.BOARD&&n===O;return oo.createElement(hd,{key:k.id,height:i,width:N,swimlane:k,isSelected:A,isDense:T,isFocused:V,listSelectedIndex:R,mode:o})}),m&&v&&oo.createElement(Td,{height:i,ticket:v}))},so=oo.memo(kp);import{render as Bp}from"ink";import{Writable as Up}from"node:stream";var Xn=e=>String(e).padStart(2,"0"),Op=e=>{let t=e.getUTCFullYear(),n=Xn(e.getUTCMonth()+1),r=Xn(e.getUTCDate()),o=Xn(e.getUTCHours()),s=Xn(e.getUTCMinutes()),i=Xn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},_p=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",$p=async(e,{width:t,height:n})=>{let r="",o=new Up({write(i,c,u){let m=Wp(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Bp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},Wp=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Md=async()=>{let{viewMode:e}=H(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),i=r.find(O=>O.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await $p(Fp.createElement(so,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(O=>O!==void 0&&Nt(O)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=fr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,I=Op(v),S=`board_${_p(i.title)}_${I}.md`,N=pi(p.value);wd.mkdirSync(N,{recursive:!0});let T=Dp.join(N,S),k=`# Board - ${i.title}
|
|
45
|
-
Date: ${v.toISOString()}
|
|
45
|
+
`)}`):(sp(),E({hasProjectDefinition:!0}),l("State booted successfully",null))}var dn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),ro=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},X=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ut=null,oo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ut,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),ut)return logger.debug("[sync] syncAndReloadState joining existing promise"),ut;logger.debug("[sync] syncAndReloadState creating promise"),ut=ip();try{let e=await ut;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),d(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),ut||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),ut=null}},ip=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=td();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(ut)return ut;logger.debug("[sync] syncAndReloadState:start");let t=X("resolveActorId",se());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=on(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=X("syncEpiqWithRemote",await so({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Qe(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=X("loadMergedEvents",Et(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=td();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:i.message,syncStatus:g().syncStatus}),i;let c=Ja(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=X("bootStateFromEventLog",an(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=X("restoreNavigationAnchor",Za(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),d(m)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},td=()=>g().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var An=3e3,nd=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<An?null:t},rd=0,Ds,Fs=!1,sr=!1,Bs=()=>{if(Fs)return!0;let e=Je();return d(e)?!1:e.value.syncStatus.status==="syncing"},ap=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-rd;return Math.max(0,e-t)},od=()=>{Ds||(Ds=setTimeout(async()=>{if(Ds=void 0,!!Rn()){if(Bs()){sr=!0;return}sr=!1,await dp()}},ap()))},dp=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Rn())return a("Cannot auto-sync before state is initialized");if(Bs())return sr=!0,a("Sync already in progress");Fs=!0,rd=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await oo()}finally{Fs=!1,sr&&od()}},io=()=>{Rn()&&(sr=!0,!Bs()&&od())};var Ot=()=>{let e=K(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},sd=()=>{let e=Ye(process.cwd());if(d(e))return!1;let t=Lt(e.value);return te(t)},id=e=>e===!0?"on":e===!1?"off":null,ad=e=>e==="on"?!0:e==="off"?!1:null;var cp=e=>e.props.tags??[],lp=e=>e.props.assignees??[],_t=e=>cp(e).map(t=>I.getTag(t)).filter(t=>!!t),$t=e=>lp(e).map(t=>I.getContributor(t)).filter(t=>!!t),ao=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",_t(n))},co=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!A(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",$t(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var up=/^(\d+)(h|d|w|mo|y)$/,mp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,pp=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},fp=(e,t=new Date)=>{let n=e.match(up);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},gp=e=>{let t=e.match(mp);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return pp({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},cn=e=>{let t=e.trim().toLowerCase();return fp(t)??gp(t)};var dd=/^(\d+)(s|m)?$/,lo=e=>{let t=e.trim().toLowerCase().match(dd);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},uo=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&dd.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},cd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,yp=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Us=(e=yp)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var vp=["BOARD","TICKET","SWIMLANE","COMMENT"],ne={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},$e={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},pe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},hp=[ne.EDITOR,ne.VIEW,ne.USERNAME,ne.AUTOSYNC,ne.SYNC_DEBOUNCE_MS,ne.ATTACHMENT_MAX_KB,ne.LOG_LEVEL],xp=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[$e.TITLE,$e.DESCRIPTION];case"BOARD":case"SWIMLANE":return[$e.TITLE];case"COMMENT":return[$e.COMMENT];default:return[]}},_s=[String(An),"5000","15000","30000","60000"],$s=["250","500","1000"],md=["10s","20s","30s","45s"],ln=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],mo=[x.NEW,x.EDIT,x.DELETE,x.MOVE],Os=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],ld=[x.FILTER,x.PEEK,x.REPLAY],bp={WORKSPACE:[...ln,...mo],BOARD:[...ld,...ln,...mo],SWIMLANE:[...ld,...ln,...mo],TICKET:[...ln,...mo,...Os],FIELD:[...ln,...Os],FIELD_LIST:[...ln,...Os],TEXT:[...ln],COMMENT:[x.EDIT,x.DELETE,x.YANK]},Ip=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ir=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&A(n)),ud=e=>e.parentNodeId===me,Ep=({selectedNode:e,breadCrumb:t})=>{let n=xp(e?.context);return ir({breadCrumb:t,selectedNode:e})?n.includes($e.DESCRIPTION)?n:[...n,$e.DESCRIPTION]:n},Cp=({selectedNode:e,breadCrumb:t})=>{let n=ir({breadCrumb:t,selectedNode:e});return n?[pe.REF,pe.TITLE,...n.props?.description?.trim()?[pe.DESCRIPTION]:[],..._t(n).length>0?[pe.TAGS]:[],...$t(n).length>0?[pe.ASSIGNEES]:[]]:e?[pe.REF,pe.TITLE]:[]},Np=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ot();if(!r)return[x.HELP,x.CONFIG];if(!sd())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let o=e?.context,s=o&&vp.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?bp[u]:[]))],c=ir({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(c??e):u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&_t(c).length>0):u===x.UNASSIGN?!!(c&&$t(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&ud(c)):u===x.CLOSE_ISSUE?!!(c&&!ud(c)):!0)},ie=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Np({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Us(),"now","prev","next"],[x.REPLAY]:[...Us()],[x.EDIT]:Ep({selectedNode:n,breadCrumb:o}),[x.YANK]:Cp({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(In),...I.getExistingTags()])],[x.UNTAG]:[...ao()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...co()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:I.getExistingAssignees(),[x.NEW]:Ip(s),[x.CONFIG]:[...hp],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Pd from"chalk";var pd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Le=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")},fd=["png","jpg","gif","webp"];import $p from"zod";import Lp from"node:os";import hd from"node:path";import{z as Nt}from"zod";import{accessSync as Sp,copyFileSync as Ap,existsSync as po,mkdirSync as gd,readdirSync as yd,readFileSync as Rp,renameSync as Tp,rmSync as wp,statSync as vd,unlinkSync as Mp,writeFileSync as Pp}from"node:fs";import Tn from"node:path";var Hs=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",He={writeToFile:(e,t)=>{try{let n=Tn.dirname(e);po(n)||gd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Pp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Rp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=He.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return po(e)&&vd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Sp(e),!0}catch{return!1}},mkDir:e=>gd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Tn.parse(t);for(;;){let r=Tn.join(t,e);try{if(po(r)&&vd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Tn.dirname(t)}return null},readFirstJSON(e){try{if(!He.dirExists(e))return null;let t=yd(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Tn.join(e,t);return He.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return He.dirExists(e)?yd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Mp(e)}catch(t){(!Hs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{wp(e,{recursive:!0,force:!0})}catch(t){(!Hs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Tn.dirname(t)),!n?.overwrite&&po(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Tp(e,t)}catch(r){if(Hs(r)&&r.code==="EXDEV"){Ap(e,t),this.rmFile(e);return}throw r}}};var kp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},xd=Nt.object({logLevel:Nt.enum(["info","error","debug"]),preferredEditor:Nt.string().optional(),userName:Nt.string().optional(),userId:Nt.string().optional(),autoSync:Nt.boolean().nullable().optional(),autoSyncDebounceMs:Nt.number().optional(),attachmentMaxKb:Nt.number().optional(),viewMode:Nt.enum(["dense","wide"]).optional()}).partial(),Dp="config.json",bd=()=>hd.join(Lp.homedir(),qe),Ws=()=>hd.join(bd(),Dp),js=()=>{try{return He.mkDir(bd()),l(`Ensured ~/${qe} exists`,null)}catch{return a(`Unable to create ~/${qe}`)}},Fp=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${qe}/config.json JSON`)}let n=xd.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${qe}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ar=()=>{let e=js();if(d(e))return a(e.message);let t=Ws(),n=He.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Fp(n)},Id=e=>{let t=js();if(d(t))return a(t.message);let n=xd.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ws();try{return He.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
46
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${qe}/config.json`)}},Ze=e=>{let t=ar();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Id(n)},wn=()=>{let e=Ws(),t=js();if(d(t))return a(`Unable to create ~/${qe}`);if(!(He.readFile(e)!==null)){let b=Id(kp);if(d(b))throw new Error(`Unable to create ~/${qe}/config.json`)}let r=ar();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value;return!s||!i?a(`User name or ID not configured in ~/${qe}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import Bp from"node:crypto";import dr from"node:fs";import Ed from"node:path";var mt=500,Up=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Mn=(e,t)=>`${e}.${t}`,Op=e=>Up.test(e),Cd=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?l("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?l("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${fd.join(", ")}`),Nd=e=>Bp.createHash("sha256").update(e).digest("hex"),_p=(e,t=mt)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Cd(e);return d(n)?n:l("Validated attachment data",{hash:Nd(e),ext:n.value,bytes:e.length})},Sd=(e,t,n=mt)=>{let r=_p(t,n);if(d(r))return r;let o=Kn(e),s=Ed.join(o,Mn(r.value.hash,r.value.ext));try{dr.existsSync(s)||(dr.mkdirSync(o,{recursive:!0}),dr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",r.value)},Ad=(e,t,n=mt)=>{if(!Op(t))return a("Invalid attachment file name");let r=Ed.join(Kn(e),t);if(!dr.existsSync(r))return a("Attachment blob not found");let o;try{o=dr.readFileSync(r)}catch(u){return a(`Unable to read attachment blob: ${u instanceof Error?u.message:String(u)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(Nd(o)!==s)return a("Attachment blob does not match its content hash");let c=Cd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):l("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var cr=50,lr=5e3,Rd=()=>{let e=Y().commandMeta.inputString,t=$p.coerce.number().int().min(cr).max(lr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${cr}-${lr} KB (default ${mt})`);let n=Ze({attachmentMaxKb:t.data});return d(n)?n:(Fe({attachmentMaxKb:t.data}),E({mode:y.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))};import Td from"chalk";var Z=e=>Td.dim(e),be=e=>Td.hex(v.primary)(e),Ie=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,b)=>zr(f)-zr(b)).slice(0,r).map(f=>qr(f)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""};var pt={None:"none",Invalid:"invalid",Valid:"valid"};var Pn=140,Hp=["BOARD","TICKET","SWIMLANE"],wd=()=>{let e=g().selectedNode;if(!e?.context)return F({message:Z("Missing target context")});if(Hp.includes(e.context))return V();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===xe(t?.parentNodeId??"","comments"))return V()}return F({message:Z("Command not available in this context")})},re="<ENTER> to confirm",V=(e="",t=[])=>({message:Z(e),validity:pt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:pt.Invalid,message:e,completionWordList:t}),go=e=>e.length===0,Md=(e,t)=>{let n=Le(g().breadCrumb,"BOARD");if(d(n))return F({message:be("Command is not applicable in this context")});let r=Xr(n.value.id);return d(r)?F({message:be(`Unable to ${t}: board id is not a valid ULID`)}):cd({date:e,horizonDate:r.value})?null:F({message:be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},fo=e=>` ${Pd.hex("#000").bgHex(le(e))(` ${e} `)} `,Vs=({modifier:e})=>{let t="confirm";return e===t?V(re):F({message:go(e)?Z("if you are certain, enter ")+qr(t):"",completionWordList:[t]})},Wp=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:Z(n)}):V():F({message:go(r)?t:"",completionWordList:[...e]}),un=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>go(n)&&go(r)?F({message:e,completionWordList:[]}):V(t??re),jp=({modifier:e,inputString:t})=>{let n=ie(x.CONFIG);if(!n.includes(e))return F({message:Ie({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ne.EDITOR:{let r=[...pd];return t.trim()?r.includes(t.trim())?V(re):F({message:Ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:Ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?V(re):F({message:Ie({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.USERNAME:return t.trim()?V(re):F({message:be("Enter a user name. Saved in ")+Pd.bgBlack("~/.epiq-global/config.json")});case ne.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?V(re):F({message:Ie({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ne.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=id(o);return F({message:Ie({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return V(re)}case ne.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<cr||o>lr){let s=Ie({prefix:" examples: ",wordList:$s,minLengthForHints:0,inputString:t});return F({message:be(`provide a size cap in KB (${cr}-${lr}). current: ${r??mt} KB.`)+s,completionWordList:$s})}return V(re)}case ne.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=nd(t);if(!t.trim()||o===null||o<An){let s=Ie({prefix:" examples: ",wordList:_s,minLengthForHints:0,inputString:t});return F({message:be(`provide duration above ${An}ms. current duration: ${r}ms.`)+s,completionWordList:_s})}return V(re)}default:return F({message:be("Unknown config option"),completionWordList:n})}},Vp=({modifier:e,inputString:t})=>{let n=ie(x.EDIT);if(!n.length)return F({message:be("Command not available in this context")});if(!n.includes(e)){let r=Ie({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||be("Unknown edit option"),completionWordList:n})}switch(e){case $e.COMMENT:return t.trim()?V(re):F({message:Z("write a comment...")});case $e.TITLE:return V(re);case $e.DESCRIPTION:{let{preferredEditor:r}=K();return r?V(Z("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:be("Unknown edit option"),completionWordList:n})}},Kp=({modifier:e})=>{let t=ie(x.YANK);return t.length?t.includes(e)?V(re+Z(" and copy to clipboard")):F({message:Ie({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):F({message:be("Nothing selected to copy from")})},Gp={[x.EXPORT]:()=>V(re+Z(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return V(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=cn(r);if(!r||!o)return F(n);let s=Md(o,"peek");return s||V(re)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=uo(e.modifier,e.inputString),r={message:Z("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=cn(t);if(!t||!o)return F(r);let s=Md(o,"replay");return s||(n&&lo(n)===null?F({message:be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):V("<ENTER> to replay board history",n?md:[]))},[x.EXIT]:()=>V(re+Z(" and exit the application")),[x.INIT]:()=>V(re),[x.PALETTE]:()=>V(re),[x.FILTER]:e=>{if(e.modifier==="clear")return V(re);let t=s=>ie(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:Ie({wordList:ie(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ie(x.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:Ie({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):V():F({message:Ie({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=ie(x.NONE);return F({message:Ie({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Wp({list:ie(x.NEW),hint:Ie({wordList:ie(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>V(re),[x.EDIT]:Vp,[x.COMMENT]:e=>{let t=un({hint:Z(`write a comment (max ${Pn} char)...`),onOk:Z(`(${e.inputString.length}/${Pn})`)})(e);return t.validity===pt.Invalid?t:e.inputString.length>Pn?V(be("max input exceeded")):t},[x.CONFIG]:jp,[x.YANK]:Kp,[x.DELETE]:e=>{let t=wd();return t.validity==="invalid"?t:Vs(e)},[x.CLOSE_ISSUE]:e=>Vs(e),[x.RE_OPEN_ISSUE]:e=>Vs(e),[x.MOVE]:e=>{let t=wd();return t.validity==="invalid"?t:un({hint:Ie({prefix:"hey hacker! These commands are blocked for you... ",wordList:ie(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(fo).join("");return un({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[x.UNTAG]:e=>{let t=ao();if(d(t))return F({message:be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(fo).slice(0,10);return n.length?un({hint:Z(" ... ")+n.join("")})(e):F({message:be("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=I.getExistingAssignees().map(fo).slice(0,10);return un({hint:Z("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=co();if(d(t))return F({message:be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(fo).slice(0,10);return n.length?un({hint:Z("remove assignee... ")+n.join("")})(e):F({message:be("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>V(re),[x.COFFEE]:e=>{let{modifier:t}=e,n=ie(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:Z("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):un({hint:Ie({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Ld=Object.fromEntries(Object.entries(Gp).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var yo=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var zp=3,qp=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Yp=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Xp=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=zp&&!qp.has(t)&&!/^\d+$/.test(t)),Jp=e=>{let t=new Map;for(let s of Yp(e))for(let i of Xp(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=yo.filter(s=>!r.has(s));return[...n,...o]},kd=yo,Dd=-1,Fd=()=>{let e=Je();if(d(e))return yo;let t=e.value,n=t.eventLog.length;return n!==Dd&&(kd=Jp(t),Dd=n),kd};var Bd=e=>Object.values(x).includes(e),Ud=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Ld[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?ie(n):m?Fd():[],{mode:f}=g(),b=f===y.COMMAND_LINE?i??"":"",N=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:b,autoCompletion:t?ya(e,N):{hint:"",hints:[],remainder:"",overlap:0}}};var Od=e=>{let t=e.trimStart(),n=Zp(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=ef(e),c=Bd(r)?r:null,u=c!==null,m=r!=="",p=c?ie(c)??[]:[],f=c&&p.includes(o)?o:"",b="word";n.length===0||n.length===1&&!s?b="command":(n.length===1&&s||n.length===2&&!s)&&(b="modifier");let N=s?"":i,S=Qp(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:b,inputToMatch:N,inputString:S}},Qp=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Zp=e=>e.trim()?e.trim().split(/\s+/):[],ef=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as tf}from"react";var Ln=e=>e===Ks||e===":",Ks=" ",Ae={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:pt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Gs=new Set,_d=()=>{for(let e of Gs)e()},zs=e=>(Gs.add(e),()=>Gs.delete(e)),ft=e=>{let n=e(Ae),r=Od(n.value),o=n.cursorPosition===n.value.length;Ae={...n,commandMeta:Ud(r,o)},_d()},ur=({message:e,status:t})=>{let n=structuredClone(Ae);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ae=n,_d(),l(e,null)},qs=e=>{ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ys=e=>{ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ln(n[o-1]);)o--;for(;o>0&&!Ln(n[o-1]);)o--}else{for(;o<n.length&&!Ln(n[o]);)o++;for(;o<n.length&&Ln(n[o]);)o++}return{...t,cursorPosition:o}})},$d=()=>{ft(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Hd=()=>{ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ln(t[r-1]);)r--;for(;r>0&&!Ln(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},vo=e=>{ft(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Wd=()=>{ft(e=>({...e,commandIsPending:!0}))},W=e=>{ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},jd=({addToHistory:e=!0})=>{ft(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Vd=()=>{ft(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Kd=()=>{ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Y=()=>Ae,Gd=()=>tf(zs,Y,Y),zd=()=>{let[e,...t]=Ae.value.split(Ks);return t.join(Ks).trim()};var h={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function nf(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function rf(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function of(e,t,n){let r=g().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function qd(e,t){let n=Y();if(e.sequence==="?"&&t!==y.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return h.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===y.COMMAND_LINE)return ca(e,n.value);if(t===y.PALETTE)return la(e,n.value);let r=nf(e)||rf(e);if(r)return sf(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"y":return h.Yank;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return K().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function sf(e,t){let n=t===y.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return of(g().contextNode.childRenderAxis,e,n)}var ho=e=>{let{context:t}=g().contextNode;if(!t)return w.None;switch(e){case x.EXIT:return w.Exit;case x.EXPORT:return w.Export;case x.COFFEE:return w.Coffee;case x.INIT:return w.Init;case x.DELETE:return w.Delete;case x.EDIT:return w.Edit;case x.COMMENT:return w.Comment;case x.HELP:return w.ViewHelp;case x.RE_OPEN_ISSUE:return w.ReopenIssue;case x.CLOSE_ISSUE:return w.CloseIssue;case x.TAG:return w.TagTicket;case x.UNTAG:return w.UntagTicket;case x.ASSIGN:return w.AssignUserToTicket;case x.UNASSIGN:return w.UnassignUserFromTicket;case x.NEW:return w.NewItem;case x.FILTER:return w.Filter;case x.MOVE:return w.Move;case x.PEEK:return w.Peek;case x.REPLAY:return w.Replay;case x.CONFIG:return w.Config;case x.YANK:return w.Yank;case x.SYNC:return w.Sync;default:return w.None}},w={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as we}from"ulid";import fc from"node:fs";import Xf from"node:path";import Jf from"react";import{Box as qf}from"ink";import No from"react";import Ef from"chalk";import{Box as Js,Text as Cf}from"ink";import gt from"react";import{Text as Yd}from"ink";import Xd,{useEffect as Jd,useState as af}from"react";var Qd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=H(),r=Qd[n]??Qd.default,[o,s]=af(0);if(Jd(()=>{s(0)},[r]),Jd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Xd.createElement(Yd,null,t);let i=r[o]??r[0]??t;return Xd.createElement(Yd,{color:v.accent,dimColor:o===1},i)};import{Box as Xs,Text as df}from"ink";import xo from"react";var et=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),f=p+c,b=e.slice(p,f),N=e.length>c,S=s,R=N?Math.max(1,Math.floor(c/e.length*S)):S,M=Math.max(0,S-R),U=Math.max(1,e.length-c),j=N?Math.floor(p/U*M):0;return xo.createElement(Xs,{flexDirection:"row",height:s,width:"100%"},xo.createElement(Xs,{flexDirection:"column",flexGrow:1,height:s},b),xo.createElement(Xs,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((D,z)=>xo.createElement(df,{key:z,color:N&&z>=j&&z<j+R?v.accent:v.secondary},N?"\u2502":" "))))};import{Box as Fn,Text as Io}from"ink";import tt from"react";import{Text as cf}from"ink";import lf from"react";var uf=e=>e.toLowerCase().trim(),mf=(e,t=In)=>{let n=uf(e);return t[n]?t[n]:tr(n)},Ht=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return lf.createElement(cf,{underline:t,color:mf(n.name)},"@"+n.name)};import{Text as pf}from"ink";import ff from"react";var kn=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return ff.createElement(pf,{underline:t,backgroundColor:le(n.name),color:v.secondary}," "+n.name+" ")};import{useEffect as gf,useState as yf}from"react";var vf=80,Zd=1400,bo=new Set,mr=null,hf=e=>(bo.add(e),mr||(mr=setInterval(()=>{for(let t of bo)t()},vf)),()=>{bo.delete(e),bo.size===0&&mr&&(clearInterval(mr),mr=null)}),xf=()=>{let e=Date.now()%Zd/Zd;return e<.5?e*2:(1-e)*2},Dn=e=>{let[,t]=yf(0);return gf(()=>{if(e)return hf(()=>t(n=>n+1))},[e]),Gr(xf())};var bf=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),nn(e.slice(r).trim(),t)]},ec=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Dn(r),s=e-4,[i,c]=bf(lt(t.title),s),u=c?null:nn(lt(t.props.description),s)||null,m=_t(t),p=$t(t);return tt.createElement(Fn,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?v.accent:v.secondary,justifyContent:"space-between"},tt.createElement(Fn,{paddingLeft:1,flexDirection:"column"},tt.createElement(Io,{color:v.primary},i),c&&tt.createElement(Io,{color:v.primary},c),u&&tt.createElement(Io,{color:v.secondary2,dimColor:!0},u)),tt.createElement(Fn,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},tt.createElement(Fn,{flexDirection:"row"},m.map(f=>tt.createElement(Fn,{paddingRight:1,key:f.id},tt.createElement(kn,{key:f.id,id:f.id}))),p.map(f=>tt.createElement(Fn,{paddingRight:1,key:f.id},tt.createElement(Ht,{key:f.id,id:f.id})))),tt.createElement(Io,{wrap:"truncate",color:v.secondary2,dimColor:!0},Ue(t.id))))};import{Box as mn,Text as pr}from"ink";import We from"react";var If=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,tc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=Dn(r),c=(t.props.tags??[]).map(D=>I.getTag(D)).filter(D=>!!D),u=(t.props.assignees??[]).map(D=>I.getContributor(D)).filter(D=>!!D),m=1,p=c.length*(1+m),f=u.length*(2+m),b=c.map(D=>We.createElement(mn,{key:D.id,paddingRight:m},We.createElement(pr,{color:le(D.name)},"\u25A0"))),N=u.map(D=>We.createElement(mn,{key:D.id,paddingRight:m},We.createElement(pr,{color:tr(D.name)},"@"+D.name.at(0)))),S=r?i:n?v.accent:s===y.MOVE?v.secondary:v.primary,R=4,M=I.getCommentsByIssue(t.id),U=M.length?String(M.length).length+2+m:0,j=M.length?We.createElement(mn,{paddingRight:m},We.createElement(pr,{color:v.accent},"[",M.length,"]")):null;return We.createElement(mn,{borderBottom:!0,justifyContent:"space-between"},We.createElement(mn,null,We.createElement(mn,{width:R},n?We.createElement(Re,{isSelected:n}):We.createElement(pr,{color:"gray",dimColor:!0},o+1)),We.createElement(pr,{wrap:"truncate",color:S},If(t.title,e-p-f-U-18))),We.createElement(mn,null,b,N,j))};var Nf=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=H(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,b=f?.has(e.id)??!1,N=Dn(b),S=`${e.title} ${Ef.hex(v.secondary2).dim("("+p.length+")")}`,R=3,M=o?1:5,U=s&&i===-1,j=n-(U?7:5),D=r-R-(o?2:1),z=gt.createElement(Js,{borderStyle:"round",borderColor:v.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},gt.createElement(Re,{isSelected:t}),gt.createElement(Cf,{bold:!0,color:b?N:t?v.accent:v.primary},S," ",e.readonly?"\u{1F512}":"")),$=(P,O)=>{let Ge=s&&i===O;if(!A(P))return null;let Ne=f?.has(P.id)??!1;return o?gt.createElement(tc,{key:P.id,index:O,width:n,ticket:P,isSelected:Ge,isFlashing:Ne,mode:c}):gt.createElement(ec,{key:P.id,width:j,ticket:P,isSelected:Ge,isFlashing:Ne})};return gt.createElement(Js,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?v.accent:v.secondary,paddingRight:1,paddingLeft:1,height:r},z,gt.createElement(Js,{padding:o?1:0},p.length>0&>.createElement(et,{selectedIndex:i,height:D,itemHeight:M},p.map($)),U&>.createElement(Re,{isSelected:!0})))},nc=gt.memo(Nf);import{Box as pn,Text as ri}from"ink";import Ee,{useMemo as fr}from"react";var rc=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},oc=(e,t,n)=>Q.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as Bn,Text as St}from"ink";import Te,{useEffect as Sf,useMemo as Af,useRef as Rf}from"react";import{decodeTime as Qs}from"ulid";var Tf=e=>xe(e,"attachments"),wf=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Qs(t.id)-Qs(n.id)),sc=e=>{for(let t of e)I.deleteNode(t.id)},Mf=(e,t,n)=>Q.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Pf=(e,t)=>{let n=I.getNode(Tf(e.id));if(!n||!Oe(n))return[];let r=t.map((o,s)=>Mf(o,s,n.id)).map(o=>I.createNode(o)).filter(te).map(({value:o})=>o).filter(Oe);return t.length>0&&g().selectedIndex<0&&T.navigate({contextNode:n,selectedIndex:0}),r},Lf=e=>`${Math.max(1,Math.round(e/1024))} KB`;function ic({ticket:e,width:t,height:n}){let r=Af(()=>wf(e),[e]),o=Rf([]);Sf(()=>(sc(o.current),o.current=Pf(e,r),()=>{sc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Te.createElement(Bn,{flexDirection:"column",width:t,height:n,padding:1},Te.createElement(St,{color:v.primary},"No attachments yet."),Te.createElement(Bn,{paddingTop:1},Te.createElement(St,{color:v.primary},"Attach images from the browser GUI"),Te.createElement(St,{color:v.accent}," epiq gui "),Te.createElement(St,{color:v.primary},"by dropping or pasting them."))):Te.createElement(Bn,{flexDirection:"column",width:t,height:n},Te.createElement(Bn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:v.secondary,borderStyle:"single",paddingBottom:1},Te.createElement(St,{color:v.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Te.createElement(et,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,b=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Te.createElement(Bn,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Te.createElement(St,{color:v.accent},f?"\u276F ":" "),Te.createElement(Bn,{paddingLeft:1},Te.createElement(St,{color:v.secondary2},`#${p+1} `),Te.createElement(St,{color:f?v.accent:v.primary},b),Te.createElement(St,{color:v.secondary2}," "+Lf(m.bytes)+" "+Cn(Qs(m.id)))))})))}import{Box as Wt,Text as At}from"ink";import fe,{useEffect as kf,useMemo as Df,useRef as Ff}from"react";import{decodeTime as Zs}from"ulid";var Bf=e=>xe(e,"comments"),Uf=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Zs(t.id)-Zs(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),ac=e=>{for(let t of e)I.deleteNode(t.id)},Of=(e,t)=>{let n=I.getNode(Bf(e.id));if(!n||!Oe(n))return[];let r=t.map((o,s)=>oc(o,s,n.id)).map(I.createNode).filter(te).map(({value:o})=>o).filter(Zn);return t.length>0&&g().selectedIndex<0&&T.navigate({contextNode:n,selectedIndex:0}),r},_f=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function dc({ticket:e,width:t,height:n}){let r=Df(()=>Uf(e),[e]),o=Ff([]);kf(()=>(ac(o.current),o.current=Of(e,r),()=>{ac(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=H(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?fe.createElement(Wt,{flexDirection:"column",width:t,height:n,padding:1},fe.createElement(At,{color:v.primary},"No comments yet."),fe.createElement(Wt,{paddingTop:1},fe.createElement(At,{color:v.primary},"Use"),fe.createElement(At,{color:v.accent}," :comment "),fe.createElement(At,{color:v.primary},"to add the first one."))):fe.createElement(Wt,{flexDirection:"column",width:t,height:n},fe.createElement(Wt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:v.secondary,borderStyle:"single",paddingBottom:1},fe.createElement(At,{color:v.secondary2},"Comments (",r.length,") ")),fe.createElement(et,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return fe.createElement(Wt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:v.secondary,borderStyle:"single"},fe.createElement(Wt,{flexDirection:"row",paddingBottom:1},fe.createElement(At,{color:v.accent},f?"\u276F ":" "),fe.createElement(Wt,{paddingLeft:1},fe.createElement(At,{color:v.secondary2},`#${p+1} `),fe.createElement(Ht,{id:m.authorId}),fe.createElement(At,{color:v.secondary2}," "+Cn(Zs(m.id))))),fe.createElement(Wt,{paddingLeft:3,paddingBottom:1},fe.createElement(At,{color:v.primary},_f(m.md,u))))})))}import{Box as Eo,Text as $f}from"ink";import Rt from"react";var cc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=H(),{title:o}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,i=s&&A(s)?o===J.ASSIGNEES?s.props.assignees??[]:o===J.TAGS?s.props.tags??[]:[]:[];return Rt.createElement(Eo,{alignItems:"center",paddingTop:1},Rt.createElement(Eo,{minWidth:12},Rt.createElement(Re,{isSelected:n}),Rt.createElement($f,{color:n?v.accent:v.secondary2},o,":")),Rt.createElement(Eo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return Rt.createElement(Eo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Rt.createElement(Re,{isSelected:m}),o===J.ASSIGNEES?Rt.createElement(Ht,{isSelected:m,id:c}):o===J.TAGS?Rt.createElement(kn,{isSelected:m,id:c}):null)})))};import{Box as Co,Text as ei}from"ink";import Tt,{useEffect as Hf,useMemo as lc}from"react";var Wf="\u2029",uc=(e,t)=>`${e}::inline-line::${t}`,ti=new Map,mc=e=>{let t=ti.get(e)??[];ti.delete(e);for(let n of t)I.deleteNode(n)},jf=(e,t)=>{mc(e);let n=[];t.forEach((r,o)=>{let s=_e(BigInt(o+1));if(!te(s))return;let i=I.createNode(Q.text({id:uc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),ti.set(e,n)},ni=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=H(),u=lc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=lc(()=>u.join("\0"),[u]);Hf(()=>(jf(e,u),()=>{mc(e)}),[e,m]);let p=b=>String(b).replace(/\r?\n/g,""),f=u.map((b,N)=>{let S=c.id===e&&i===N;return Tt.createElement(Co,{key:uc(e,N)},Tt.createElement(ei,{color:S?v.primary:v.secondary2,dimColor:!S},`${N+1} `.padStart(5,"\xA0")),Tt.createElement(ei,{backgroundColor:S?"gray":void 0},p(b.length?nn(b,s-10):Wf)))});return Tt.createElement(Co,{flexDirection:"column",paddingTop:1},Tt.createElement(Co,null,Tt.createElement(Re,{isSelected:o}),Tt.createElement(ei,{color:o?v.accent:v.secondary2},t)),Tt.createElement(Co,{flexDirection:"row",borderStyle:"round",borderColor:v.secondary,paddingLeft:1,marginLeft:1},Tt.createElement(et,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var Vf=e=>xe(e,"description"),Kf=e=>xe(e,"comments"),Gf=e=>xe(e,"history"),zf=e=>xe(e,"attachments"),pc=({ticket:e,height:t})=>{let n=fr(()=>rc(e),[e]),{selectedIndex:r,contextNode:o}=H(),s=process.stdout.columns||120,i=fr(()=>Vf(e.id),[e.id]),c=fr(()=>Kf(e.id),[e.id]),u=fr(()=>Gf(e.id),[e.id]),m=fr(()=>zf(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,f=o.id===e.id,b=o.id===c||o.parentNodeId===c,N=o.id===u||o.parentNodeId===u,S=o.id===m||o.parentNodeId===m,R=G(e.id);if(b){let O=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(dc,{ticket:e,width:s,height:O}))}if(S){let O=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(ic,{ticket:e,width:s,height:O}))}if(N){let P=I.getNode(u),O=P&&Oe(P)?P.props.value??"":"",Ne=t-3;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},P?Ee.createElement(ni,{id:P.id,label:"Event log",text:O,selected:!1,maxWidth:s,height:Ne}):null)}let M=R.reduce((P,O)=>Qn(O)||O.id===c||O.id===m||O.id===u?P+1:P,0),U=2,j=3,D=M,z=t-j-D-U,$=(P,O)=>P.id===i?Ee.createElement(ni,{key:P.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:O,maxWidth:s,height:z}):Qn(P)?Ee.createElement(cc,{key:P.id,parent:P,selected:O,selectedIndex:r}):P.id===c?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(ri,{backgroundColor:v.secondary,color:O?v.accent:v.primary},` Comments (${n}) \u203A\u203A `)):P.id===m?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(ri,{backgroundColor:v.secondary,color:O?v.accent:v.primary},` Attachments (${p}) \u203A\u203A `)):P.id===u?Ee.createElement(pn,{key:P.id,paddingTop:1},Ee.createElement(Re,{isSelected:O}),Ee.createElement(ri,{backgroundColor:v.secondary,color:O?v.accent:v.primary}," History \u203A\u203A ")):null;return Ee.createElement(pn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((P,O)=>$(P,f&&r===O)))};var Yf=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===L.TICKET||u===L.FIELD_LIST||u===L.FIELD,p=u===L.BOARD||u===L.SWIMLANE,f=u===L.TICKET?t:r.find(M=>M.context===L.TICKET),b=Math.floor(c/3),N=Math.floor(c/Math.max(e.length,1)),S=Math.min(N,b),R=s==="dense";return No.createElement(qf,{flexDirection:"row",height:i},p&&e.map((M,U)=>{let j=t.id===M.id,D=j?n:-1,z=t.context===L.BOARD&&n===U;return No.createElement(nc,{key:M.id,height:i,width:S,swimlane:M,isSelected:z,isDense:R,isFocused:j,listSelectedIndex:D,mode:o})}),m&&f&&No.createElement(pc,{height:i,ticket:f}))},So=No.memo(Yf);import{render as Qf}from"ink";import{Writable as Zf}from"node:stream";var gr=e=>String(e).padStart(2,"0"),eg=e=>{let t=e.getUTCFullYear(),n=gr(e.getUTCMonth()+1),r=gr(e.getUTCDate()),o=gr(e.getUTCHours()),s=gr(e.getUTCMinutes()),i=gr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},tg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",ng=async(e,{width:t,height:n})=>{let r="",o=new Zf({write(i,c,u){let m=rg(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Qf(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},rg=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),gc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),i=r.find(U=>U.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await ng(Jf.createElement(So,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(U=>U!==void 0&&Dt(U)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=Lr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,b=eg(f),N=`board_${tg(i.title)}_${b}.md`,S=ki(p.value);fc.mkdirSync(S,{recursive:!0});let R=Xf.join(S,N),M=`# Board - ${i.title}
|
|
47
|
+
Date: ${f.toISOString()}
|
|
46
48
|
|
|
47
49
|
\`\`\`text
|
|
48
50
|
${m}
|
|
49
51
|
\`\`\`
|
|
50
|
-
`;return
|
|
51
|
-
`),l("Config written",null)}catch{return a(`Unable to write ~/${Ue}/config.json`)}},xt=e=>{let t=Jn();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Ud(n)},Qn=()=>{let e=Bs(),t=Us();if(d(t))return a(`Unable to create ~/${Ue}`);if(!(Le.readFile(e)!==null)){let p=Ud(Xp);if(d(p))throw new Error(`Unable to create ~/${Ue}/config.json`)}let r=Jn();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,logLevel:m}=r.value;return!s||!i?a(`User name or ID not configured in ~/${Ue}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,l("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))};var ao=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as oN}from"react";var co,Zp=new Set,Od=()=>{for(let e of Zp)e()};var Dt=()=>{if(!co)throw new Error("Ui state not initialized. Call initUiState() first.");return co};var _d=(e={})=>(co=e,Od(),l("UX state initialized",null)),ef=e=>{let t=Dt();return co=e(t),Od(),l("UX state updated",null)},Ft=e=>ef(t=>({...t,...e}));import{spawn as tf}from"node:child_process";function Os(e){let t=process.platform,o=tf(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as _s}from"ulid";import{spawnSync as nf}from"node:child_process";import rf from"node:os";import $d from"node:path";import{ulid as of}from"ulid";function sf(){let{preferredEditor:e}=H(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function af(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Wd(e){let t=$d.join(rf.tmpdir(),"epiq");Le.mkDir(t);let n=$d.join(t,of());Le.writeToFile(n,e??"");let r=sf();for(let o of r){let s=af(o,n),i=nf(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=Le.readFile(n);if(c==null)return a("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return a("Unable to open editor")}var Hd=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(e.modifier===we.DESCRIPTION)return cf();if(r&&Un(r))return df(e);if(e.modifier===we.TITLE){let o=Z();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await qe();return d(c)?c:B([{id:_s(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},df=async e=>{let t=Z();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=W(n.id)[r];if(!o||!Un(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=f().nodes[s];if(!i||!w(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=b.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await qe();if(d(p))return p;let v=p.value;return B([{id:_s(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],v)},cf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let t=await qe();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=be([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!w(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=W(i.id).find(v=>v.title===se.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Wd(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:_s(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import uf from"node:fs";import Vd from"node:path";import $s from"node:fs";import lf from"node:path";var jd=async e=>{let t=lf.join(e,".gitignore"),n=$s.existsSync(t)?$s.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
52
|
+
`;return fc.writeFileSync(R,M,"utf8"),l("Exported board layout",R)};var Ao=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as QA}from"react";var Ro,og=new Set,yc=()=>{for(let e of og)e()};var jt=()=>{if(!Ro)throw new Error("Ui state not initialized. Call initUiState() first.");return Ro};var vc=(e={})=>(Ro=e,yc(),l("UX state initialized",null)),sg=e=>{let t=jt();return Ro=e(t),yc(),l("UX state updated",null)},Vt=e=>sg(t=>({...t,...e}));import{spawn as ig}from"node:child_process";function yr(e){let t=process.platform,o=ig(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as oi}from"ulid";import{spawnSync as ag}from"node:child_process";import dg from"node:os";import hc from"node:path";import{ulid as cg}from"ulid";function lg(){let{preferredEditor:e}=K(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function ug(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function xc(e){let t=hc.join(dg.tmpdir(),"epiq");He.mkDir(t);let n=hc.join(t,cg());He.writeToFile(n,e??"");let r=lg();for(let o of r){let s=ug(o,n),i=ag(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=He.readFile(n);if(c==null)return a("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return a("Unable to open editor")}var bc=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(e.modifier===$e.DESCRIPTION)return pg();if(r&&Zn(r))return mg(e);if(e.modifier===$e.TITLE){let o=se();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await at();return d(c)?c:B([{id:oi(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},mg=async e=>{let t=se();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=G(n.id)[r];if(!o||!Zn(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=g().nodes[s];if(!i||!A(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=I.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await at();if(d(p))return p;let f=p.value;return B([{id:oi(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],f)},pg=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let t=await at();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=Le([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!A(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=G(i.id).find(f=>f.title===J.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=xc(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:oi(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import gg from"node:fs";import Ec from"node:path";import si from"node:fs";import fg from"node:path";var Ic=async e=>{let t=fg.join(e,".gitignore"),n=si.existsSync(t)?si.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
52
53
|
`).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
53
54
|
`);return n=n.trimEnd()+`
|
|
54
55
|
|
|
55
56
|
${c}
|
|
56
|
-
|
|
57
|
-
`));let ze=We();if(d(ze))return Y(16,ze.message);let{rootNodeId:Dl,nodes:Fl}=ze.value,li=Fl[Dl];return li?(M.navigate({contextNode:li,selectedIndex:0}),C({hasProjectDefinition:!0,mode:g.DEFAULT}),l(Ae,null)):Y(16,"Unable to resolve initialized root node")};import{ulid as ff}from"ulid";import{ulid as pf}from"ulid";var zd=null,Bt=()=>structuredClone(zd),Zn=e=>{zd=e},Kd=()=>{let{contextNode:e,selectedIndex:t}=f(),r=z(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},Ws=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z(t).filter(o=>o.id!==e);return Br(r,n)},qd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=Ws({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:pf(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Yd=e=>{Zn(e);let t=At(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function Hs(e){let t=Kd();if(d(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=z(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=qd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Yd(u.value)}function js(e){let t=Kd();if(d(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=z(n.id)[r+e];if(!s)return a("Missing sibling node");let i=qd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Yd(i.value)}var Xd=()=>{let e=Bt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return a("Move parent not found");let o=z(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},lo=(e,t="Moved preview")=>{if(d(e))return e;let n=Xd();return d(n)?n:(C({mode:g.MOVE}),l(t,null))},Jd=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=z(n.id)[r];if(!o)return C({mode:g.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=z(o.parentNodeId),i=s.findIndex(({id:v})=>v===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Ws({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Zn({id:ff(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:g.MOVE}),l("Move initialized",null))}if(t==="next")return lo(js(1));if(t==="previous")return lo(js(-1));if(t==="to-next")return lo(Hs(1));if(t==="to-previous")return lo(Hs(-1));if(t==="confirm"){let s=Bt();if(!s)return a("No pending move to confirm");let i=await qe();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=Xd();return d(u)?u:(Zn(null),C({mode:g.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Zn(null),C({mode:g.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as mo}from"ulid";import{monotonicFactory as gf,ulid as vf}from"ulid";var yf=gf(),uo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=yf();return l("Created issue events",[{id:vf(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Qd=async(e,t)=>{let n=Z();if(d(n))return a("Unable to resolve user ID");let r=await qe();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=f(),u=m=>{let p=B([m],o);if(d(p))return p;let v=b.getNode(p.value[0].result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let I=b.getNode(v.parentNodeId);return I?(M.navigate({contextNode:I,selectedIndex:b.getSiblings(v.parentNodeId).findIndex(({id:S})=>S===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=b.getNode(m);if(!p)return a("Workspace not found");let v=yn(p.id,n.value,o);return d(v)?v:u({id:mo(),action:"add.board",payload:{id:mo(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=be(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=yn(m.value.id,n.value,o);return d(p)?p:u({id:mo(),action:"add.swimlane",payload:{id:mo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=W(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let V=be(s,"SWIMLANE");return d(V)?null:V.value})();if(!p)return a("Unable to add issue in this context");let v=yn(p.id,n.value,o);if(d(v))return v;let I=uo({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(I))return I;let S=I.value,N=B([...S],o);if(d(N))return N;if(!N.value[0])return a("Issue creation failed");let O=S.find(V=>V.action==="add.issue")?.payload.id;return O?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:V})=>V===O)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var po=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=ma(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Ut();if(d(u))return u;let p=Tt(i).filter(d);if(p.length>0)return Ut(),C(o),a(p.map(I=>I.message).join(", "));let v=f().nodes[e];return v?(M.navigate({contextNode:v,selectedIndex:r}),l("",{unappliedEvents:c})):(Ut(),C(o),a("Board did not exist at that date"))};var hf=20,xf=16,If=150,fo=null,go=null;var on=()=>{fo!==null&&(clearInterval(fo),fo=null),go!==null&&(clearTimeout(go),go=null)},Zd=()=>{on(),C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},bf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},ec=({events:e,startTime:t,durationMs:n})=>{on();let r=e.length,o=e.map(v=>vn(v)??t),s=o[r-1]??Date.now(),i=bf(o),c=Math.max(1,Math.round(n*hf/1e3)),u=Math.max(Math.round(n/c),xf),m=0,p=0;C({mode:g.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),fo=setInterval(()=>{m++;let v=m/c,I=[],S;for(;p<r&&i[p]<=v;){let T=e[p],k=At(T);if(d(k)){Zd();return}I.push(...us(T)),S=T,p++}if(p>=r||m>=c){for(;p<r;p++){let k=At(e[p]);if(d(k))break}let T=f().replay;C({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),on(),go=setTimeout(Zd,If);return}let N=f().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:S?vn(S)??N?.currentTime??t:N?.currentTime??t,currentLabel:S?aa(S):N?.currentLabel??"",flashNodeIds:S?[...new Set(I)]:N?.flashNodeIds??[]}})},u)};var tc=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(on(),r==="now"){let c=ft(n.value);if(d(c))return a(c.message);let u=Ut();if(d(u))return u;let p=Tt(c.value).filter(d);return p.length>0?a(p.map(v=>v.message).join(", ")):(C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=f().eventLog.at(-1),u=vn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=f().unappliedEvents.at(0),u=vn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=Zt(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=po({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var nc=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Gr(r,o);if(on(),f().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=Zt(s);if(!c)return a("Invalid replay date");let u=i?Vr(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=f(),v=po({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(v))return v;let{unappliedEvents:I}=v.value;return I.length===0?(Ut(),C(p),l("Nothing to replay from that point",!0)):(ec({events:I,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Ef from"zod";var rc=()=>{let e=q().commandMeta.inputString,t=Ef.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=xt({autoSyncDebounceMs:t.data});return d(n)?n:(_e({autoSyncIntervalMs:t.data}),C({mode:g.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var oc=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ba(e),n=xt({autoSync:t});return d(n)?n:(_e({autoSync:t}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var sc=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=xt({logLevel:e});return d(n)?n:(_e({logLevel:e}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var ic=async()=>{_(""),C({mode:g.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await _r();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:g.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Sf=e=>e.action==="add.issue.comment",ac=e=>Object.values(f().tags).find(t=>t.name===e),dc=e=>Object.values(f().contributors).find(t=>t.name===e),It=async()=>{let e=await qe();return d(e)?e:l("Resolved persist root",e.value)},vo=[{systemOnly:!0,intent:L.Move,description:"Internal move-state command",mode:g.COMMAND_LINE,action:Jd},{intent:L.Delete,description:"Delete the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await It();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=w(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=f().nodes[i];if(!c||!w(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Sf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:xe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>le(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:g.DEFAULT})),l("Filter updated",null)}},{intent:L.ViewHelp,description:"Open the help screen",mode:g.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Ft({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:g.HELP}),l("Viewing help",null)}},{intent:L.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!w(r))return a("Cannot close in this context");let o=f().nodes[ce];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await It();if(d(s))return s;let i=s.value,c=Xt(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):pt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=f().nodes[ce];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!w(s))return a("Target node is not issue");let c=ao(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=f().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await It();if(d(m))return m;let p=m.value,v=Xt(u.id,s.id,{at:"end"},e.value,p);if(d(v))return v;let I=B([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return d(I)?I:l("Issue reopened",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Init,description:"Initialize Epiq in the current git repository",mode:g.COMMAND_LINE,action:Gd},{intent:L.NewItem,description:"Create a new board, swimlane, or issue",mode:g.COMMAND_LINE,action:Qd,onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Rename,description:"itle] Rename the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=cd();if(!o)return a("Provide a title");let s=await It();return d(s)?s:B([{id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UntagTicket,description:"Remove a tag from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=ac(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid untag target");let i=pt(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await It();return d(m)?m:B([{id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.TagTicket,description:"Add or create a tag on the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=f();if(!o)return a("Invalid tag target");let s=pt(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!w(i))return a("Target node is not issue");let c=await It();if(d(c))return c;let u=ac(r),m=u?.id??xe();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.AssignUserToTicket,description:"Assign a user to the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=f(),i=W(s.id)[o];if(!i)return a("Invalid assign target");let c=pt(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!w(u))return a("Target node is not issue");let m=await It();if(d(m))return m;let p=dc(r),v=p?.id??xe();return(u.props.assignees??[]).includes(v)?a("Assignee already assigned"):B([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:v,name:r},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:v},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=dc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid unassign target");let i=pt(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await It();return d(m)?m:B([{id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Comment,description:"Add a comment to the selected issue",mode:g.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>In)return a(`Cannot exceed ${In} characters`);let r=Z();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),i=be([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):pt(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!w(m))return a("Target node is not issue");let p=await It();return d(p)?p:B([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Sync,description:"Pull, commit, and push Epiq state",mode:g.COMMAND_LINE,action:ic},{intent:L.Peek,description:"View board state at another point in time",mode:g.COMMAND_LINE,action:tc},{intent:L.Replay,description:"Replay board history forward from a point in time",mode:g.COMMAND_LINE,action:nc},{intent:L.Export,description:"Export the current board layout to markdown",mode:g.COMMAND_LINE,action:async()=>{let e=await Md();return d(e)?e:(C({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:L.Exit,description:"Exit the application",mode:g.COMMAND_LINE,action:async()=>(M.exit(),l("Exit successful",!0))},{intent:L.Edit,description:"Edit title or description",mode:g.COMMAND_LINE,action:async(e,t)=>Hd(t),onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ae.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=H(),i=n||s,c=r??xe();if(!i||!c)return a("Unable to resolve user name or id");let u=xt({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(_e({userName:i,userId:c}),C({mode:g.DEFAULT}),l(`Username set to "${i}"`,null))}case ae.EDITOR:{if(!n)return a("No editor provided");let r=xt({preferredEditor:n});return d(r)?r:(_e({preferredEditor:n}),C({mode:g.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ae.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(_e({viewMode:n}),l(`View set to "${n}"`,null));case ae.AUTOSYNC:return oc();case ae.LOG_LEVEL:return sc();case ae.SYNC_DEBOUNCE_MS:return rc();default:return a("Unknown config command")}}},{intent:L.Coffee,description:"Sponsor the development of Epiq!",mode:g.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?Os("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Os(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),_(""),l("Thanks you!",null)}}];var Nf=new Set(["peek","replay","filter","view-help"]),st=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=q();if(!t)return a("No command to confirm");if(!e&&n===Mt.Invalid)return a("Invalid command");let s=Jr(t);od();let{readOnly:i}=f();if(i&&!Nf.has(s))return zn({status:Ct.Fail,message:"Command not available in readonly state",value:null});let c=vo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return zn({status:Ct.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return zn({status:Ct.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?zn(u):(sd({addToHistory:!e}),c.onSuccess?.(),H().autoSync&&Wr(),u)};var yo=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:g.COMMAND_LINE}),_("move cancel"),st({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:g.COMMAND_LINE}),_("move start"),st({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(C({mode:g.COMMAND_LINE}),_("move confirm"),st({isForceExecutedBySystem:!0}))}],ho=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move previous"),st({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move next"),st({isForceExecutedBySystem:!0})):a("No pending move")}],cc=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move to-next"),st({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move to-previous"),st({isForceExecutedBySystem:!0})):a("No pending move")}];var lc={[P.WORKSPACE]:[...yo,...ho],[P.BOARD]:[...yo,...ho],[P.SWIMLANE]:[...yo,...ho,...cc],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[],[P.COMMENT]:[]};var uc=()=>{_("");let{pendingNavTarget:e}=Dt();C({mode:g.DEFAULT}),e&&M.navigate(e),Ft({pendingNavTarget:void 0})},mc=[{intent:h.ExitCommandLine,mode:g.HELP,action:()=>(uc(),l("Exiting help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(uc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:g.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:g.HELP,action:()=>(M.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:g.HELP,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:g.HELP,action:()=>(M.navigateToNextContainer(),l("Navigating to next help container",null))}];var Rf=e=>{C({mode:g.COMMAND_LINE});let{pendingNavTarget:t}=Dt();t&&M.navigate(t),Ft({pendingNavTarget:void 0}),_(`${e} `)},pc=()=>{_("");let{pendingNavTarget:e}=Dt();e&&M.navigate(e),Ft({pendingNavTarget:void 0}),C({mode:g.DEFAULT})},fc=[{intent:h.InitCommandPalette,mode:g.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{_("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Ft({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:g.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:g.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!St(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Rf(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:g.PALETTE,action:()=>(pc(),l("Exiting palette",null))},{intent:h.Exit,mode:g.PALETTE,action:()=>(pc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:g.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.PALETTE,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.PALETTE,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.PALETTE,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var gc=[...mc,...fc,{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:g.COMMAND_LINE}),_(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!z(e?.id??"")?.length){if(e?.title===se.DESCRIPTION)return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===se.ASSIGNEES)return C({mode:g.COMMAND_LINE}),_(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===se.TAGS)return C({mode:g.COMMAND_LINE}),_(`${x.TAG} `),l("Propose command",!0);if(t.title===se.DESCRIPTION&&e?.context==="TEXT")return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0)}return M.enterChildNode(),l("Entering context",null)}},{intent:h.EditTitle,mode:g.DEFAULT,description:"[r] rename title",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:g.DEFAULT,description:"[e] edit description",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Af=500,Tf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),vc=e=>{let t=Tf(e);t&&Xr(n=>(n+t).slice(0,Af))};var wf=[g.COMMAND_LINE,g.PALETTE],Mf=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(As(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(As(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Ts("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Ts("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(Xr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(vc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(nd(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(rd(),l("Erasing input word",null))}],yc=[{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(st(),l("Executing command",null))},{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(C({mode:g.HELP}),l("Viewing help",null))},...wf.flatMap(Mf),{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(C({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(id(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ad(),l("Getting next command from history",null))}];import Ic from"chalk";var xo=Ic.dim.hex(y.secondary2)(": for command line"),hc="q to exit",xc=`${Ic.hex(y.accent)("m")} to confirm`,Vs={[P.WORKSPACE]:[xo],[P.BOARD]:[xo],[P.BOARD+g.COMMAND_LINE]:[xo],[P.SWIMLANE]:[xo],[P.TICKET+g.HELP]:[hc],[P.SWIMLANE+g.HELP]:[hc],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[xc],[P.TICKET+g.MOVE]:[xc]};var er=e=>e.trim().toLocaleLowerCase(),Pf=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Lf=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},bc=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return er(e.title??"").includes(n);case"description":return er(e.props.description??"").includes(n);case"tag":return Pf(e).map(er).some(o=>o.includes(n));case"assignee":return Lf(e).map(er).some(o=>o.includes(n));case"ref":return Qi(e.id,t.value);default:return!0}};function Cc(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Ec=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var sn,Gs,zs=new Set,Sc=()=>{for(let e of zs)e()},Df=e=>(zs.add(e),()=>zs.delete(e));function Nc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=Cc(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Vs[p+n]??Vs[p]??[],I=[...gc,...lc[p]??[],...yc],S=Ec(I),N=Ff(o,s),T=N[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:I,actionIndex:S,selectedNode:T,renderedChildrenIndex:N})}var f=()=>{if(!sn)throw new Error("State not initialized. Call initWorkspaceState() first.");return sn},We=()=>sn?l("Retrieved state",sn):a("State not initialized. Call initWorkspaceState() first.");function $n(e){Gs=e;let t=Ke(process.cwd()),n=!1;if(!d(t)){let s=Et(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Nc(r);return d(o)?o:(sn=o.value,Sc(),l("State initialized",null))}function fe(e){let t=f(),n=e(t),r=Nc(n);return d(r)?a(r.message??"Unable to update state"):(sn=r.value,Sc(),l("State updated",null))}var C=e=>fe(t=>({...t,...e}));var $=()=>kf(Df,f,f),Ff=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>bc(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},W=e=>f()?.renderedChildrenIndex[e]??[],Ut=()=>Gs?$n(Gs):a("Cannot reset state: no initial workspace found"),xn=()=>sn!==void 0;var Ks=e=>{xn()&&(C({syncStatus:e}),zt({type:"sync-status",payload:e}))},Io=(e="Syncing...")=>{Ks({status:"syncing",msg:e})},bo=(e="Synced")=>{Ks({status:"synced",msg:e})},qs=e=>{Ks({status:"failed",msg:e})},He=e=>(qs(e),a(e));import{decodeTime as PM}from"ulid";var Bf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await Ye(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Te({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=K("ensureInitialCommit",await Di(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=K("bootstrapStateBranchStorage",await Bi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=K("hasInProgressGitOperation(stateBranchRoot)",await yr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=K("ensureStateBranchLayout",Pi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Uf=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=K("stageStateBranchOwnEventFile",await Er({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=K("hasStagedChanges(after stage)",await Ni(t));if(d(o))return a(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=K("createStateBranchSyncCommit",await Fi({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},$r=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Io();let n=K("ensureSyncReady",await Bf({cwd:e,ensureUpstream:!0}));if(d(n))return He(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=K("isDetachedHead(stateBranchRoot)",await Ri(o));if(d(i))return He(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return He("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=K("getStateBranch",cn(r));if(d(v))return He(v.message);let I=v.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let S=K("commitOwnEventFileToStateBranch",await Uf({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(S))return He(S.message);c=S.value.createdCommit,u=S.value.commitSha;let N=K("pullBranchRebaseIfPresent",await Qo({cwd:o,branch:I}));if(d(N))return He(N.message);if(m=N.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=K("pushStateBranch",await Fn({stateBranchRoot:o,repoRoot:r}));if(d(T)&&Si(T.message)){let k=K("pullBranchRebaseIfPresent(retry)",await Qo({cwd:o,branch:I}));if(d(k))return He(k.message);m=m||k.value,T=K("pushStateBranch(retry)",await Fn({stateBranchRoot:o,repoRoot:r}))}if(d(T))return He(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=K("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(d(T))return He(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return bo(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var Ys=e=>{let t=Ke(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ke=async e=>{let t=Ys(e);if(d(t))return t;let n=Te({repoRoot:t.value});if(d(n))return a(n.message);let r=dn(),o=await Gt({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await U({cwd:n.value,args:["pull","--ff-only"]});d(s)&&re.info(3,s.message);let i=ft(n.value);if(d(i))return a(i.message);let c=Jt(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},De=()=>{let e=Qn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=We();return d(e)?a(e.message):e},Rc=e=>(e.props.tags??[]).map(t=>b.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)})),Ac=e=>(e.props.assignees??[]).map(t=>b.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)}));var Tc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==ce).map(o=>({id:o.id,ref:et(o.id),title:Rt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ce,readonly:!!o.readonly,tags:Rc(o),assignees:Ac(o)}));return l("Listed issues",r)},wc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=yn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=uo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Mc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Xt(ce,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:Ie(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ce,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},Pc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Target node is not issue");if(o.parentNodeId!==ce)return a("Issue is not closed");let s=ao(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ce)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=Xt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:Ie(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},Lc=async e=>{let t=Ys(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Te({repoRoot:t.value});if(d(r))return r;let o=ft(r.value);if(d(o))return o;let s=Jt(o.value);if(d(s))return s;let i=Xt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:Ie(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},Co=async(e={})=>{Io();let t=Ys(e.repoRoot);if(d(t))return a("Sync failed");let n=De();if(d(n))return n;let r=await $r({cwd:t.value,ownEventFileName:Yt(n.value)});return d(r)?(qs(r.message),r):(bo(),l("Synced",r.value))};var Ot=async(e={})=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(m=>Nr(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of r)if(!m.isDeleted){if(Nt(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(w(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=Qn();if(d(c))return c;let u={};for(let m of r.filter(w))m.isDeleted||(u[m.id]=b.getCommentsByIssue(m.id).map(p=>{let v=b.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:v?.name??"Unknown",color:ie(v?.name??p.authorId)},createdAt:Of(p.id)}}));return l("Retrieved Epiq GUI state",{boards:o.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,ref:et(m.id),title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,v)=>p.rank.localeCompare(v.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((v,I)=>v.rank.localeCompare(I.rank)).map(v=>({id:v.id,ref:et(v.id),title:Rt(v.title),description:v.props.description??"",readonly:!!v.readonly,tags:Rc(v),assignees:Ac(v),parentNodeId:v.parentNodeId,isClosed:v.parentNodeId===ce})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:ie(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:ie(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:ie(c.value.userName??"")},commentsByIssueId:u})},kc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:Ie(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},Dc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Rt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:Ie(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},Fc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Rt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},Bc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Ie(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Uc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=Rt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Oc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:Ie(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Eo=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=Ie(),c={id:Ie(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},So=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!w(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:Ie(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})};var _c=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=Jn();if(d(p))return re.error(p.message);let{autoSync:v,userName:I,preferredEditor:S}=p.value;return!!(v&&I&&S)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await Co({repoRoot:e.repoRoot}),zt({type:"state",payload:await Ot({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=Jn();if(d(p))return re.error(p.message);let{autoSyncDebounceMs:v}=p.value;i()&&(t=setTimeout(()=>{c(),m()},v??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as _f}from"ws";var Fe=(e,t)=>{e.send(JSON.stringify(t))},tr=async(e,t)=>Fe(e,{type:"state",payload:await Ot({repoRoot:t})}),it=async(e,t,n,r,o)=>{if(Fe(e,{type:r,payload:o}),d(o))return Fe(e,{type:"failed",payload:o.message});n(),tr(e,t)},$c=(e,t,{onStateChanged:n})=>{new _f({server:e,path:"/ws"}).on("connection",o=>{Ui(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return tr(o,t);if(c==="sync"){let u=await Co({repoRoot:t});return Fe(o,{type:"sync:result",payload:u}),n(),tr(o,t)}if(c==="issue:comment:add"){let u=await Eo({repoRoot:t,...i.payload});return it(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await So({repoRoot:t,...i.payload});return Fe(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Fe(o,{type:"failed",payload:u.message}):(n(),tr(o,t))}if(c==="issue:edit:description"){let u=await kc({repoRoot:t,...i.payload});return it(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await Dc({repoRoot:t,...i.payload});return it(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await Fc({repoRoot:t,...i.payload});return it(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await Bc({repoRoot:t,...i.payload});return it(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await Uc({repoRoot:t,...i.payload});return it(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Oc({repoRoot:t,...i.payload});return it(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Fe(o,{type:"issues",payload:await Tc({repoRoot:t})});if(c==="issues:create"){let u=await wc({...i.payload,repoRoot:t});return Fe(o,{type:"issues:create:result",payload:u}),d(u)?zt({type:"failed",payload:u.message}):(zt({type:"issue:created",payload:u.value}),n(),tr(o,t))}if(c==="issues:move"){if(!i.payload.position)return Fe(o,{type:"error",message:"Missing move position"});let u=await Lc({...i.payload,repoRoot:t});return it(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Mc({repoRoot:t,issueId:i.payload.issueId});return it(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Pc({repoRoot:t,issueId:i.payload.issueId});return it(o,t,n,"issue:reopen:result",u)}return Fe(o,{type:"error",message:"Unknown message type"})}catch(i){return Fe(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var jf=an.dirname(Hf(import.meta.url)),Vf=process.env.IS_LOCAL==="true"?an.resolve(process.cwd(),"dist/gui"):an.join(jf,"gui"),at=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Gf=async e=>new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o}),e.on("end",()=>{try{t(r?JSON.parse(r):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),zf=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",Wc=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=an.resolve(Vf),o=an.resolve(r,n),s=an.relative(r,o);if(s.startsWith("..")||an.isAbsolute(s))return at(t,403,{isError:!0,message:"Forbidden"});try{let i=await $f(o);return t.writeHead(200,{"content-type":zf(o)}),t.end(i)}catch{return at(t,404,{isError:!0,message:`Not found: ${n}`})}},Kf=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Hc=async e=>{let t=Wf.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return at(s,200,await Ot({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Gf(o);if(!c.issueId||!c.body?.trim())return at(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Eo({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?at(s,400,u):at(s,200,await Ot({repoRoot:e.repoRoot}))}catch(c){return at(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return at(s,400,{isError:!0,message:"Missing comment id"});let u=await So({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?at(s,400,u):at(s,200,await Ot({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?Wc("/",s):Wc(i.pathname,s)});try{await Kf(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=_c({repoRoot:e.repoRoot});$c(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var jc=async e=>{let t=await Hc({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${qf.cyan(n)}`),mi(n),l("Started GUI",{url:n})};import{Box as jt}from"ink";import ee from"react";import{Box as Xs,Text as nr}from"ink";import Ve,{useEffect as Yf,useMemo as Xf}from"react";import{ulid as Jf}from"ulid";var Vc=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ve.createElement(nr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?Ve.createElement(nr,{color:n,dimColor:o},e):Ve.createElement(nr,{color:n,dimColor:o},e.slice(0,c),Ve.createElement(nr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Gc=Jf(),Qf=e=>`${e}`,Zf=e=>{let{pendingNavTarget:t}=Dt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(le(x.NONE,{breadCrumb:n,contextNode:r,readOnly:f().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=Jr(i),u=vo.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},eg=e=>Q.text({id:Gc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),tg=(e,t,n)=>Q.text({id:Qf(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Js=[],ng=e=>{zc();let t=b.createNode(eg(f().rootNodeId));d(t)||!St(t.value)||(Js=[t.value,...e.map((n,r)=>tg(n,r,Gc)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0}))},zc=()=>{let e=Js.map(t=>t.id);Js=[];for(let t of e)b.deleteNode(t)};function Kc({width:e,height:t}){let r=dd().value.trim().toLowerCase(),o=Xf(()=>Zf(r),[r]);Yf(()=>(ng(o),()=>{zc()}),[o]);let s=f().selectedIndex;return Ve.createElement(Xs,{flexDirection:"column",width:e,height:t-2},Ve.createElement(rt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ve.createElement(Xs,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ve.createElement(nr,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",Ve.createElement(Vc,{text:ji(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ve.createElement(Xs,{paddingLeft:2},Ve.createElement(Vc,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as xg}from"ink";import Ao from"react";import or from"chalk";import{Box as Qs,Text as qc}from"ink";import rr,{useEffect as rg,useMemo as og,useState as sg}from"react";var Yc=or.hex(y.secondary),ig=or.inverse,ag=or.inverse.hex(y.secondary2),dg={hint:"",hints:[],overlap:0,remainder:""},Jc=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},cg=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ie(t);return{bg:r=>or.bgHex(n).black(r),bgCursor:r=>or.bgHex(n).inverse.black(r)}}return cs(t)},lg=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Jc({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},Xc=()=>({value:he.value,cursorPosition:he.cursorPosition,commandIsPending:he.commandIsPending,autoCompletion:he.commandMeta.autoCompletion??dg,infoMessage:he.commandMeta.infoMessage,validationStatus:he.commandMeta.validity,command:he.commandMeta.command,inputString:he.commandMeta.inputString,modifier:he.commandMeta.modifier}),ug=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,Qc=({width:e,mode:t})=>{let[n,r]=sg(Xc());rg(()=>{let I=()=>{let N=Xc();r(T=>ug(T,N)?T:N)},S=Rs(I);return I(),()=>{S()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=og(()=>{let I=Math.max(0,Math.min(s,o.length)),S=Jc({value:o,command:m}),N=lg({value:o,command:m,modifier:p}),T=m?cs(m):null,k=cg({command:m,modifier:p}),O=(de,X)=>{let lt=S&&X>=S.start&&X<S.end,ze=N&&X>=N.start&&X<N.end;return lt&&T?T.fg(de):ze&&k?k.bg(de):de},V=(de,X)=>{let lt=S&&X>=S.start&&X<S.end,ze=N&&X>=N.start&&X<N.end;return lt&&T?T.fgCursor(de):ze&&k?k.bgCursor(de):ig(de)},R=o.slice(0,I),A=o[I]??" ",G=I<o.length?o.slice(I+1):"",Re=Array.from(R).map((de,X)=>O(de,X)).join(""),Ae=V(A,I),Ge=Array.from(G).map((de,X)=>O(de,I+1+X)).join("");if(u.hint){let de=u.hint[u.overlap]??A;Ae=ag(de),Ge=Yc(u.remainder.slice(1)+G)}return Yc(t===g.PALETTE?"?":":")+Re+Ae+Ge},[o,s,u,m,p]);return rr.createElement(Qs,{flexDirection:"column",justifyContent:"flex-start"},rr.createElement(Qs,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},rr.createElement(Qs,null,rr.createElement(qc,null,v),i&&rr.createElement(qc,{wrap:"truncate",color:c?y.red:y.secondary2},` ${i} `))))};import{Box as mg,Text as pg}from"ink";import Zc from"react";var fg=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},el=({width:e,availableHints:t})=>{let n=fg(t,e).join(" | ");return Zc.createElement(mg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},Zc.createElement(pg,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as gg,Text as No}from"ink";import sr,{useEffect as vg,useRef as Nn,useState as yg}from"react";var hg=40,Ro=.3,Zs="\u2500",tl=1,nl=16,rl=({width:e})=>{let{replay:t}=$(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*tl,[c,u]=yg(0),m=Nn(r);m.current=r;let p=Nn(0),v=Nn(0),I=Nn(0),S=Nn(0),N=Nn(0);if(vg(()=>{if(!n){p.current=0,I.current=0,S.current=0,N.current=0,u(0);return}p.current=m.current,v.current=Date.now(),I.current=m.current;let R=setInterval(()=>{let A=Date.now(),G=m.current;if(G!==I.current){let X=G-I.current,lt=A-v.current;if(X<0)S.current=0,N.current=0;else if(X>0&<>0){let ze=X/lt;S.current=S.current===0?ze:S.current*(1-Ro)+ze*Ro,N.current=N.current===0?X:N.current*(1-Ro)+X*Ro}p.current=G,v.current=A,I.current=G}let Re=A-v.current,Ae=Math.min(N.current,S.current*Re),Ge=Math.min(1,p.current+Ae),de=Math.round(Ge*i);u(X=>X===de?X:de)},hg);return()=>clearInterval(R)},[n,i]),!t)return null;let T=R=>{let A=s>1?R/(s-1):0,G=Math.round(A*(nl-1))/(nl-1);return Ar(G)},k=Math.min(s,Math.floor(c/tl)),O=[];for(let R=0;R<k;R++){let A=T(R),G=O[O.length-1];G&&G.color===A?G.text+=Zs:O.push({text:Zs,color:A})}let V=Zs.repeat(Math.max(0,s-k));return sr.createElement(gg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},sr.createElement(No,{color:y.secondary2},"\u25B6"),sr.createElement(No,null,O.map((R,A)=>sr.createElement(No,{key:A,color:R.color},R.text)),sr.createElement(No,{color:y.secondary,dimColor:!0},V)))};var ir=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=$(),o=t===g.COMMAND_LINE||t===g.PALETTE;return Ao.createElement(xg,null,o?Ao.createElement(Qc,{width:e,mode:t}):r==="replay"?Ao.createElement(rl,{width:e}):Ao.createElement(el,{width:e,mode:t,availableHints:n}))};import{Box as _t,Text as Rn}from"ink";import Ee,{useEffect as Ig,useMemo as bg}from"react";import{ulid as ol}from"ulid";var wo=ol(),Cg=()=>[...new Set([...f().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Eg=e=>Q.text({id:wo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Sg=(e,t,n)=>Q.text({id:ol(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),To=[],sl=()=>{let e=To.filter(n=>n.id!==wo).map(n=>n.id),t=To.filter(n=>n.id===wo).map(n=>n.id);To=[];for(let n of[...e,...t])b.deleteNode(n)},Ng=e=>{sl();let t=b.createNode(Eg(f().rootNodeId));if(d(t)||!St(t.value))return logger.error("Could not attach help nodes");To=[t.value,...e.map((n,r)=>Sg(n,r,wo)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0})},il=({width:e,height:t})=>{let n=bg(()=>Cg(),[]);Ig(()=>(Ng(n),()=>{sl()}),[n]);let r=f().selectedIndex;return Ee.createElement(_t,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Ee.createElement(_t,{paddingX:1,justifyContent:"center"},Ee.createElement(Rn,{color:y.accent},"Help"),Ee.createElement(Rn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Ee.createElement(_t,{paddingX:1,marginTop:1},Ee.createElement(_t,{width:20,justifyContent:"flex-end"},Ee.createElement(Rn,{color:y.secondary},"Key(s)")),Ee.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},Ee.createElement(Rn,{color:y.secondary},"Action"))),Ee.createElement(rt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Ee.createElement(_t,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Ee.createElement(_t,{width:20,justifyContent:"flex-end"},Ee.createElement(Rn,{color:y.accent},o)),Ee.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},Ee.createElement(Rn,{color:c?y.primary:y.secondary2},s)))})))};import Rg from"chalk";import{Box as Mo,Text as bt}from"ink";import Be from"react";var al=({width:e,height:t})=>Be.createElement(Mo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Be.createElement(bt,{color:y.accent,bold:!0},"Initialize project"),Be.createElement(bt,null,`This folder is not an ${Rg.hex(y.accent)("epiq")} project yet.`),Be.createElement(bt,{color:y.primary},"To start tracking issues here, we need to initialize a new",Be.createElement(bt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Be.createElement(Mo,{marginTop:1,flexDirection:"column"},Be.createElement(Mo,null,Be.createElement(bt,{color:y.accent}," "),Be.createElement(bt,{color:y.primary},"Type "),Be.createElement(bt,{backgroundColor:y.secondary}," :init "))),Be.createElement(Mo,{marginTop:1},Be.createElement(bt,{color:y.secondary2},"This will create, commit and push "),Be.createElement(bt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Po,Text as dt}from"ink";import pe from"react";var Ag=({isDone:e,command:t,value:n})=>pe.createElement(Po,null,pe.createElement(dt,{color:y.accent,dimColor:e},e?" \u2714 ":" "),pe.createElement(dt,{dimColor:e},"Type "),pe.createElement(dt,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&pe.createElement(pe.Fragment,null,pe.createElement(dt,{dimColor:e}," "),pe.createElement(dt,{color:y.secondary,dimColor:e},"<"+n+">"))),Tg=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function ei({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=wt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return pe.createElement(Po,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(dt,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),pe.createElement(dt,null,"Let's get you started - it's a breeze."),pe.createElement(dt,{color:y.secondary2},"Remember - you can always search available commands by typing:",pe.createElement(dt,{color:y.accent}," ? ")),p&&pe.createElement(dt,{color:y.secondary2},p.message),pe.createElement(Po,{flexDirection:"column"},u.map((v,I)=>m===-1||I<=m?pe.createElement(Po,{key:v.key,marginBottom:1},pe.createElement(Ag,{isDone:v.done,command:v.command,value:v.done?Tg(v.value):void 0})):null)))}import Bo from"chalk";import{Box as dr,Text as An}from"ink";import me from"react";import{Box as Lo,Text as dl}from"ink";import $t from"react";import wg from"chalk";var Mg=e=>(b.getTag(e)?.name??"").length+3,Pg=e=>(b.getContributor(e)?.name??"").length+3,cl=({width:e})=>{let{viewMode:t}=H(),n=$(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=pt(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],v=m?.props.assignees??[],I=m?.parentNodeId?!is(o.id,m.parentNodeId)&&t==="dense":!1,S=r.map((A,G)=>{let Re=G===r.length-1,Ae=z(A.id),Ge=Re?Ae?.[s]?.title:void 0;return`${G?" / ":""}${A.title??""}${Ge?` \u25B8 ${Ge}`:""}`}).join(""),N=m?b.getCommentsByIssue(m.id):[],T=N.length?String(N.length).length+11:0,k=I?p.reduce((A,G)=>A+Mg(G),0)+v.reduce((A,G)=>A+Pg(G),0)+T:0,O=Math.max(0,e-k),V=S.substring(0,O)+(c?.id?wg.hex(y.secondary2).dim(` #${et(c.id)}`):""),R=I?[...p.map(A=>$t.createElement(Lo,{key:`tag-${A}`,paddingLeft:1},$t.createElement(Cn,{id:A}))),...v.map(A=>$t.createElement(Lo,{key:`assignee-${A}`,paddingLeft:1},$t.createElement(Pt,{id:A}))),N.length?$t.createElement(Lo,{key:"comments",paddingLeft:1},$t.createElement(dl,{color:y.accent},"[",N.length," comment",N.length===1?"":"s","]")):null]:[];return $t.createElement(Lo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},$t.createElement(dl,{color:y.secondary2},V),R)};import{Box as Lg,Text as ll}from"ink";import ko from"react";var kg=({filters:e})=>ko.createElement(Lg,{columnGap:1},ko.createElement(ll,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ko.createElement(ll,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),ul=ko.memo(kg);import{Box as Dg,Text as Do}from"ink";import ar from"react";function ml(){let{eventLog:e,unappliedEvents:t}=$(),n=e.at(-1)?.id,r=Lr(n??""),o=te(r)?Pr(r.value):"INVALID DATE";return ar.createElement(Dg,{paddingLeft:1},ar.createElement(Do,{backgroundColor:y.accent,color:y.secondary}," Readonly "),ar.createElement(Do,{color:y.accent}," "+t.length+" edits ago at "+o+"."),ar.createElement(Do,{color:y.accent}," Resume with "),ar.createElement(Do,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as Fg,Text as ti}from"ink";import Fo from"react";function pl(){let{replay:e}=$();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Fo.createElement(Fg,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Fo.createElement(ti,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Fo.createElement(ti,{color:y.secondary2},Pr(new Date(r))),Fo.createElement(ti,{color:y.accent},`${t}/${n} edits`))}import ni from"chalk";import{Box as Bg,Text as fl}from"ink";import ri,{useEffect as Ug,useState as Og}from"react";var _g=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],$g=150,gl=12,Wg=.36,vl=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Hg=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},jg=(e,t,n)=>{let r=vl(e),o=vl(t);return Hg({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Vg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return jg(s,i,o)};function yl({syncStatus:e,autoSync:t}){let[n,r]=Og(0);Ug(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Wg)+1)/2,p=Math.round(m*(gl-1));r(v=>v===p?v:p)},$g);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Vg(_g,n/(gl-1))??""}[e.status];return ri.createElement(Bg,null,ri.createElement(fl,null,ni.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ri.createElement(fl,null,ni.hex(i)("\u25CF")+ni.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Cl from"chalk";import{Text as El}from"ink";import Sl,{useEffect as qg,useState as Yg}from"react";var Wt="1.2.2";import oi from"chalk";var Gg="https://registry.npmjs.org/epiq/latest",si=null,hl=0,zg=1e3*60*60*24,xl=e=>e.replace(/^v/,""),Kg=(e,t)=>{let n=xl(e).split(".").map(Number),r=xl(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Il=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(si&&Date.now()-hl<zg)return si;try{let t=await fetch(Gg);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?Kg(r,e)>0:!1};return si=o,hl=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},bl=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?oi.hex(y.accent).dim(s):oi.hex(y.secondary).dim(s)).join(oi.hex(y.secondary2).dim("."))};function Nl(){let[e,t]=Yg({current:Wt,latest:null,updateAvailable:!1});return qg(()=>{let n=!0;return Il(Wt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Sl.createElement(El,{dimColor:!0,color:y.secondary2},Wt+" "):Sl.createElement(El,null,Cl.hex(y.secondary2).dim(Wt),Cl.hex(y.accent).dim(" \u2197 "),bl(Wt,e.latest))}function cr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=$(),{userName:i,preferredEditor:c,autoSync:u}=H(),m=64,p=process.stdout.columns-m-8,v=t||n==="replay",I=s?mn(s.currentLabel,Math.max(0,p)):"";return me.createElement(dr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?me.createElement(dr,{paddingLeft:1},me.createElement(An,{color:y.secondary2},I)):v?me.createElement(An,null," "):o===g.PALETTE?me.createElement(dr,null,me.createElement(An,{color:y.accent},"Command Palette"),me.createElement(An,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):me.createElement(dr,{paddingLeft:1},e.length>0?me.createElement(ul,{filters:e}):me.createElement(cl,{width:p})),n==="live"?me.createElement(dr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},me.createElement(yl,{autoSync:!!u,syncStatus:r}),me.createElement(An,null,Bo.hex(y.secondary2).dim("Mode: ")+Bo.hex(y.secondary2).dim(o.padEnd(8," "))," "),me.createElement(Rl,{icon:"@",value:i}),me.createElement(Rl,{icon:"\u276F",value:c}),me.createElement(Nl,null)):"",n==="peek"?me.createElement(ml,null):"",n==="replay"?me.createElement(pl,null):"")}function Rl({icon:e,value:t}){return me.createElement(An,null,Bo.dim(e)+Bo.hex(y.accent)(` ${t??"-"} `))}import{Box as Xg,Text as Jg}from"ink";import lr from"react";import{Box as Uo,Text as ii}from"ink";import Ht from"react";function ai(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?W(t?.id):[];return Ht.createElement(Uo,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Ht.createElement(Uo,{padding:1,paddingTop:0,paddingBottom:0},Ht.createElement(ii,null,"Select a board:")),Ht.createElement(Uo,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=W(c.id).flatMap(({id:I})=>z(I)).length;return Ht.createElement(Uo,{key:c.id??u},Ht.createElement(ii,{color:m?y.accent:y.secondary2},Ht.createElement(Ce,{isSelected:m})),Ht.createElement(ii,{color:m?y.accent:y.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var Qg=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=$(),u=n.find(({context:I})=>I==="BOARD"),v=s-1-3;return lr.createElement(Xg,{flexDirection:"row"},e.context==="WORKSPACE"?lr.createElement(ai,null):u?lr.createElement(so,{height:v,width:i,swimlanes:(c[u.id]??[]).filter(I=>I!==void 0&&Nt(I)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):lr.createElement(Jg,null))},Al=lr.memo(Qg);import{useEffect as Zg}from"react";var ev=e=>{Zg(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=H();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=f();u==="default"&&!c&&Wr(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Tl=({autoSync:e})=>(ev(e),null);function di({width:e,height:t}){let n=$(),{autoSync:r,viewMode:o}=Yi(),s=n.filters;if(n.mode===g.HELP)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(il,{width:e,height:t}));if(n.mode===g.PALETTE)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{filters:s}),ee.createElement(Kc,{width:e,height:t-2}),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=wt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{hideBreadCrumb:!0,filters:s}),ee.createElement(ei,{height:t,width:e})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{hideBreadCrumb:!0,filters:s}),ee.createElement(al,{height:t,width:e})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=be(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,v=W(p).length,I=3,S=Math.floor(e/I),N=Math.floor(e/Math.max(v,1));e=Math.min(N,S)*Math.max(v,I)}return ee.createElement(jt,{flexDirection:"column"},ee.createElement(Tl,{autoSync:r}),ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{filters:s}),ee.createElement(Al,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}))}import tv from"readline";var Oo,_o,ct,nv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),rv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp]),wl=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=f(),s=ld(e,n);if(!s||r&&!nv.has(s)||o==="replay"&&n===g.DEFAULT&&rv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},ov=()=>async function(t,n){n.name!=="escape"&&(ct&&(clearTimeout(ct),ct=void 0),await wl(n))},sv=()=>async function(t){if(t.length===1&&t[0]===27){ct&&clearTimeout(ct),ct=setTimeout(()=>{wl({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ct=void 0},25);return}ct&&(clearTimeout(ct),ct=void 0)};function Ml(){Oo&&process.stdin.removeListener("keypress",Oo),_o&&process.stdin.removeListener("data",_o),Oo=ov(),_o=sv(),tv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",_o),process.stdin.on("keypress",Oo)}async function Pl(){try{let e=Qn();te(e)&&_e(e.value);let t=Ke(process.cwd()),n=[];if(te(t)){let s=Te({repoRoot:t.value});if(d(s))return Qt(3,s.message);let i=dn(),c=await Gt({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return Qt(3,c.message);let u=await U({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=ft(s.value);if(d(m))return Qt(3,m.message);n=m.value}let r=Jt(n);if(d(r))return Qt(4,r.message);C({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=ci();return d(o)?Qt(6,o.message):(Ml(),l("Booted Epiq",void 0))}catch(e){return Qt(0,Or(e))}}_d();var cv=`${Vt.bold("Epiq CLI")}
|
|
57
|
+
`,si.writeFileSync(t,n,"utf8"),oe.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var yg=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},ee=(e,t)=>a(`[${e}] ${t}`),Cc=async()=>{W("");let e=vn(),t=await dt(process.cwd());if(d(t))return ee(1,t.message);let n=t.value,r=await Fr(n);if(d(r))return ee(2,r.message);if(r.value)return ee(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await yg(n);if(d(o))return ee(2.5,o.message);if(o.value)return ee(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(cs(n))return ee(4,"Epiq project already initialized");let s=Ot();if(!s.isSetupDone||!s.userName)return ee(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=K(),c=i.userName,u=i.userId;if(!u||!c)return ee(5,"Missing Epiq user id");let m=e.stateBranch,p=await Ur({repoRoot:n,branch:m});if(d(p))return ee(6,p.message);if(p.value)return ee(6,`State branch already exists: ${m}`);let f=await bs({repoRoot:n,stateBranchName:m});if(d(f))return ee(6,f.message);let b=$r();if(d(b))return ee(7,b.message);let N=Ec.join(_r(),e.projectId),S=await en({repoRoot:n,stateBranchRoot:N,stateBranchName:m});if(d(S))return ee(8,S.message);let R=Ec.join(N,".epiq");gg.mkdirSync(R,{recursive:!0});let M=ed({userId:u,userName:c});if(d(M))return ee(9,M.message);for(let is of M.value){let Pi=eo({event:is,rootDir:N});if(d(Pi))return ee(9,Pi.message)}let U=await Wr({stateBranchRoot:N,eventFileName:on({userId:u,userName:c})});if(d(U))return ee(10,U.message);let j=await xn({cwd:N,message:"[epiq:init]"});if(d(j))return ee(10,j.message);let D=await Ic(n);if(d(D))return ee(11,D.message);let z=Bi({repoRoot:n,fileContents:e});if(d(z))return ee(12,z.message);let $=await de.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d($))return ee(13,$.message);let P=await de.commit({cwd:n,message:"[epiq:init-project]"});if(d(P))return ee(13,P.message);let O="Project initialized!",Ge=await _({cwd:n,args:["push","-u","origin","HEAD"]});d(Ge)&&(O+=` Warn: [init:14] ${Ge.message}`);let Ne=await Jn({repoRoot:n,stateBranchRoot:N});d(Ne)&&(O+=` Warn: [init:15] ${Ne.message}`);let ue=Ut(M.value).filter(d);if(ue.length>0)return ee(16,ue.map(is=>is.message).join(`
|
|
58
|
+
`));let ce=Je();if(d(ce))return ee(16,ce.message);let{rootNodeId:$n,nodes:Hn}=ce.value,Mi=Hn[$n];return Mi?(T.navigate({contextNode:Mi,selectedIndex:0}),E({hasProjectDefinition:!0,mode:y.DEFAULT}),l(O,null)):ee(16,"Unable to resolve initialized root node")};import{ulid as hg}from"ulid";import{ulid as vg}from"ulid";var Nc=null,Kt=()=>structuredClone(Nc),vr=e=>{Nc=e},Sc=()=>{let{contextNode:e,selectedIndex:t}=g(),r=q(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},ii=({id:e,parentId:t,position:n={at:"end"}})=>{let r=q(t).filter(o=>o.id!==e);return to(r,n)},Ac=({id:e,parentId:t,position:n={at:"end"}})=>{let r=se();if(d(r))return a("Unable to resolve user ID");let o=ii({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:vg(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Rc=e=>{vr(e);let t=Bt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function ai(e){let t=Sc();if(d(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=q(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=Ac({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Rc(u.value)}function di(e){let t=Sc();if(d(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=q(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Ac({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Rc(i.value)}var Tc=()=>{let e=Kt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return a("Move parent not found");let o=q(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(T.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},To=(e,t="Moved preview")=>{if(d(e))return e;let n=Tc();return d(n)?n:(E({mode:y.MOVE}),l(t,null))},wc=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=Y().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=q(n.id)[r];if(!o)return E({mode:y.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=q(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=ii({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(vr({id:hg(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:y.MOVE}),l("Move initialized",null))}if(t==="next")return To(di(1));if(t==="previous")return To(di(-1));if(t==="to-next")return To(ai(1));if(t==="to-previous")return To(ai(-1));if(t==="confirm"){let s=Kt();if(!s)return a("No pending move to confirm");let i=await at();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=Tc();return d(u)?u:(vr(null),E({mode:y.DEFAULT}),l("Moved item",null))}return t==="cancel"?(vr(null),E({mode:y.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Mo}from"ulid";import{monotonicFactory as xg,ulid as bg}from"ulid";var Ig=xg(),wo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Ig();return l("Created issue events",[{id:bg(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Mc=async(e,t)=>{let n=se();if(d(n))return a("Unable to resolve user ID");let r=await at();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=g(),u=m=>{let p=B([m],o);if(d(p))return p;let f=I.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let b=I.getNode(f.parentNodeId);return b?(T.navigate({contextNode:b,selectedIndex:I.getSiblings(f.parentNodeId).findIndex(({id:N})=>N===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return a("Workspace not found");let f=Sn(p.id,n.value,o);return d(f)?f:u({id:Mo(),action:"add.board",payload:{id:Mo(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Le(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Sn(m.value.id,n.value,o);return d(p)?p:u({id:Mo(),action:"add.swimlane",payload:{id:Mo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=G(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let j=Le(s,"SWIMLANE");return d(j)?null:j.value})();if(!p)return a("Unable to add issue in this context");let f=Sn(p.id,n.value,o);if(d(f))return f;let b=wo({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(b))return b;let N=b.value,S=B([...N],o);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let U=N.find(j=>j.action==="add.issue")?.payload.id;return U?(T.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:j})=>j===U)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var Po=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Oa(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Gt();if(d(u))return u;let p=Ut(i).filter(d);if(p.length>0)return Gt(),E(o),a(p.map(b=>b.message).join(", "));let f=g().nodes[e];return f?(T.navigate({contextNode:f,selectedIndex:r}),l("",{unappliedEvents:c})):(Gt(),E(o),a("Board did not exist at that date"))};var Eg=20,Cg=16,Ng=150,Lo=null,ko=null;var fn=()=>{Lo!==null&&(clearInterval(Lo),Lo=null),ko!==null&&(clearTimeout(ko),ko=null)},Pc=()=>{fn(),E({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Sg=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},Lc=({events:e,startTime:t,durationMs:n})=>{fn();let r=e.length,o=e.map(f=>Nn(f)??t),s=o[r-1]??Date.now(),i=Sg(o),c=Math.max(1,Math.round(n*Eg/1e3)),u=Math.max(Math.round(n/c),Cg),m=0,p=0;E({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Lo=setInterval(()=>{m++;let f=m/c,b=[],N;for(;p<r&&i[p]<=f;){let R=e[p],M=Bt(R);if(d(M)){Pc();return}b.push(...Ts(R)),N=R,p++}if(p>=r||m>=c){for(;p<r;p++){let M=Bt(e[p]);if(d(M))break}let R=g().replay;E({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),fn(),ko=setTimeout(Pc,Ng);return}let S=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?Nn(N)??S?.currentTime??t:S?.currentTime??t,currentLabel:N?Pa(N):S?.currentLabel??"",flashNodeIds:N?[...new Set(b)]:S?.flashNodeIds??[]}})},u)};var kc=async()=>{let e=Le(g().breadCrumb,"BOARD");if(d(e))return e;let t=await dt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=Y().commandMeta;if(fn(),r==="now"){let c=Et(n.value);if(d(c))return a(c.message);let u=Gt();if(d(u))return u;let p=Ut(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(E({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=g().eventLog.at(-1),u=Nn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=g().unappliedEvents.at(0),u=Nn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=cn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Po({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(E({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var Dc=async()=>{let e=Le(g().breadCrumb,"BOARD");if(d(e))return e;let t=await dt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=Y().commandMeta,{dateInput:s,durationInput:i}=uo(r,o);if(fn(),g().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=cn(s);if(!c)return a("Invalid replay date");let u=i?lo(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=Po({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:b}=f.value;return b.length===0?(Gt(),E(p),l("Nothing to replay from that point",!0)):(Lc({events:b,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Rg from"zod";var Fc=()=>{let e=Y().commandMeta.inputString,t=Rg.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=Ze({autoSyncDebounceMs:t.data});return d(n)?n:(Fe({autoSyncIntervalMs:t.data}),E({mode:y.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Bc=()=>{let e=Y().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=ad(e),n=Ze({autoSync:t});return d(n)?n:(Fe({autoSync:t}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var Uc=()=>{let e=Y().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Ze({logLevel:e});return d(n)?n:(Fe({logLevel:e}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))};import{spawn as Tg}from"node:child_process";var wg=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},Oc=async e=>new Promise(t=>{let{command:n,args:r}=wg();try{let o=Tg(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var hr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Oc(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},_c=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=ir({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case pe.REF:return hr(Ue(o.id),"ref");case pe.TITLE:return hr(o.title,"title");case pe.DESCRIPTION:return r?hr(r.props?.description??"","description"):a("No issue in scope");case pe.TAGS:{if(!r)return a("No issue in scope");let s=_t(r).map(({name:i})=>i);return hr(s.join(", "),"tags")}case pe.ASSIGNEES:{if(!r)return a("No issue in scope");let s=$t(r).map(({name:i})=>i);return hr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var $c=async()=>{W(""),E({mode:y.DEFAULT});let e=Je();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await oo();return d(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Mg=e=>e.action==="add.issue.comment",Hc=e=>Object.values(g().tags).find(t=>t.name===e),Wc=e=>Object.values(g().contributors).find(t=>t.name===e),wt=async()=>{let e=await at();return d(e)?e:l("Resolved persist root",e.value)},Do=[{systemOnly:!0,intent:w.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:wc},{intent:w.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await wt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=A(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!A(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Mg).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:we(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:we(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Y().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>ie(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return he(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),l("Filter updated",null)}},{intent:w.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Vt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:y.HELP}),l("Viewing help",null)}},{intent:w.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!A(r))return a("Cannot close in this context");let o=g().nodes[me];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await wt();if(d(s))return s;let i=s.value,c=sn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:we(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):It(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=g().nodes[me];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!A(s))return a("Target node is not issue");let c=Ao(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await wt();if(d(m))return m;let p=m.value,f=sn(u.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let b=B([{id:we(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return d(b)?b:l("Issue reopened",null)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Cc},{intent:w.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:Mc,onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=G(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=zd();if(!o)return a("Provide a title");let s=await wt();return d(s)?s:B([{id:we(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Hc(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid untag target");let i=It(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await wt();return d(m)?m:B([{id:we(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=g();if(!o)return a("Invalid tag target");let s=It(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!A(i))return a("Target node is not issue");let c=await wt();if(d(c))return c;let u=Hc(r),m=u?.id??we();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:we(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:we(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=g(),i=G(s.id)[o];if(!i)return a("Invalid assign target");let c=It(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!A(u))return a("Target node is not issue");let m=await wt();if(d(m))return m;let p=Wc(r),f=p?.id??we();return(u.props.assignees??[]).includes(f)?a("Assignee already assigned"):B([...p?[]:[{id:we(),action:"create.contributor",payload:{id:f,name:r},...e.value}],{id:we(),action:"add.issue.assignee",payload:{id:u.id,assignee:f},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=Wc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid unassign target");let i=It(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!A(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await wt();return d(m)?m:B([{id:we(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>Pn)return a(`Cannot exceed ${Pn} characters`);let r=se();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),i=Le([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):It(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!A(m))return a("Target node is not issue");let p=await wt();return d(p)?p:B([{id:we(),action:"add.issue.comment",payload:{id:we(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:$c},{intent:w.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:kc},{intent:w.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:Dc},{intent:w.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await gc();return d(e)?e:(E({mode:y.DEFAULT}),l("Export successful",!0))}},{intent:w.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(T.exit(),l("Exit successful",!0))},{intent:w.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>bc(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>_c(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:w.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ne.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??we();if(!i||!c)return a("Unable to resolve user name or id");let u=Ze({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(Fe({userName:i,userId:c}),E({mode:y.DEFAULT}),l(`Username set to "${i}"`,null))}case ne.EDITOR:{if(!n)return a("No editor provided");let r=Ze({preferredEditor:n});return d(r)?r:(Fe({preferredEditor:n}),E({mode:y.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ne.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Ze({viewMode:n});return d(r)?r:(Fe({viewMode:n}),E({mode:y.DEFAULT}),l(`View set to "${n}"`,null))}case ne.AUTOSYNC:return Bc();case ne.LOG_LEVEL:return Uc();case ne.SYNC_DEBOUNCE_MS:return Fc();case ne.ATTACHMENT_MAX_KB:return Rd();default:return a("Unknown config command")}}},{intent:w.Coffee,description:"Sponsor the development of Epiq!",mode:y.COMMAND_LINE,action:()=>{let e=Y().commandMeta.modifier;return e==="custom"?yr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):yr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),W(""),l("Thanks you!",null)}}];var Pg=new Set(["peek","replay","filter","view-help","yank"]),yt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Y();if(!t)return a("No command to confirm");if(!e&&n===pt.Invalid)return a("Invalid command");let s=ho(t);Wd();let{readOnly:i}=g();if(i&&!Pg.has(s))return ur({status:Pt.Fail,message:"Command not available in readonly state",value:null});let c=Do.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return ur({status:Pt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return ur({status:Pt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?ur(u):(jd({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&io(),u)};var Fo=[{intent:h.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:y.COMMAND_LINE}),W("move cancel"),yt({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:y.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:y.COMMAND_LINE}),W("move start"),yt({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:y.MOVE,action:()=>(E({mode:y.COMMAND_LINE}),W("move confirm"),yt({isForceExecutedBySystem:!0}))}],Bo=[{intent:h.MovePreviousItem,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move next"),yt({isForceExecutedBySystem:!0})):a("No pending move")}],jc=[{intent:h.MoveToNextContainer,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move to-next"),yt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:y.MOVE,action:()=>Kt()?(E({mode:y.COMMAND_LINE}),W("move to-previous"),yt({isForceExecutedBySystem:!0})):a("No pending move")}];var Vc={[L.WORKSPACE]:[...Fo,...Bo],[L.BOARD]:[...Fo,...Bo],[L.SWIMLANE]:[...Fo,...Bo,...jc],[L.TICKET]:[],[L.FIELD]:[],[L.FIELD_LIST]:[],[L.TEXT]:[],[L.COMMENT]:[]};import Lg from"node:fs";import kg from"node:path";var Kc=e=>{let t=Ye(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=Mn(e.hash,e.ext),o=kg.join(Kn(n.value),r);return Lg.existsSync(o)?(yr(o),l(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var Gc=()=>{W("");let{pendingNavTarget:e}=jt();E({mode:y.DEFAULT}),e&&T.navigate(e),Vt({pendingNavTarget:void 0})},zc=[{intent:h.ExitCommandLine,mode:y.HELP,action:()=>(Gc(),l("Exiting help",null))},{intent:h.Exit,mode:y.HELP,action:()=>(Gc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:y.HELP,action:()=>(T.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:y.HELP,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:y.HELP,action:()=>(T.navigateToNextContainer(),l("Navigating to next help container",null))}];var Dg=e=>{E({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=jt();t&&T.navigate(t),Vt({pendingNavTarget:void 0}),W(`${e} `)},qc=()=>{W("");let{pendingNavTarget:e}=jt();e&&T.navigate(e),Vt({pendingNavTarget:void 0}),E({mode:y.DEFAULT})},Yc=[{intent:h.InitCommandPalette,mode:y.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{W("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Vt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:y.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!kt(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Dg(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:y.PALETTE,action:()=>(qc(),l("Exiting palette",null))},{intent:h.Exit,mode:y.PALETTE,action:()=>(qc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:y.PALETTE,action:()=>(T.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:y.PALETTE,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:y.PALETTE,action:()=>(T.navigateToNextContainer(),l("Navigating to next container",null))}];var Xc=[...zc,...Yc,{intent:h.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:y.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:y.COMMAND_LINE}),W(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!q(e?.id??"")?.length){let r=e?I.getAttachment(e.id):void 0;if(r)return Kc(r);if(e?.title===J.DESCRIPTION)return E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===J.ASSIGNEES)return E({mode:y.COMMAND_LINE}),W(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===J.TAGS)return E({mode:y.COMMAND_LINE}),W(`${x.TAG} `),l("Propose command",!0);if(t.title===J.DESCRIPTION&&e?.context==="TEXT")return E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Propose command",!0)}return T.enterChildNode(),l("Entering context",null)}},{intent:h.Yank,mode:y.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===J.DESCRIPTION?pe.DESCRIPTION:e?.title===J.TAGS?pe.TAGS:e?.title===J.ASSIGNEES?pe.ASSIGNEES:pe.REF,r=ie(x.YANK).includes(t)?t:pe.REF;return E({mode:y.COMMAND_LINE}),W(`${x.YANK} ${r}`),l("Propose command",!0)}},{intent:h.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:y.DEFAULT,description:"[e] edit description",action:()=>(E({mode:y.COMMAND_LINE}),W(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(T.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:y.DEFAULT,action:()=>(T.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(T.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:y.DEFAULT,action:()=>(T.navigateToNextContainer(),l("Navigating to next container",null))}];var Fg=500,Bg=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Jc=e=>{let t=Bg(e);t&&vo(n=>(n+t).slice(0,Fg))};var Ug=[y.COMMAND_LINE,y.PALETTE],Og=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(qs(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(qs(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Ys("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Ys("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(vo((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(Jc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>($d(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(Hd(),l("Erasing input word",null))}],Qc=[{intent:h.Confirm,mode:y.COMMAND_LINE,action:()=>(yt(),l("Executing command",null))},{intent:h.ViewHelp,mode:y.DEFAULT,action:()=>(E({mode:y.HELP}),l("Viewing help",null))},...Ug.flatMap(Og),{intent:h.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(E({mode:y.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Vd(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Kd(),l("Getting next command from history",null))}];import tl from"chalk";var Uo=tl.dim.hex(v.secondary2)(": for command line"),Zc="q to exit",el=`${tl.hex(v.accent)("m")} to confirm`,ci={[L.WORKSPACE]:[Uo],[L.BOARD]:[Uo],[L.BOARD+y.COMMAND_LINE]:[Uo],[L.SWIMLANE]:[Uo],[L.TICKET+y.HELP]:[Zc],[L.SWIMLANE+y.HELP]:[Zc],[L.TICKET]:[],[L.FIELD]:[],[L.SWIMLANE+y.MOVE]:[el],[L.TICKET+y.MOVE]:[el]};var xr=e=>e.trim().toLocaleLowerCase(),_g=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},$g=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},nl=(e,t)=>{let n=xr(t.value);if(!n)return!0;switch(t.target){case"title":return xr(e.title??"").includes(n);case"description":return xr(e.props.description??"").includes(n);case"tag":return _g(e).map(xr).some(o=>o.includes(n));case"assignee":return $g(e).map(xr).some(o=>o.includes(n));case"ref":return ba(e.id,t.value);default:return!0}};function rl(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var ol=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var gn,li,ui=new Set,sl=()=>{for(let e of ui)e()},Wg=e=>(ui.add(e),()=>ui.delete(e));function il(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=rl(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=ci[p+n]??ci[p]??[],b=[...Xc,...Vc[p]??[],...Qc],N=ol(b),S=jg(o,s),R=S[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:b,actionIndex:N,selectedNode:R,renderedChildrenIndex:S})}var g=()=>{if(!gn)throw new Error("State not initialized. Call initWorkspaceState() first.");return gn},Je=()=>gn?l("Retrieved state",gn):a("State not initialized. Call initWorkspaceState() first.");function nr(e){li=e;let t=Ye(process.cwd()),n=!1;if(!d(t)){let s=Lt(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=il(r);return d(o)?o:(gn=o.value,sl(),l("State initialized",null))}function he(e){let t=g(),n=e(t),r=il(n);return d(r)?a(r.message??"Unable to update state"):(gn=r.value,sl(),l("State updated",null))}var E=e=>he(t=>({...t,...e}));var H=()=>Hg(Wg,g,g),jg=(e,t)=>{let n={};for(let r of Object.values(e))A(r)&&t.length>0&&!t.every(o=>nl(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},G=e=>g()?.renderedChildrenIndex[e]??[],Gt=()=>li?nr(li):a("Cannot reset state: no initial workspace found"),Rn=()=>gn!==void 0;var mi=e=>{Rn()&&(E({syncStatus:e}),tn({type:"sync-status",payload:e}))},Oo=(e="Syncing...")=>{mi({status:"syncing",msg:e})},_o=(e="Synced")=>{mi({status:"synced",msg:e})},pi=e=>{mi({status:"failed",msg:e})},Qe=e=>(pi(e),a(e));import{decodeTime as JL}from"ulid";var Vg=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=X("getRepoRootDir",await dt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=X("getStateBranchRoot",Pe({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=X("ensureInitialCommit",await ta(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=X("bootstrapStateBranchStorage",await oa({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=X("hasInProgressGitOperation(stateBranchRoot)",await Fr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=X("ensureStateBranchLayout",Qi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Kg=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=X("stageStateBranchOwnEventFile",await Wr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=X("stageStateBranchMediaFiles",await na({stateBranchRoot:t}));if(d(o))return a(o.message);let s=X("hasStagedChanges(after stage)",await Ki(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=X("createStateBranchSyncCommit",await ra({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),l("Committed own event file",{createdCommit:!0,commitSha:i.value}))},so=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Oo();let n=X("ensureSyncReady",await Vg({cwd:e,ensureUpstream:!0}));if(d(n))return Qe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=X("isDetachedHead(stateBranchRoot)",await Gi(o));if(d(i))return Qe(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Qe("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=X("getStateBranch",hn(r));if(d(f))return Qe(f.message);let b=f.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:o});let N=X("commitOwnEventFileToStateBranch",await Kg({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(N))return Qe(N.message);c=N.value.createdCommit,u=N.value.commitSha;let S=X("pullBranchRebaseIfPresent",await vs({cwd:o,branch:b}));if(d(S))return Qe(S.message);if(m=S.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let R=X("pushStateBranch",await Jn({stateBranchRoot:o,repoRoot:r}));if(d(R)&&Vi(R.message)){let M=X("pullBranchRebaseIfPresent(retry)",await vs({cwd:o,branch:b}));if(d(M))return Qe(M.message);m=m||M.value,R=X("pushStateBranch(retry)",await Jn({stateBranchRoot:o,repoRoot:r}))}if(d(R))return Qe(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let R=X("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(d(R))return Qe(R.message);u=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return _o(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var fi=()=>{let e=wn();return d(e)?mt:e.value.attachmentMaxKb??mt},gi=e=>{let t=Ye(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},Me=async e=>{let t=gi(e);if(d(t))return t;let n=Pe({repoRoot:t.value});if(d(n))return a(n.message);let r=vn(),o=await en({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await _({cwd:n.value,args:["pull","--ff-only"]});d(s)&&oe.info(3,s.message);let i=Et(n.value);if(d(i))return a(i.message);let c=an(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},ke=()=>{let e=wn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=Je();return d(e)?a(e.message):e},dl=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:le(t.name)})),cl=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:le(t.name)}));var ll=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(A).filter(o=>e.includeClosed||o.parentNodeId!==me).map(o=>({id:o.id,ref:Ue(o.id),title:lt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===me,readonly:!!o.readonly,tags:dl(o),assignees:cl(o)}));return l("Listed issues",r)},ul=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=Sn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=wo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},ml=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=sn(me,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:ge(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:me,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},pl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Target node is not issue");if(o.parentNodeId!==me)return a("Issue is not closed");let s=Ao(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===me)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=sn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:ge(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},fl=async e=>{let t=gi(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=Pe({repoRoot:t.value});if(d(r))return r;let o=Et(r.value);if(d(o))return o;let s=an(o.value);if(d(s))return s;let i=sn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:ge(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},$o=async(e={})=>{Oo();let t=gi(e.repoRoot);if(d(t))return a("Sync failed");let n=ke();if(d(n))return n;let r=await so({cwd:t.value,ownEventFileName:on(n.value)});return d(r)?(pi(r.message),r):(_o(),l("Synced",r.value))};var vt=async(e={})=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(f=>Vr(f)&&!f.isDeleted),s=new Map,i=new Map;for(let f of r)if(!f.isDeleted){if(Dt(f)&&f.parentNodeId){let b=s.get(f.parentNodeId)??[];b.push(f),s.set(f.parentNodeId,b)}if(A(f)&&f.parentNodeId){let b=i.get(f.parentNodeId)??[];b.push(f),i.set(f.parentNodeId,b)}}let c=wn();if(d(c))return c;let u={};for(let f of r.filter(A))f.isDeleted||(u[f.id]=I.getCommentsByIssue(f.id).map(b=>{let N=I.getContributor(b.authorId);return{id:b.id,issueId:b.issue,body:b.md,author:{id:b.authorId,name:N?.name??"Unknown",color:le(N?.name??b.authorId)},createdAt:al(b.id)}}));let m=new Map;for(let f of n.value.eventLog)f.action==="add.issue.attachment"&&m.set(f.payload.id,f.payload.author);let p={};for(let f of r.filter(A))f.isDeleted||(p[f.id]=I.getAttachmentsByIssue(f.id).map(b=>({id:b.id,issueId:b.issue,name:b.name,fileName:Mn(b.hash,b.ext),bytes:b.bytes,createdAt:al(b.id),canDelete:m.get(b.id)===c.value.userId})));return l("Retrieved Epiq GUI state",{boards:o.sort((f,b)=>f.rank.localeCompare(b.rank)).map(f=>({id:f.id,ref:Ue(f.id),title:f.title,swimlanes:(s.get(f.id)??[]).sort((b,N)=>b.rank.localeCompare(N.rank)).map(b=>({id:b.id,title:b.title,readonly:!!b.readonly,issues:(i.get(b.id)??[]).sort((N,S)=>N.rank.localeCompare(S.rank)).map(N=>({id:N.id,ref:Ue(N.id),title:lt(N.title),description:N.props.description??"",readonly:!!N.readonly,tags:dl(N),assignees:cl(N),parentNodeId:N.parentNodeId,isClosed:N.parentNodeId===me})),parentNodeId:b.parentNodeId}))})),tags:Object.values(n.value.tags).map(f=>({...f,color:le(f.name)})),contributors:Object.values(n.value.contributors).map(f=>({...f,color:le(f.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:le(c.value.userName??"")},commentsByIssueId:u,attachmentsByIssueId:p,attachmentMaxKb:fi()})},gl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:ge(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},yl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=lt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:ge(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},vl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=lt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??ge(),u=[...i?[]:[{id:ge(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:ge(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},hl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:ge(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},xl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=lt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??ge(),u=[...i?[]:[{id:ge(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:ge(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},bl=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:ge(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Ho=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=ge(),c={id:ge(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},Wo=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!A(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:ge(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Il=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!A(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=Sd(t.value.stateBranchRoot,s,fi());if(d(i))return i;let c=lt(e.name??"").trim()||"image",u=ge(),m={id:ge(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);return d(p)?a(p.message):l("Added issue attachment",{id:u,issueId:e.issueId,fileName:Mn(i.value.hash,i.value.ext),bytes:i.value.bytes})},El=async e=>{let t=await Me(e.repoRoot);if(d(t))return t;let n=ke();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return a("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return a("You can only delete your own attachments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!A(s))return a("Attachment target must be an issue");if(s.readonly)return a("Cannot delete attachment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return l("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:ge(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Cl=async e=>{let t=await Me(e.repoRoot);return d(t)?t:Ad(t.value.stateBranchRoot,e.fileName,fi())};var Nl=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=ar();if(d(p))return oe.error(p.message);let{autoSync:f,userName:b,preferredEditor:N}=p.value;return!!(f&&b&&N)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await $o({repoRoot:e.repoRoot}),tn({type:"state",payload:await vt({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=ar();if(d(p))return oe.error(p.message);let{autoSyncDebounceMs:f}=p.value;i()&&(t=setTimeout(()=>{c(),m()},f??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as Gg}from"ws";var Ve=(e,t)=>{e.send(JSON.stringify(t))},br=async(e,t)=>Ve(e,{type:"state",payload:await vt({repoRoot:t})}),ht=async(e,t,n,r,o)=>{if(Ve(e,{type:r,payload:o}),d(o))return Ve(e,{type:"failed",payload:o.message});n(),br(e,t)},Sl=(e,t,{onStateChanged:n})=>{new Gg({server:e,path:"/ws"}).on("connection",o=>{sa(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return br(o,t);if(c==="sync"){let u=await $o({repoRoot:t});return Ve(o,{type:"sync:result",payload:u}),n(),br(o,t)}if(c==="issue:comment:add"){let u=await Ho({repoRoot:t,...i.payload});return ht(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await Wo({repoRoot:t,...i.payload});return Ve(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Ve(o,{type:"failed",payload:u.message}):(n(),br(o,t))}if(c==="issue:edit:description"){let u=await gl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await yl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await vl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await hl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await xl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await bl({repoRoot:t,...i.payload});return ht(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Ve(o,{type:"issues",payload:await ll({repoRoot:t})});if(c==="issues:create"){let u=await ul({...i.payload,repoRoot:t});return Ve(o,{type:"issues:create:result",payload:u}),d(u)?tn({type:"failed",payload:u.message}):(tn({type:"issue:created",payload:u.value}),n(),br(o,t))}if(c==="issues:move"){if(!i.payload.position)return Ve(o,{type:"error",message:"Missing move position"});let u=await fl({...i.payload,repoRoot:t});return ht(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Ve(o,{type:"error",message:"Missing issueId"});let u=await ml({repoRoot:t,issueId:i.payload.issueId});return ht(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Ve(o,{type:"error",message:"Missing issueId"});let u=await pl({repoRoot:t,issueId:i.payload.issueId});return ht(o,t,n,"issue:reopen:result",u)}return Ve(o,{type:"error",message:"Unknown message type"})}catch(i){return Ve(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Yg=yn.dirname(qg(import.meta.url)),Xg=process.env.IS_LOCAL==="true"?yn.resolve(process.cwd(),"dist/gui"):yn.join(Yg,"gui"),ye=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Al=async(e,t=1024*1024)=>new Promise((n,r)=>{let o="",s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),Jg=2*1024*1024,Qg={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},Zg=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",Rl=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=yn.resolve(Xg),o=yn.resolve(r,n),s=yn.relative(r,o);if(s.startsWith("..")||yn.isAbsolute(s))return ye(t,403,{isError:!0,message:"Forbidden"});try{let i=await Tl(o);return t.writeHead(200,{"content-type":Zg(o)}),t.end(i)}catch{return ye(t,404,{isError:!0,message:`Not found: ${n}`})}},ey=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),wl=async e=>{let t=zg.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return ye(s,200,await vt({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Al(o);if(!c.issueId||!c.body?.trim())return ye(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Ho({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?ye(s,400,u):ye(s,200,await vt({repoRoot:e.repoRoot}))}catch(c){return ye(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await Al(o,Jg);if(!c.issueId||!c.dataBase64)return ye(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let u=await Il({repoRoot:e.repoRoot,issueId:c.issueId,name:c.name??"",dataBase64:c.dataBase64});return d(u)?ye(s,400,{isError:!0,message:u.message}):ye(s,200,await vt({repoRoot:e.repoRoot}))}catch(c){return ye(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));if(!c)return ye(s,400,{isError:!0,message:"Missing attachment id"});let u=await El({repoRoot:e.repoRoot,attachmentId:c});return d(u)?ye(s,400,{isError:!0,message:u.message}):ye(s,200,await vt({repoRoot:e.repoRoot}))}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),u=await Cl({repoRoot:e.repoRoot,fileName:c});if(d(u))return ye(s,404,{isError:!0,message:u.message});try{let m=await Tl(u.value.filePath);return s.writeHead(200,{"content-type":Qg[u.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return ye(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return ye(s,400,{isError:!0,message:"Missing comment id"});let u=await Wo({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?ye(s,400,u):ye(s,200,await vt({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?Rl("/",s):Rl(i.pathname,s)});try{await ey(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Nl({repoRoot:e.repoRoot});Sl(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Ml=async e=>{let t=await wl({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${ty.cyan(n)}`),Li(n),l("Started GUI",{url:n})};import{Box as Jt}from"ink";import ae from"react";import{Box as yi,Text as Ir}from"ink";import ot,{useEffect as ny,useMemo as ry}from"react";import{ulid as oy}from"ulid";var Pl=({text:e,match:t,color:n,highlightColor:r=v.secondary,dimColor:o=!1})=>{if(!t)return ot.createElement(Ir,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?ot.createElement(Ir,{color:n,dimColor:o},e):ot.createElement(Ir,{color:n,dimColor:o},e.slice(0,c),ot.createElement(Ir,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Ll=oy(),sy=e=>`${e}`,iy=e=>{let{pendingNavTarget:t}=jt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(ie(x.NONE,{breadCrumb:n,contextNode:r,readOnly:g().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=ho(i),u=Do.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},ay=e=>Q.text({id:Ll,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),dy=(e,t,n)=>Q.text({id:sy(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),vi=[],cy=e=>{kl();let t=I.createNode(ay(g().rootNodeId));d(t)||!kt(t.value)||(vi=[t.value,...e.map((n,r)=>dy(n,r,Ll)).map(I.createNode).filter(te).map(({value:n})=>n).filter(kt)],T.navigate({contextNode:t.value,selectedIndex:0}))},kl=()=>{let e=vi.map(t=>t.id);vi=[];for(let t of e)I.deleteNode(t)};function Dl({width:e,height:t}){let r=Gd().value.trim().toLowerCase(),o=ry(()=>iy(r),[r]);ny(()=>(cy(o),()=>{kl()}),[o]);let s=g().selectedIndex;return ot.createElement(yi,{flexDirection:"column",width:e,height:t-2},ot.createElement(et,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?v.accent:v.secondary2,p=i.isAvailable?"":"[unavailable] ";return ot.createElement(yi,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:v.secondary,borderStyle:"single"},ot.createElement(Ir,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",ot.createElement(Pl,{text:ua(i.command),match:r,color:m,dimColor:!i.isAvailable})),ot.createElement(yi,{paddingLeft:2},ot.createElement(Pl,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?v.primary:v.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Ay}from"ink";import Ko from"react";import Cr from"chalk";import{Box as hi,Text as Fl}from"ink";import Er,{useEffect as ly,useMemo as uy,useState as my}from"react";var Bl=Cr.hex(v.secondary),py=Cr.inverse,fy=Cr.inverse.hex(v.secondary2),gy={hint:"",hints:[],overlap:0,remainder:""},Ol=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},yy=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=le(t);return{bg:r=>Cr.bgHex(n).black(r),bgCursor:r=>Cr.bgHex(n).inverse.black(r)}}return Rs(t)},vy=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Ol({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},Ul=()=>({value:Ae.value,cursorPosition:Ae.cursorPosition,commandIsPending:Ae.commandIsPending,autoCompletion:Ae.commandMeta.autoCompletion??gy,infoMessage:Ae.commandMeta.infoMessage,validationStatus:Ae.commandMeta.validity,command:Ae.commandMeta.command,inputString:Ae.commandMeta.inputString,modifier:Ae.commandMeta.modifier}),hy=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,_l=({width:e,mode:t})=>{let[n,r]=my(Ul());ly(()=>{let S=()=>{let M=Ul();r(U=>hy(U,M)?U:M)},R=zs(S);return S(),()=>{R()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p,validationStatus:f}=n,b=c&&f===pt.Invalid,N=uy(()=>{let S=Math.max(0,Math.min(s,o.length)),R=Ol({value:o,command:m}),M=vy({value:o,command:m,modifier:p}),U=m?Rs(m):null,j=yy({command:m,modifier:p}),D=(ue,ce)=>{let $n=R&&ce>=R.start&&ce<R.end,Hn=M&&ce>=M.start&&ce<M.end;return $n&&U?U.fg(ue):Hn&&j?j.bg(ue):ue},z=(ue,ce)=>{let $n=R&&ce>=R.start&&ce<R.end,Hn=M&&ce>=M.start&&ce<M.end;return $n&&U?U.fgCursor(ue):Hn&&j?j.bgCursor(ue):py(ue)},$=o.slice(0,S),P=o[S]??" ",O=S<o.length?o.slice(S+1):"",Ge=Array.from($).map((ue,ce)=>D(ue,ce)).join(""),Ne=z(P,S),ze=Array.from(O).map((ue,ce)=>D(ue,S+1+ce)).join("");if(u.hint){let ue=u.hint[u.overlap]??P;Ne=fy(ue),ze=Bl(u.remainder.slice(1)+O)}return Bl(t===y.PALETTE?"?":":")+Ge+Ne+ze},[o,s,u,m,p]);return Er.createElement(hi,{flexDirection:"column",justifyContent:"flex-start"},Er.createElement(hi,{flexDirection:"column",paddingX:1,borderColor:v.secondary,borderStyle:"round",width:e},Er.createElement(hi,null,Er.createElement(Fl,null,N),i&&Er.createElement(Fl,{wrap:"truncate",color:b?v.red:v.secondary2},` ${i} `))))};import{Box as xy,Text as by}from"ink";import $l from"react";var Iy=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Hl=({width:e,availableHints:t})=>{let n=Iy(t,e).join(" | ");return $l.createElement(xy,{width:e,borderStyle:"round",borderColor:v.secondary,paddingX:1},$l.createElement(by,{color:v.secondary2},n.length?n:"\xA0"))};import{Box as Ey,Text as jo}from"ink";import Nr,{useEffect as Cy,useRef as Un,useState as Ny}from"react";var Sy=40,Vo=.3,xi="\u2500",Wl=1,jl=16,Vl=({width:e})=>{let{replay:t}=H(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Wl,[c,u]=Ny(0),m=Un(r);m.current=r;let p=Un(0),f=Un(0),b=Un(0),N=Un(0),S=Un(0);if(Cy(()=>{if(!n){p.current=0,b.current=0,N.current=0,S.current=0,u(0);return}p.current=m.current,f.current=Date.now(),b.current=m.current;let D=setInterval(()=>{let z=Date.now(),$=m.current;if($!==b.current){let ze=$-b.current,ue=z-f.current;if(ze<0)N.current=0,S.current=0;else if(ze>0&&ue>0){let ce=ze/ue;N.current=N.current===0?ce:N.current*(1-Vo)+ce*Vo,S.current=S.current===0?ze:S.current*(1-Vo)+ze*Vo}p.current=$,f.current=z,b.current=$}let P=z-f.current,O=Math.min(S.current,N.current*P),Ge=Math.min(1,p.current+O),Ne=Math.round(Ge*i);u(ze=>ze===Ne?ze:Ne)},Sy);return()=>clearInterval(D)},[n,i]),!t)return null;let R=D=>{let z=s>1?D/(s-1):0,$=Math.round(z*(jl-1))/(jl-1);return Gr($)},M=Math.min(s,Math.floor(c/Wl)),U=[];for(let D=0;D<M;D++){let z=R(D),$=U[U.length-1];$&&$.color===z?$.text+=xi:U.push({text:xi,color:z})}let j=xi.repeat(Math.max(0,s-M));return Nr.createElement(Ey,{width:e,borderStyle:"round",borderColor:v.secondary,paddingX:1,columnGap:1},Nr.createElement(jo,{color:v.secondary2},"\u25B6"),Nr.createElement(jo,null,U.map((D,z)=>Nr.createElement(jo,{key:z,color:D.color},D.text)),Nr.createElement(jo,{color:v.secondary,dimColor:!0},j)))};var Sr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=H(),o=t===y.COMMAND_LINE||t===y.PALETTE;return Ko.createElement(Ay,null,o?Ko.createElement(_l,{width:e,mode:t}):r==="replay"?Ko.createElement(Vl,{width:e}):Ko.createElement(Hl,{width:e,mode:t,availableHints:n}))};import{Box as zt,Text as On}from"ink";import De,{useEffect as Ry,useMemo as Ty}from"react";import{ulid as Kl}from"ulid";var zo=Kl(),wy=()=>[...new Set([...g().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),My=e=>Q.text({id:zo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Py=(e,t,n)=>Q.text({id:Kl(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Go=[],Gl=()=>{let e=Go.filter(n=>n.id!==zo).map(n=>n.id),t=Go.filter(n=>n.id===zo).map(n=>n.id);Go=[];for(let n of[...e,...t])I.deleteNode(n)},Ly=e=>{Gl();let t=I.createNode(My(g().rootNodeId));if(d(t)||!kt(t.value))return logger.error("Could not attach help nodes");Go=[t.value,...e.map((n,r)=>Py(n,r,zo)).map(I.createNode).filter(te).map(({value:n})=>n).filter(kt)],T.navigate({contextNode:t.value,selectedIndex:0})},zl=({width:e,height:t})=>{let n=Ty(()=>wy(),[]);Ry(()=>(Ly(n),()=>{Gl()}),[n]);let r=g().selectedIndex;return De.createElement(zt,{flexDirection:"column",marginTop:3,borderColor:v.secondary,borderStyle:"round",width:e,height:t-2},De.createElement(zt,{paddingX:1,justifyContent:"center"},De.createElement(On,{color:v.accent},"Help"),De.createElement(On,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),De.createElement(zt,{paddingX:1,marginTop:1},De.createElement(zt,{width:20,justifyContent:"flex-end"},De.createElement(On,{color:v.secondary},"Key(s)")),De.createElement(zt,{flexGrow:1,width:40,paddingLeft:2},De.createElement(On,{color:v.secondary},"Action"))),De.createElement(et,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return De.createElement(zt,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},De.createElement(zt,{width:20,justifyContent:"flex-end"},De.createElement(On,{color:v.accent},o)),De.createElement(zt,{flexGrow:1,width:40,paddingLeft:2},De.createElement(On,{color:c?v.primary:v.secondary2},s)))})))};import ky from"chalk";import{Box as qo,Text as Mt}from"ink";import Ke from"react";var ql=({width:e,height:t})=>Ke.createElement(qo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:v.secondary,rowGap:1},Ke.createElement(Mt,{color:v.accent,bold:!0},"Initialize project"),Ke.createElement(Mt,null,`This folder is not an ${ky.hex(v.accent)("epiq")} project yet.`),Ke.createElement(Mt,{color:v.primary},"To start tracking issues here, we need to initialize a new",Ke.createElement(Mt,{color:v.primary,backgroundColor:v.secondary}," .epiq/project.json "),"file in this repository."),Ke.createElement(qo,{marginTop:1,flexDirection:"column"},Ke.createElement(qo,null,Ke.createElement(Mt,{color:v.accent}," "),Ke.createElement(Mt,{color:v.primary},"Type "),Ke.createElement(Mt,{backgroundColor:v.secondary}," :init "))),Ke.createElement(qo,{marginTop:1},Ke.createElement(Mt,{color:v.secondary2},"This will create, commit and push "),Ke.createElement(Mt,{color:v.primary,backgroundColor:v.secondary}," .epiq/project.json ")));import{Box as Yo,Text as xt}from"ink";import Ce from"react";var Dy=({isDone:e,command:t,value:n})=>Ce.createElement(Yo,null,Ce.createElement(xt,{color:v.accent,dimColor:e},e?" \u2714 ":" "),Ce.createElement(xt,{dimColor:e},"Type "),Ce.createElement(xt,{backgroundColor:v.secondary,dimColor:e}," "+t+" "),n!==void 0&&Ce.createElement(Ce.Fragment,null,Ce.createElement(xt,{dimColor:e}," "),Ce.createElement(xt,{color:v.secondary,dimColor:e},"<"+n+">"))),Fy=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function bi({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Ot(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(f=>!f.done),p=m===-1?void 0:u[m];return Ce.createElement(Yo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:v.secondary,rowGap:1},Ce.createElement(xt,{color:v.accent,bold:!0},"Welcome! \u{1F539}"),Ce.createElement(xt,null,"Let's get you started - it's a breeze."),Ce.createElement(xt,{color:v.secondary2},"Remember - you can always search available commands by typing:",Ce.createElement(xt,{color:v.accent}," ? ")),p&&Ce.createElement(xt,{color:v.secondary2},p.message),Ce.createElement(Yo,{flexDirection:"column"},u.map((f,b)=>m===-1||b<=m?Ce.createElement(Yo,{key:f.key,marginBottom:1},Ce.createElement(Dy,{isDone:f.done,command:f.command,value:f.done?Fy(f.value):void 0})):null)))}import es from"chalk";import{Box as Rr,Text as _n}from"ink";import ve from"react";import{Box as Xo,Text as Yl}from"ink";import qt from"react";import By from"chalk";var Uy=e=>(I.getTag(e)?.name??"").length+3,Oy=e=>(I.getContributor(e)?.name??"").length+3,Xl=({width:e})=>{let{viewMode:t}=K(),n=H(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=It(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],b=m?.parentNodeId?!Ns(o.id,m.parentNodeId)&&t==="dense":!1,N=r.map(($,P)=>{let O=P===r.length-1,Ge=q($.id),Ne=O?Ge?.[s]?.title:void 0;return`${P?" / ":""}${$.title??""}${Ne?` \u25B8 ${Ne}`:""}`}).join(""),S=m?I.getCommentsByIssue(m.id):[],R=S.length?String(S.length).length+11:0,M=b?p.reduce(($,P)=>$+Uy(P),0)+f.reduce(($,P)=>$+Oy(P),0)+R:0,U=c?.id!=null&&!(t==="wide"&&A(c)),j=Math.max(0,e-M),D=N.substring(0,j)+(U?By.hex(v.secondary2).dim(` ${Ue(c.id)}`):""),z=b?[...p.map($=>qt.createElement(Xo,{key:`tag-${$}`,paddingLeft:1},qt.createElement(kn,{id:$}))),...f.map($=>qt.createElement(Xo,{key:`assignee-${$}`,paddingLeft:1},qt.createElement(Ht,{id:$}))),S.length?qt.createElement(Xo,{key:"comments",paddingLeft:1},qt.createElement(Yl,{color:v.accent},"[",S.length," comment",S.length===1?"":"s","]")):null]:[];return qt.createElement(Xo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},qt.createElement(Yl,{color:v.secondary2},D),z)};import{Box as _y,Text as Jl}from"ink";import Jo from"react";var $y=({filters:e})=>Jo.createElement(_y,{columnGap:1},Jo.createElement(Jl,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Jo.createElement(Jl,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ql=Jo.memo($y);import{Box as Hy,Text as Qo}from"ink";import Ar from"react";function Zl(){let{eventLog:e,unappliedEvents:t}=H(),n=e.at(-1)?.id,r=Xr(n??""),o=te(r)?Yr(r.value):"INVALID DATE";return Ar.createElement(Hy,{paddingLeft:1},Ar.createElement(Qo,{backgroundColor:v.accent,color:v.secondary}," Readonly "),Ar.createElement(Qo,{color:v.accent}," "+t.length+" edits ago at "+o+"."),Ar.createElement(Qo,{color:v.accent}," Resume with "),Ar.createElement(Qo,{backgroundColor:v.accent,color:v.secondary}," ",":peek now"," "))}import{Box as Wy,Text as Ii}from"ink";import Zo from"react";function eu(){let{replay:e}=H();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Zo.createElement(Wy,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Zo.createElement(Ii,{backgroundColor:v.accent,color:v.secondary}," \u25B6 REPLAY "),Zo.createElement(Ii,{color:v.secondary2},Yr(new Date(r))),Zo.createElement(Ii,{color:v.accent},`${t}/${n} edits`))}import Ei from"chalk";import{Box as jy,Text as tu}from"ink";import Ci,{useEffect as Vy,useState as Ky}from"react";var Gy=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],zy=150,nu=12,qy=.36,ru=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Yy=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},Xy=(e,t,n)=>{let r=ru(e),o=ru(t);return Yy({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Jy=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return Xy(s,i,o)};function ou({syncStatus:e,autoSync:t}){let[n,r]=Ky(0);Vy(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*qy)+1)/2,p=Math.round(m*(nu-1));r(f=>f===p?f:p)},zy);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:v.secondary2,failed:v.yellow,pending:v.secondary2,syncing:Jy(Gy,n/(nu-1))??""}[e.status];return Ci.createElement(jy,null,Ci.createElement(tu,null,Ei.hex(v.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Ci.createElement(tu,null,Ei.hex(i)("\u25CF")+Ei.hex(v.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import cu from"chalk";import{Text as lu}from"ink";import uu,{useEffect as tv,useState as nv}from"react";var Yt="1.3.0";import Ni from"chalk";var Qy="https://registry.npmjs.org/epiq/latest",Si=null,su=0,Zy=1e3*60*60*24,iu=e=>e.replace(/^v/,""),ev=(e,t)=>{let n=iu(e).split(".").map(Number),r=iu(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},au=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Si&&Date.now()-su<Zy)return Si;try{let t=await fetch(Qy);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?ev(r,e)>0:!1};return Si=o,su=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},du=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Ni.hex(v.accent).dim(s):Ni.hex(v.secondary).dim(s)).join(Ni.hex(v.secondary2).dim("."))};function mu(){let[e,t]=nv({current:Yt,latest:null,updateAvailable:!1});return tv(()=>{let n=!0;return au(Yt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?uu.createElement(lu,{dimColor:!0,color:v.secondary2},Yt+" "):uu.createElement(lu,null,cu.hex(v.secondary2).dim(Yt),cu.hex(v.accent).dim(" \u2197 "),du(Yt,e.latest))}function Tr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=H(),{userName:i,preferredEditor:c,autoSync:u}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",b=s?nn(s.currentLabel,Math.max(0,p)):"";return ve.createElement(Rr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?ve.createElement(Rr,{paddingLeft:1},ve.createElement(_n,{color:v.secondary2},b)):f?ve.createElement(_n,null," "):o===y.PALETTE?ve.createElement(Rr,null,ve.createElement(_n,{color:v.accent},"Command Palette"),ve.createElement(_n,{dimColor:!0,color:v.secondary2}," ","- search, select and press enter")):ve.createElement(Rr,{paddingLeft:1},e.length>0?ve.createElement(Ql,{filters:e}):ve.createElement(Xl,{width:p})),n==="live"?ve.createElement(Rr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},ve.createElement(ou,{autoSync:!!u,syncStatus:r}),ve.createElement(_n,null,es.hex(v.secondary2).dim("Mode: ")+es.hex(v.secondary2).dim(o.padEnd(8," "))," "),ve.createElement(pu,{icon:"@",value:i}),ve.createElement(pu,{icon:"\u276F",value:c}),ve.createElement(mu,null)):"",n==="peek"?ve.createElement(Zl,null):"",n==="replay"?ve.createElement(eu,null):"")}function pu({icon:e,value:t}){return ve.createElement(_n,null,es.dim(e)+es.hex(v.accent)(` ${t??"-"} `))}import{Box as rv,Text as ov}from"ink";import wr from"react";import{Box as ts,Text as Ai}from"ink";import Xt from"react";function Ri(){let e=H(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?G(t?.id):[];return Xt.createElement(ts,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:v.secondary,width:s},Xt.createElement(ts,{padding:1,paddingTop:0,paddingBottom:0},Xt.createElement(Ai,null,"Select a board:")),Xt.createElement(ts,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,f=G(c.id).flatMap(({id:b})=>q(b)).length;return Xt.createElement(ts,{key:c.id??u},Xt.createElement(Ai,{color:m?v.accent:v.secondary2},Xt.createElement(Re,{isSelected:m})),Xt.createElement(Ai,{color:m?v.accent:v.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var sv=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=H(),u=n.find(({context:b})=>b==="BOARD"),f=s-1-3;return wr.createElement(rv,{flexDirection:"row"},e.context==="WORKSPACE"?wr.createElement(Ri,null):u?wr.createElement(So,{height:f,width:i,swimlanes:(c[u.id]??[]).filter(b=>b!==void 0&&Dt(b)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):wr.createElement(ov,null))},fu=wr.memo(sv);import{useEffect as iv}from"react";var av=e=>{iv(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=g();u==="default"&&!c&&io(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},gu=({autoSync:e})=>(av(e),null);function Ti({width:e,height:t}){let n=H(),{autoSync:r,viewMode:o}=va(),s=n.filters;if(n.mode===y.HELP)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(zl,{width:e,height:t}));if(n.mode===y.PALETTE)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{filters:s}),ae.createElement(Dl,{width:e,height:t-2}),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Ot(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{hideBreadCrumb:!0,filters:s}),ae.createElement(bi,{height:t,width:e})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{hideBreadCrumb:!0,filters:s}),ae.createElement(ql,{height:t,width:e})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Le(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,f=G(p).length,b=3,N=Math.floor(e/b),S=Math.floor(e/Math.max(f,1));e=Math.min(S,N)*Math.max(f,b)}return ae.createElement(Jt,{flexDirection:"column"},ae.createElement(gu,{autoSync:r}),ae.createElement(Jt,{flexDirection:"column"},ae.createElement(Tr,{filters:s}),ae.createElement(fu,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ae.createElement(Sr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import dv from"readline";var ns,rs,bt,cv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.Yank,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),lv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp,h.Yank]),yu=async e=>{if(e.ctrl&&e.name==="c")return T.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=g(),s=qd(e,n);if(!s||r&&!cv.has(s)||o==="replay"&&n===y.DEFAULT&&lv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},uv=()=>async function(t,n){n.name!=="escape"&&(bt&&(clearTimeout(bt),bt=void 0),await yu(n))},mv=()=>async function(t){if(t.length===1&&t[0]===27){bt&&clearTimeout(bt),bt=setTimeout(()=>{yu({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),bt=void 0},25);return}bt&&(clearTimeout(bt),bt=void 0)};function vu(){ns&&process.stdin.removeListener("keypress",ns),rs&&process.stdin.removeListener("data",rs),ns=uv(),rs=mv(),dv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",rs),process.stdin.on("keypress",ns)}async function hu(){try{let e=wn();te(e)&&Fe(e.value);let t=Ye(process.cwd()),n=[];if(te(t)){let s=Pe({repoRoot:t.value});if(d(s))return dn(3,s.message);let i=vn(),c=await en({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return dn(3,c.message);let u=await _({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=Et(s.value);if(d(m))return dn(3,m.message);n=m.value}let r=an(n);if(d(r))return dn(4,r.message);E({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=wi();return d(o)?dn(6,o.message):(vu(),l("Booted Epiq",void 0))}catch(e){return dn(0,ro(e))}}vc();var yv=`${Qt.bold("Epiq CLI")}
|
|
58
59
|
|
|
59
|
-
${
|
|
60
|
-
${
|
|
60
|
+
${Qt.dim("Boot in directory:")}
|
|
61
|
+
${Qt.cyan("$ epiq")}
|
|
61
62
|
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
`,
|
|
65
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
66
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
63
|
+
${Qt.dim("Launch GUI:")}
|
|
64
|
+
${Qt.cyan("$ epiq gui")}
|
|
65
|
+
`,vv=fv(yv,{importMeta:import.meta,version:Yt,flags:{init:{type:"boolean",default:!1}}}),os=vv.input[0];os&&os!=="gui"&&(console.error(Qt.red(`Unknown command: ${os}`)),process.exit(1));var xu=process.stdout.columns||120,bu=process.stdout.rows||20,ss=null,hv=e=>{try{return ss?(ss.rerender(e),l("Rerendered app",void 0)):(ss=pv(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${ro(t)}`)}},wi=()=>hv(gv.createElement(Ti,{width:xu,height:bu}));process.stdout.on("resize",()=>{if(xu=process.stdout.columns||120,bu=process.stdout.rows||20,!ss)return;let e=wi();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(os==="gui"){let e=await Ml({repoRoot:process.cwd()});d(e)&&(console.error(Qt.red(`Failed to start Epiq GUI:
|
|
66
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await hu();d(e)&&(logger.info(e.message),console.error(Qt.red(`Failed to boot Epiq:
|
|
67
|
+
${e.message}`)),process.exitCode=1)}export{wi as renderApp};
|