epiq 0.6.6 → 0.6.8
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/index.js +47 -50
- package/dist/mcp.js +47 -47
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,66 +1,63 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Pr from"chalk";import{render as
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import Pr from"chalk";import{render as Gm}from"ink";import qm from"meow";import Ym from"react";import Hr from"node:fs";import _d from"node:os";import Me from"node:path";import qt from"node:fs";import{ulid as Pd}from"ulid";import{z as In}from"zod";var qe={None:"none",Success:"success",Fail:"fail"},a=e=>({status:qe.Fail,message:e,value:null}),c=(e,t)=>({status:qe.Success,message:e,value:t}),d=e=>e.status==="fail",X=e=>e.status==="success";import zt from"node:fs";import Oe from"node:path";var op=process.env.IS_LOCAL==="true",$e=".epiq",he=".epiq-global",Nn="events",wd="project.json",En=e=>Oe.join(e,$e),Sn=e=>Oe.join(En(e),wd),Gt=e=>Oe.join(En(e),Nn),qo=e=>Oe.join(e,$e),Md=e=>{let t=Oe.join(e,$e);return zt.existsSync(t)&&zt.statSync(t).isDirectory()},Dr=e=>{let t=Sn(e);return zt.existsSync(t)&&zt.statSync(t).isFile()},bn=e=>{let t=Oe.resolve(e);for(;;){if(Md(t))return c("Resolved closest .epiq root",t);let n=Oe.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ye=e=>{let t=Oe.resolve(e);for(;;){if(Dr(t))return c("Resolved closest epiq project root",t);let n=Oe.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Yo=e=>{let t=Gt(e);try{return zt.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Re=async()=>{let e=await Je(process.cwd());if(d(e))return e;let t=Xe({repoRoot:e.value});return d(t)?t:c("Resolved persist root",t.value)};var kd="_epiq/_evt",Ld=In.object({projectId:In.string().min(1),stateBranch:In.string().min(1),createdAt:In.iso.datetime()}),Xo=()=>({projectId:Pd(),stateBranch:kd,createdAt:new Date().toISOString()}),Qe=e=>{let t=Sn(e);if(!qt.existsSync(t))return a("Missing .epiq/project.json");try{let n=qt.readFileSync(t,"utf8"),r=JSON.parse(n),o=Ld.safeParse(r);return o.success?c("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Jo=e=>{let t=Qe(e);return d(t)?a(t.message):c("Read projectId",t.value.projectId)},Qo=({repoRoot:e,fileContents:t})=>{let n=En(e),r=Sn(e);try{if(qt.mkdirSync(n,{recursive:!0}),qt.existsSync(r)){let o=Qe(e);return d(o)?a(o.message):c("Project already initialized",null)}return qt.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),c("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Fr=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let s=r(...i);if(!n.has(s)){let l=e(...i).then(u=>(d(u)&&n.delete(s),u));n.set(s,l)}return n.get(s)});return o.clear=()=>n.clear(),o};import Yt from"fs";import ei from"path";import Dd from"util";var Zo=1e3,Fd=50,Br=0,ti=()=>{let e=process.cwd(),t=bn(e);if(!d(t))return ei.join(t.value,$e,"log","epiq.log")};function Bd(){let e=ti();if(!e||!Yt.existsSync(e))return;let n=Yt.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Zo)return;let r=n.slice(-Zo).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:s,stderr:g,exitCode:124}:a(g))},
|
|
9
|
-
`)))}),o.on("close",g=>{let y=g??1;if(n){u({stdout:s,stderr:
|
|
10
|
-
`)));return}u(
|
|
11
|
-
${n.message}`);let r=await
|
|
12
|
-
${r.message}`):
|
|
13
|
-
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(
|
|
14
|
-
${o.message}`);let i=await
|
|
15
|
-
${i.message}`):
|
|
16
|
-
`+e.message);let t=
|
|
17
|
-
`+t.message):
|
|
6
|
+
`;Yt.writeFileSync(e,r,"utf8")}function Ur(e,t,n=!1){let r=ti();if(!r)return;let o=Dd.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
7
|
+
`;Yt.mkdirSync(ei.dirname(r),{recursive:!0}),Yt.appendFileSync(r,l,"utf8"),Br++,Br>=Fd&&(Br=0,Bd())}var ae={info(...e){Ur("[Info]",e,!1)},debug(...e){Ur("[debug]",e,!0)},error(...e){let t=e.find(n=>n instanceof Error)instanceof Error?void 0:new Error().stack;Ur("[Error]",[...e,t].filter(Boolean),!1)}};globalThis.logger=ae;import{spawn as Ud}from"node:child_process";import Rn from"node:fs";import Xt from"node:path";var V={stage:({cwd:e,pathspec:t})=>L({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>L({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>L({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>L({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>L({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 L({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>L({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>L({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>L({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>L({args:["worktree","prune"],cwd:e})};var wt=e=>{let t=Ye(e);if(d(t))return a("Unable to resolve epiq project root");let n=Qe(t.value);return d(n)?a("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},Ce="origin";var ni=1e4,Od={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},oi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Rn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(a(g));return}let o=Ud("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Od}),i=!1,s="",l="",u=g=>{i||(i=!0,clearTimeout(m),r(g))},m=setTimeout(()=>{o.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ni}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:s,stderr:g,exitCode:124}:a(g))},ni);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{s+=g}),o.stderr.on("data",g=>{l+=g}),o.on("error",g=>{if(n){u({stdout:s,stderr:g.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
|
|
9
|
+
`)))}),o.on("close",g=>{let y=g??1;if(n){u({stdout:s,stderr:l,exitCode:y});return}if(y!==0){u(a([`git ${e.join(" ")}`,l.trim()||s.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
+
`)));return}u(c("Git command succeeded",{stdout:s,stderr:l,exitCode:y}))})}),L=({args:e,cwd:t})=>oi({args:e,cwd:t,allowFail:!1}),we=({args:e,cwd:t})=>oi({args:e,cwd:t,allowFail:!0}),Mt=async({cwd:e,message:t})=>{let n=await V.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
|
+
${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
12
|
+
${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},$d=async e=>{let t=await L({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Xt.isAbsolute(n)?n:Xt.resolve(e,n))},Wd=async e=>{let t=await $d(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress",REBASE_HEAD:"rebase in progress",CHERRY_PICK_HEAD:"cherry-pick in progress",REVERT_HEAD:"revert in progress",BISECT_LOG:"bisect in progress"};for(let[u,m]of Object.entries(r))if(Rn.existsSync(Xt.join(n,u)))return c("Checked for in-progress Git operation",m);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[u,m]of Object.entries(o))if(Rn.existsSync(Xt.join(n,u)))return c("Checked for in-progress Git operation",m);let i=await L({cwd:e,args:["status","--porcelain=v1","--branch"]});if(d(i))return a(i.message);let s=i.value.stdout.toLowerCase(),l=["rebase in progress","merge in progress","cherry-pick in progress","revert in progress","bisect in progress"].find(u=>s.includes(u));return c("Checked for in-progress Git operation",l??null)},An=async e=>{let t=await Wd(e);return d(t)?a(t.message):c("Checked for in-progress Git operation",t.value!==null)},Or=async({repoRoot:e})=>{let n=(await we({args:["remote","get-url",Ce],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Tn=async({repoRoot:e,branch:t})=>{let n=await we({args:["ls-remote","--heads",Ce,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Ce}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},wn=async({repoRoot:e,branch:t})=>{let n=await we({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},ri=e=>{try{return Rn.realpathSync.native(e)}catch{return Xt.resolve(e)}},ii=async({repoRoot:e,worktreeRoot:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=ri(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(ri).includes(r);return c("Checked worktree registration",o)},$r=async e=>{let t=await we({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Mn=async e=>{let t=await L({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):c("Resolved current branch",t.value.stdout.trim())},si=async e=>{let t=await L({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},ai=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Hd=async e=>(await we({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1);var Wr=async({cwd:e,branch:t})=>{let n=await Tn({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await Hd(e);if(d(r))return a(r.message);let o=await V.fetch({cwd:e,remote:Ce,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
14
|
+
${o.message}`);let i=await V.pullRebase({cwd:e,remote:Ce,branch:t});return d(i)?a(`Failed during pull --rebase
|
|
15
|
+
${i.message}`):c("Pulled with rebase",!0)},di=async e=>{let t=await we({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var ci=async e=>{let t=await Mn(e);return d(t)?a(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var ui="4b825dc642cb6eb9a060e54bf8d69288fbee4904",_r=e=>Me.join($e,Nn,e),mi=()=>Me.join(_d.homedir(),he),Pn=()=>Me.join(mi(),"worktrees"),Xe=({repoRoot:e})=>{let t=Jo(e);return d(t)?a(t.message):c("Resolved state branch root",Me.join(Pn(),t.value))},jd=e=>Me.join(e,$e),li=e=>Me.join(jd(e),Nn);var Jt=e=>{try{return Hr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},kn=()=>{let e=Jt(mi());if(d(e))return a(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=Jt(Pn());return d(t)?a(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):c("Ensured epiq storage",!0)},pi=e=>{Hr.existsSync(e)&&(ae.debug("[sync] remove path",e),Hr.rmSync(e,{recursive:!0,force:!0}))};var gi=(e,t)=>{for(let n of[li(e),li(t)]){let r=Jt(n);if(d(r))return a(r.message)}return c("Ensured state branch",void 0)},fi=async e=>{let t=await L({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(s=>s
|
|
20
|
-
${o.message}`);let i=await Pt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?a(i.message):l("Cleaned storage branch",!0)},Ze=Fr(async(e=process.cwd())=>{let t=await D({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=>ke.resolve(e)),dg=Fr(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=ke.isAbsolute(n)?n:ke.join(e,n);return l("Resolved git dir",r)},e=>ke.resolve(e));import{Box as ft}from"ink";import q from"react";var Fn={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},U=()=>Fn,Le=e=>(Fn={...Fn,...e},Fn);var tt=()=>{let e=U(),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}},Ci=()=>{let e=Je(process.cwd());if(d(e))return!1;let t=et(e.value);return Y(t)},Ni=e=>e===!0?"yes":e===!1?"no":null,Ei=e=>e==="yes"?!0:e==="no"?!1:null;var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};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{useSyncExternalStore as um}from"react";var M={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function _r(e){return e.context===M.WORKSPACE}function W(e){return e.context===M.TICKET}function nt(e){return e.context===M.TEXT}function rt(e){return e.context===M.FIELD}function tn(e){return e.context===M.FIELD_LIST}var kt=e=>e.context===M.SWIMLANE,Si=e=>e.context===M.BOARD;function Bn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var On=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",bi=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Ii=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ri=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},Ai=(e,t)=>t?e.get(t)??[]:[];var Ti=new WeakMap,Zd=e=>{let t=Ti.get(e);return t||(t=Ri(e),Ti.set(e,t)),t};var wi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ai(Zd(e),r).filter(i=>Bn(r,i)>=n)};var ec={hint:"",hints:[],overlap:0,remainder:""},Mi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ec;let o=wi({wordList:r,inputToMatch:e,overlapThreshold:1});return tc(t,o)},tc=(e,t)=>{let n=t[0]??"",r=Bn(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),s=r<(o??"").length,c=!!i,g=(c&&s?o:n)+(c&&s?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};import $t from"node:fs";import co from"node:path";import{ulid as oc}from"ulid";var Lt=24n,nc=Lt*4n,We=(1n<<nc)-1n,rc=/^[0-9a-f]+$/;function Pi(e){return!e||!rc.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Me(e,t=Lt){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 me(e,t){if(!e&&!t)return Me(We/2n,Lt);let n=e?Pi(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Pi(t):l("Resolved upper bound",We);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Me(We/2n,Lt);let s=(o+i)/2n;return s===o||s===i?a("No rank space available between neighbors"):Me(s,Lt)}function ki(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Me(o,Lt);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var jr=(e,t)=>{let n=$(e),r=ki(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let s=n[i],c=r.value[i];if(!s||!c)return a("Unable to assign rebalance rank");o[s.id]=c}return l("Created rebalance event",{id:oc(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var X={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var ot=(e,t)=>{let{nodes:n}=v(),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}`)},Kr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},yt=(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={deleteNode(e){Ie(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=yt(r,"edit");if(o)return o;let i={...r,props:{...r.props,description:t}};return this.updateNode(i),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=yt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return $(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return a("Node not found");if(!i)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 s=yt(o,"move");if(s)return s;if(Kr(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}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let i=new Set,s=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of $(m.id))s(g.id)}};s(e);let c={...structuredClone(t)};for(let u of i){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(S({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=Ie(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=yt(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return a("Contributor already assigned");let s={...r,props:{...r.props,assignees:[...i,t]}};return this.updateNode(s),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=yt(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.assignees??[];if(!i.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let s={...r,props:{...r.props,assignees:i.filter(c=>c!==t)}};return this.updateNode(s),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=yt(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return a("Tag already assigned");let s={...r,props:{...r.props,tags:[...i,t]}};return this.updateNode(s),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=yt(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.tags??[];if(!i.includes(t))return l("Issue is not tagged with that tag",{tag:t});let s={...r,props:{...r.props,tags:i.filter(c=>c!==t)}};return this.updateNode(s),l("Tag removed",{tag:t})},createTag(e){let t=Ie(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=Ie(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=Ie(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=Ie(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return $(e)}};var V={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:M.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:M.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:M.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:s})};import Ct from"chalk";import _i from"string-width";import{decodeTime as gc}from"ulid";import Dt from"chalk";var ae={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},h={accent:ae.cyan,accent2:ae.magenta,primary:ae.white,secondary:ae.grayDark,secondary2:ae.grayLight,gray:ae.gray,green:ae.green,yellow:ae.yellow,red:ae.red};var C={red:ae.red,yellow:ae.yellow,green:ae.green,blue:ae.blue,magenta:ae.magenta,cyan:ae.cyan},ht={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 ic=[0,0,0],Gr=.2,zr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Li=(e,t,n)=>Math.max(t,Math.min(n,e)),Vr=(e,t,n)=>e+(t-e)*n,Di=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},sc=e=>e.toLowerCase().trim(),ac=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,s=e/60,c=i*(1-Math.abs(s%2-1)),u=0,m=0,g=0;s>=0&&s<1?(u=i,m=c):s>=1&&s<2?(u=c,m=i):s>=2&&s<3?(m=i,g=c):s>=3&&s<4?(m=c,g=i):s>=4&&s<5?(u=c,g=i):(u=i,g=c);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Fi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,dc=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},Bi=(e,t,n)=>{let r=Li(n,0,1);return[Math.round(Vr(e[0],t[0],r)),Math.round(Vr(e[1],t[1],r)),Math.round(Vr(e[2],t[2],r))]},cc=(e,t=Gr)=>Bi(e,ic,t),lc=(e,t=Gr)=>Fi(cc(dc(e),t)),uc=(e,t,n)=>Bi(e,t,n),nn=e=>{let n=Di(e)%360,r=ac(n,zr.stringColor.saturation,zr.stringColor.lightness);return Fi(r)},Re=(e,t=ht)=>{let n=sc(e);return n&&t[n]?t[n]:nn(n)},Oi=(e,t=ht,n=Gr)=>lc(Re(e,t),n),mc=e=>{let t=zr.gradient.stops,n=Li(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,i=Math.min(Math.floor(o),r-1),s=o-i;return uc(t[i],t[i+1],s)},Un=e=>Di(e.toLowerCase().trim())/4294967295,Ui=e=>{let t=Un(e);return mc(t)},pc=e=>{let[t,n,r]=Ui(e);return{normal:o=>Dt.bgRgb(t,n,r).black(o),cursor:o=>Dt.bgRgb(t,n,r).white.bold(o)}},qr=e=>{let[t,n,r]=Ui(e);return{fg:o=>Dt.rgb(t,n,r)(o),fgCursor:o=>Dt.rgb(t,n,r).inverse(o),bg:o=>Dt.bgRgb(t,n,r).black(o),bgCursor:o=>Dt.bgRgb(t,n,r).white.bold(o)}},$n=e=>pc(e).normal(` ${e} `);import{decodeTime as $i}from"ulid";var Hi=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 i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Wi=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())}`},Hn=e=>{try{return l("Decoded date",new Date($i(e)))}catch(t){return a("Decoding failed + "+t.message)}},Yr=e=>{if(!e?.id)return null;try{return $i(e.id)}catch{return null}};var fc=(e,t)=>e+" ".repeat(Math.max(0,t-_i(e))),vc=(e,t)=>" ".repeat(Math.max(0,t-_i(e)))+e,xc=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),yc=(e,t)=>t?e<t?"up":e>t?"down":null:null,hc=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?Ct.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=yc(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},Cc=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Ct.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Ct.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ct.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ct.hex(Re(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""}},Nc=e=>{let t=Hi(gc(e));return Ct.gray(vc(t,8))},Ec=12,Sc=e=>fc(`${e}`,Ec),ji=(e,t)=>{let n=Nc(e.id),r=Sc(e.userName),o=Ct.dim("\u203A"),i=e.action==="move.node"?hc(e,t):[xc(e.action),Cc(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};import{decodeTime as bc,encodeTime as Ic}from"ulid";var Rc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ac=e=>{let t=2166136261;for(let o of e)t^=o.charCodeAt(0),t=Math.imul(t,16777619);let n=BigInt(t>>>0),r="";for(let o=0;o<16;o++)n=n*1103515245n+12345n&0xffffffffn,r+=Rc[Number(n%32n)];return r},it=(e,t)=>{let n=bc(e);return Ic(n,10)+Ac(`${e}:${t}`)};var Tc=e=>it(e,"description"),wc=e=>it(e,"assignees"),Mc=e=>it(e,"tags"),Pc=e=>it(e,"history"),Ki=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:s="horizontal"})=>{let c=b.getNode(e);if(!c){b.createNode({...V.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:s});return}!rt(c)||!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==i||c.childRenderAxis!==s)||b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:i,childRenderAxis:s})},Vi=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let s=b.getNode(e);if(!s){b.createNode({...V.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return}!tn(s)||!(s.title!==t||s.parentNodeId!==n||s.rank!==r||s.readonly!==o||s.childRenderAxis!==i)||b.updateNode({...s,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i})},zi=e=>{let t=Me(We/4n),n=Me(We/2n),r=Me(We*3n/4n),o=Me(We);d(t)||d(n)||d(r)||d(o)||(Ki({id:Tc(e.id),name:X.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"}),Vi({id:wc(e.id),name:X.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0}),Vi({id:Mc(e.id),name:X.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0}),Ki({id:Pc(e.id),name:X.HISTORY,parentNodeId:e.id,rank:o.value,value:kc(e),readonly:!0,childRenderAxis:"vertical"}))},kc=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=>ji(r,n.get(r.action)??[])).join(`
|
|
21
|
-
`)};var
|
|
22
|
-
`)){let i=o.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{return a(`Failed to parse event JSON from ${e}: ${i}`)}let
|
|
23
|
-
`,"utf8"),
|
|
19
|
+
`).filter(Boolean).filter(s=>s!==$e);if(r.length===0)return c("State branch is storage-only",!1);let o=await L({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
20
|
+
${o.message}`);let i=await Mt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?a(i.message):c("Cleaned storage branch",!0)},Je=Fr(async(e=process.cwd())=>{let t=await L({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Me.resolve(e)),Gp=Fr(async e=>{let t=await L({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=Me.isAbsolute(n)?n:Me.join(e,n);return c("Resolved git dir",r)},e=>Me.resolve(e));import{Box as pt}from"ink";import Y from"react";var Ln={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},U=()=>Ln,Pe=e=>(Ln={...Ln,...e},Ln);var Ze=()=>{let e=U(),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}},vi=()=>{let e=Ye(process.cwd());if(d(e))return!1;let t=Qe(e.value);return X(t)},xi=e=>e===!0?"yes":e===!1?"no":null,yi=e=>e==="yes"?!0:e==="no"?!1:null;var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ne=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):a("Unable to find node in breadcrumb")};import{useSyncExternalStore as Ju}from"react";var M={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function jr(e){return e.context===M.WORKSPACE}function $(e){return e.context===M.TICKET}function et(e){return e.context===M.TEXT}function tt(e){return e.context===M.FIELD}function Qt(e){return e.context===M.FIELD_LIST}var Pt=e=>e.context===M.SWIMLANE,hi=e=>e.context===M.BOARD;var Ci=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Ni=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Ei=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Si=(e,t)=>{if(Ni(e,e.sequence))return f.MoveCursorLeftOfWord;if(Ei(e,e.sequence))return f.MoveCursorRightOfWord;if(Ci(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.GetLastCommandFromHistory;case"down":return f.GetNextCommandFromHistory;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}},bi=(e,t)=>{if(Ni(e,e.sequence))return f.MoveCursorLeftOfWord;if(Ei(e,e.sequence))return f.MoveCursorRightOfWord;if(Ci(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.NavPreviousItem;case"down":return f.NavNextItem;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}};function Dn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ii=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Ri=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ai=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},Ti=(e,t)=>t?e.get(t)??[]:[];var wi=new WeakMap,Vd=e=>{let t=wi.get(e);return t||(t=Ai(e),wi.set(e,t)),t};var Mi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ti(Vd(e),r).filter(i=>Dn(r,i)>=n)};var Kd={hint:"",hints:[],overlap:0,remainder:""},Pi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Kd;let o=Mi({wordList:r,inputToMatch:e,overlapThreshold:1});return zd(t,o)},zd=(e,t)=>{let n=t[0]??"",r=Dn(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),s=r<(o??"").length,l=!!i,g=(l&&s?o:n)+(l&&s?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};import{ulid as Yd}from"ulid";var kt=24n,Gd=kt*4n,We=(1n<<Gd)-1n,qd=/^[0-9a-f]+$/;function ki(e){return!e||!qd.test(e)?a(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ae(e,t=kt){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function ue(e,t){if(!e&&!t)return Ae(We/2n,kt);let n=e?ki(e):c("Resolved lower bound",0n);if(d(n))return n;let r=t?ki(t):c("Resolved upper bound",We);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Ae(We/2n,kt);let s=(o+i)/2n;return s===o||s===i?a("No rank space available between neighbors"):Ae(s,kt)}function Li(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Ae(o,kt);if(d(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Vr=(e,t)=>{let n=W(e),r=Li(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let s=n[i],l=r.value[i];if(!s||!l)return a("Unable to assign rebalance rank");o[s.id]=l}return c("Created rebalance event",{id:Yd(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var J={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Kr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},ft=(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"),S={deleteNode(e){Ee(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=ft(r,"edit");if(o)return o;let i={...r,props:{...r.props,description:t}};return this.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=ft(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return W(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return a("Node not found");if(!i)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 s=ft(o,"move");if(s)return s;if(Kr(t,e))return a("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let i=new Set,s=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of W(m.id))s(g.id)}};s(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return a("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(b({nodes:l}),c("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=Ee(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):c("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=ft(r,"edit");if(o)return o;if(!$(r))return a("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return a("Contributor already assigned");let s={...r,props:{...r.props,assignees:[...i,t]}};return this.updateNode(s),c("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=ft(r,"edit");if(o)return o;if(!$(r))return a("Target is not an issue");let i=r.props.assignees??[];if(!i.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let s={...r,props:{...r.props,assignees:i.filter(l=>l!==t)}};return this.updateNode(s),c("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=ft(r,"edit");if(o)return o;if(!$(r))return a("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return a("Tag already assigned");let s={...r,props:{...r.props,tags:[...i,t]}};return this.updateNode(s),c("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=ft(r,"edit");if(o)return o;if(!$(r))return a("Target is not an issue");let i=r.props.tags??[];if(!i.includes(t))return c("Issue is not tagged with that tag",{tag:t});let s={...r,props:{...r.props,tags:i.filter(l=>l!==t)}};return this.updateNode(s),c("Tag removed",{tag:t})},createTag(e){let t=Ee(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):c("Tag created",e)},createNode(e){let t=Ee(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=Ee(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):c("Locked node",n)},updateNode(e){let t=Ee(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return W(e)}};var K={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:M.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:M.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:M.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:s})};import xt from"chalk";import ji from"string-width";import{decodeTime as ic}from"ulid";import Lt from"chalk";var ie={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"},h={accent:ie.cyan,accent2:ie.magenta,primary:ie.white,secondary:ie.grayDark,secondary2:ie.grayLight,gray:ie.gray,green:ie.green,yellow:ie.yellow,red:ie.red};var C={red:ie.red,yellow:ie.yellow,green:ie.green,blue:ie.blue,magenta:ie.magenta,cyan:ie.cyan},vt={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 Xd=[0,0,0],qr=.2,Gr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Di=(e,t,n)=>Math.max(t,Math.min(n,e)),zr=(e,t,n)=>e+(t-e)*n,Fi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Jd=e=>e.toLowerCase().trim(),Qd=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,s=e/60,l=i*(1-Math.abs(s%2-1)),u=0,m=0,g=0;s>=0&&s<1?(u=i,m=l):s>=1&&s<2?(u=l,m=i):s>=2&&s<3?(m=i,g=l):s>=3&&s<4?(m=l,g=i):s>=4&&s<5?(u=l,g=i):(u=i,g=l);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Bi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Zd=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},Ui=(e,t,n)=>{let r=Di(n,0,1);return[Math.round(zr(e[0],t[0],r)),Math.round(zr(e[1],t[1],r)),Math.round(zr(e[2],t[2],r))]},ec=(e,t=qr)=>Ui(e,Xd,t),tc=(e,t=qr)=>Bi(ec(Zd(e),t)),nc=(e,t,n)=>Ui(e,t,n),Zt=e=>{let n=Fi(e)%360,r=Qd(n,Gr.stringColor.saturation,Gr.stringColor.lightness);return Bi(r)},Se=(e,t=vt)=>{let n=Jd(e);return n&&t[n]?t[n]:Zt(n)},Oi=(e,t=vt,n=qr)=>tc(Se(e,t),n),rc=e=>{let t=Gr.gradient.stops,n=Di(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,i=Math.min(Math.floor(o),r-1),s=o-i;return nc(t[i],t[i+1],s)},Bn=e=>Fi(e.toLowerCase().trim())/4294967295,$i=e=>{let t=Bn(e);return rc(t)},oc=e=>{let[t,n,r]=$i(e);return{normal:o=>Lt.bgRgb(t,n,r).black(o),cursor:o=>Lt.bgRgb(t,n,r).white.bold(o)}},Yr=e=>{let[t,n,r]=$i(e);return{fg:o=>Lt.rgb(t,n,r)(o),fgCursor:o=>Lt.rgb(t,n,r).inverse(o),bg:o=>Lt.bgRgb(t,n,r).black(o),bgCursor:o=>Lt.bgRgb(t,n,r).white.bold(o)}},Un=e=>oc(e).normal(` ${e} `);import{decodeTime as Wi}from"ulid";var Hi=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 i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},_i=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())}`},On=e=>{try{return c("Decoded date",new Date(Wi(e)))}catch(t){return a("Decoding failed + "+t.message)}},Xr=e=>{if(!e?.id)return null;try{return Wi(e.id)}catch{return null}};var sc=(e,t)=>e+" ".repeat(Math.max(0,t-ji(e))),ac=(e,t)=>" ".repeat(Math.max(0,t-ji(e)))+e,dc=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),cc=(e,t)=>t?e<t?"up":e>t?"down":null:null,lc=(e,t)=>{let n=S.getNode(e.payload.parent),r=n?xt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=cc(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},uc=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?xt.bgHex(Se(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?xt.bgHex(Se(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?xt.hex(Se(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?xt.hex(Se(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},mc=e=>{let t=Hi(ic(e));return xt.gray(ac(t,8))},pc=12,gc=e=>sc(`${e}`,pc),Vi=(e,t)=>{let n=mc(e.id),r=gc(e.userName),o=xt.dim("\u203A"),i=e.action==="move.node"?lc(e,t):[dc(e.action),uc(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};import{createHash as fc}from"node:crypto";var vc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",xc=e=>{let t=fc("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 i=BigInt((25-o)*5);r+=vc[Number(n>>i&31n)]}return r},rt=(e,t)=>xc(`${e}:virtual:${t}`);var yc=e=>rt(e,"description"),hc=e=>rt(e,"assignees"),Cc=e=>rt(e,"tags"),Nc=e=>rt(e,"history"),Ki=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:s="horizontal"})=>{let l=S.getNode(e);if(!l){let g=S.createNode({...K.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:s});return d(g)?g:c("Virtual field created",void 0)}if(!tt(l))return a(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==i||l.childRenderAxis!==s))return c("Virtual field unchanged",void 0);let m=S.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:i,childRenderAxis:s});return d(m)?m:c("Virtual field updated",void 0)},zi=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let s=S.getNode(e);if(!s){let m=S.createNode({...K.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return d(m)?m:c("Virtual field list created",void 0)}if(!Qt(s))return a(`Existing virtual node ${e} is not a field list`);if(!(s.title!==t||s.parentNodeId!==n||s.rank!==r||s.readonly!==o||s.childRenderAxis!==i))return c("Virtual field list unchanged",void 0);let u=S.updateNode({...s,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i});return d(u)?u:c("Virtual field list updated",void 0)},Gi=e=>{let t=Ae(We/4n),n=Ae(We/2n),r=Ae(We*3n/4n),o=Ae(We*7n/8n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;let i=Ki({id:yc(e.id),name:J.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let s=zi({id:hc(e.id),name:J.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(s))return s;let l=zi({id:Cc(e.id),name:J.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(l))return l;let u=Ki({id:Nc(e.id),name:J.HISTORY,parentNodeId:e.id,rank:o.value,value:Ec(e),readonly:!0,childRenderAxis:"vertical"});return d(u)?u:c("Ticket virtual nodes materialized",void 0)},Ec=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=>Vi(r,n.get(r.action)??[])).join(`
|
|
21
|
+
`)};var Sc=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[He,$n]=Sc;var k=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),qi=e=>{let t=S.getNode(e);if(!t||!$(t)||t.isDeleted)return null;let n=Gi(t);return d(n)?n:null},bc=e=>{for(let t of e){let n=qi(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=qi(r);if(o)return o}return null},Ic=(e,t)=>{let n=S.getNode(e);n&&S.updateNode({...n,log:[...n.log??[],t]})},Rc=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ac=e=>{switch(e.action){case"delete.node":case"edit.description":return Rc(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":default:return[]}},Tc=e=>{Ee(t=>({...t,eventLog:[...t.eventLog,e]}))},wc=e=>{let t=e.userId,n=e.userName;if(!t?.length||!n?.length)return k("Invalid user ID format",e);let r=S.createContributor({id:t,name:n});return d(r)?k(r.message,e):null},Mc=(e,t)=>{let n=wc(e);if(n)return n;let r=[...new Set(Ac(e))];t||(r.forEach(i=>Ic(i,e)),Tc(e));let o=bc(r);return o||null},Pc={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=K.workspace(t,n,r),i=tn(o);if(d(i))return k(i.message,e);let s=S.createNode(o);return d(s)?k(s.message??"Failed to initialize workspace",e):jr(s.value)?c("Workspace initialized",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=S.createNode(K.workspace(t,n,r));return d(o)?k(o.message??"Failed to add workspace",e):jr(o.value)?c("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,i=S.createNode(K.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):hi(i.value)?c("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=S.createNode(K.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):Pt(i.value)?c("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=S.createNode(K.ticket(t,n,r,o));return d(i)?k(i.message??"Unable to create issue",e):$(i.value)?c("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,s=S.createNode(K.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(J.DESCRIPTION)?"vertical":"horizontal"}));return d(s)?k(s.message??`Unable to create field: ${n}`,e):tt(s.value)?c("Added field",{action:e.action,result:s.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!S.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=S.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=S.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=S.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=S.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.tag(t,n);return d(r)?k(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.untag(t,n);return d(r)?k(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.assign(t,n);return d(r)?k(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=S.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return k("Unable to locate issue",e);if(!$(o))return k("Can only close issues",e);let i=S.getNode(He);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let s=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(s)?k(s.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return k("Unable to locate issue",e);if(!$(o))return k("Can only reopen issues",e);let i=S.getNode(He);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!S.getNode(n))return k("Reopen parent no longer exists",e);let l=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?k(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=S.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=S.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let s=S.updateNode({...i,rank:o});if(d(s))return k(s.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};function en(e,t=!1){let n=Pc[e.action](e);if(d(n))return n;let r=Mc(e,t);return r||n}var yt=e=>e.map(t=>en(t));import _c from"node:fs";import jc from"node:path";import{decodeTime as Vc,monotonicFactory as Kc}from"ulid";import{z as nn}from"zod";import Wn from"node:fs";import Qr from"node:path";import{decodeTime as kc}from"ulid";import{z as Jr}from"zod";var Lc=Jr.object({userId:Jr.string().min(1).default("unknown"),userName:Jr.string().min(1).default("unknown")}),Dc=e=>{let[t,n]=Qr.basename(e,".jsonl").split("."),r=Lc.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):a(`Invalid event file name ${Qr.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Fc=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"):c("Resolved persisted action",t[0])},Bc=(e,t)=>t in e,Uc=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Oc=e=>{let{userId:t,userName:n,...r}=e,o=Fc(r);if(d(o))return a(o.message);let i=o.value,s=e.id?.[0];return s?Bc(r,i)?c("Decoded persisted event",Uc({id:s,action:i,payload:r[i],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${i}`):a("Persisted event is missing id")},Zr=e=>{let t=[];for(let n of e){let r=Oc(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return c("Decoded reconstructed events",t)},$c=e=>{if(!Wn.existsSync(e))return c("Event file missing",[]);let t=Dc(e);if(d(t))return a(t.message);let n=Wn.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
22
|
+
`)){let i=o.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{return a(`Failed to parse event JSON from ${e}: ${i}`)}let l=to(s);if(d(l))return a(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function eo(e){let t=Gt(e);if(!Wn.existsSync(t))return c("No events found",[]);let n=Wn.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Qr.join(t,o)),r=[];for(let o of n){let i=$c(o);if(d(i))return a(i.message);r.push(...i.value)}return c("All events loaded",Wc(r))}function Dt(e){let t=eo(e);return d(t)?a(t.message):Zr(t.value)}function Yi(e,t){let n=eo(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=Hc(n.value,t),i=Zr(r);if(d(i))return a(i.message);let s=Zr(o);return d(s)?a(s.message):c("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:s.value})}function Xi(e=process.cwd()){let t=eo(e);return d(t)?a(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Wc=e=>{let t=new Map,n=new Map;for(let m of e){let g=m.id[0],y=m.id[1]??null;t.set(g,m);let N=n.get(y)??[];N.push(m),n.set(y,N)}for(let m of n.values())m.sort((g,y)=>g.id[0].localeCompare(y.id[0]));let r=[],o=new Set,i=m=>{let g=m.id[0];if(o.has(g))return;r.push(m),o.add(g);let y=n.get(g)??[];for(let N of y)i(N)},s=n.get(null)??[];for(let m of s)i(m);let l=e.filter(m=>{let g=m.id[0],y=m.id[1]??null;return!o.has(g)&&y!==null&&!t.has(y)}).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of l)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of u)i(m);return r},Hc=(e,t)=>{let n=new Set,r=[],o=[];for(let i of e){let s=i.id[0],l=i.id[1],u=!1;try{u=kc(s)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(s),o.push(i)):r.push(i)}return{appliedEvents:r,unappliedEvents:o}};var Ji=e=>({action:e.action,payload:e.payload});var Zi=1,Qi=Kc(),zc=nn.tuple([nn.string().min(1),nn.string().min(1).nullable()]),Gc=nn.looseObject({v:nn.literal(Zi),id:zc}),to=e=>{let t=Gc.safeParse(e);return t.success?c("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Hn=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",z=()=>{let{userName:e,userId:t}=U();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Hn(t),userName:Hn(e)}):a("Unable to resolve actor ID from settings or OS user info"):a("User ID not configured"):a("User name not configured")},rn=({userId:e,userName:t})=>`${Hn(e)}.${Hn(t)}.jsonl`,qc=(e,{userId:t,userName:n})=>{let r=rn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let i=jc.join(Gt(e),r);return c("Successfully resolved event log path",i)},Yc=(e,t)=>{let n={[e.action]:e.payload,v:Zi,id:t};return to(n)};function _n({event:e,rootDir:t}){try{let n=Yo(t);if(d(n))return n;let r=qc(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=Xi(t);if(d(o))return a(o.message);let i=o.value?Qi(Math.max(Date.now(),Vc(o.value)+1)):Qi(),s=Yc(Ji(e),[i,o.value]);return d(s)?a(s.message):(_c.appendFileSync(r.value,`${JSON.stringify(s.value)}
|
|
23
|
+
`,"utf8"),c("Event persisted",{path:r.value,entry:s.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function Te(e,t){let n=en(e);if(n.status!==qe.Success)return n;let r=_n({event:e,rootDir:t});return d(r)?r:n}function es(e,t){return e.map(n=>Te(n,t))}var be=async e=>{let t=await Re();return d(t)?t:Te(e,t.value)};var ts=e=>jn(W(e),{at:"end"}),jn=(e,t={at:"end"})=>{let n=r=>d(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(ue(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(ue(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(ue(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ns(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(ue(o?.rank,i.rank)):a("Sibling not found")}case"after":{let r=ns(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(ue(o.rank,i?.rank)):a("Sibling not found")}}},W=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ns=(e,t)=>e.findIndex(n=>n.id===t),rs=(e,t,n={at:"end"})=>jn(W(t).filter(r=>r.id!==e),n),no=(e,t,n,r,o)=>{let i=rs(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let s=Vr(e,r);if(d(s))return s;let l=Te(s.value,o);if(d(l))return l;let u=rs(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},Vn=(e,t,n)=>{let r=ts(e);if(d(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Vr(e,t);if(d(o))return o;let i=Te(o.value,n);if(d(i))return i;let s=ts(e);return d(s)?s:s.value.needsRebalance?a("Rank rebalance failed to create space"):c("Resolved rank after rebalance",s.value.rank)};var T={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=W(t.id)[n];!r||t.context==="FIELD"||T.navigate({contextNode:r,selectedIndex:F(r.id).length?0:-1})},enterParentNode(){let{contextNode:e,nodes:t}=v();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=F(n.id),o=r.findIndex(({id:s})=>s===e.id),i=r.length===0?-1:o>=0?o:0;T.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>os(1),navigateToPreviousItem:()=>os(-1),navigateToNextContainer:()=>is(1),navigateToPreviousContainer:()=>is(-1),navigate:({contextNode:e,selectedIndex:t})=>{b({contextNodeId:e.id,selectedIndex:t})}},os=e=>{let{selectedIndex:t,contextNode:n}=v(),r=F(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;T.navigate({selectedIndex:i,contextNode:n})},is=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=F(o.id),s=i.findIndex(N=>N.id===t.id);if(s<0)return;let l=i.at(s+e)??i.at(0);if(!l)return;let u=F(l.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),y=u.length?g:-1;T.navigate({contextNode:l,selectedIndex:y})};var as=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),ds=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Xc=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&tt(t)&&t.childRenderAxis==="vertical"},Kn=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=F(r.id);return T.navigate({contextNode:r,selectedIndex:as(t,o.length)}),!0},cs=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Kn(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let s=W(o.id).findIndex(l=>l.id===n.id);return s>=0?(T.navigate({contextNode:o,selectedIndex:s}),!0):cs(o.id)},ss=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),cs(n))return!0;n=t[n]?.parentNodeId}return!1},Jc=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},ls=e=>{let{nodes:t,rootNodeId:n}=v();if(Xc(e.contextNodeId)&&Kn(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Jc(e.selectedNodeId)&&e.selectedNodeId&&ss(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Kn(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Kn(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(ss(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=F(r.id);return T.navigate({contextNode:r,selectedIndex:as(e.selectedIndex,o.length)}),c("Restored navigation to root",null)};import{monotonicFactory as Qc,ulid as _e}from"ulid";var on=Qc();function Zc(){let e=ot();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(i=>i.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=F(n.id),[o]=r?F(r.id):[];if(o){let i=t.renderedChildrenIndex?.[o.id]??[];return c("Resolved boot nav target",{contextNode:o,selectedIndex:i.length>0?0:-1})}else return r?c("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?c("Resolved boot nav target",{contextNode:n,selectedIndex:0}):c("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function el(){let e=Zc();return d(e)?e:T.navigate(e.value)}function us({userId:e,userName:t}){let n=on(),r=on(),o=on(),i=on(),s=on(),l=ue(void 0,void 0);if(d(l))return l;let u=ue(void 0,void 0);if(d(u))return u;let m=ue(u.value,void 0);if(d(m))return m;let g=ue(void 0,void 0);if(d(g))return g;let y=ue(g.value,void 0);if(d(y))return y;let N=ue(y.value,void 0);if(d(N))return N;let E=ue(void 0,void 0);return d(E)?E:c("Created default events",[{id:_e(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:_e(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:_e(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:g.value}},{id:_e(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:y.value}},{id:_e(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"Done",parent:r,rank:N.value}},{id:_e(),userId:e,userName:t,action:"add.board",payload:{id:$n,name:"Closed",parent:n,rank:m.value}},{id:_e(),userId:e,userName:t,action:"add.swimlane",payload:{id:He,name:"Closed",parent:$n,rank:E.value}},{id:_e(),userId:e,userName:t,action:"lock.node",payload:{id:$n}},{id:_e(),userId:e,userName:t,action:"lock.node",payload:{id:He}}])}function zn(e){if(!e.length){let r=K.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=tn(r);return d(o)?o:(b({hasProjectDefinition:!1,mode:p.DEFAULT}),c("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=yt(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
24
24
|
${n.map(r=>r.message).join(`
|
|
25
|
-
`)}`):(
|
|
26
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
27
|
-
${o.message}`):
|
|
28
|
-
`+n.message);let r=n.value,o=r?await
|
|
29
|
-
`+o.message);let i=o.value;if(r&&i){let
|
|
30
|
-
${
|
|
31
|
-
`+s.message);if(s.value)return
|
|
32
|
-
${
|
|
33
|
-
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return
|
|
34
|
-
`+r.message);Ut.existsSync(t)&&!Ut.existsSync(
|
|
35
|
-
${o.message}`):
|
|
36
|
-
${u.message}`)}if(i&&!Ut.existsSync(i)){
|
|
37
|
-
${u.message}`)}let s=await
|
|
38
|
-
${u.message}`)}return
|
|
39
|
-
${o.message}`):
|
|
40
|
-
${
|
|
41
|
-
${u.message}`):
|
|
42
|
-
${o.message}`):
|
|
43
|
-
`+n.message):
|
|
44
|
-
${i.message}`):l("Pushed state branch",!0)},vs=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Mt(e);if(d(o))return o;let i=o.value,s=[Dn(),await pl({repoRoot:e,stateBranchName:i}),await io({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await vl({stateBranchRoot:t,stateBranchName:i}),await hi(t),n?await xl({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of s){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{decodeTime as yl}from"ulid";var ao=e=>{let t=[];for(let n of e.split(`
|
|
45
|
-
`)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{return a("Failed to parse persisted events")}}return l("Parsed persisted events",t)},so=e=>{let[t,n]=e.id;return`${t}:${n??""}`},xs=e=>{try{return yl(e.id[0])}catch{return 0}},ys=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.set(so(r),r);return[...n.values()].sort((r,o)=>{let i=xs(r)-xs(o);return i!==0?i:so(r).localeCompare(so(o))})},hs=e=>e.length===0?"":e.map(t=>JSON.stringify(t)).join(`
|
|
46
|
-
`)+`
|
|
47
|
-
`;var lo=e=>$t.existsSync(e)?$t.readFileSync(e,"utf8"):null,hl=(e,t)=>lo(e)===t?!1:($t.mkdirSync(co.dirname(e),{recursive:!0}),$t.writeFileSync(e,t,"utf8"),!0),Cl=({stateBranchRoot:e,ownEventFileName:t})=>co.join(e,en(t)),Nl=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=en(t),r=co.join(e,n);return(await we({cwd:e,args:["checkout","--",n]})).exitCode!==0&&$t.existsSync(r)&&$t.rmSync(r,{force:!0}),l("Restored own event file to HEAD",null)},Cs=({ownEventPath:e,ownSnapshot:t})=>{if(t===null)return l("No own snapshot to merge",!1);let n=lo(e)??"",r=ao(n);if(d(r))return a(r.message);let o=ao(t);if(d(o))return a(o.message);let i=ys(r.value,o.value),s=hl(e,hs(i));return l("Merged own snapshot",s)};var El=async({cwd:e,ensureUpstream:t})=>{logger.info("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=H("getRepoRootDir",await Ze(e));if(d(n))return a(n.message);let r=n.value;logger.info("[sync] repo root",r);let o=H("getStateBranchRoot",Qe({repoRoot:r}));if(d(o))return a(o.message);let i=o.value;logger.info("[sync] state branch root",i);let s=H("ensureInitialCommit",await gs(r));if(d(s))return a(s.message);logger.info("[sync] initial commit result",{created:s.value}),logger.info("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let c=H("bootstrapStateBranchStorage",await vs({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(d(c))return a(c.message);logger.info("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:i}),logger.info("[sync] checking state branch git operation",{stateBranchRoot:i});let u=H("hasInProgressGitOperation(stateBranchRoot)",await wn(i));if(d(u))return a(u.message);if(logger.info("[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.info("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:i});let m=H("ensureStateBranchLayout",yi(r,i));return d(m)?a(m.message):(logger.info("[sync] state branch layout ready"),logger.info("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:i,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:c.value}))},Ns=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.info("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.info("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=H("stageStateBranchOwnEventFile",await Yn({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=H("hasStagedChanges(after stage)",await mi(t));if(d(o))return a(o.message);if(logger.info("[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.info("[sync] creating sync commit");let i=H("createStateBranchSyncCommit",await fs({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.info("[sync] created sync commit",i.value),l("Committed own event file",{createdCommit:!0,commitSha:i.value}))},Sl=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.info("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.info("[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.info("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");us("Syncing");let n=H("ensureSyncReady",await El({cwd:e,ensureUpstream:!0}));if(d(n))return pe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value;logger.info("[sync] sync preconditions ready",{repoRoot:r,stateBranchRoot:o,bootstrapped:i}),logger.info("[sync] checking detached state branch",{stateBranchRoot:o});let s=H("isDetachedHead(stateBranchRoot)",await pi(o));if(d(s))return pe(s.message);if(logger.info("[sync] detached state branch check result",{detached:s.value}),s.value)return logger.info("[sync] state branch is detached"),pe("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,g=!1,y=H("getStateBranch",Mt(r));if(d(y))return pe(y.message);let N=y.value;logger.info("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:o});let E=Cl({stateBranchRoot:o,ownEventFileName:t}),I=lo(E),w=H("restoreOwnEventFileToHead",await Nl({stateBranchRoot:o,ownEventFileName:t}));if(d(w))return pe(w.message);let R=H("pullBranchRebaseIfPresent",await Hr({cwd:o,branch:N}));if(d(R))return pe(R.message);m=R.value;let T=H("mergeOwnSnapshot",Cs({ownEventPath:E,ownSnapshot:I}));if(d(T))return pe(T.message);let L=H("commitOwnEventFileToStateBranch",await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(L))return pe(L.message);if(c=L.value.createdCommit,u=L.value.commitSha,logger.info("[sync] sync own result",{createdCommit:c,commitSha:u}),c||i){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:i,stateBranchRoot:o});let ne=H("pushStateBranch(initial)",await ln({stateBranchRoot:o,repoRoot:r})),ie=ne;if(d(ne)&&ui(ne.message)){logger.info("[sync] non-fast-forward, retrying sync");let Ue=H("pullBranchRebaseIfPresent(retry)",await Hr({cwd:o,branch:N}));if(d(Ue))return pe(Ue.message);logger.info("[sync] pull retry result",Ue.value);let vt=H("mergeOwnSnapshot(retry)",Cs({ownEventPath:E,ownSnapshot:I}));if(d(vt))return pe(vt.message);let Ne=H("commitOwnEventFileToStateBranch(retry)",await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(Ne))return pe(Ne.message);logger.info("[sync] retry sync result",Ne.value),Ne.value.createdCommit&&(c=!0,u=Ne.value.commitSha),ie=H("pushStateBranch(retry)",await ln({stateBranchRoot:o,repoRoot:r}))}if(d(ie))return pe(ie.message);g=ie.value,logger.info("[sync] pushed to state branch",g)}else logger.info("[sync] no commit created, skipped push");if(c){logger.info("[sync] resolving final sync commit sha",{stateBranchRoot:o});let ne=H("git rev-parse HEAD",await D({args:["rev-parse","HEAD"],cwd:o}));if(d(ne))return pe(ne.message);u=ne.value.stdout.trim(),logger.info("[sync] final sync commit sha",u)}return ms(g?"Synced and pushed":m||c||T.value?"Synced local state":"Already synced"),logger.info("[sync] syncEpiqWithRemote:done",{pulled:m,pushed:g,createdCommit:c,bootstrapped:i,commitSha:u}),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:g,bootstrapped:i})},Xn=async()=>{let e=Es();if(e)return e;logger.info("[sync] syncAndReloadState:start");let t=H("resolveActorId",z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),a("Unable to resolve event log path");let n=an(t.value);logger.info("[sync] resolved own event file name",{ownEventFileName:n});let r=H("syncEpiqWithRemote",await Sl({ownEventFileName:n}));if(d(r))return logger.info("[sync] syncAndReloadState:sync failed",r.message),a(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.info("[sync] loading merged events after sync",{stateBranchRoot:o});let i=H("loadMergedEvents",Ft(o));if(d(i))return a(`Unable to load events. ${i.message}`);logger.info("[sync] loaded merged events after sync",{count:i.value.length});let s=Es();if(s)return s;let c=as(),u=H("bootStateFromEventLog",qn(i.value));if(d(u))return a(`Unable to boot synced state. ${u.message}`);logger.info("[sync] booted state from synced events"),S({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}});let m=H("restoreNavigationAnchor",cs(c));return d(m)?m:(logger.info("[sync] syncAndReloadState:done"),l("Synced",!0))},Es=()=>v().mode===p.DEFAULT?null:(S({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Ht=3e3,Ss=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ht?null:t},bs=0,uo,mo=!1,un=!1,po=()=>{if(mo)return!0;let e=st();return d(e)?!1:e.value.syncStatus.status==="syncing"},bl=()=>{let e=U().autoSyncIntervalMs??1e4,t=Date.now()-bs;return Math.max(0,e-t)},Is=()=>{uo||(uo=setTimeout(async()=>{if(uo=void 0,!!Bt()){if(po()){un=!0;return}un=!1,await Il()}},bl()))},Il=async()=>{if(v().readOnly||v().timeMode==="peek")return a("Cannot auto-sync while peeking");if(!Bt())return a("Cannot auto-sync before state is initialized");if(po())return un=!0,a("Sync already in progress");mo=!0,bs=Date.now(),S({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Xn()}finally{mo=!1,un&&Is()}},Rs=()=>{Bt()&&(un=!0,!po()&&Is())};var Rl=e=>e.props.tags??[],Al=e=>e.props.assignees??[],go=e=>Rl(e).map(t=>b.getTag(t)).filter(t=>!!t),fo=e=>Al(e).map(t=>b.getContributor(t)).filter(t=>!!t),Jn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",go(n))},Qn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",fo(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var Tl=/^(\d+)(h|d|w|mo|y)$/,wl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ml=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},Pl=(e,t=new Date)=>{let n=e.match(Tl);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let s=new Date(t);switch(o){case"h":return s.setHours(s.getHours()-i),s;case"d":return s.setDate(s.getDate()-i),s;case"w":return s.setDate(s.getDate()-i*7),s;case"mo":return s.setMonth(s.getMonth()-i),s;case"y":return s.setFullYear(s.getFullYear()-i),s;default:return null}},kl=e=>{let t=e.match(wl);if(!t)return null;let[,n,r,o,i,s]=t,c=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,y=s?Number(s):0;return Ml({year:c,month:u,day:m,hour:g,minute:y})?new Date(c,u-1,m,g,y):null},Zn=e=>{let t=e.trim().toLowerCase();return Pl(t)??kl(t)},As=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ll=[{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}],Ts=(e=Ll)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var Dl=["BOARD","TICKET","SWIMLANE"],re={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},at={TITLE:"title",DESCRIPTION:"description"},Fl=[re.EDITOR,re.VIEW,re.USERNAME,re.AUTOSYNC,re.SYNC_DEBOUNCE_MS],Bl=[at.TITLE,at.DESCRIPTION],xo=[String(Ht),"5000","15000","30000","60000"],Et=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],er=[x.NEW,x.EDIT,x.DELETE,x.MOVE],vo=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT],ws=[x.FILTER,x.PEEK],Ol={WORKSPACE:[...Et,...er],BOARD:[...ws,...Et,...er],SWIMLANE:[...ws,...Et,...er],TICKET:[...Et,...er,...vo],FIELD:[...Et,...vo],FIELD_LIST:[...Et,...vo],TEXT:[...Et]},Ul=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],$l=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=tt();if(!r)return[x.HELP,x.CONFIG];if(!Ci())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.EXPORT,x.CONFIG];let o=e?.context,i=o&&Dl.includes(o);return[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Ol[c]:[]))].filter(c=>c===x.MOVE?!1:c===x.EDIT||c===x.DELETE?i:!0)},J=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[x.NONE]:$l({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Ts(),"now","prev","next"],[x.EDIT]:[...Bl],[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","clear"],[x.TAG]:[...new Set([...Object.keys(ht),...b.getExistingTags()])],[x.UNTAG]:[...Jn()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...Qn()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:Ul(i),[x.CONFIG]:[...Fl]}[e]??[]};import Ls from"chalk";var Ms=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Ps from"chalk";var Q=e=>Ps.dim(e),ge=e=>Ps.hex(h.primary)(e),fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let s=o.trim();if(s.length<i)return"";let g=[...t.filter(Boolean).filter(y=>y.startsWith(s))].sort((y,N)=>Un(y)-Un(N)).slice(0,r).map(y=>$n(y)).join(" ");return g?`${Q(e)}${g}${Q(n)}`:""};var St={None:"none",Invalid:"invalid",Valid:"valid"};var Hl=["BOARD","TICKET","SWIMLANE"],ks=()=>{let e=v().selectedNode;return e?.context?Hl.includes(e.context)?j():F({message:Q("Command not available in this context")}):F({message:Q("Missing target context")})},Z="<ENTER> to confirm",j=(e="",t=[])=>({message:Q(e),validity:St.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:St.Invalid,message:e,completionWordList:t}),nr=e=>e.length===0,tr=e=>` ${Ls.dim.bgHex(Oi(e))(` ${e} `)} `,yo=({modifier:e})=>{let t="confirm";return e===t?j(Z):F({message:nr(e)?Q("if you are certain, enter ")+$n(t):"",completionWordList:[t]})},Wl=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:Q(n)}):j():F({message:nr(r)?t:"",completionWordList:[...e]}),mn=({hint:e})=>({modifier:t,inputString:n})=>nr(t)&&nr(n)?F({message:e,completionWordList:[]}):j(Z),_l=({modifier:e,inputString:t})=>{let n=J(x.CONFIG);if(!n.includes(e))return F({message:fe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case re.EDITOR:{let r=[...Ms];return t.trim()?r.includes(t.trim())?j(Z):F({message:fe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:fe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(Z):F({message:fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.USERNAME:return t.trim()?j(Z):F({message:ge("Enter a user name. Saved in ")+Ls.bgBlack("~/.epiq-global/config.json")});case re.AUTOSYNC:{let r=["yes","no"],o=U().autoSync;if(!r.includes(t.trim())){let i=Ni(o);return F({message:fe({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(Z)}case re.SYNC_DEBOUNCE_MS:{let r=U().autoSyncIntervalMs,o=Ss(t);if(!t.trim()||o===null||o<Ht){let i=fe({prefix:" examples: ",wordList:xo,minLengthForHints:0,inputString:t});return F({message:ge(`provide duration above ${Ht}ms. current duration: ${r}ms.`)+i,completionWordList:xo})}return j(Z)}default:return F({message:ge("Unknown config option"),completionWordList:n})}},jl=({modifier:e})=>{let t=J(x.EDIT);if(!t.includes(e)){let i=fe({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return F({message:i||ge("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!be([...n,r],"TICKET"))return F({message:ge("Command not available in this context")});switch(e){case at.TITLE:return j(Z);case at.DESCRIPTION:let{preferredEditor:i}=U();return i?j(Q("<ENTER> to edit in ")+i):F({message:"No editor selected"});default:return F({message:ge("Unknown edit option"),completionWordList:t})}},Kl={[x.EXPORT]:()=>j(Z+Q(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(Z);let n={message:Q("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return j(Z);let r=Zn(t);if(!t||!r)return F(n);let o=be(v().breadCrumb,"BOARD");if(d(o))return F({message:ge("Command is not applicable in this context")});let i=Hn(o.value.id);return d(i)?F({message:ge("Unable to peek: board id is not a valid ULID")}):As({date:r,horizonDate:i.value})?j(Z):F({message:ge(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[x.EXIT]:()=>j(Z+Q(" and exit the application")),[x.INIT]:()=>j(Z),[x.PALETTE]:()=>j(Z),[x.FILTER]:e=>{if(e.modifier==="clear")return j();let t=i=>J(x.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return F({message:fe({wordList:J(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:J(x.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:fe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):j():F({message:fe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[x.NONE]:e=>{let t=J(x.NONE);return F({message:fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Wl({list:J(x.NEW),hint:fe({wordList:J(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(Z),[x.EDIT]:jl,[x.CONFIG]:_l,[x.DELETE]:e=>{let t=ks();return t.validity==="invalid"?t:yo(e)},[x.CLOSE_ISSUE]:e=>yo(e),[x.RE_OPEN_ISSUE]:e=>yo(e),[x.MOVE]:e=>{let t=ks();return t.validity==="invalid"?t:mn({hint:fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:J(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(tr).join("");return mn({hint:n.length?Q("create tag or reuse:")+n+Q(""):Q("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Jn();if(d(t))return F({message:ge("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(tr).slice(0,10);return n.length?mn({hint:Q(" ... ")+n.join("")})(e):F({message:ge("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(tr).slice(0,10);return mn({hint:Q("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=Qn();if(d(t))return F({message:ge("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(tr).slice(0,10);return n.length?mn({hint:Q("remove assignee... ")+n.join("")})(e):F({message:ge("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(Z)},Ds=Object.fromEntries(Object.entries(Kl).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Fs=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var Bs=e=>Object.values(x).includes(e),Os=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:s,validity:c,completionWordList:u}=Ds[n].validate(n,r,i),m=o==="command"||o==="modifier"?J(n):Fs,{mode:g}=v(),y=g===p.COMMAND_LINE?s??"":"",N=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Mi(e,N):{hint:"",hints:[],remainder:"",overlap:0}}};var Us=e=>{let t=e.trimStart(),n=zl(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),s=Gl(e),c=Bs(r)?r:null,u=c!==null,m=r!=="",g=c?J(c)??[]:[],y=c&&g.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let E=i?"":s,I=Vl(t,c,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:E,inputString:I}},Vl=(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},zl=e=>e.trim()?e.trim().split(/\s+/):[],Gl=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as ql}from"react";var Wt=e=>e===ho||e===":",ho=" ",de={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:St.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Co=new Set,$s=()=>{for(let e of Co)e()},No=e=>(Co.add(e),()=>Co.delete(e)),Ke=e=>{let n=e(de),r=Us(n.value),o=n.cursorPosition===n.value.length;de={...n,commandMeta:Os(r,o)},$s()},pn=({message:e,status:t})=>{let n=structuredClone(de);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,de=n,$s(),l(e,null)},Eo=e=>{Ke(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},So=e=>{Ke(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Wt(n[o-1]);)o--;for(;o>0&&!Wt(n[o-1]);)o--}else{for(;o<n.length&&!Wt(n[o]);)o++;for(;o<n.length&&Wt(n[o]);)o++}return{...t,cursorPosition:o}})},Hs=()=>{Ke(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}})},Ws=()=>{Ke(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Wt(t[r-1]);)r--;for(;r>0&&!Wt(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},B=e=>{Ke(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),s=i+o,c=Math.max(0,Math.min(i.length,s.length));return{...t,value:s,cursorPosition:c,commandIsPending:!1}})},_s=()=>{Ke(e=>({...e,commandIsPending:!0}))},js=({addToHistory:e=!0})=>{Ke(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Yl()},Ks=()=>{Ke(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}})},Vs=()=>{Ke(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Yl=()=>B(()=>""),G=()=>de,zs=()=>ql(No,G,G),Gs=()=>{let[e,...t]=de.value.split(ho);return t.join(ho).trim()};var qs=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Ys=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Xs=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Js=(e,t)=>{if(Ys(e,e.sequence))return f.MoveCursorLeftOfWord;if(Xs(e,e.sequence))return f.MoveCursorRightOfWord;if(qs(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.GetLastCommandFromHistory;case"down":return f.GetNextCommandFromHistory;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}},Qs=(e,t)=>{if(Ys(e,e.sequence))return f.MoveCursorLeftOfWord;if(Xs(e,e.sequence))return f.MoveCursorRightOfWord;if(qs(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.NavPreviousItem;case"down":return f.NavNextItem;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}};var f={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 Xl(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Jl(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Ql(e,t,n){let r=v().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 Zs(e,t){let n=G();if(e.sequence==="?"&&t!==p.PALETTE)return f.InitCommandPalette;if(e.sequence===":"&&t!==p.COMMAND_LINE)return f.InitCommandLine;if(t===p.MOVE)switch(e.name){case"m":case"return":return f.ConfirmMove}if(t===p.COMMAND_LINE)return Js(e,n.value);if(t===p.PALETTE)return Qs(e,n.value);let r=Xl(e)||Jl(e);if(r)return Zl(r,t);if(e.ctrl&&e.name==="c")return f.Exit;switch(e.name){case"r":return f.EditTitle;case"e":return f.EditDescription;case"n":return f.AddItem;case"m":return f.InitMove;case"d":return f.Delete;case"return":return f.Confirm;case"space":return f.Confirm;case"v":return U().viewMode==="wide"?f.SetViewDense:f.SetViewWide;case"q":case"escape":return f.Exit;default:return null}}function Zl(e,t){let n=t===p.MOVE?{prevItem:f.MovePreviousItem,nextItem:f.MoveNextItem,prevContainer:f.MoveToPreviousContainer,nextContainer:f.MoveToNextContainer}:{prevItem:f.NavPreviousItem,nextItem:f.NavNextItem,prevContainer:f.NavToPreviousContainer,nextContainer:f.NavToNextContainer};return Ql(v().contextNode.childRenderAxis,e,n)}var rr=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case x.EXIT:return P.Exit;case x.EXPORT:return P.Export;case x.INIT:return P.Init;case x.DELETE:return P.Delete;case x.EDIT:return P.Edit;case x.HELP:return P.ViewHelp;case x.RE_OPEN_ISSUE:return P.ReopenIssue;case x.CLOSE_ISSUE:return P.CloseIssue;case x.TAG:return P.TagTicket;case x.UNTAG:return P.UntagTicket;case x.ASSIGN:return P.AssignUserToTicket;case x.UNASSIGN:return P.UnassignUserFromTicket;case x.NEW:return P.NewItem;case x.FILTER:return P.Filter;case x.MOVE:return P.Move;case x.PEEK:return P.Peek;case x.CONFIG:return P.Config;case x.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};import{ulid as xe}from"ulid";import la from"node:fs";import Nu from"node:path";import Eu from"react";import{Box as hu}from"ink";import dr from"react";import{Box as Ro,Text as uu}from"ink";import De from"react";import{Text as ea}from"ink";import ta,{useEffect as na,useState as eu}from"react";var ra={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ve=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=ee(),r=ra[n]??ra.default,[o,i]=eu(0);if(na(()=>{i(0)},[r]),na(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return ta.createElement(ea,null,t);let s=r[o]??r[0]??t;return ta.createElement(ea,{color:h.accent,dimColor:o===1},s)};import{Box as bo,Text as tu}from"ink";import or from"react";var dt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),s=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(i/s)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),g=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),y=g+c,N=e.slice(g,y),E=e.length>c,I=i,w=E?Math.max(1,Math.floor(c/e.length*I)):I,R=Math.max(0,I-w),T=Math.max(1,e.length-c),L=E?Math.floor(g/T*R):0;return or.createElement(bo,{flexDirection:"row",height:i,width:"100%"},or.createElement(bo,{flexDirection:"column",flexGrow:1,height:i},N),or.createElement(bo,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((ne,ie)=>or.createElement(tu,{key:ie,color:E&&ie>=L&&ie<L+w?h.accent:h.secondary},E?"\u2502":" "))))};import{Box as ir,Text as du}from"ink";import bt from"react";import{Text as nu}from"ink";import ru from"react";var ou=e=>e.toLowerCase().trim(),iu=(e,t=ht)=>{let n=ou(e);return t[n]?t[n]:nn(n)},_t=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return ru.createElement(nu,{underline:t,color:iu(n.name)},"@"+n.name)};import{Text as su}from"ink";import au from"react";var jt=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return au.createElement(su,{underline:t,backgroundColor:Re(n.name),color:h.primary}," "+n.name+" ")};var oa=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=On(bi(t.title),r),i=go(t),s=fo(t);return bt.createElement(ir,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?h.accent:h.secondary,justifyContent:"space-between"},bt.createElement(ir,{borderBottom:!0},bt.createElement(ir,{paddingLeft:1,flexDirection:"column"},bt.createElement(du,{color:h.primary},o))),bt.createElement(ir,{flexDirection:"row",paddingLeft:1},i.map(c=>bt.createElement(jt,{key:c.id,id:c.id})),s.map(c=>bt.createElement(_t,{key:c.id,id:c.id}))))};import cu from"chalk";import{Box as gn,Text as Io}from"ink";import Ve from"react";var lu=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ia=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(E=>b.getTag(E)).filter(E=>!!E),s=(t.props.assignees??[]).map(E=>b.getContributor(E)).filter(E=>!!E),c=1,u=i.length*(1+c),m=s.length*(2+c),g=i.map(E=>Ve.createElement(gn,{key:E.id,paddingRight:c},Ve.createElement(Io,{color:Re(E.name)},"\u25A0"))),y=s.map(E=>Ve.createElement(gn,{key:E.id,paddingRight:c},Ve.createElement(Io,{color:nn(E.name)},"@"+E.name.at(0)))),N=n?h.accent:o===p.MOVE?h.secondary:h.primary;return Ve.createElement(gn,{borderBottom:!0,justifyContent:"space-between"},Ve.createElement(gn,null,Ve.createElement(ve,{isSelected:n,placeholder:cu.dim.gray(r+1+" ")}),Ve.createElement(Io,{wrap:"truncate",color:N},lu(t.title,e-u-m-14))),Ve.createElement(gn,null,g,y))};import mu from"chalk";var pu=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:s,mode:c})=>{let{renderedChildrenIndex:u}=ee(),m=u[e.id]??[],g=`${e.title} ${mu.hex(h.secondary2).dim("("+m.length+")")}`,y=3,N=o?1:4,E=r-y-(o?2:1),I=De.createElement(Ro,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},De.createElement(ve,{isSelected:t}),De.createElement(uu,{bold:!0,color:t?h.accent:h.primary},g," ",e.readonly?"\u{1F512}":"")),w=(R,T)=>{let L=i&&s===T;return o?De.createElement(ia,{key:R.id,index:T,width:n,ticket:R,isSelected:L,mode:c}):De.createElement(oa,{key:R.id,width:n,ticket:R,isSelected:L})};return De.createElement(Ro,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},I,De.createElement(Ro,{padding:o?1:0},m.length>0&&De.createElement(dt,{selectedIndex:s,height:E,itemHeight:N},m.map(w)),De.createElement(ve,{isSelected:i&&s===-1})))},sa=De.memo(pu);import{Box as wo,Text as vu}from"ink";import ct,{useMemo as da}from"react";import{Box as sr,Text as gu}from"ink";import ze from"react";var aa=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=ee(),{title:o}=t,i=t.parentNodeId?b.getNode(t.parentNodeId):void 0,s=i&&W(i)?o===X.ASSIGNEES?i.props.assignees??[]:o===X.TAGS?i.props.tags??[]:[]:[];return ze.createElement(sr,{alignItems:"center",paddingTop:1},ze.createElement(sr,{minWidth:12},ze.createElement(ve,{isSelected:n}),ze.createElement(gu,{color:n?h.accent:h.secondary2},o,":")),ze.createElement(sr,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((c,u)=>{let m=r.id===t.id&&u===e;return ze.createElement(sr,{key:`${o}-${c}`,paddingRight:2,minHeight:1},ze.createElement(ve,{isSelected:m}),o===X.ASSIGNEES?ze.createElement(_t,{isSelected:m,id:c}):o===X.TAGS?ze.createElement(jt,{isSelected:m,id:c}):null)})))};import{Box as ar,Text as Ao}from"ink";import Ge,{useEffect as fu}from"react";var To=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:s,contextNode:c}=ee(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];fu(()=>{let N=[];return m.forEach((E,I)=>{let w=Me(BigInt(I+1));if(!Y(w))return;let R=V.text({id:`${e}-${I}`,name:`Line ${I+1}`,parentNodeId:e,rank:w.value,props:{value:E},readonly:!0,isVirtual:!0}),T=b.createNode(R);Y(T)&&N.push(T.value.id)}),()=>N.forEach(b.deleteNode)},[e,n]);let g="\u2029",y=m.map((N,E)=>{let I=c.id===e&&s===E;return Ge.createElement(ar,{key:`${e}-${E}`},Ge.createElement(Ao,{color:I?h.primary:h.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),Ge.createElement(Ao,{backgroundColor:I?"gray":""},u(N.length?On(N,i-10):g)))});return Ge.createElement(ar,{flexDirection:"column",paddingTop:1},Ge.createElement(ar,null,Ge.createElement(ve,{isSelected:o}),Ge.createElement(Ao,{color:o?h.accent:h.secondary2},t)),Ge.createElement(ar,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},Ge.createElement(dt,{scrollByOne:!0,children:y,height:r-2,selectedIndex:s,itemHeight:1})))};var xu=e=>it(e,"description"),yu=e=>it(e,"history"),ca=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=ee(),o=process.stdout.columns||120,i=da(()=>xu(e.id),[e.id]),s=da(()=>yu(e.id),[e.id]),c=r.id===e.id,u=r.id===s||r.parentNodeId===s,m=O(e.id);if(u){let R=b.getNode(s),T=R&&rt(R)?R.props.value??"":"",ne=t-3;return ct.createElement(wo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?ct.createElement(To,{id:R.id,label:"Event log",text:T,selected:!1,maxWidth:o,height:ne}):null)}let g=m.reduce((R,T)=>tn(T)||T.id===s?R+1:R,0),y=2,N=3,E=g,I=t-N-E-y,w=(R,T)=>R.id===i?ct.createElement(To,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:T,maxWidth:o,height:I}):tn(R)?ct.createElement(aa,{key:R.id,parent:R,selected:T,selectedIndex:n}):R.id===s?ct.createElement(wo,{key:R.id,paddingTop:1},ct.createElement(ve,{isSelected:T}),ct.createElement(vu,{backgroundColor:h.secondary,color:T?h.accent:h.primary}," History \u203A\u203A ")):null;return ct.createElement(wo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,T)=>w(R,c&&n===T)))};var Cu=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:s,width:c})=>{let u=t.context,m=u===M.TICKET||u===M.FIELD_LIST||u===M.FIELD,g=u===M.BOARD||u===M.SWIMLANE,y=u===M.TICKET?t:r.find(R=>R.context===M.TICKET),N=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),I=Math.min(E,N),w=i==="dense";return dr.createElement(hu,{flexDirection:"row",height:s},g&&e.map((R,T)=>{let L=t.id===R.id,ne=L?n:-1,ie=t.context===M.BOARD&&n===T;return dr.createElement(sa,{key:R.id,height:s,width:I,swimlane:R,isSelected:ie,isDense:w,isFocused:L,listSelectedIndex:ne,mode:o})}),m&&y&&dr.createElement(ca,{height:s,ticket:y}))},cr=dr.memo(Cu);import{render as Su}from"ink";import{Writable as bu}from"node:stream";var fn=e=>String(e).padStart(2,"0"),Iu=e=>{let t=e.getUTCFullYear(),n=fn(e.getUTCMonth()+1),r=fn(e.getUTCDate()),o=fn(e.getUTCHours()),i=fn(e.getUTCMinutes()),s=fn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${s}`},Ru=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Au=async(e,{width:t,height:n})=>{let r="",o=new bu({write(s,c,u){let m=Tu(s.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Su(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(s=>setTimeout(s,0)),i.unmount(),r},Tu=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ua=async()=>{let{viewMode:e}=U(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),s=r.find(T=>T.context==="BOARD");if(!s)return a("No board found to export");let c=120,u=40,m=await Au(Eu.createElement(cr,{height:u,width:c,swimlanes:(i[s.id]??[]).filter(T=>T!==void 0&&kt(T)),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 g=Rn(process.cwd());if(d(g))return a("Unable to export, epiq root not found");let y=new Date,N=Iu(y),E=`board_${Ru(s.title)}_${N}.md`,I=Qo(g.value);la.mkdirSync(I,{recursive:!0});let w=Nu.join(I,E),R=`# Board - ${s.title}
|
|
25
|
+
`)}`):(el(),b({hasProjectDefinition:!0}),c("State booted successfully",null))}var ro=({status:e,msg:t})=>{Ft()&&b({syncStatus:{status:e,msg:t}})},ms=(e="Syncing...")=>{ro({status:"syncing",msg:e})},ps=(e="Synced")=>{ro({status:"synced",msg:e})},tl=e=>{ro({status:"failed",msg:e})},ke=e=>(tl(e),a(e));var Bt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),oo=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)}},H=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);import Ut from"node:fs";import sn from"node:path";var fs=async e=>{if((await we({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ae.info("Creating initial commit");let n=await V.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):c("Created initial commit",!0)},gs=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",nl=async e=>{let t=await Mn(e);if(d(t))return a(t.message);let n=await si(e);return d(n)?a(n.message):c("Built sync commit message",`[epiq:sync:${gs(t.value)}:${gs(n.value)}]`)},io=async({repoRoot:e,stateBranchName:t})=>{ae.info(`Creating ${t}`);let n=await L({args:["commit-tree",ui,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
26
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await L({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
27
|
+
${o.message}`):c("Created state branch",!0)},rl=async({repoRoot:e,stateBranchName:t})=>{let n=await Or({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
28
|
+
`+n.message);let r=n.value,o=r?await Tn({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
29
|
+
`+o.message);let i=o.value;if(r&&i){let l=await V.fetch({cwd:e,remote:Ce,branch:t});if(d(l))return a(`Failed to fetch ${t} from remote
|
|
30
|
+
${l.message}`)}let s=await wn({repoRoot:e,branch:t});if(d(s))return a(`Ensure local state branch failed
|
|
31
|
+
`+s.message);if(s.value)return c("Local state branch already exists",!1);if(i){let l=await L({args:["branch","--track",t,`${Ce}/${t}`],cwd:e});return d(l)?a(`Failed to create local ${t} from remote
|
|
32
|
+
${l.message}`):c("Created local state branch from remote",!0)}return io({repoRoot:e,stateBranchName:t})},ol=async({repoRoot:e,branch:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
33
|
+
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},il=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Jt(sn.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
34
|
+
`+r.message);Ut.existsSync(t)&&!Ut.existsSync(sn.join(t,".git"))&&(ae.info("Removing broken state branch worktree path"),pi(t)),ae.info("Creating state branch worktree");let o=await V.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
35
|
+
${o.message}`):c("Created state branch worktree",!0)},so=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await ol({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=sn.resolve(t),i=r.value?sn.resolve(r.value):null;if(i&&i===o&&Ut.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){ae.info("Moving state branch worktree to expected location");let u=await V.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return a(`Failed to remove existing state branch worktree
|
|
36
|
+
${u.message}`)}if(i&&!Ut.existsSync(i)){ae.info("Pruning stale state branch worktree");let u=await V.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
37
|
+
${u.message}`)}let s=await ii({repoRoot:e,worktreeRoot:t});if(d(s))return a(s.message);let l=Ut.existsSync(t);if(s.value&&l)return c("State branch worktree already exists",!1);if(s.value&&!l){ae.info("Pruning missing registered state branch worktree");let u=await V.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
38
|
+
${u.message}`)}return il({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},sl=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Mn(e);if(d(n))return a(n.message);if(n.value===t)return c("State branch already checked out",!1);(await we({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ae.info("Aborted stale state branch rebase");let o=await V.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
39
|
+
${o.message}`):c("Checked out state branch",!0)},al=async({repoRoot:e,stateBranchRoot:t})=>{let n=await $r(t);if(d(n))return a(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Or({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=wt(e);if(d(o))return o;let i=o.value,s=await Tn({repoRoot:t,branch:i});if(d(s))return a(s.message);if(!s.value)return c("Remote state branch missing; upstream will be configured on first push",!1);ae.info(`Configuring ${i} upstream`);let l=await V.fetch({cwd:t,remote:Ce,branch:i});if(d(l))return a(`Failed to fetch ${i}
|
|
40
|
+
${l.message}`);let u=await V.setUpstream({cwd:t,branch:i,upstream:`${Ce}/${i}`});return d(u)?a(`Failed to set state branch upstream
|
|
41
|
+
${u.message}`):c("Configured state branch upstream",!0)},Gn=async({stateBranchRoot:e,eventFileName:t})=>{let n=_r(t),r=sn.join(e,n);if(!Ut.existsSync(r))return c("No event file to stage",void 0);let o=await V.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
42
|
+
${o.message}`):c("Staged state branch event file",void 0)},vs=async({repoRoot:e,stateBranchRoot:t})=>{let n=await nl(e);return d(n)?a(`Create state branch sync commit failed
|
|
43
|
+
`+n.message):Mt({cwd:t,message:n.value})},an=async({repoRoot:e,stateBranchRoot:t})=>{let n=await $r(t);if(d(n))return a(n.message);let r=wt(e);if(d(r))return r;let o=r.value,i=n.value?await V.push({cwd:t}):await V.push({cwd:t,remote:Ce,branch:o,setUpstream:!0});return d(i)?a(`Failed during state branch push
|
|
44
|
+
${i.message}`):c("Pushed state branch",!0)},xs=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=wt(e);if(d(o))return o;let i=o.value,s=[kn(),await rl({repoRoot:e,stateBranchName:i}),await so({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await sl({stateBranchRoot:t,stateBranchName:i}),await fi(t),n?await al({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of s){if(d(l))return a(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{decodeTime as Qv}from"ulid";var dl=async({cwd:e,ensureUpstream:t})=>{logger.info("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=H("getRepoRootDir",await Je(e));if(d(n))return a(n.message);let r=n.value;logger.info("[sync] repo root",r);let o=H("getStateBranchRoot",Xe({repoRoot:r}));if(d(o))return a(o.message);let i=o.value;logger.info("[sync] state branch root",i);let s=H("ensureInitialCommit",await fs(r));if(d(s))return a(s.message);logger.info("[sync] initial commit result",{created:s.value}),logger.info("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let l=H("bootstrapStateBranchStorage",await xs({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(d(l))return a(l.message);logger.info("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.info("[sync] checking state branch git operation",{stateBranchRoot:i});let u=H("hasInProgressGitOperation(stateBranchRoot)",await An(i));if(d(u))return a(u.message);if(logger.info("[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.info("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:i});let m=H("ensureStateBranchLayout",gi(r,i));return d(m)?a(m.message):(logger.info("[sync] state branch layout ready"),logger.info("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:i,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:l.value}))},cl=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.info("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.info("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=H("stageStateBranchOwnEventFile",await Gn({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=H("hasStagedChanges(after stage)",await di(t));if(d(o))return a(o.message);if(logger.info("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.info("[sync] creating sync commit");let i=H("createStateBranchSyncCommit",await vs({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.info("[sync] created sync commit",i.value),c("Committed own event file",{createdCommit:!0,commitSha:i.value}))},ll=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.info("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.info("[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.info("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");ms("Syncing");let n=H("ensureSyncReady",await dl({cwd:e,ensureUpstream:!0}));if(d(n))return ke(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,s=H("isDetachedHead(stateBranchRoot)",await ci(o));if(d(s))return ke(s.message);if(logger.info("[sync] detached state branch check result",{detached:s.value}),s.value)return ke("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,y=H("getStateBranch",wt(r));if(d(y))return ke(y.message);let N=y.value;logger.info("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:o});let E=H("commitOwnEventFileToStateBranch",await cl({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(E))return ke(E.message);l=E.value.createdCommit,u=E.value.commitSha;let I=H("pullBranchRebaseIfPresent",await Wr({cwd:o,branch:N}));if(d(I))return ke(I.message);if(m=I.value,l||i){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:i,stateBranchRoot:o});let A=H("pushStateBranch",await an({stateBranchRoot:o,repoRoot:r}));if(d(A)&&ai(A.message)){let R=H("pullBranchRebaseIfPresent(retry)",await Wr({cwd:o,branch:N}));if(d(R))return ke(R.message);m=m||R.value,A=H("pushStateBranch(retry)",await an({stateBranchRoot:o,repoRoot:r}))}if(d(A))return ke(A.message);g=A.value}if(l){logger.info("[sync] resolving final sync commit sha",{stateBranchRoot:o});let A=H("git rev-parse HEAD",await L({args:["rev-parse","HEAD"],cwd:o}));if(d(A))return ke(A.message);u=A.value.stdout.trim(),logger.info("[sync] final sync commit sha",u)}return ps(g?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.info("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:g,bootstrapped:i})},qn=async()=>{let e=ys();if(e)return e;logger.info("[sync] syncAndReloadState:start");let t=H("resolveActorId",z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),a("Unable to resolve event log path");let n=rn(t.value);logger.info("[sync] resolved own event file name",{ownEventFileName:n});let r=H("syncEpiqWithRemote",await ll({ownEventFileName:n}));if(d(r))return logger.info("[sync] syncAndReloadState:sync failed",r.message),a(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.info("[sync] loading merged events after sync",{stateBranchRoot:o});let i=H("loadMergedEvents",Dt(o));if(d(i))return a(`Unable to load events. ${i.message}`);logger.info("[sync] loaded merged events after sync",{count:i.value.length});let s=ys();if(s)return s;let l=ds(),u=H("bootStateFromEventLog",zn(i.value));if(d(u))return a(`Unable to boot synced state. ${u.message}`);logger.info("[sync] booted state from synced events"),b({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}});let m=H("restoreNavigationAnchor",ls(l));return d(m)?m:(logger.info("[sync] syncAndReloadState:done"),c("Synced",!0))},ys=()=>v().mode===p.DEFAULT?null:(b({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Ot=3e3,hs=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ot?null:t},Cs=0,ao,co=!1,dn=!1,lo=()=>{if(co)return!0;let e=ot();return d(e)?!1:e.value.syncStatus.status==="syncing"},ul=()=>{let e=U().autoSyncIntervalMs??1e4,t=Date.now()-Cs;return Math.max(0,e-t)},Ns=()=>{ao||(ao=setTimeout(async()=>{if(ao=void 0,!!Ft()){if(lo()){dn=!0;return}dn=!1,await ml()}},ul()))},ml=async()=>{if(v().readOnly||v().timeMode==="peek")return a("Cannot auto-sync while peeking");if(!Ft())return a("Cannot auto-sync before state is initialized");if(lo())return dn=!0,a("Sync already in progress");co=!0,Cs=Date.now(),b({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await qn()}finally{co=!1,dn&&Ns()}},Es=()=>{Ft()&&(dn=!0,!lo()&&Ns())};var pl=e=>e.props.tags??[],gl=e=>e.props.assignees??[],uo=e=>pl(e).map(t=>S.getTag(t)).filter(t=>!!t),mo=e=>gl(e).map(t=>S.getContributor(t)).filter(t=>!!t),Yn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!$(n)?a("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",uo(n))},Xn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!$(n)?a("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",mo(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var fl=/^(\d+)(h|d|w|mo|y)$/,vl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,xl=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},yl=(e,t=new Date)=>{let n=e.match(fl);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let s=new Date(t);switch(o){case"h":return s.setHours(s.getHours()-i),s;case"d":return s.setDate(s.getDate()-i),s;case"w":return s.setDate(s.getDate()-i*7),s;case"mo":return s.setMonth(s.getMonth()-i),s;case"y":return s.setFullYear(s.getFullYear()-i),s;default:return null}},hl=e=>{let t=e.match(vl);if(!t)return null;let[,n,r,o,i,s]=t,l=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,y=s?Number(s):0;return xl({year:l,month:u,day:m,hour:g,minute:y})?new Date(l,u-1,m,g,y):null},Jn=e=>{let t=e.trim().toLowerCase();return yl(t)??hl(t)},Ss=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Cl=[{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}],bs=(e=Cl)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var Nl=["BOARD","TICKET","SWIMLANE"],ne={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},it={TITLE:"title",DESCRIPTION:"description"},El=[ne.EDITOR,ne.VIEW,ne.USERNAME,ne.AUTOSYNC,ne.SYNC_DEBOUNCE_MS],Sl=[it.TITLE,it.DESCRIPTION],go=[String(Ot),"5000","15000","30000","60000"],ht=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],Qn=[x.NEW,x.EDIT,x.DELETE,x.MOVE],po=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT],Is=[x.FILTER,x.PEEK],bl={WORKSPACE:[...ht,...Qn],BOARD:[...Is,...ht,...Qn],SWIMLANE:[...Is,...ht,...Qn],TICKET:[...ht,...Qn,...po],FIELD:[...ht,...po],FIELD_LIST:[...ht,...po],TEXT:[...ht]},Il=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Rl=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ze();if(!r)return[x.HELP,x.CONFIG];if(!vi())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.EXPORT,x.CONFIG];let o=e?.context,i=o&&Nl.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?bl[l]:[]))].filter(l=>l===x.MOVE?!1:l===x.EDIT||l===x.DELETE?i:!0)},Q=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[x.NONE]:Rl({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...bs(),"now","prev","next"],[x.EDIT]:[...Sl],[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","clear"],[x.TAG]:[...new Set([...Object.keys(vt),...S.getExistingTags()])],[x.UNTAG]:[...Yn()?.value?.map(({name:l})=>l)??[]],[x.UNASSIGN]:[...Xn()?.value?.map(({name:l})=>l)??[]],[x.ASSIGN]:S.getExistingAssignees(),[x.NEW]:Il(i),[x.CONFIG]:[...El]}[e]??[]};import ws from"chalk";var Rs=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import As from"chalk";var Z=e=>As.dim(e),me=e=>As.hex(h.primary)(e),pe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let s=o.trim();if(s.length<i)return"";let g=[...t.filter(Boolean).filter(y=>y.startsWith(s))].sort((y,N)=>Bn(y)-Bn(N)).slice(0,r).map(y=>Un(y)).join(" ");return g?`${Z(e)}${g}${Z(n)}`:""};var Ct={None:"none",Invalid:"invalid",Valid:"valid"};var Al=["BOARD","TICKET","SWIMLANE"],Ts=()=>{let e=v().selectedNode;return e?.context?Al.includes(e.context)?j():D({message:Z("Command not available in this context")}):D({message:Z("Missing target context")})},ee="<ENTER> to confirm",j=(e="",t=[])=>({message:Z(e),validity:Ct.Valid,completionWordList:t}),D=({message:e,completionWordList:t=[]})=>({validity:Ct.Invalid,message:e,completionWordList:t}),er=e=>e.length===0,Zn=e=>` ${ws.dim.bgHex(Oi(e))(` ${e} `)} `,fo=({modifier:e})=>{let t="confirm";return e===t?j(ee):D({message:er(e)?Z("if you are certain, enter ")+Un(t):"",completionWordList:[t]})},Tl=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?D({message:Z(n)}):j():D({message:er(r)?t:"",completionWordList:[...e]}),cn=({hint:e})=>({modifier:t,inputString:n})=>er(t)&&er(n)?D({message:e,completionWordList:[]}):j(ee),wl=({modifier:e,inputString:t})=>{let n=Q(x.CONFIG);if(!n.includes(e))return D({message:pe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ne.EDITOR:{let r=[...Rs];return t.trim()?r.includes(t.trim())?j(ee):D({message:pe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):D({message:pe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ee):D({message:pe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.USERNAME:return t.trim()?j(ee):D({message:me("Enter a user name. Saved in ")+ws.bgBlack("~/.epiq-global/config.json")});case ne.AUTOSYNC:{let r=["yes","no"],o=U().autoSync;if(!r.includes(t.trim())){let i=xi(o);return D({message:pe({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ee)}case ne.SYNC_DEBOUNCE_MS:{let r=U().autoSyncIntervalMs,o=hs(t);if(!t.trim()||o===null||o<Ot){let i=pe({prefix:" examples: ",wordList:go,minLengthForHints:0,inputString:t});return D({message:me(`provide duration above ${Ot}ms. current duration: ${r}ms.`)+i,completionWordList:go})}return j(ee)}default:return D({message:me("Unknown config option"),completionWordList:n})}},Ml=({modifier:e})=>{let t=Q(x.EDIT);if(!t.includes(e)){let i=pe({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return D({message:i||me("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!Ne([...n,r],"TICKET"))return D({message:me("Command not available in this context")});switch(e){case it.TITLE:return j(ee);case it.DESCRIPTION:let{preferredEditor:i}=U();return i?j(Z("<ENTER> to edit in ")+i):D({message:"No editor selected"});default:return D({message:me("Unknown edit option"),completionWordList:t})}},Pl={[x.EXPORT]:()=>j(ee+Z(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(ee);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return j(ee);let r=Jn(t);if(!t||!r)return D(n);let o=Ne(v().breadCrumb,"BOARD");if(d(o))return D({message:me("Command is not applicable in this context")});let i=On(o.value.id);return d(i)?D({message:me("Unable to peek: board id is not a valid ULID")}):Ss({date:r,horizonDate:i.value})?j(ee):D({message:me(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[x.EXIT]:()=>j(ee+Z(" and exit the application")),[x.INIT]:()=>j(ee),[x.PALETTE]:()=>j(ee),[x.FILTER]:e=>{if(e.modifier==="clear")return j();let t=i=>Q(x.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return D({message:pe({wordList:Q(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Q(x.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?D({message:pe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):j():D({message:pe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[x.NONE]:e=>{let t=Q(x.NONE);return D({message:pe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Tl({list:Q(x.NEW),hint:pe({wordList:Q(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ee),[x.EDIT]:Ml,[x.CONFIG]:wl,[x.DELETE]:e=>{let t=Ts();return t.validity==="invalid"?t:fo(e)},[x.CLOSE_ISSUE]:e=>fo(e),[x.RE_OPEN_ISSUE]:e=>fo(e),[x.MOVE]:e=>{let t=Ts();return t.validity==="invalid"?t:cn({hint:pe({prefix:"hey hacker! These commands are blocked for you... ",wordList:Q(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=S.getExistingTags().slice(0,10).map(Zn).join("");return cn({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Yn();if(d(t))return D({message:me("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Zn).slice(0,10);return n.length?cn({hint:Z(" ... ")+n.join("")})(e):D({message:me("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=S.getExistingAssignees().map(Zn).slice(0,10);return cn({hint:Z("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=Xn();if(d(t))return D({message:me("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Zn).slice(0,10);return n.length?cn({hint:Z("remove assignee... ")+n.join("")})(e):D({message:me("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ee)},Ms=Object.fromEntries(Object.entries(Pl).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ps=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var ks=e=>Object.values(x).includes(e),Ls=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:s,validity:l,completionWordList:u}=Ms[n].validate(n,r,i),m=o==="command"||o==="modifier"?Q(n):Ps,{mode:g}=v(),y=g===p.COMMAND_LINE?s??"":"",N=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Pi(e,N):{hint:"",hints:[],remainder:"",overlap:0}}};var Ds=e=>{let t=e.trimStart(),n=Ll(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),s=Dl(e),l=ks(r)?r:null,u=l!==null,m=r!=="",g=l?Q(l)??[]:[],y=l&&g.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let E=i?"":s,I=kl(t,l,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:E,inputString:I}},kl=(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},Ll=e=>e.trim()?e.trim().split(/\s+/):[],Dl=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Fl}from"react";var $t=e=>e===vo||e===":",vo=" ",se={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ct.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},xo=new Set,Fs=()=>{for(let e of xo)e()},yo=e=>(xo.add(e),()=>xo.delete(e)),Le=e=>{let n=e(se),r=Ds(n.value),o=n.cursorPosition===n.value.length;se={...n,commandMeta:Ls(r,o)},Fs()},ln=({message:e,status:t})=>{let n=structuredClone(se);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,se=n,Fs(),c(e,null)},ho=e=>{Le(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Co=e=>{Le(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&$t(n[o-1]);)o--;for(;o>0&&!$t(n[o-1]);)o--}else{for(;o<n.length&&!$t(n[o]);)o++;for(;o<n.length&&$t(n[o]);)o++}return{...t,cursorPosition:o}})},Bs=()=>{Le(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}})},Us=()=>{Le(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&$t(t[r-1]);)r--;for(;r>0&&!$t(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},tr=e=>{Le(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),s=i+o,l=Math.max(0,Math.min(i.length,s.length));return{...t,value:s,cursorPosition:l,commandIsPending:!1}})},Os=()=>{Le(e=>({...e,commandIsPending:!0}))},O=e=>{Le(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},$s=({addToHistory:e=!0})=>{Le(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ws=()=>{Le(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}})},Hs=()=>{Le(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},G=()=>se,_s=()=>Fl(yo,G,G),js=()=>{let[e,...t]=se.value.split(vo);return t.join(vo).trim()};var f={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 Bl(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Ul(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Ol(e,t,n){let r=v().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 Vs(e,t){let n=G();if(e.sequence==="?"&&t!==p.PALETTE)return f.InitCommandPalette;if(e.sequence===":"&&t!==p.COMMAND_LINE)return f.InitCommandLine;if(t===p.MOVE)switch(e.name){case"m":case"return":return f.ConfirmMove}if(t===p.COMMAND_LINE)return Si(e,n.value);if(t===p.PALETTE)return bi(e,n.value);let r=Bl(e)||Ul(e);if(r)return $l(r,t);if(e.ctrl&&e.name==="c")return f.Exit;switch(e.name){case"r":return f.EditTitle;case"e":return f.EditDescription;case"n":return f.AddItem;case"m":return f.InitMove;case"d":return f.Delete;case"return":return f.Confirm;case"space":return f.Confirm;case"v":return U().viewMode==="wide"?f.SetViewDense:f.SetViewWide;case"q":case"escape":return f.Exit;default:return null}}function $l(e,t){let n=t===p.MOVE?{prevItem:f.MovePreviousItem,nextItem:f.MoveNextItem,prevContainer:f.MoveToPreviousContainer,nextContainer:f.MoveToNextContainer}:{prevItem:f.NavPreviousItem,nextItem:f.NavNextItem,prevContainer:f.NavToPreviousContainer,nextContainer:f.NavToNextContainer};return Ol(v().contextNode.childRenderAxis,e,n)}var nr=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case x.EXIT:return P.Exit;case x.EXPORT:return P.Export;case x.INIT:return P.Init;case x.DELETE:return P.Delete;case x.EDIT:return P.Edit;case x.HELP:return P.ViewHelp;case x.RE_OPEN_ISSUE:return P.ReopenIssue;case x.CLOSE_ISSUE:return P.CloseIssue;case x.TAG:return P.TagTicket;case x.UNTAG:return P.UntagTicket;case x.ASSIGN:return P.AssignUserToTicket;case x.UNASSIGN:return P.UnassignUserFromTicket;case x.NEW:return P.NewItem;case x.FILTER:return P.Filter;case x.MOVE:return P.Move;case x.PEEK:return P.Peek;case x.CONFIG:return P.Config;case x.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};import{ulid as fe}from"ulid";import ta from"node:fs";import au from"node:path";import du from"react";import{Box as iu}from"ink";import ar from"react";import{Box as So,Text as Jl}from"ink";import De from"react";import{Text as Ks}from"ink";import zs,{useEffect as Gs,useState as Wl}from"react";var qs={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ge=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=q(),r=qs[n]??qs.default,[o,i]=Wl(0);if(Gs(()=>{i(0)},[r]),Gs(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return zs.createElement(Ks,null,t);let s=r[o]??r[0]??t;return zs.createElement(Ks,{color:h.accent,dimColor:o===1},s)};import{Box as No,Text as Hl}from"ink";import rr from"react";var st=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),s=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/s)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),g=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),y=g+l,N=e.slice(g,y),E=e.length>l,I=i,A=E?Math.max(1,Math.floor(l/e.length*I)):I,R=Math.max(0,I-A),w=Math.max(1,e.length-l),B=E?Math.floor(g/w*R):0;return rr.createElement(No,{flexDirection:"row",height:i,width:"100%"},rr.createElement(No,{flexDirection:"column",flexGrow:1,height:i},N),rr.createElement(No,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((Ie,ce)=>rr.createElement(Hl,{key:ce,color:E&&ce>=B&&ce<B+A?h.accent:h.secondary},E?"\u2502":" "))))};import{Box as or,Text as ql}from"ink";import Nt from"react";import{Text as _l}from"ink";import jl from"react";var Vl=e=>e.toLowerCase().trim(),Kl=(e,t=vt)=>{let n=Vl(e);return t[n]?t[n]:Zt(n)},Wt=({id:e,isSelected:t})=>{let n=S.getContributor(e);if(n)return jl.createElement(_l,{underline:t,color:Kl(n.name)},"@"+n.name)};import{Text as zl}from"ink";import Gl from"react";var Ht=({id:e,isSelected:t})=>{let n=S.getTag(e);if(n)return Gl.createElement(zl,{underline:t,backgroundColor:Se(n.name),color:h.primary}," "+n.name+" ")};var Ys=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Fn(Ii(t.title),r),i=uo(t),s=mo(t);return Nt.createElement(or,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?h.accent:h.secondary,justifyContent:"space-between"},Nt.createElement(or,{borderBottom:!0},Nt.createElement(or,{paddingLeft:1,flexDirection:"column"},Nt.createElement(ql,{color:h.primary},o))),Nt.createElement(or,{flexDirection:"row",paddingLeft:1},i.map(l=>Nt.createElement(Ht,{key:l.id,id:l.id})),s.map(l=>Nt.createElement(Wt,{key:l.id,id:l.id}))))};import Yl from"chalk";import{Box as un,Text as Eo}from"ink";import je from"react";var Xl=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Xs=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(E=>S.getTag(E)).filter(E=>!!E),s=(t.props.assignees??[]).map(E=>S.getContributor(E)).filter(E=>!!E),l=1,u=i.length*(1+l),m=s.length*(2+l),g=i.map(E=>je.createElement(un,{key:E.id,paddingRight:l},je.createElement(Eo,{color:Se(E.name)},"\u25A0"))),y=s.map(E=>je.createElement(un,{key:E.id,paddingRight:l},je.createElement(Eo,{color:Zt(E.name)},"@"+E.name.at(0)))),N=n?h.accent:o===p.MOVE?h.secondary:h.primary;return je.createElement(un,{borderBottom:!0,justifyContent:"space-between"},je.createElement(un,null,je.createElement(ge,{isSelected:n,placeholder:Yl.dim.gray(r+1+" ")}),je.createElement(Eo,{wrap:"truncate",color:N},Xl(t.title,e-u-m-14))),je.createElement(un,null,g,y))};import Ql from"chalk";var Zl=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:s,mode:l})=>{let{renderedChildrenIndex:u}=q(),m=u[e.id]??[],g=`${e.title} ${Ql.hex(h.secondary2).dim("("+m.length+")")}`,y=3,N=o?1:4,E=r-y-(o?2:1),I=De.createElement(So,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},De.createElement(ge,{isSelected:t}),De.createElement(Jl,{bold:!0,color:t?h.accent:h.primary},g," ",e.readonly?"\u{1F512}":"")),A=(R,w)=>{let B=i&&s===w;return o?De.createElement(Xs,{key:R.id,index:w,width:n,ticket:R,isSelected:B,mode:l}):De.createElement(Ys,{key:R.id,width:n,ticket:R,isSelected:B})};return De.createElement(So,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},I,De.createElement(So,{padding:o?1:0},m.length>0&&De.createElement(st,{selectedIndex:s,height:E,itemHeight:N},m.map(A)),De.createElement(ge,{isSelected:i&&s===-1})))},Js=De.memo(Zl);import{Box as Ro,Text as nu}from"ink";import at,{useMemo as Zs}from"react";import{Box as ir,Text as eu}from"ink";import Ve from"react";var Qs=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=q(),{title:o}=t,i=t.parentNodeId?S.getNode(t.parentNodeId):void 0,s=i&&$(i)?o===J.ASSIGNEES?i.props.assignees??[]:o===J.TAGS?i.props.tags??[]:[]:[];return Ve.createElement(ir,{alignItems:"center",paddingTop:1},Ve.createElement(ir,{minWidth:12},Ve.createElement(ge,{isSelected:n}),Ve.createElement(eu,{color:n?h.accent:h.secondary2},o,":")),Ve.createElement(ir,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((l,u)=>{let m=r.id===t.id&&u===e;return Ve.createElement(ir,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Ve.createElement(ge,{isSelected:m}),o===J.ASSIGNEES?Ve.createElement(Wt,{isSelected:m,id:l}):o===J.TAGS?Ve.createElement(Ht,{isSelected:m,id:l}):null)})))};import{Box as sr,Text as bo}from"ink";import Ke,{useEffect as tu}from"react";var Io=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:s,contextNode:l}=q(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];tu(()=>{let N=[];return m.forEach((E,I)=>{let A=Ae(BigInt(I+1));if(!X(A))return;let R=K.text({id:`${e}-${I}`,name:`Line ${I+1}`,parentNodeId:e,rank:A.value,props:{value:E},readonly:!0,isVirtual:!0}),w=S.createNode(R);X(w)&&N.push(w.value.id)}),()=>N.forEach(S.deleteNode)},[e,n]);let g="\u2029",y=m.map((N,E)=>{let I=l.id===e&&s===E;return Ke.createElement(sr,{key:`${e}-${E}`},Ke.createElement(bo,{color:I?h.primary:h.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),Ke.createElement(bo,{backgroundColor:I?"gray":""},u(N.length?Fn(N,i-10):g)))});return Ke.createElement(sr,{flexDirection:"column",paddingTop:1},Ke.createElement(sr,null,Ke.createElement(ge,{isSelected:o}),Ke.createElement(bo,{color:o?h.accent:h.secondary2},t)),Ke.createElement(sr,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},Ke.createElement(st,{scrollByOne:!0,children:y,height:r-2,selectedIndex:s,itemHeight:1})))};var ru=e=>rt(e,"description"),ou=e=>rt(e,"history"),ea=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=q(),o=process.stdout.columns||120,i=Zs(()=>ru(e.id),[e.id]),s=Zs(()=>ou(e.id),[e.id]),l=r.id===e.id,u=r.id===s||r.parentNodeId===s,m=F(e.id);if(u){let R=S.getNode(s),w=R&&tt(R)?R.props.value??"":"",Ie=t-3;return at.createElement(Ro,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?at.createElement(Io,{id:R.id,label:"Event log",text:w,selected:!1,maxWidth:o,height:Ie}):null)}let g=m.reduce((R,w)=>Qt(w)||w.id===s?R+1:R,0),y=2,N=3,E=g,I=t-N-E-y,A=(R,w)=>R.id===i?at.createElement(Io,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:w,maxWidth:o,height:I}):Qt(R)?at.createElement(Qs,{key:R.id,parent:R,selected:w,selectedIndex:n}):R.id===s?at.createElement(Ro,{key:R.id,paddingTop:1},at.createElement(ge,{isSelected:w}),at.createElement(nu,{backgroundColor:h.secondary,color:w?h.accent:h.primary}," History \u203A\u203A ")):null;return at.createElement(Ro,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,w)=>A(R,l&&n===w)))};var su=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:s,width:l})=>{let u=t.context,m=u===M.TICKET||u===M.FIELD_LIST||u===M.FIELD,g=u===M.BOARD||u===M.SWIMLANE,y=u===M.TICKET?t:r.find(R=>R.context===M.TICKET),N=Math.floor(l/3),E=Math.floor(l/Math.max(e.length,1)),I=Math.min(E,N),A=i==="dense";return ar.createElement(iu,{flexDirection:"row",height:s},g&&e.map((R,w)=>{let B=t.id===R.id,Ie=B?n:-1,ce=t.context===M.BOARD&&n===w;return ar.createElement(Js,{key:R.id,height:s,width:I,swimlane:R,isSelected:ce,isDense:A,isFocused:B,listSelectedIndex:Ie,mode:o})}),m&&y&&ar.createElement(ea,{height:s,ticket:y}))},dr=ar.memo(su);import{render as cu}from"ink";import{Writable as lu}from"node:stream";var mn=e=>String(e).padStart(2,"0"),uu=e=>{let t=e.getUTCFullYear(),n=mn(e.getUTCMonth()+1),r=mn(e.getUTCDate()),o=mn(e.getUTCHours()),i=mn(e.getUTCMinutes()),s=mn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${s}`},mu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",pu=async(e,{width:t,height:n})=>{let r="",o=new lu({write(s,l,u){let m=gu(s.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=cu(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(s=>setTimeout(s,0)),i.unmount(),r},gu=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),na=async()=>{let{viewMode:e}=U(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),s=r.find(w=>w.context==="BOARD");if(!s)return a("No board found to export");let l=120,u=40,m=await pu(du.createElement(dr,{height:u,width:l,swimlanes:(i[s.id]??[]).filter(w=>w!==void 0&&Pt(w)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return a("Failed to render board export");let g=bn(process.cwd());if(d(g))return a("Unable to export, epiq root not found");let y=new Date,N=uu(y),E=`board_${mu(s.title)}_${N}.md`,I=qo(g.value);ta.mkdirSync(I,{recursive:!0});let A=au.join(I,E),R=`# Board - ${s.title}
|
|
48
45
|
Date: ${y.toISOString()}
|
|
49
46
|
|
|
50
47
|
\`\`\`text
|
|
51
48
|
${m}
|
|
52
49
|
\`\`\`
|
|
53
|
-
`;return
|
|
54
|
-
`),
|
|
55
|
-
`).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return
|
|
50
|
+
`;return ta.writeFileSync(A,R,"utf8"),c("Exported board layout",A)};import Eu from"node:os";import sa from"node:path";import{z as Et}from"zod";import{accessSync as fu,copyFileSync as vu,existsSync as cr,mkdirSync as ra,readdirSync as oa,readFileSync as xu,renameSync as yu,rmSync as hu,statSync as ia,unlinkSync as Cu,writeFileSync as Nu}from"node:fs";import _t from"node:path";var xe={writeToFile:(e,t)=>{try{let n=_t.dirname(e);cr(n)||ra(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Nu(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return xu(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=xe.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 cr(e)&&ia(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await fu(e),!0}catch{return!1}},mkDir:e=>ra(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=_t.parse(t);for(;;){let r=_t.join(t,e);try{if(cr(r)&&ia(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=_t.dirname(t)}return null},readFirstJSON(e){try{if(!xe.dirExists(e))return null;let t=oa(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=_t.join(e,t);return xe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return xe.dirExists(e)?oa(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Cu(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{hu(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(_t.dirname(t)),!n?.overwrite&&cr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{yu(e,t)}catch(r){if(r?.code==="EXDEV"){vu(e,t),this.rmFile(e);return}throw r}}};var Su={userId:"",userName:"",preferredEditor:"",autoSync:!1},aa=Et.object({preferredEditor:Et.string().optional(),userName:Et.string().optional(),userId:Et.string().optional(),autoSync:Et.boolean().nullable().optional(),autoSyncDebounceMs:Et.number().optional(),viewMode:Et.enum(["dense","wide"]).optional()}),bu="config.json",da=()=>sa.join(Eu.homedir(),he),Ao=()=>sa.join(da(),bu),To=()=>{try{return xe.mkDir(da()),c(`Ensured ~/${he} exists`,null)}catch{return a(`Unable to create ~/${he}`)}},Iu=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${he}/config.json JSON`)}let n=aa.safeParse(t??{});return n.success?c("Parsed config",n.data):a(`Invalid ~/${he}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ca=()=>{let e=To();if(d(e))return a(e.message);let t=Ao(),n=xe.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Iu(n)},la=e=>{let t=To();if(d(t))return a(t.message);let n=aa.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ao();try{return xe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
51
|
+
`),c("Config written",null)}catch{return a(`Unable to write ~/${he}/config.json`)}},St=e=>{let t=ca();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return la(n)},ua=()=>{let e=Ao(),t=To();if(d(t))return a(`Unable to create ~/${he}`);if(!(xe.readFile(e)!==null)){let m=la(Su);if(d(m))throw new Error(`Unable to create ~/${he}/config.json`)}let r=ca();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:s,autoSync:l,autoSyncDebounceMs:u}=r.value;return!i||!s?a(`User name or ID not configured in ~/${he}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:s,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"})};var ma=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)return r.payload.parent}return null};import{ulid as Pu}from"ulid";import{spawnSync as Ru}from"node:child_process";import Au from"node:os";import pa from"node:path";import{ulid as Tu}from"ulid";function wu(){let{preferredEditor:e}=U(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Mu(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function ga(e){let t=pa.join(Au.tmpdir(),"epiq");xe.mkDir(t);let n=pa.join(t,Tu());xe.writeToFile(n,e??"");let r=wu();for(let o of r){let i=Mu(o,n),s=Ru(i,{stdio:"inherit",shell:!0});if(!s.error&&s.status===0){let l=xe.readFile(n);if(l==null)return a("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return a("Unable to open editor")}var fa=async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let t=await Re();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),i=Ne([...r,o],"TICKET");if(d(i))return a("Edit target must be an issue");let s=i.value;if(!$(s))return a("Edit target must be an issue");if(s.readonly)return a("Cannot edit readonly issue");let l=F(s.id).find(y=>y.title===J.DESCRIPTION);if(!l)return a("No target found");if(l.readonly)return a("Cannot edit readonly field");let u=s.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=ga(u);if(d(m))return a("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):Te({id:Pu(),action:"edit.description",payload:{id:s.id,md:g},...e.value},n)};import Lu from"node:fs";import xa from"node:path";import wo from"node:fs";import ku from"node:path";var va=async e=>{let t=ku.join(e,".gitignore"),n=wo.existsSync(t)?wo.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
52
|
+
`).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...i].join(`
|
|
56
53
|
`);return n=n.trimEnd()+`
|
|
57
54
|
|
|
58
|
-
${
|
|
59
|
-
`,
|
|
60
|
-
`));let xt=st();if(d(xt))return _(16,xt.message);let{rootNodeId:Bd,nodes:Od}=xt.value,Xo=Od[Bd];return Xo?(A.navigate({contextNode:Xo,selectedIndex:0}),S({hasProjectDefinition:!0,mode:p.DEFAULT}),l(Ne,null)):_(16,"Unable to resolve initialized root node")};import{ulid as Xu}from"ulid";import{ulid as Yu}from"ulid";var Ta=null,lt=()=>structuredClone(Ta),vn=e=>{Ta=e},wa=()=>{let{contextNode:e,selectedIndex:t}=v(),r=$(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},Lo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=$(t).filter(o=>o.id!==e);return Vn(r,n)},Ma=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z();if(d(r))return a("Unable to resolve user ID");let o=Lo({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:Yu(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Pa=e=>{vn(e);let t=rn(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function Do(e){let t=wa();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let i=$(o.id),s=i.findIndex(({id:m})=>m===n.id);if(s<0)return a("Current node not found among siblings");let c=i[s+e];if(!c)return a("Missing sibling node");let u=Ma({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Pa(u.value)}function Fo(e){let t=wa();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=$(n.id)[r+e];if(!i)return a("Missing sibling node");let s=Ma({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(s)?s:Pa(s.value)}var ka=()=>{let e=lt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=$(n).findIndex(i=>i.id===t);return o===-1?a("Moved node not found among rendered children"):(A.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},ur=(e,t="Moved preview")=>{if(d(e))return e;let n=ka();return d(n)?n:(S({mode:p.MOVE}),l(t,null))},La=async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=G().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=$(n.id)[r];if(!o)return S({mode:p.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 i=$(o.parentNodeId),s=i.findIndex(({id:y})=>y===o.id);if(s===-1)return a("Target not found among siblings");let c=i[s-1],u=i[s+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},g=Lo({parentId:o.parentNodeId,id:o.id,position:m});return d(g)?g:(vn({id:Xu(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:g.value.rank},...e.value}),S({mode:p.MOVE}),l("Move initialized",null))}if(t==="next")return ur(Fo(1));if(t==="previous")return ur(Fo(-1));if(t==="to-next")return ur(Do(1));if(t==="to-previous")return ur(Do(-1));if(t==="confirm"){let i=lt();if(!i)return a("No pending move to confirm");let s=await Te();if(d(s))return s;let c=Pe(i,s.value);if(d(c))return c;let u=ka();return d(u)?u:(vn(null),S({mode:p.DEFAULT}),l("Moved item",null))}return t==="cancel"?(vn(null),S({mode:p.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as mr}from"ulid";import{monotonicFactory as Ju,ulid as Qu}from"ulid";var Zu=Ju(),Da=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=Zu();return l("Created issue events",[{id:Qu(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var Fa=async(e,t)=>{let n=z();if(d(n))return a("Unable to resolve user ID");let r=await Te();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:s,selectedIndex:c}=v(),u=m=>{let g=Pe(m,o);if(d(g))return g;let y=b.getNode(g.value.result.id);if(!y)return a("Created node not found");if(!y.parentNodeId)return g;let N=b.getNode(y.parentNodeId);return N?(A.navigate({contextNode:N,selectedIndex:b.getSiblings(y.parentNodeId).findIndex(({id:E})=>E===y.id)}),g):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),g=b.getNode(m);if(!g)return a("Workspace not found");let y=zn(g.id,n.value,o);return d(y)?y:u({id:mr(),action:"add.board",payload:{id:mr(),name:t.inputString,parent:g.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=be(i,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let g=zn(m.value.id,n.value,o);return d(g)?g:u({id:mr(),action:"add.swimlane",payload:{id:mr(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=O(s.id)[c],g=s.context==="SWIMLANE"?s:s.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let L=be(i,"SWIMLANE");return d(L)?null:L.value})();if(!g)return a("Unable to add issue in this context");let y=zn(g.id,n.value,o);if(d(y))return y;let N=Da({name:t.inputString,parent:g.id,rank:y.value,user:n.value});if(d(N))return N;let E=N.value,I=Zi(E,o);if(I.some(L=>d(L)))return a("Issue create failed: "+I.filter(d).map(L=>L.message).filter(Boolean).join(", "));let w=I[0];if(!w||d(w))return a("Issue creation failed");let T=E.find(L=>L.action==="add.issue")?.payload.id;return T?(A.navigate({contextNode:g,selectedIndex:b.getSiblings(g.id).findIndex(({id:L})=>L===T)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var Ba=async()=>{let e=be(v().breadCrumb,"BOARD");if(d(e))return e;let t=await Ze(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Qe({repoRoot:t.value});if(d(n))throw new Error(n.message);let{modifier:r}=G().commandMeta;if(r==="now"){let I=Ft(n.value);if(d(I))return a(I.message);let w=xn();if(d(w))return w;let T=Nt(I.value).filter(d);return T.length>0?a(T.map(L=>L.message).join(", ")):(S({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}let o;if(r==="prev"){let I=v().eventLog.at(-1),w=Yr(I);if(w===null)return a("No previous event to peek");o=w}else if(r==="next"){let I=v().unappliedEvents.at(0),w=Yr(I);if(w===null)return a("No next event to peek");o=w+1}else{let I=Zn(r);if(!I)return a("Invalid peek date");o=I.getTime()}let i=v(),s=e.value.id,c=qi(n.value,o);if(d(c))return a(c.message);let{appliedEvents:u,unappliedEvents:m}=c.value,g=xn();if(d(g))return g;let N=Nt(u).filter(d);if(N.length>0)return xn(),S(i),a(N.map(I=>I.message).join(", "));let E=v().nodes[s];return E?(A.navigate({contextNode:E,selectedIndex:0}),S({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),l("Peeking",!0)):(xn(),S(i),a("Board did not exist at peek date"))};import em from"zod";var Oa=()=>{let e=G().commandMeta.inputString,t=em.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=Rt({autoSyncDebounceMs:t.data});return d(n)?n:(Le({autoSyncIntervalMs:t.data}),S({mode:p.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Ua=()=>{let e=G().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return a("Invalid response");let t=Ei(e),n=Rt({autoSync:t});return d(n)?n:(Le({autoSync:t}),S({mode:p.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var $a=async()=>{B(()=>""),S({mode:p.DEFAULT});let e=st();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");S({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Xn();return d(t)?(S({syncStatus:{msg:t.message,status:"failed"}}),t):(S({mode:p.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{useSyncExternalStore as LS}from"react";var pr,tm=new Set,Ha=()=>{for(let e of tm)e()};var ut=()=>{if(!pr)throw new Error("Ui state not initialized. Call initUiState() first.");return pr};var Wa=(e={})=>(pr=e,Ha(),l("UX state initialized",null)),nm=e=>{let t=ut();return pr=e(t),Ha(),l("UX state updated",null)},mt=e=>nm(t=>({...t,...e}));var _a=e=>Object.values(v().tags).find(t=>t.name===e),ja=e=>Object.values(v().contributors).find(t=>t.name===e),gr=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:La},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];return r?Ae({id:xe(),action:"delete.node",payload:{id:r.id},...e.value}):a("Unable to resolve child to delete")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=G().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(s=>J(x.FILTER).map(c=>c.split(n)[0]).includes(s))(r))return a("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return Ie(s=>({...s,filters:e==="clear"?[]:[...s.filters,i],mode:p.DEFAULT})),l("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:p.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return mt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),S({mode:p.HELP}),l("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(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=v().nodes[_e];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let i=await Te();if(d(i))return i;let s=i.value,c=to(o.id,r.id,{at:"end"},e.value,s);if(d(c))return c;let u=await Ae({id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value});return d(u)?u:l("Issue closed",null)},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):ot(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let i=o.value,s=v().nodes[_e];if(!s)return a("Unable to locate closed swimlane");if(i.parentNodeId!==s.id)return a("Issue is not closed");if(!W(i))return a("Target node is not issue");let c=Na(i);if(!c)return a("Unable to resolve previous parent from issue history");if(c===s.id)return a("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await Te();if(d(m))return m;let g=m.value,y=to(u.id,i.id,{at:"end"},e.value,g);if(d(y))return y;let N=await Ae({id:xe(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:y.value},...e.value});return d(N)?N:l("Issue reopened",null)},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:Aa},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:Fa,onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=Gs();return o?Ae({id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):a("Provide a title")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=_a(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid untag target");let s=ot(i.id,"TICKET");if(d(s))return a("Unable to untag issue in this context");let c=s.value;return W(c)?(c.props.tags??[]).includes(o.id)?Ae({id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}):a("Issue is not tagged with that tag"):a("Target node is not issue")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let i=ot(o.id,"TICKET");if(d(i))return a("Unable to tag issue in this context");let s=i.value;if(!W(s))return a("Target node is not issue");let c=_a(r),u;if(c)u=c.id;else{let g=xe(),y=await Ae({id:xe(),action:"create.tag",payload:{id:g,name:r},...e.value});if(d(y))return y;u=y.value.result.id}return(s.props.tags??[]).includes(u)?a("Already tagged with that tag"):Ae({id:xe(),action:"add.issue.tag",payload:{id:s.id,tag:u},...e.value})},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),s=O(i.id)[o];if(!s)return a("Invalid assign target");let c=ot(s.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=ja(r),g;if(m)g=m.id;else{let N=xe(),E=await Ae({id:xe(),action:"create.contributor",payload:{id:N,name:r},...e.value});if(d(E))return E;g=E.value.result.id}return(u.props.assignees??[]).includes(g)?a("Assignee already assigned"):Ae({id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value})},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=ja(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid unassign target");let s=ot(i.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let c=s.value;return W(c)?(c.props.assignees??[]).includes(o.id)?Ae({id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}):a(`Issue is not assigned to "${r}"`):a("Target node is not issue")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:$a},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:Ba},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await ua();return d(e)?e:(S({mode:p.DEFAULT}),l("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(A.exit(),l("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===at.DESCRIPTION)return ba();if(t.modifier===at.TITLE){let n=z();if(d(n))return a("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=O(r.id)[o];if(!i)return a("Missing node");if(i.readonly)return a("Cannot rename readonly node");let s=t.inputString.trim();return s?Ae({id:xe(),action:"edit.title",payload:{id:i.id,name:s},...n.value}):a("Provide a title")}return a("Unknown edit command")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:p.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case re.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=U(),s=n||i,c=r??xe();if(!s||!c)return a("Unable to resolve user name or id");let u=Rt({userName:s,userId:c,preferredEditor:o??""});return d(u)?u:(Le({userName:s,userId:c}),S({mode:p.DEFAULT}),l(`Username set to "${s}"`,null))}case re.EDITOR:{if(!n)return a("No editor provided");let r=Rt({preferredEditor:n});return d(r)?r:(Le({preferredEditor:n}),S({mode:p.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case re.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(Le({viewMode:n}),l(`View set to "${n}"`,null));case re.AUTOSYNC:return Ua();case re.SYNC_DEBOUNCE_MS:return Oa();default:return a("Unknown config command")}}}];var rm=new Set(["peek","filter","view-help"]),Fe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=G();if(!t)return a("No command to confirm");if(!e&&n===St.Invalid)return a("Invalid command");let i=rr(t);_s();let{readOnly:s}=v();if(s&&!rm.has(i))return pn({status:Xe.Fail,message:"Command not available in readonly state",value:null});let c=gr.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!c)return pn({status:Xe.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return pn({status:Xe.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?pn(u):(js({addToHistory:!e}),c.onSuccess?.(),U().autoSync&&Rs(),u)};var fr=[{intent:f.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>"move cancel"),Fe({isForceExecutedBySystem:!0}))},{intent:f.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>"move start"),Fe({isForceExecutedBySystem:!0}))},{intent:f.ConfirmMove,mode:p.MOVE,action:()=>(S({mode:p.COMMAND_LINE}),B(()=>"move confirm"),Fe({isForceExecutedBySystem:!0}))}],vr=[{intent:f.MovePreviousItem,mode:p.MOVE,action:()=>lt()?(S({mode:p.COMMAND_LINE}),B(()=>"move previous"),Fe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveNextItem,mode:p.MOVE,action:()=>lt()?(S({mode:p.COMMAND_LINE}),B(()=>"move next"),Fe({isForceExecutedBySystem:!0})):a("No pending move")}],Ka=[{intent:f.MoveToNextContainer,mode:p.MOVE,action:()=>lt()?(S({mode:p.COMMAND_LINE}),B(()=>"move to-next"),Fe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveToPreviousContainer,mode:p.MOVE,action:()=>lt()?(S({mode:p.COMMAND_LINE}),B(()=>"move to-previous"),Fe({isForceExecutedBySystem:!0})):a("No pending move")}];var Va={[M.WORKSPACE]:[...fr,...vr],[M.BOARD]:[...fr,...vr],[M.SWIMLANE]:[...fr,...vr,...Ka],[M.TICKET]:[],[M.FIELD]:[],[M.FIELD_LIST]:[],[M.TEXT]:[]};var za=()=>{B(()=>"");let{pendingNavTarget:e}=ut();S({mode:p.DEFAULT}),e&&A.navigate(e),mt({pendingNavTarget:void 0})},Ga=[{intent:f.ExitCommandLine,mode:p.HELP,action:()=>(za(),l("Exiting help",null))},{intent:f.Exit,mode:p.HELP,action:()=>(za(),l("Closed help",null))},{intent:f.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:f.NavNextItem,mode:p.HELP,action:()=>(A.navigateToNextItem(),l("Navigating to next help item",null))},{intent:f.NavToPreviousContainer,mode:p.HELP,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:f.NavToNextContainer,mode:p.HELP,action:()=>(A.navigateToNextContainer(),l("Navigating to next help container",null))}];var om=e=>{S({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=ut();t&&A.navigate(t),mt({pendingNavTarget:void 0}),B(()=>`${e} `)},qa=()=>{B(()=>"");let{pendingNavTarget:e}=ut();e&&A.navigate(e),mt({pendingNavTarget:void 0}),S({mode:p.DEFAULT})},Ya=[{intent:f.InitCommandPalette,mode:p.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{B(()=>"");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return mt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),S({mode:p.PALETTE}),l("Opening command palette",null)}},{intent:f.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!nt(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?(om(t),l("Selected command",t)):l("No command selected",null)}},{intent:f.ExitCommandLine,mode:p.PALETTE,action:()=>(qa(),l("Exiting palette",null))},{intent:f.Exit,mode:p.PALETTE,action:()=>(qa(),l("Closed command palette",null))},{intent:f.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.PALETTE,action:()=>(A.navigateToNextItem(),l("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.PALETTE,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.PALETTE,action:()=>(A.navigateToNextContainer(),l("Navigating to next container",null))}];var Xa=[...Ga,...Ya,{intent:f.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>`${x.NEW} `),l("Adding new item",null))},{intent:f.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>`${x.DELETE} `),l("Deleting item",null))},{intent:f.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>""),l("Entering command line mode",null))},{intent:f.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!$(e?.id??"")?.length){if(e?.title===X.DESCRIPTION)return S({mode:p.COMMAND_LINE}),B(()=>`${x.EDIT} description `),l("Propose command",!0);if(e?.title===X.ASSIGNEES)return S({mode:p.COMMAND_LINE}),B(()=>`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===X.TAGS)return S({mode:p.COMMAND_LINE}),B(()=>`${x.TAG} `),l("Propose command",!0);if(t.title===X.DESCRIPTION&&e?.context==="TEXT")return S({mode:p.COMMAND_LINE}),B(()=>`${x.EDIT} description `),l("Propose command",!0)}return A.enterChildNode(),l("Entering context",null)}},{intent:f.EditTitle,mode:p.DEFAULT,description:"[r] rename title",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>`${x.EDIT} title ${v().selectedNode?.title}`),l("Exiting context",null))},{intent:f.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(S({mode:p.COMMAND_LINE}),B(()=>`${x.EDIT} description `),l("Exiting context",null))},{intent:f.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(A.enterParentNode(),l("Exiting context",null))},{intent:f.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.DEFAULT,action:()=>(A.navigateToNextItem(),l("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.DEFAULT,action:()=>(A.navigateToNextContainer(),l("Navigating to next container",null))}];var im=500,sm=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ja=e=>{let t=sm(e);t&&B(n=>(n+t).slice(0,im))};var am=[p.COMMAND_LINE,p.PALETTE],dm=e=>[{intent:f.MoveCursorLeft,mode:e,action:()=>(Eo(-1),l("Moving cursor left",null))},{intent:f.MoveCursorRight,mode:e,action:()=>(Eo(1),l("Moving cursor right",null))},{intent:f.MoveCursorLeftOfWord,mode:e,action:()=>(So("left"),l("Moving cursor left of word",null))},{intent:f.MoveCursorRightOfWord,mode:e,action:()=>(So("right"),l("Moving cursor right of word",null))},{intent:f.AutoCompleteCommand,mode:e,action:()=>(B((t,{remainder:n})=>n?t+n:t),l("Auto-completing command",null))},{intent:f.CaptureInput,mode:e,action:(t,{sequence:n})=>(Ja(n??""),l("Capturing input",null))},{intent:f.EraseInput,mode:e,action:()=>(Hs(),l("Erasing input",null))},{intent:f.EraseInputWord,mode:e,action:()=>(Ws(),l("Erasing input word",null))}],Qa=[{intent:f.Confirm,mode:p.COMMAND_LINE,action:()=>(Fe(),l("Executing command",null))},{intent:f.ViewHelp,mode:p.DEFAULT,action:()=>(S({mode:p.HELP}),l("Viewing help",null))},...am.flatMap(dm),{intent:f.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(S({mode:p.DEFAULT}),l("Exiting command line",null))},{intent:f.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Ks(),l("Getting last command from history",null))},{intent:f.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Vs(),l("Getting next command from history",null))}];import td from"chalk";var xr=td.dim.hex(h.secondary2)(": for command line"),Za="q to exit",ed=`${td.hex(h.accent)("m")} to confirm`,Bo={[M.WORKSPACE]:[xr],[M.BOARD]:[xr],[M.BOARD+p.COMMAND_LINE]:[xr],[M.SWIMLANE]:[xr],[M.TICKET+p.HELP]:[Za],[M.SWIMLANE+p.HELP]:[Za],[M.TICKET]:[],[M.FIELD]:[],[M.SWIMLANE+p.MOVE]:[ed],[M.TICKET+p.MOVE]:[ed]};var yn=e=>e.trim().toLocaleLowerCase(),cm=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},lm=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},nd=(e,t)=>{let n=yn(t.value);if(!n)return!0;switch(t.target){case"title":return yn(e.title??"").includes(n);case"description":return yn(e.props.description??"").includes(n);case"tag":return cm(e).map(yn).some(o=>o.includes(n));case"assignee":return lm(e).map(yn).some(o=>o.includes(n));default:return!0}};function rd(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let s=o[o.length-1];return!s||s.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var od=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 At,Oo,Uo=new Set,id=()=>{for(let e of Uo)e()},mm=e=>(Uo.add(e),()=>Uo.delete(e));function sd(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=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=rd(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:g}=c,y=Bo[g+n]??Bo[g]??[],N=[...Xa,...Va[g]??[],...Qa],E=od(N),I=pm(o,i),w=I[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:E,selectedNode:w,renderedChildrenIndex:I})}var v=()=>{if(!At)throw new Error("State not initialized. Call initWorkspaceState() first.");return At},st=()=>At?l("Retrieved state",At):a("State not initialized. Call initWorkspaceState() first.");function on(e){Oo=e;let t=Je(process.cwd()),n=!1;if(!d(t)){let i=et(t.value);if(d(i))return a(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:p.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1},o=sd(r);return d(o)?o:(At=o.value,id(),l("State initialized",null))}function Ie(e){let t=v(),n=e(t),r=sd(n);return d(r)?a(r.message??"Unable to update state"):(At=r.value,id(),l("State updated",null))}var S=e=>Ie(t=>({...t,...e}));var ee=()=>um(mm,v,v),pm=(e,t)=>{let n={};for(let r of Object.values(e))W(r)&&t.length>0&&!t.every(o=>nd(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,i)=>{let s=e[o.id],c=e[i.id];return!s||!c?0:s.rank.localeCompare(c.rank)});return n},O=e=>v()?.renderedChildrenIndex[e]??[],xn=()=>Oo?on(Oo):a("Cannot reset state: no initial workspace found"),Bt=()=>At!==void 0;import{Box as yr,Text as Tt}from"ink";import ye,{useEffect as gm,useMemo as fm}from"react";import{ulid as vm}from"ulid";var ad=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return ye.createElement(Tt,{color:n,dimColor:o},e);let i=e.toLowerCase(),s=t.toLowerCase(),c=i.indexOf(s);return c===-1?ye.createElement(Tt,{color:n,dimColor:o},e):ye.createElement(Tt,{color:n,dimColor:o},e.slice(0,c),ye.createElement(Tt,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},dd=vm(),xm=e=>`${e}`,ym=e=>{let{pendingNavTarget:t}=ut();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,i=new Set(J(x.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(s=>s!=="move").filter(s=>s.length>0).filter(s=>s!==x.PALETTE).map(s=>{let c=rr(s),u=gr.find(m=>m.intent===c);return{command:s,description:u?.description??`[${s}] Run command`,isAvailable:i.has(s)}}).filter(s=>s.command.toLowerCase().startsWith(e)||e.length>=2&&s.description.toLowerCase().includes(e)).sort((s,c)=>s.isAvailable!==c.isAvailable?s.isAvailable?-1:1:s.command.localeCompare(c.command))},hm=e=>V.text({id:dd,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Cm=(e,t,n)=>V.text({id:xm(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),$o=[],Nm=e=>{cd();let t=b.createNode(hm(v().rootNodeId));d(t)||!nt(t.value)||($o=[t.value,...e.map((n,r)=>Cm(n,r,dd)).map(b.createNode).filter(Y).map(({value:n})=>n).filter(nt)],A.navigate({contextNode:t.value,selectedIndex:0}))},cd=()=>{let e=$o.map(t=>t.id);$o=[];for(let t of e)b.deleteNode(t)};function ld({width:e,height:t}){let r=zs().value.trim().toLowerCase(),o=fm(()=>ym(r),[r]);gm(()=>(Nm(o),()=>{cd()}),[o]);let i=v().selectedIndex;return ye.createElement(yr,{flexDirection:"column",width:e,height:t-2},ye.createElement(yr,{paddingX:1},ye.createElement(Tt,{color:h.accent},"Command Palette"),ye.createElement(Tt,{dimColor:!0}," \u2014 select a command and press enter")),ye.createElement(dt,{height:t-4,itemHeight:3,selectedIndex:i},o.map((s,c)=>{let u=c===i,m=s.isAvailable?h.accent:h.secondary2,g=s.isAvailable?"":"[unavailable] ";return ye.createElement(yr,{key:s.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},ye.createElement(Tt,{color:m,dimColor:!s.isAvailable},u?"\u276F ":" ",ye.createElement(ad,{text:Ii(s.command),match:r,color:m,dimColor:!s.isAvailable})),ye.createElement(yr,{paddingLeft:2},ye.createElement(ad,{text:g+s.description,match:r.length>=2?r:"",color:u&&s.isAvailable?h.primary:h.secondary2,dimColor:!s.isAvailable})))})))}import{Box as Dm}from"ink";import _o from"react";import Cn from"chalk";import{Box as Ho,Text as ud}from"ink";import hn,{useEffect as Em,useMemo as Sm,useState as bm}from"react";var md=Cn.gray,Im=Cn.inverse,Rm=Cn.inverse.gray,Am={hint:"",hints:[],overlap:0,remainder:""},gd=({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}},Tm=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=Re(t);return{bg:r=>Cn.bgHex(n).black(r),bgCursor:r=>Cn.bgHex(n).inverse.black(r)}}return qr(t)},wm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=gd({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,s=r.end+i;return e.slice(s,s+n.length)!==n?null:{start:s,end:s+n.length}},pd=()=>({value:de.value,cursorPosition:de.cursorPosition,commandIsPending:de.commandIsPending,autoCompletion:de.commandMeta.autoCompletion??Am,infoMessage:de.commandMeta.infoMessage,validationStatus:de.commandMeta.validity,command:de.commandMeta.command,inputString:de.commandMeta.inputString,modifier:de.commandMeta.modifier}),Mm=(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,fd=({width:e,mode:t})=>{let[n,r]=bm(pd());Em(()=>{let N=()=>{let I=pd();r(w=>Mm(w,I)?w:I)},E=No(N);return N(),()=>{E()}},[]);let{value:o,cursorPosition:i,infoMessage:s,commandIsPending:c,autoCompletion:u,command:m,modifier:g}=n,y=Sm(()=>{let N=Math.max(0,Math.min(i,o.length)),E=gd({value:o,command:m}),I=wm({value:o,command:m,modifier:g}),w=m?qr(m):null,R=Tm({command:m,modifier:g}),T=(se,ue)=>{let wt=E&&ue>=E.start&&ue<E.end,xt=I&&ue>=I.start&&ue<I.end;return wt&&w?w.fg(se):xt&&R?R.bg(se):se},L=(se,ue)=>{let wt=E&&ue>=E.start&&ue<E.end,xt=I&&ue>=I.start&&ue<I.end;return wt&&w?w.fgCursor(se):xt&&R?R.bgCursor(se):Im(se)},ne=o.slice(0,N),ie=o[N]??" ",Ue=N<o.length?o.slice(N+1):"",vt=Array.from(ne).map((se,ue)=>T(se,ue)).join(""),Ne=L(ie,N),Gt=Array.from(Ue).map((se,ue)=>T(se,N+1+ue)).join("");if(u.hint){let se=u.hint[u.overlap]??ie;Ne=Rm(se),Gt=md(u.remainder.slice(1)+Ue)}return md(t===p.PALETTE?"?":":")+vt+Ne+Gt},[o,i,u,m,g]);return hn.createElement(Ho,{flexDirection:"column",justifyContent:"flex-start"},hn.createElement(Ho,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},hn.createElement(Ho,null,hn.createElement(ud,null,y),s&&hn.createElement(ud,{wrap:"truncate",color:c?h.red:h.secondary2},` ${s} `))))};import vd from"chalk";import{Box as Pm,Text as Wo}from"ink";import hr from"react";var km=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Lm=(e,t)=>{let n=[],r=0;for(let o of e){let s=(n.length>0?" | ":"").length+o.length;if(r+s>t-4)break;n.push(o),r+=s}return n},xd=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=Lm(t,e).join(" | "),o=vd.hex(h.secondary),i=vd.hex(h.secondary2),s=o(`\u256D${"\u2500".repeat(n)}\u256E`),c=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(km(` ${r} `,n))}${o("\u2502")}`;return hr.createElement(Pm,{flexDirection:"column",width:e},hr.createElement(Wo,null,s),hr.createElement(Wo,null,u),hr.createElement(Wo,null,c))};var Nn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let c=(r.length>0?" | ":"").length+i.length;if(o+c>e+2)break;r.push(i),o+=c}return _o.createElement(Dm,null,t===p.COMMAND_LINE||t===p.PALETTE?_o.createElement(fd,{width:e,mode:t}):_o.createElement(xd,{width:e,mode:t,availableHints:n}))};import{Box as pt,Text as Vt}from"ink";import le,{useEffect as Fm,useMemo as Bm}from"react";import{ulid as yd}from"ulid";var Nr=yd(),Om=()=>[...new Set([...v().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})),Um=e=>V.text({id:Nr,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),$m=(e,t,n)=>V.text({id:yd(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Cr=[],hd=()=>{let e=Cr.filter(n=>n.id!==Nr).map(n=>n.id),t=Cr.filter(n=>n.id===Nr).map(n=>n.id);Cr=[];for(let n of[...e,...t])b.deleteNode(n)},Hm=e=>{hd();let t=b.createNode(Um(v().rootNodeId));if(d(t)||!nt(t.value))return logger.error("Could not attach help nodes");Cr=[t.value,...e.map((n,r)=>$m(n,r,Nr)).map(b.createNode).filter(Y).map(({value:n})=>n).filter(nt)],A.navigate({contextNode:t.value,selectedIndex:0})},Cd=({width:e,height:t})=>{let n=Bm(()=>Om(),[]);Fm(()=>(Hm(n),()=>{hd()}),[n]);let r=v().selectedIndex;return le.createElement(pt,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},le.createElement(pt,{paddingX:1,justifyContent:"center"},le.createElement(Vt,{color:h.accent},"Help"),le.createElement(Vt,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),le.createElement(pt,{paddingX:1,marginTop:1},le.createElement(pt,{width:20,justifyContent:"flex-end"},le.createElement(Vt,{color:h.secondary},"Key(s)")),le.createElement(pt,{flexGrow:1,width:40,paddingLeft:2},le.createElement(Vt,{color:h.secondary},"Action"))),le.createElement(dt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:i},s)=>{let c=s===r;return le.createElement(pt,{paddingX:1,key:`${o}-${i}-${s}`,flexDirection:"row"},le.createElement(pt,{width:20,justifyContent:"flex-end"},le.createElement(Vt,{color:h.accent},o)),le.createElement(pt,{flexGrow:1,width:40,paddingLeft:2},le.createElement(Vt,{color:c?h.primary:h.secondary2},i)))})))};import Wm from"chalk";import{Box as Er,Text as qe}from"ink";import Ce from"react";var Nd=({width:e,height:t})=>Ce.createElement(Er,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Ce.createElement(qe,{color:h.accent,bold:!0},"Initialize project"),Ce.createElement(qe,null,`This folder is not an ${Wm.hex(h.accent)("epiq")} project yet.`),Ce.createElement(qe,{color:h.primary},"To start tracking issues here, we need to initialize a new",Ce.createElement(qe,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),Ce.createElement(Er,{marginTop:1,flexDirection:"column"},Ce.createElement(Er,null,Ce.createElement(qe,{color:h.accent}," "),Ce.createElement(qe,{color:h.primary},"Type "),Ce.createElement(qe,{backgroundColor:h.secondary}," :init "))),Ce.createElement(Er,{marginTop:1},Ce.createElement(qe,{color:h.secondary2},"This will create, commit and push "),Ce.createElement(qe,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as Sr,Text as Be}from"ink";import oe from"react";var _m=({isDone:e,command:t,value:n})=>oe.createElement(Sr,null,oe.createElement(Be,{color:h.accent,dimColor:e},e?" \u2714 ":" "),oe.createElement(Be,{dimColor:e},"Type "),oe.createElement(Be,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&oe.createElement(oe.Fragment,null,oe.createElement(Be,{dimColor:e}," "),oe.createElement(Be,{color:h.secondary,dimColor:e},"<"+n+">"))),jm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function jo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:s,isSetAutoSync:c}=tt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:s,message:"Almost there. Configure auto sync."}],m=u.findIndex(y=>!y.done),g=m===-1?void 0:u[m];return oe.createElement(Sr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},oe.createElement(Be,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),oe.createElement(Be,null,"Let's get you started - it's a breeze."),oe.createElement(Be,{color:h.secondary2},"Remember - you can always search available commands by typing:",oe.createElement(Be,{color:h.accent}," ? ")),g&&oe.createElement(Be,{color:h.secondary2},g.message),oe.createElement(Sr,{flexDirection:"column"},u.map((y,N)=>m===-1||N<=m?oe.createElement(Sr,{key:y.key,marginBottom:1},oe.createElement(_m,{isDone:y.done,command:y.command,value:y.done?jm(y.value):void 0})):null)))}import Rr from"chalk";import{Box as Ir,Text as Ye}from"ink";import te from"react";import{Box as Ko,Text as Km}from"ink";import zt from"react";var Vm=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Ed=({width:e})=>{let{viewMode:t}=U(),{breadCrumb:n,contextNode:r,selectedIndex:o}=v(),i=$(r.id)[o],s=ot(i?.id??r.id,"TICKET"),c=Y(s)?s.value:void 0,u=c?.props.tags??[],m=c?.props.assignees??[],g=c?.parentNodeId?!Kr(r.id,c.parentNodeId)&&t==="dense":!1,y=n.map((E,I)=>{let w=I===n.length-1,R=$(E.id),T=w?R?.[o]?.title:void 0;return`${I?" / ":""}${E.title??""}${T?` \u25B8 ${T}`:""}`}).join(""),N=Vm(y,e);return zt.createElement(Ko,null,zt.createElement(Km,{color:h.secondary2},N),g?u.map(E=>zt.createElement(Ko,{key:E,paddingLeft:2},zt.createElement(jt,{id:E}))):null,g?m.map(E=>zt.createElement(Ko,{key:E,paddingLeft:2},zt.createElement(_t,{id:E}))):null)};import{Box as zm,Text as Sd}from"ink";import br from"react";var Gm=({filters:e})=>br.createElement(zm,{columnGap:1},br.createElement(Sd,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>br.createElement(Sd,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),bd=br.memo(Gm);var Id="0.6.6";import Vo from"chalk";import{Box as qm,Text as Rd}from"ink";import zo,{useEffect as Ym,useState as Xm}from"react";var Jm=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ad=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)}},Qm=({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)}`},Zm=(e,t,n)=>{let r=Ad(e),o=Ad(t);return Qm({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},ep=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],s=e[Math.min(r+1,e.length-1)];return Zm(i,s,o)};function Td({syncStatus:e,autoSync:t}){let[n,r]=Xm(0);Ym(()=>{if(e.status!=="syncing"){r(0);return}let c=setInterval(()=>{r(u=>u+1)},50);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"retry",syncing:"...",pending:"wait"},s={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:ep(Jm,(Math.sin(n*.12)+1)/2)??""}[e.status];return zo.createElement(qm,null,zo.createElement(Rd,null,Vo.hex(h.secondary2).dim(t?"AutoSync: ":"Sync: ")),zo.createElement(Rd,null,Vo.hex(s)("\u25CF")+Vo.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Ar({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i,mode:s}=ee(),{userName:c,preferredEditor:u,autoSync:m}=U(),g=56,y=process.stdout.columns-g-8,N=r.at(-1)?.id,E=Hn(N??""),I=Y(E)?Wi(E.value):"INVALID DATE";return te.createElement(Ir,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?te.createElement(Ye,null," "):te.createElement(Ir,{paddingLeft:1},e.length>0?te.createElement(bd,{filters:e}):te.createElement(Ed,{width:y})),n==="live"?te.createElement(Ir,{columnGap:1,paddingRight:2,"max-width":g,overflow:"hidden",justifyContent:"flex-end"},te.createElement(Td,{autoSync:!!m,syncStatus:i}),te.createElement(Ye,null,Rr.hex(h.secondary2).dim("Mode: ")+Rr.hex(h.secondary2).dim(s.padEnd(8," "))," "),te.createElement(wd,{icon:"@",value:c}),te.createElement(wd,{icon:"\u276F",value:u}),te.createElement(Ye,{dimColor:!0,color:h.secondary2},Id+" ")):"",n==="peek"?te.createElement(Ir,{paddingLeft:1},te.createElement(Ye,{backgroundColor:h.yellow}," Readonly "),te.createElement(Ye,{color:h.yellow}," "+o.length+" edits ago at "),te.createElement(Ye,{backgroundColor:h.yellow,color:h.accent}," "+I+" "),te.createElement(Ye,{color:h.yellow},". Resume with "),te.createElement(Ye,{backgroundColor:h.yellow}," :peek now ")):"")}function wd({icon:e,value:t}){return te.createElement(Ye,null,Rr.dim(e)+Rr.hex(h.accent)(` ${t??"-"} `))}import{Box as tp,Text as np}from"ink";import En from"react";import{Box as Tr,Text as Go}from"ink";import gt from"react";function qo(){let e=ee(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,s=t?.id?O(t?.id):[];return gt.createElement(Tr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},gt.createElement(Tr,{padding:1,paddingTop:0,paddingBottom:0},gt.createElement(Go,null,"Select a board:")),gt.createElement(Tr,{padding:1,flexDirection:"column"},s.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,y=O(c.id).flatMap(({id:N})=>$(N)).length;return gt.createElement(Tr,{key:c.id??u},gt.createElement(Go,{color:m?h.accent:h.secondary2},gt.createElement(ve,{isSelected:m})),gt.createElement(Go,{color:m?h.accent:h.secondary2},c.title," (",y," issues)",c.readonly?" \u{1F512}":""))})))}var rp=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:s})=>{let{renderedChildrenIndex:c}=ee(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return En.createElement(tp,{flexDirection:"row"},e.context==="WORKSPACE"?En.createElement(qo,null):u?En.createElement(cr,{height:y,width:s,swimlanes:(c[u.id]??[]).filter(N=>N!==void 0&&kt(N)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):En.createElement(np,null))},Md=En.memo(rp);function Yo({width:e,height:t}){let n=ee(),r=n.filters;if(n.mode===p.HELP)return q.createElement(ft,{flexDirection:"column"},q.createElement(Cd,{width:e,height:t}));if(n.mode===p.PALETTE)return q.createElement(ft,{flexDirection:"column"},q.createElement(ld,{width:e,height:t}),q.createElement(Nn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:o}=tt(),i=!o,s=o&&!n.hasProjectDefinition;if(i)return q.createElement(ft,{flexDirection:"column"},q.createElement(ft,{flexDirection:"column"},q.createElement(Ar,{hideBreadCrumb:!0,filters:r}),q.createElement(jo,{height:t,width:e})),q.createElement(Nn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(s)return q.createElement(ft,{flexDirection:"column"},q.createElement(ft,{flexDirection:"column"},q.createElement(Ar,{hideBreadCrumb:!0,filters:r}),q.createElement(Nd,{height:t,width:e})),q.createElement(Nn,{width:e,mode:n.mode,availableHints:n.availableHints}));let c=be(n.breadCrumb??[],"BOARD");if(Y(c)){let u=c.value.id,m=O(u).length,g=3,y=Math.floor(e/g),N=Math.floor(e/Math.max(m,1));e=Math.min(N,y)*Math.max(m,g)}return q.createElement(ft,{flexDirection:"column"},q.createElement(ft,{flexDirection:"column"},q.createElement(Ar,{filters:r}),q.createElement(Md,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:U().viewMode??"dense",mode:n.mode})),q.createElement(Nn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import op from"readline";var wr,Mr,Oe,ip=new Set([f.MoveCursorLeft,f.EraseInputWord,f.MoveCursorLeftOfWord,f.MoveCursorRight,f.MoveCursorRightOfWord,f.NavToPreviousContainer,f.NavToNextContainer,f.NavPreviousItem,f.NavNextItem,f.SetViewDense,f.SetViewWide,f.Confirm,f.Exit,f.InitCommandLine,f.InitCommandPalette,f.ExitCommandLine,f.CaptureInput,f.EraseInput,f.EraseInputWord,f.HideHelp,f.ViewHelp,f.SetViewDense,f.SetViewWide,f.GetLastCommandFromHistory,f.GetNextCommandFromHistory,f.AutoCompleteCommand]),Pd=async e=>{if(e.ctrl&&e.name==="c")return A.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Zs(e,n);if(!o||r&&!ip.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(s){logger.error(s)}},sp=()=>async function(t,n){n.name!=="escape"&&(Oe&&(clearTimeout(Oe),Oe=void 0),await Pd(n))},ap=()=>async function(t){if(t.length===1&&t[0]===27){Oe&&clearTimeout(Oe),Oe=setTimeout(()=>{Pd({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Oe=void 0},25);return}Oe&&(clearTimeout(Oe),Oe=void 0)};function kd(){wr&&process.stdin.removeListener("keypress",wr),Mr&&process.stdin.removeListener("data",Mr),wr=sp(),Mr=ap(),op.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Mr),process.stdin.on("keypress",wr)}Wa();cp(`${Pr.bold("Epiq CLI")}
|
|
55
|
+
${l}
|
|
56
|
+
`,wo.writeFileSync(t,n,"utf8"),ae.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var Du=async e=>{let t=await L({cwd:e,args:["status","--porcelain"]});return d(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},_=(e,t)=>a(`[${e}] ${t}`),ya=async()=>{O("");let e=Xo(),t=await Je(process.cwd());if(d(t))return _(1,t.message);let n=t.value,r=await An(n);if(d(r))return _(2,r.message);if(r.value)return _(2,"Cannot initialize Epiq while a git operation is in progress");let o=await Du(n);if(d(o))return _(2.5,o.message);if(o.value)return _(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Dr(n))return _(4,"Epiq project already initialized");let i=Ze();if(!i.isSetupDone||!i.userName)return _(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let s=U(),l=s.userName,u=s.userId;if(!u||!l)return _(5,"Missing Epiq user id");let m=e.stateBranch,g=await wn({repoRoot:n,branch:m});if(d(g))return _(6,g.message);if(g.value)return _(6,`State branch already exists: ${m}`);let y=await io({repoRoot:n,stateBranchName:m});if(d(y))return _(6,y.message);let N=kn();if(d(N))return _(7,N.message);let E=xa.join(Pn(),e.projectId),I=await so({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(I))return _(8,I.message);let A=xa.join(E,".epiq");Lu.mkdirSync(A,{recursive:!0});let R=us({userId:u,userName:l});if(d(R))return _(9,R.message);for(let Lr of R.value){let Go=_n({event:Lr,rootDir:E});if(d(Go))return _(9,Go.message)}let w=await Gn({stateBranchRoot:E,eventFileName:rn({userId:u,userName:l})});if(d(w))return _(10,w.message);let B=await Mt({cwd:E,message:"[epiq:init]"});if(d(B))return _(10,B.message);let Ie=await va(n);if(d(Ie))return _(11,Ie.message);let ce=Qo({repoRoot:n,fileContents:e});if(d(ce))return _(12,ce.message);let Vt=await V.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(Vt))return _(13,Vt.message);let Cn=await V.commit({cwd:n,message:"[epiq:init-project]"});if(d(Cn))return _(13,Cn.message);let At="Project initialized!",Kt=await L({cwd:n,args:["push","-u","origin","HEAD"]});d(Kt)&&(At+=` Warn: [init:14] ${Kt.message}`);let oe=await an({repoRoot:n,stateBranchRoot:E});d(oe)&&(At+=` Warn: [init:15] ${oe.message}`);let Tt=yt(R.value).filter(d);if(Tt.length>0)return _(16,Tt.map(Lr=>Lr.message).join(`
|
|
57
|
+
`));let gt=ot();if(d(gt))return _(16,gt.message);let{rootNodeId:Ad,nodes:Td}=gt.value,zo=Td[Ad];return zo?(T.navigate({contextNode:zo,selectedIndex:0}),b({hasProjectDefinition:!0,mode:p.DEFAULT}),c(At,null)):_(16,"Unable to resolve initialized root node")};import{ulid as Bu}from"ulid";import{ulid as Fu}from"ulid";var ha=null,dt=()=>structuredClone(ha),pn=e=>{ha=e},Ca=()=>{let{contextNode:e,selectedIndex:t}=v(),r=W(e.id)[t];return r?c("Resolved selected child",r):a("Target node not found")},Mo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=W(t).filter(o=>o.id!==e);return jn(r,n)},Na=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z();if(d(r))return a("Unable to resolve user ID");let o=Mo({parentId:t,id:e,position:n});return d(o)?o:c("Created pending move state",{id:Fu(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Ea=e=>{pn(e);let t=en(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function Po(e){let t=Ca();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let i=W(o.id),s=i.findIndex(({id:m})=>m===n.id);if(s<0)return a("Current node not found among siblings");let l=i[s+e];if(!l)return a("Missing sibling node");let u=Na({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:Ea(u.value)}function ko(e){let t=Ca();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=W(n.id)[r+e];if(!i)return a("Missing sibling node");let s=Na({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(s)?s:Ea(s.value)}var Sa=()=>{let e=dt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=W(n).findIndex(i=>i.id===t);return o===-1?a("Moved node not found among rendered children"):(T.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},lr=(e,t="Moved preview")=>{if(d(e))return e;let n=Sa();return d(n)?n:(b({mode:p.MOVE}),c(t,null))},ba=async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=G().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=W(n.id)[r];if(!o)return b({mode:p.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 i=W(o.parentNodeId),s=i.findIndex(({id:y})=>y===o.id);if(s===-1)return a("Target not found among siblings");let l=i[s-1],u=i[s+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},g=Mo({parentId:o.parentNodeId,id:o.id,position:m});return d(g)?g:(pn({id:Bu(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:g.value.rank},...e.value}),b({mode:p.MOVE}),c("Move initialized",null))}if(t==="next")return lr(ko(1));if(t==="previous")return lr(ko(-1));if(t==="to-next")return lr(Po(1));if(t==="to-previous")return lr(Po(-1));if(t==="confirm"){let i=dt();if(!i)return a("No pending move to confirm");let s=await Re();if(d(s))return s;let l=Te(i,s.value);if(d(l))return l;let u=Sa();return d(u)?u:(pn(null),b({mode:p.DEFAULT}),c("Moved item",null))}return t==="cancel"?(pn(null),b({mode:p.DEFAULT}),c("Cancelling move",null)):a("Invalid move modifier")};import{ulid as ur}from"ulid";import{monotonicFactory as Uu,ulid as Ou}from"ulid";var $u=Uu(),Ia=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=$u();return c("Created issue events",[{id:Ou(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var Ra=async(e,t)=>{let n=z();if(d(n))return a("Unable to resolve user ID");let r=await Re();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:s,selectedIndex:l}=v(),u=m=>{let g=Te(m,o);if(d(g))return g;let y=S.getNode(g.value.result.id);if(!y)return a("Created node not found");if(!y.parentNodeId)return g;let N=S.getNode(y.parentNodeId);return N?(T.navigate({contextNode:N,selectedIndex:S.getSiblings(y.parentNodeId).findIndex(({id:E})=>E===y.id)}),g):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),g=S.getNode(m);if(!g)return a("Workspace not found");let y=Vn(g.id,n.value,o);return d(y)?y:u({id:ur(),action:"add.board",payload:{id:ur(),name:t.inputString,parent:g.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=Ne(i,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let g=Vn(m.value.id,n.value,o);return d(g)?g:u({id:ur(),action:"add.swimlane",payload:{id:ur(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=F(s.id)[l],g=s.context==="SWIMLANE"?s:s.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let B=Ne(i,"SWIMLANE");return d(B)?null:B.value})();if(!g)return a("Unable to add issue in this context");let y=Vn(g.id,n.value,o);if(d(y))return y;let N=Ia({name:t.inputString,parent:g.id,rank:y.value,user:n.value});if(d(N))return N;let E=N.value,I=es(E,o);if(I.some(B=>d(B)))return a("Issue create failed: "+I.filter(d).map(B=>B.message).filter(Boolean).join(", "));let A=I[0];if(!A||d(A))return a("Issue creation failed");let w=E.find(B=>B.action==="add.issue")?.payload.id;return w?(T.navigate({contextNode:g,selectedIndex:S.getSiblings(g.id).findIndex(({id:B})=>B===w)}),c("Issue created",null)):a("Unable to determine ticket id")}return c("Success",null)};var Aa=async()=>{let e=Ne(v().breadCrumb,"BOARD");if(d(e))return e;let t=await Je(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Xe({repoRoot:t.value});if(d(n))throw new Error(n.message);let{modifier:r}=G().commandMeta;if(r==="now"){let I=Dt(n.value);if(d(I))return a(I.message);let A=gn();if(d(A))return A;let w=yt(I.value).filter(d);return w.length>0?a(w.map(B=>B.message).join(", ")):(b({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let o;if(r==="prev"){let I=v().eventLog.at(-1),A=Xr(I);if(A===null)return a("No previous event to peek");o=A}else if(r==="next"){let I=v().unappliedEvents.at(0),A=Xr(I);if(A===null)return a("No next event to peek");o=A+1}else{let I=Jn(r);if(!I)return a("Invalid peek date");o=I.getTime()}let i=v(),s=e.value.id,l=Yi(n.value,o);if(d(l))return a(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=gn();if(d(g))return g;let N=yt(u).filter(d);if(N.length>0)return gn(),b(i),a(N.map(I=>I.message).join(", "));let E=v().nodes[s];return E?(T.navigate({contextNode:E,selectedIndex:0}),b({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(gn(),b(i),a("Board did not exist at peek date"))};import Wu from"zod";var Ta=()=>{let e=G().commandMeta.inputString,t=Wu.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=St({autoSyncDebounceMs:t.data});return d(n)?n:(Pe({autoSyncIntervalMs:t.data}),b({mode:p.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var wa=()=>{let e=G().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return a("Invalid response");let t=yi(e),n=St({autoSync:t});return d(n)?n:(Pe({autoSync:t}),b({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var Ma=async()=>{O(""),b({mode:p.DEFAULT});let e=ot();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");b({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await qn();return d(t)?(b({syncStatus:{msg:t.message,status:"failed"}}),t):(b({mode:p.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{useSyncExternalStore as ES}from"react";var mr,Hu=new Set,Pa=()=>{for(let e of Hu)e()};var ct=()=>{if(!mr)throw new Error("Ui state not initialized. Call initUiState() first.");return mr};var ka=(e={})=>(mr=e,Pa(),c("UX state initialized",null)),_u=e=>{let t=ct();return mr=e(t),Pa(),c("UX state updated",null)},lt=e=>_u(t=>({...t,...e}));var La=e=>Object.values(v().tags).find(t=>t.name===e),Da=e=>Object.values(v().contributors).find(t=>t.name===e),pr=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:ba},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=F(t.id)[n];return r?be({id:fe(),action:"delete.node",payload:{id:r.id},...e.value}):a("Unable to resolve child to delete")},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=G().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(s=>Q(x.FILTER).map(l=>l.split(n)[0]).includes(s))(r))return a("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return Ee(s=>({...s,filters:e==="clear"?[]:[...s.filters,i],mode:p.DEFAULT})),c("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:p.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return lt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),b({mode:p.HELP}),c("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=F(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!$(r))return a("Cannot close in this context");let o=v().nodes[He];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let i=await Re();if(d(i))return i;let s=i.value,l=no(o.id,r.id,{at:"end"},e.value,s);if(d(l))return l;let u=await be({id:fe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value});return d(u)?u:c("Issue closed",null)},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=F(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):nt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let i=o.value,s=v().nodes[He];if(!s)return a("Unable to locate closed swimlane");if(i.parentNodeId!==s.id)return a("Issue is not closed");if(!$(i))return a("Target node is not issue");let l=ma(i);if(!l)return a("Unable to resolve previous parent from issue history");if(l===s.id)return a("Previous parent resolves to closed swimlane");let u=v().nodes[l];if(!u)return a("Previous parent no longer exists");let m=await Re();if(d(m))return m;let g=m.value,y=no(u.id,i.id,{at:"end"},e.value,g);if(d(y))return y;let N=await be({id:fe(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:y.value},...e.value});return d(N)?N:c("Issue reopened",null)},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:ya},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:Ra,onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=F(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=js();return o?be({id:fe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):a("Provide a title")},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=La(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid untag target");let s=nt(i.id,"TICKET");if(d(s))return a("Unable to untag issue in this context");let l=s.value;return $(l)?(l.props.tags??[]).includes(o.id)?be({id:fe(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}):a("Issue is not tagged with that tag"):a("Target node is not issue")},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let i=nt(o.id,"TICKET");if(d(i))return a("Unable to tag issue in this context");let s=i.value;if(!$(s))return a("Target node is not issue");let l=La(r),u;if(l)u=l.id;else{let g=fe(),y=await be({id:fe(),action:"create.tag",payload:{id:g,name:r},...e.value});if(d(y))return y;u=y.value.result.id}return(s.props.tags??[]).includes(u)?a("Already tagged with that tag"):be({id:fe(),action:"add.issue.tag",payload:{id:s.id,tag:u},...e.value})},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),s=F(i.id)[o];if(!s)return a("Invalid assign target");let l=nt(s.id,"TICKET");if(d(l))return a("Unable to assign issue in this context");let u=l.value;if(!$(u))return a("Target node is not issue");let m=Da(r),g;if(m)g=m.id;else{let N=fe(),E=await be({id:fe(),action:"create.contributor",payload:{id:N,name:r},...e.value});if(d(E))return E;g=E.value.result.id}return(u.props.assignees??[]).includes(g)?a("Assignee already assigned"):be({id:fe(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value})},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=Da(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid unassign target");let s=nt(i.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let l=s.value;return $(l)?(l.props.assignees??[]).includes(o.id)?be({id:fe(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}):a(`Issue is not assigned to "${r}"`):a("Target node is not issue")},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:Ma},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:Aa},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await na();return d(e)?e:(b({mode:p.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(T.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===it.DESCRIPTION)return fa();if(t.modifier===it.TITLE){let n=z();if(d(n))return a("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=F(r.id)[o];if(!i)return a("Missing node");if(i.readonly)return a("Cannot rename readonly node");let s=t.inputString.trim();return s?be({id:fe(),action:"edit.title",payload:{id:i.id,name:s},...n.value}):a("Provide a title")}return a("Unknown edit command")},onSuccess:()=>b({mode:p.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:p.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ne.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=U(),s=n||i,l=r??fe();if(!s||!l)return a("Unable to resolve user name or id");let u=St({userName:s,userId:l,preferredEditor:o??""});return d(u)?u:(Pe({userName:s,userId:l}),b({mode:p.DEFAULT}),c(`Username set to "${s}"`,null))}case ne.EDITOR:{if(!n)return a("No editor provided");let r=St({preferredEditor:n});return d(r)?r:(Pe({preferredEditor:n}),b({mode:p.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case ne.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(Pe({viewMode:n}),c(`View set to "${n}"`,null));case ne.AUTOSYNC:return wa();case ne.SYNC_DEBOUNCE_MS:return Ta();default:return a("Unknown config command")}}}];var ju=new Set(["peek","filter","view-help"]),Fe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=G();if(!t)return a("No command to confirm");if(!e&&n===Ct.Invalid)return a("Invalid command");let i=nr(t);Os();let{readOnly:s}=v();if(s&&!ju.has(i))return ln({status:qe.Fail,message:"Command not available in readonly state",value:null});let l=pr.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return ln({status:qe.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return ln({status:qe.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?ln(u):($s({addToHistory:!e}),l.onSuccess?.(),U().autoSync&&Es(),u)};var gr=[{intent:f.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(b({mode:p.COMMAND_LINE}),O("move cancel"),Fe({isForceExecutedBySystem:!0}))},{intent:f.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(b({mode:p.COMMAND_LINE}),O("move start"),Fe({isForceExecutedBySystem:!0}))},{intent:f.ConfirmMove,mode:p.MOVE,action:()=>(b({mode:p.COMMAND_LINE}),O("move confirm"),Fe({isForceExecutedBySystem:!0}))}],fr=[{intent:f.MovePreviousItem,mode:p.MOVE,action:()=>dt()?(b({mode:p.COMMAND_LINE}),O("move previous"),Fe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveNextItem,mode:p.MOVE,action:()=>dt()?(b({mode:p.COMMAND_LINE}),O("move next"),Fe({isForceExecutedBySystem:!0})):a("No pending move")}],Fa=[{intent:f.MoveToNextContainer,mode:p.MOVE,action:()=>dt()?(b({mode:p.COMMAND_LINE}),O("move to-next"),Fe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveToPreviousContainer,mode:p.MOVE,action:()=>dt()?(b({mode:p.COMMAND_LINE}),O("move to-previous"),Fe({isForceExecutedBySystem:!0})):a("No pending move")}];var Ba={[M.WORKSPACE]:[...gr,...fr],[M.BOARD]:[...gr,...fr],[M.SWIMLANE]:[...gr,...fr,...Fa],[M.TICKET]:[],[M.FIELD]:[],[M.FIELD_LIST]:[],[M.TEXT]:[]};var Ua=()=>{O("");let{pendingNavTarget:e}=ct();b({mode:p.DEFAULT}),e&&T.navigate(e),lt({pendingNavTarget:void 0})},Oa=[{intent:f.ExitCommandLine,mode:p.HELP,action:()=>(Ua(),c("Exiting help",null))},{intent:f.Exit,mode:p.HELP,action:()=>(Ua(),c("Closed help",null))},{intent:f.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:f.NavNextItem,mode:p.HELP,action:()=>(T.navigateToNextItem(),c("Navigating to next help item",null))},{intent:f.NavToPreviousContainer,mode:p.HELP,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:f.NavToNextContainer,mode:p.HELP,action:()=>(T.navigateToNextContainer(),c("Navigating to next help container",null))}];var Vu=e=>{b({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=ct();t&&T.navigate(t),lt({pendingNavTarget:void 0}),O(`${e} `)},$a=()=>{O("");let{pendingNavTarget:e}=ct();e&&T.navigate(e),lt({pendingNavTarget:void 0}),b({mode:p.DEFAULT})},Wa=[{intent:f.InitCommandPalette,mode:p.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{O("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return lt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),b({mode:p.PALETTE}),c("Opening command palette",null)}},{intent:f.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!et(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?(Vu(t),c("Selected command",t)):c("No command selected",null)}},{intent:f.ExitCommandLine,mode:p.PALETTE,action:()=>($a(),c("Exiting palette",null))},{intent:f.Exit,mode:p.PALETTE,action:()=>($a(),c("Closed command palette",null))},{intent:f.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.PALETTE,action:()=>(T.navigateToNextItem(),c("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.PALETTE,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.PALETTE,action:()=>(T.navigateToNextContainer(),c("Navigating to next container",null))}];var Ha=[...Oa,...Wa,{intent:f.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(b({mode:p.COMMAND_LINE}),O(`${x.NEW} `),c("Adding new item",null))},{intent:f.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(b({mode:p.COMMAND_LINE}),O(`${x.DELETE} `),c("Deleting item",null))},{intent:f.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(b({mode:p.COMMAND_LINE}),O(""),c("Entering command line mode",null))},{intent:f.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!W(e?.id??"")?.length){if(e?.title===J.DESCRIPTION)return b({mode:p.COMMAND_LINE}),O(`${x.EDIT} description `),c("Propose command",!0);if(e?.title===J.ASSIGNEES)return b({mode:p.COMMAND_LINE}),O(`${x.ASSIGN} `),c("Propose command",!0);if(e?.title===J.TAGS)return b({mode:p.COMMAND_LINE}),O(`${x.TAG} `),c("Propose command",!0);if(t.title===J.DESCRIPTION&&e?.context==="TEXT")return b({mode:p.COMMAND_LINE}),O(`${x.EDIT} description `),c("Propose command",!0)}return T.enterChildNode(),c("Entering context",null)}},{intent:f.EditTitle,mode:p.DEFAULT,description:"[r] rename title",action:()=>(b({mode:p.COMMAND_LINE}),O(`${x.EDIT} title ${v().selectedNode?.title}`),c("Exiting context",null))},{intent:f.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(b({mode:p.COMMAND_LINE}),O(`${x.EDIT} description `),c("Exiting context",null))},{intent:f.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(T.enterParentNode(),c("Exiting context",null))},{intent:f.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.DEFAULT,action:()=>(T.navigateToNextItem(),c("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.DEFAULT,action:()=>(T.navigateToNextContainer(),c("Navigating to next container",null))}];var Ku=500,zu=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),_a=e=>{let t=zu(e);t&&tr(n=>(n+t).slice(0,Ku))};var Gu=[p.COMMAND_LINE,p.PALETTE],qu=e=>[{intent:f.MoveCursorLeft,mode:e,action:()=>(ho(-1),c("Moving cursor left",null))},{intent:f.MoveCursorRight,mode:e,action:()=>(ho(1),c("Moving cursor right",null))},{intent:f.MoveCursorLeftOfWord,mode:e,action:()=>(Co("left"),c("Moving cursor left of word",null))},{intent:f.MoveCursorRightOfWord,mode:e,action:()=>(Co("right"),c("Moving cursor right of word",null))},{intent:f.AutoCompleteCommand,mode:e,action:()=>(tr((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:f.CaptureInput,mode:e,action:(t,{sequence:n})=>(_a(n??""),c("Capturing input",null))},{intent:f.EraseInput,mode:e,action:()=>(Bs(),c("Erasing input",null))},{intent:f.EraseInputWord,mode:e,action:()=>(Us(),c("Erasing input word",null))}],ja=[{intent:f.Confirm,mode:p.COMMAND_LINE,action:()=>(Fe(),c("Executing command",null))},{intent:f.ViewHelp,mode:p.DEFAULT,action:()=>(b({mode:p.HELP}),c("Viewing help",null))},...Gu.flatMap(qu),{intent:f.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(b({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:f.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Ws(),c("Getting last command from history",null))},{intent:f.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Hs(),c("Getting next command from history",null))}];import za from"chalk";var vr=za.dim.hex(h.secondary2)(": for command line"),Va="q to exit",Ka=`${za.hex(h.accent)("m")} to confirm`,Lo={[M.WORKSPACE]:[vr],[M.BOARD]:[vr],[M.BOARD+p.COMMAND_LINE]:[vr],[M.SWIMLANE]:[vr],[M.TICKET+p.HELP]:[Va],[M.SWIMLANE+p.HELP]:[Va],[M.TICKET]:[],[M.FIELD]:[],[M.SWIMLANE+p.MOVE]:[Ka],[M.TICKET+p.MOVE]:[Ka]};var fn=e=>e.trim().toLocaleLowerCase(),Yu=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Xu=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Ga=(e,t)=>{let n=fn(t.value);if(!n)return!0;switch(t.target){case"title":return fn(e.title??"").includes(n);case"description":return fn(e.props.description??"").includes(n);case"tag":return Yu(e).map(fn).some(o=>o.includes(n));case"assignee":return Xu(e).map(fn).some(o=>o.includes(n));default:return!0}};function qa(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let s=o[o.length-1];return!s||s.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var Ya=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 bt,Do,Fo=new Set,Xa=()=>{for(let e of Fo)e()},Qu=e=>(Fo.add(e),()=>Fo.delete(e));function Ja(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let u=qa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,y=Lo[g+n]??Lo[g]??[],N=[...Ha,...Ba[g]??[],...ja],E=Ya(N),I=Zu(o,i),A=I[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:E,selectedNode:A,renderedChildrenIndex:I})}var v=()=>{if(!bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return bt},ot=()=>bt?c("Retrieved state",bt):a("State not initialized. Call initWorkspaceState() first.");function tn(e){Do=e;let t=Ye(process.cwd()),n=!1;if(!d(t)){let i=Qe(t.value);if(d(i))return a(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:p.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1},o=Ja(r);return d(o)?o:(bt=o.value,Xa(),c("State initialized",null))}function Ee(e){let t=v(),n=e(t),r=Ja(n);return d(r)?a(r.message??"Unable to update state"):(bt=r.value,Xa(),c("State updated",null))}var b=e=>Ee(t=>({...t,...e}));var q=()=>Ju(Qu,v,v),Zu=(e,t)=>{let n={};for(let r of Object.values(e))$(r)&&t.length>0&&!t.every(o=>Ga(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,i)=>{let s=e[o.id],l=e[i.id];return!s||!l?0:s.rank.localeCompare(l.rank)});return n},F=e=>v()?.renderedChildrenIndex[e]??[],gn=()=>Do?tn(Do):a("Cannot reset state: no initial workspace found"),Ft=()=>bt!==void 0;import{Box as xr,Text as It}from"ink";import ve,{useEffect as em,useMemo as tm}from"react";import{ulid as nm}from"ulid";var Qa=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return ve.createElement(It,{color:n,dimColor:o},e);let i=e.toLowerCase(),s=t.toLowerCase(),l=i.indexOf(s);return l===-1?ve.createElement(It,{color:n,dimColor:o},e):ve.createElement(It,{color:n,dimColor:o},e.slice(0,l),ve.createElement(It,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},Za=nm(),rm=e=>`${e}`,om=e=>{let{pendingNavTarget:t}=ct();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,i=new Set(Q(x.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(s=>s!=="move").filter(s=>s.length>0).filter(s=>s!==x.PALETTE).map(s=>{let l=nr(s),u=pr.find(m=>m.intent===l);return{command:s,description:u?.description??`[${s}] Run command`,isAvailable:i.has(s)}}).filter(s=>s.command.toLowerCase().startsWith(e)||e.length>=2&&s.description.toLowerCase().includes(e)).sort((s,l)=>s.isAvailable!==l.isAvailable?s.isAvailable?-1:1:s.command.localeCompare(l.command))},im=e=>K.text({id:Za,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),sm=(e,t,n)=>K.text({id:rm(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Bo=[],am=e=>{ed();let t=S.createNode(im(v().rootNodeId));d(t)||!et(t.value)||(Bo=[t.value,...e.map((n,r)=>sm(n,r,Za)).map(S.createNode).filter(X).map(({value:n})=>n).filter(et)],T.navigate({contextNode:t.value,selectedIndex:0}))},ed=()=>{let e=Bo.map(t=>t.id);Bo=[];for(let t of e)S.deleteNode(t)};function td({width:e,height:t}){let r=_s().value.trim().toLowerCase(),o=tm(()=>om(r),[r]);em(()=>(am(o),()=>{ed()}),[o]);let i=v().selectedIndex;return ve.createElement(xr,{flexDirection:"column",width:e,height:t-2},ve.createElement(xr,{paddingX:1},ve.createElement(It,{color:h.accent},"Command Palette"),ve.createElement(It,{dimColor:!0}," \u2014 select a command and press enter")),ve.createElement(st,{height:t-4,itemHeight:3,selectedIndex:i},o.map((s,l)=>{let u=l===i,m=s.isAvailable?h.accent:h.secondary2,g=s.isAvailable?"":"[unavailable] ";return ve.createElement(xr,{key:s.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},ve.createElement(It,{color:m,dimColor:!s.isAvailable},u?"\u276F ":" ",ve.createElement(Qa,{text:Ri(s.command),match:r,color:m,dimColor:!s.isAvailable})),ve.createElement(xr,{paddingLeft:2},ve.createElement(Qa,{text:g+s.description,match:r.length>=2?r:"",color:u&&s.isAvailable?h.primary:h.secondary2,dimColor:!s.isAvailable})))})))}import{Box as Cm}from"ink";import $o from"react";import xn from"chalk";import{Box as Uo,Text as nd}from"ink";import vn,{useEffect as dm,useMemo as cm,useState as lm}from"react";var rd=xn.gray,um=xn.inverse,mm=xn.inverse.gray,pm={hint:"",hints:[],overlap:0,remainder:""},id=({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}},gm=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=Se(t);return{bg:r=>xn.bgHex(n).black(r),bgCursor:r=>xn.bgHex(n).inverse.black(r)}}return Yr(t)},fm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=id({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,s=r.end+i;return e.slice(s,s+n.length)!==n?null:{start:s,end:s+n.length}},od=()=>({value:se.value,cursorPosition:se.cursorPosition,commandIsPending:se.commandIsPending,autoCompletion:se.commandMeta.autoCompletion??pm,infoMessage:se.commandMeta.infoMessage,validationStatus:se.commandMeta.validity,command:se.commandMeta.command,inputString:se.commandMeta.inputString,modifier:se.commandMeta.modifier}),vm=(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,sd=({width:e,mode:t})=>{let[n,r]=lm(od());dm(()=>{let N=()=>{let I=od();r(A=>vm(A,I)?A:I)},E=yo(N);return N(),()=>{E()}},[]);let{value:o,cursorPosition:i,infoMessage:s,commandIsPending:l,autoCompletion:u,command:m,modifier:g}=n,y=cm(()=>{let N=Math.max(0,Math.min(i,o.length)),E=id({value:o,command:m}),I=fm({value:o,command:m,modifier:g}),A=m?Yr(m):null,R=gm({command:m,modifier:g}),w=(oe,le)=>{let Tt=E&&le>=E.start&&le<E.end,gt=I&&le>=I.start&&le<I.end;return Tt&&A?A.fg(oe):gt&&R?R.bg(oe):oe},B=(oe,le)=>{let Tt=E&&le>=E.start&&le<E.end,gt=I&&le>=I.start&&le<I.end;return Tt&&A?A.fgCursor(oe):gt&&R?R.bgCursor(oe):um(oe)},Ie=o.slice(0,N),ce=o[N]??" ",Vt=N<o.length?o.slice(N+1):"",Cn=Array.from(Ie).map((oe,le)=>w(oe,le)).join(""),At=B(ce,N),Kt=Array.from(Vt).map((oe,le)=>w(oe,N+1+le)).join("");if(u.hint){let oe=u.hint[u.overlap]??ce;At=mm(oe),Kt=rd(u.remainder.slice(1)+Vt)}return rd(t===p.PALETTE?"?":":")+Cn+At+Kt},[o,i,u,m,g]);return vn.createElement(Uo,{flexDirection:"column",justifyContent:"flex-start"},vn.createElement(Uo,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},vn.createElement(Uo,null,vn.createElement(nd,null,y),s&&vn.createElement(nd,{wrap:"truncate",color:l?h.red:h.secondary2},` ${s} `))))};import ad from"chalk";import{Box as xm,Text as Oo}from"ink";import yr from"react";var ym=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),hm=(e,t)=>{let n=[],r=0;for(let o of e){let s=(n.length>0?" | ":"").length+o.length;if(r+s>t-4)break;n.push(o),r+=s}return n},dd=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=hm(t,e).join(" | "),o=ad.hex(h.secondary),i=ad.hex(h.secondary2),s=o(`\u256D${"\u2500".repeat(n)}\u256E`),l=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(ym(` ${r} `,n))}${o("\u2502")}`;return yr.createElement(xm,{flexDirection:"column",width:e},yr.createElement(Oo,null,s),yr.createElement(Oo,null,u),yr.createElement(Oo,null,l))};var yn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let l=(r.length>0?" | ":"").length+i.length;if(o+l>e+2)break;r.push(i),o+=l}return $o.createElement(Cm,null,t===p.COMMAND_LINE||t===p.PALETTE?$o.createElement(sd,{width:e,mode:t}):$o.createElement(dd,{width:e,mode:t,availableHints:n}))};import{Box as ut,Text as jt}from"ink";import de,{useEffect as Nm,useMemo as Em}from"react";import{ulid as cd}from"ulid";var Cr=cd(),Sm=()=>[...new Set([...v().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})),bm=e=>K.text({id:Cr,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Im=(e,t,n)=>K.text({id:cd(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),hr=[],ld=()=>{let e=hr.filter(n=>n.id!==Cr).map(n=>n.id),t=hr.filter(n=>n.id===Cr).map(n=>n.id);hr=[];for(let n of[...e,...t])S.deleteNode(n)},Rm=e=>{ld();let t=S.createNode(bm(v().rootNodeId));if(d(t)||!et(t.value))return logger.error("Could not attach help nodes");hr=[t.value,...e.map((n,r)=>Im(n,r,Cr)).map(S.createNode).filter(X).map(({value:n})=>n).filter(et)],T.navigate({contextNode:t.value,selectedIndex:0})},ud=({width:e,height:t})=>{let n=Em(()=>Sm(),[]);Nm(()=>(Rm(n),()=>{ld()}),[n]);let r=v().selectedIndex;return de.createElement(ut,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},de.createElement(ut,{paddingX:1,justifyContent:"center"},de.createElement(jt,{color:h.accent},"Help"),de.createElement(jt,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),de.createElement(ut,{paddingX:1,marginTop:1},de.createElement(ut,{width:20,justifyContent:"flex-end"},de.createElement(jt,{color:h.secondary},"Key(s)")),de.createElement(ut,{flexGrow:1,width:40,paddingLeft:2},de.createElement(jt,{color:h.secondary},"Action"))),de.createElement(st,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:i},s)=>{let l=s===r;return de.createElement(ut,{paddingX:1,key:`${o}-${i}-${s}`,flexDirection:"row"},de.createElement(ut,{width:20,justifyContent:"flex-end"},de.createElement(jt,{color:h.accent},o)),de.createElement(ut,{flexGrow:1,width:40,paddingLeft:2},de.createElement(jt,{color:l?h.primary:h.secondary2},i)))})))};import Am from"chalk";import{Box as Nr,Text as ze}from"ink";import ye from"react";var md=({width:e,height:t})=>ye.createElement(Nr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},ye.createElement(ze,{color:h.accent,bold:!0},"Initialize project"),ye.createElement(ze,null,`This folder is not an ${Am.hex(h.accent)("epiq")} project yet.`),ye.createElement(ze,{color:h.primary},"To start tracking issues here, we need to initialize a new",ye.createElement(ze,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),ye.createElement(Nr,{marginTop:1,flexDirection:"column"},ye.createElement(Nr,null,ye.createElement(ze,{color:h.accent}," "),ye.createElement(ze,{color:h.primary},"Type "),ye.createElement(ze,{backgroundColor:h.secondary}," :init "))),ye.createElement(Nr,{marginTop:1},ye.createElement(ze,{color:h.secondary2},"This will create, commit and push "),ye.createElement(ze,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as Er,Text as Be}from"ink";import re from"react";var Tm=({isDone:e,command:t,value:n})=>re.createElement(Er,null,re.createElement(Be,{color:h.accent,dimColor:e},e?" \u2714 ":" "),re.createElement(Be,{dimColor:e},"Type "),re.createElement(Be,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&re.createElement(re.Fragment,null,re.createElement(Be,{dimColor:e}," "),re.createElement(Be,{color:h.secondary,dimColor:e},"<"+n+">"))),wm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function Wo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:s,isSetAutoSync:l}=Ze(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:s,message:"Almost there. Configure auto sync."}],m=u.findIndex(y=>!y.done),g=m===-1?void 0:u[m];return re.createElement(Er,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},re.createElement(Be,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),re.createElement(Be,null,"Let's get you started - it's a breeze."),re.createElement(Be,{color:h.secondary2},"Remember - you can always search available commands by typing:",re.createElement(Be,{color:h.accent}," ? ")),g&&re.createElement(Be,{color:h.secondary2},g.message),re.createElement(Er,{flexDirection:"column"},u.map((y,N)=>m===-1||N<=m?re.createElement(Er,{key:y.key,marginBottom:1},re.createElement(Tm,{isDone:y.done,command:y.command,value:y.done?wm(y.value):void 0})):null)))}import Rr from"chalk";import{Box as Ir,Text as Ge}from"ink";import te from"react";import{Box as Sr,Text as Mm}from"ink";import Rt from"react";var pd=({width:e})=>{let{viewMode:t}=U(),n=q(),{breadCrumb:r,contextNode:o,selectedIndex:i,renderedChildrenIndex:s}=n,l=s[o.id]?.[i],u=nt(l?.id??o.id,"TICKET"),m=X(u)?u.value:void 0,g=m?.props.tags??[],y=m?.props.assignees??[],N=m?.parentNodeId?!Kr(o.id,m.parentNodeId)&&t==="dense":!1,E=r.map((R,w)=>{let B=w===r.length-1,Ie=W(R.id),ce=B?Ie?.[i]?.title:void 0;return`${w?" / ":""}${R.title??""}${ce?` \u25B8 ${ce}`:""}`}).join(""),I=g.reduce((R,w)=>R+(S.getTag(w)?.name.length??0)+4,0)+y.reduce((R,w)=>R+(S.getContributor(w)?.name.length??0)+4,0),A=e-I;return Rt.createElement(Sr,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Rt.createElement(Sr,{overflow:"hidden",width:A},Rt.createElement(Mm,{wrap:"truncate-end",color:h.secondary2},E)),N?g.map(R=>Rt.createElement(Sr,{key:R,paddingLeft:1},Rt.createElement(Ht,{id:R}))):null,N?y.map(R=>Rt.createElement(Sr,{key:R,paddingLeft:1},Rt.createElement(Wt,{id:R}))):null)};import{Box as Pm,Text as gd}from"ink";import br from"react";var km=({filters:e})=>br.createElement(Pm,{columnGap:1},br.createElement(gd,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>br.createElement(gd,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),fd=br.memo(km);var vd="0.6.8";import Ho from"chalk";import{Box as Lm,Text as xd}from"ink";import _o,{useEffect as Dm,useState as Fm}from"react";var Bm=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],yd=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)}},Um=({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)}`},Om=(e,t,n)=>{let r=yd(e),o=yd(t);return Um({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},$m=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],s=e[Math.min(r+1,e.length-1)];return Om(i,s,o)};function hd({syncStatus:e,autoSync:t}){let[n,r]=Fm(0);Dm(()=>{if(e.status!=="syncing"){r(0);return}let l=setInterval(()=>{r(u=>u+1)},50);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"retry",syncing:"...",pending:"wait"},s={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:$m(Bm,(Math.sin(n*.12)+1)/2)??""}[e.status];return _o.createElement(Lm,null,_o.createElement(xd,null,Ho.hex(h.secondary2).dim(t?"AutoSync: ":"Sync: ")),_o.createElement(xd,null,Ho.hex(s)("\u25CF")+Ho.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Ar({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i,mode:s}=q(),{userName:l,preferredEditor:u,autoSync:m}=U(),g=56,y=process.stdout.columns-g-8,N=r.at(-1)?.id,E=On(N??""),I=X(E)?_i(E.value):"INVALID DATE";return te.createElement(Ir,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?te.createElement(Ge,null," "):te.createElement(Ir,{paddingLeft:1},e.length>0?te.createElement(fd,{filters:e}):te.createElement(pd,{width:y})),n==="live"?te.createElement(Ir,{columnGap:1,paddingRight:2,"max-width":g,overflow:"hidden",justifyContent:"flex-end"},te.createElement(hd,{autoSync:!!m,syncStatus:i}),te.createElement(Ge,null,Rr.hex(h.secondary2).dim("Mode: ")+Rr.hex(h.secondary2).dim(s.padEnd(8," "))," "),te.createElement(Cd,{icon:"@",value:l}),te.createElement(Cd,{icon:"\u276F",value:u}),te.createElement(Ge,{dimColor:!0,color:h.secondary2},vd+" ")):"",n==="peek"?te.createElement(Ir,{paddingLeft:1},te.createElement(Ge,{backgroundColor:h.yellow}," Readonly "),te.createElement(Ge,{color:h.yellow}," "+o.length+" edits ago at "),te.createElement(Ge,{backgroundColor:h.yellow}," "+I+" "),te.createElement(Ge,{color:h.yellow},". Resume with "),te.createElement(Ge,{backgroundColor:h.yellow}," :peek now ")):"")}function Cd({icon:e,value:t}){return te.createElement(Ge,null,Rr.dim(e)+Rr.hex(h.accent)(` ${t??"-"} `))}import{Box as Wm,Text as Hm}from"ink";import hn from"react";import{Box as Tr,Text as jo}from"ink";import mt from"react";function Vo(){let e=q(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,s=t?.id?F(t?.id):[];return mt.createElement(Tr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},mt.createElement(Tr,{padding:1,paddingTop:0,paddingBottom:0},mt.createElement(jo,null,"Select a board:")),mt.createElement(Tr,{padding:1,flexDirection:"column"},s.map((l,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,y=F(l.id).flatMap(({id:N})=>W(N)).length;return mt.createElement(Tr,{key:l.id??u},mt.createElement(jo,{color:m?h.accent:h.secondary2},mt.createElement(ge,{isSelected:m})),mt.createElement(jo,{color:m?h.accent:h.secondary2},l.title," (",y," issues)",l.readonly?" \u{1F512}":""))})))}var _m=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:s})=>{let{renderedChildrenIndex:l}=q(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return hn.createElement(Wm,{flexDirection:"row"},e.context==="WORKSPACE"?hn.createElement(Vo,null):u?hn.createElement(dr,{height:y,width:s,swimlanes:(l[u.id]??[]).filter(N=>N!==void 0&&Pt(N)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):hn.createElement(Hm,null))},Nd=hn.memo(_m);function Ko({width:e,height:t}){let n=q(),r=n.filters;if(n.mode===p.HELP)return Y.createElement(pt,{flexDirection:"column"},Y.createElement(ud,{width:e,height:t}));if(n.mode===p.PALETTE)return Y.createElement(pt,{flexDirection:"column"},Y.createElement(td,{width:e,height:t}),Y.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:o}=Ze(),i=!o,s=o&&!n.hasProjectDefinition;if(i)return Y.createElement(pt,{flexDirection:"column"},Y.createElement(pt,{flexDirection:"column"},Y.createElement(Ar,{hideBreadCrumb:!0,filters:r}),Y.createElement(Wo,{height:t,width:e})),Y.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(s)return Y.createElement(pt,{flexDirection:"column"},Y.createElement(pt,{flexDirection:"column"},Y.createElement(Ar,{hideBreadCrumb:!0,filters:r}),Y.createElement(md,{height:t,width:e})),Y.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));let l=Ne(n.breadCrumb??[],"BOARD");if(X(l)){let u=l.value.id,m=F(u).length,g=3,y=Math.floor(e/g),N=Math.floor(e/Math.max(m,1));e=Math.min(N,y)*Math.max(m,g)}return Y.createElement(pt,{flexDirection:"column"},Y.createElement(pt,{flexDirection:"column"},Y.createElement(Ar,{filters:r}),Y.createElement(Nd,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:U().viewMode??"dense",mode:n.mode})),Y.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import jm from"readline";var wr,Mr,Ue,Vm=new Set([f.MoveCursorLeft,f.EraseInputWord,f.MoveCursorLeftOfWord,f.MoveCursorRight,f.MoveCursorRightOfWord,f.NavToPreviousContainer,f.NavToNextContainer,f.NavPreviousItem,f.NavNextItem,f.SetViewDense,f.SetViewWide,f.Confirm,f.Exit,f.InitCommandLine,f.InitCommandPalette,f.ExitCommandLine,f.CaptureInput,f.EraseInput,f.EraseInputWord,f.HideHelp,f.ViewHelp,f.SetViewDense,f.SetViewWide,f.GetLastCommandFromHistory,f.GetNextCommandFromHistory,f.AutoCompleteCommand]),Ed=async e=>{if(e.ctrl&&e.name==="c")return T.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Vs(e,n);if(!o||r&&!Vm.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(s){logger.error(s)}},Km=()=>async function(t,n){n.name!=="escape"&&(Ue&&(clearTimeout(Ue),Ue=void 0),await Ed(n))},zm=()=>async function(t){if(t.length===1&&t[0]===27){Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{Ed({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ue=void 0},25);return}Ue&&(clearTimeout(Ue),Ue=void 0)};function Sd(){wr&&process.stdin.removeListener("keypress",wr),Mr&&process.stdin.removeListener("data",Mr),wr=Km(),Mr=zm(),jm.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Mr),process.stdin.on("keypress",wr)}ka();qm(`${Pr.bold("Epiq CLI")}
|
|
61
58
|
|
|
62
59
|
${Pr.dim("Boot in directory:")}
|
|
63
60
|
${Pr.cyan("$ epiq")}
|
|
64
61
|
|
|
65
|
-
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var
|
|
62
|
+
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var bd=process.stdout.columns||120,Id=process.stdout.rows||20,kr=null,Xm=e=>{try{return kr?(kr.rerender(e),c("Rerendered app",void 0)):(kr=Gm(e),c("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${oo(t)}`)}},Rd=()=>Xm(Ym.createElement(Ko,{width:bd,height:Id}));async function Jm(){try{let e=ua();X(e)&&Pe(e.value);let t=Ye(process.cwd()),n=[];if(X(t)){let i=Xe({repoRoot:t.value});if(d(i))return Bt(3,i.message);let s=Dt(i.value);if(d(s))return Bt(3,s.message);n=s.value}let r=zn(n);if(d(r))return Bt(4,r.message);b({hasProjectDefinition:X(t),hasInitializingEvents:!!n.length});let o=Rd();return d(o)?Bt(6,o.message):(Sd(),c("Booted Epiq",void 0))}catch(e){return Bt(0,oo(e))}}process.stdout.on("resize",()=>{if(bd=process.stdout.columns||120,Id=process.stdout.rows||20,!kr)return;let e=Rd();d(e)&&logger.info(`[boot:resize] ${e.message}`)});(async()=>{console.clear();let e=await Jm();d(e)&&(logger.info(e.message),console.error(Pr.red(`Failed to boot Epiq:
|
|
66
63
|
${e.message}`)),process.exitCode=1)})();
|