epiq 0.3.9 → 0.3.10
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 +52 -46
- package/dist/mcp.js +52 -45
- package/package.json +1 -2
package/dist/index.js
CHANGED
|
@@ -1,63 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Dr from"chalk";import{render as Tl}from"ink";import wl from"meow";import Rl from"react";import El from"chalk";import{Box as fe,Text as Ke}from"ink";import F from"react";import st from"chalk";import{monotonicFactory as hd,ulid as Se}from"ulid";import{useSyncExternalStore as vd}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function ve(e){return e.context==="TICKET"}var Or=e=>e.context==="SWIMLANE";var Ne={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Ne.Fail,message:e,value:null}),c=(e,t)=>({status:Ne.Success,message:e,value:t}),l=e=>e.status==="fail",Fe=e=>e.status==="success";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Pt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Lt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",wn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Br=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},Ur=(e,t)=>t?e.get(t)??[]:[];var $r=new WeakMap,Ts=e=>{let t=$r.get(e);return t||(t=Br(e),$r.set(e,t)),t};var Wr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ur(Ts(e),r).filter(i=>Pt(r,i)>=n)};var _r=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Wr({wordList:n,inputToMatch:e,overlapThreshold:1});return ws(t,r)},ws=(e,t)=>{let n=t[0]??"",r=Pt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,g=(d&&a?o:n)+(d&&a?":":" "),h=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:h}};var Hr=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Ye=24n,Rs=Ye*4n,Dt=(1n<<Rs)-1n,Ms=/^[0-9a-f]+$/;function Kr(e){if(!e||!Ms.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function Ft(e,t=Ye){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function ut(e,t){if(!e&&!t)return Ft(Dt/2n,Ye);let n=e?Kr(e):0n,r=t?Kr(t):Dt;if(r<=n)return Ft(Dt/2n,Ye);let o=(n+r)/2n;return o===n||o===r?"":Ft(o,Ye)}function me(){return Ft(Dt/2n,Ye)}var Q={workspace:(e,t)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var U=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Vr=(e,t)=>e.findIndex(n=>n.id===t),Rn=(e,t={at:"end"})=>{if(e.length===0)return c("Resolved rank",me());switch(t.at){case"start":{let n=e[0];return n?c("Resolved rank",ut(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?c("Resolved rank",ut(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Vr(e,t.sibling);if(n<0)return s("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?c("Resolved rank",ut(r?.rank,o.rank)):s("Sibling not found")}case"after":{let n=Vr(e,t.sibling);if(n<0)return s("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?c("Resolved rank",ut(r.rank,o?.rank)):s("Sibling not found")}}};var ke=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("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 s(`No ancestor found for context: ${t}`)},Pn=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Mn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),E={deleteNode(e){oe(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 s("Edit target node not found");let o=Mn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return E.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Mn(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 U(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Mn(o,"move");if(a)return a;if(Pn(t,e))return s("Cannot move node into its own descendant");let d=U(t).filter(g=>g.id!==e),u=Rn(d,n);if(l(u))return u;let m={...o,parentNodeId:t,rank:u.value};return this.updateNode(m),c("Moved node successfully",m)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of U(m.id))a(g.id)}};a(e);let d={...structuredClone(t)};for(let u of i){if(!d[u])return s("Unable to locate node to delete");d[u]={...d[u],isDeleted:!0}}return n?(T({nodes:d}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=oe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return l(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n){let r=E.getContributor(t),o=E.getNode(e);if(!o||!r)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(U(i.id).some(u=>u.props?.value===t))return s("Contributor already assigned");let d=this.createNodeAtPosition(Q.field(n,r.name,i.id,{value:t}));return l(d)?d:c("Assigned contributor",d.value)},createTag(e){let t=oe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return l(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,n){let r=E.getTag(t),o=E.getNode(e);if(!r)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(U(i.id).some(u=>u.props?.value===t))return s("Tag already assigned");let d=this.createNodeAtPosition(Q.field(n,r.name,i.id,{value:t}));return l(d)?d:c("Tag added",d.value)},untag(e,t){let n=E.getTag(t),r=E.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=U(o.id).find(d=>d.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Tag removed",a)},unassign(e,t){let n=E.getContributor(t),r=E.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=U(o.id).find(d=>d.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Assignee removed",a)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:me()};return this.createNode(i),c("Created node",i)}let n=U(e.parentNodeId),r=Rn(n,t);if(l(r))return r;let o={...e,rank:r.value};return this.createNode(o),c("Created node",o)},createNode(e){let t=oe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return l(t)?s("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=oe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return l(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=oe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return l(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=>Object.values(v().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var kt={autoSync:!1,preferredEditor:null,userName:null,userId:null},pe=()=>kt,Je=e=>(kt={...kt,...e},kt);var Ot=()=>{let e=pe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},jr=()=>!Ve();var G={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"},N={accent:G.cyan,accent2:G.magenta,primary:G.white,secondary:G.grayDark,secondary2:G.grayLight,gray:G.gray,green:G.green,yellow:G.yellow,red:G.red};var y={red:G.red,yellow:G.yellow,green:G.green,blue:G.blue,magenta:G.magenta,cyan:G.cyan},Xe={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var zr=(e,t)=>{let r=w(e.id).find(o=>o.title===t);return r?w(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Ln=e=>zr(e,"Tags").map(t=>E.getTag(t)).filter(t=>!!t),Bt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ve(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Ln(n)??[])},Ut=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ve(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Dn(n)??[])},Dn=e=>zr(e,"Assignees").map(t=>E.getContributor(t)).filter(t=>!!t);var p={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",NONE:""};var Ps=/^(\d+)(h|d|w|mo|y)$/,Ls=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ds=({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},Fs=(e,t=new Date)=>{let n=e.match(Ps);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},ks=e=>{let t=e.match(Ls);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,h=a?Number(a):0;return Ds({year:d,month:u,day:m,hour:g,minute:h})?new Date(d,u-1,m,g,h):null},$t=e=>{let t=e.trim().toLowerCase();return Fs(t)??ks(t)},Gr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Os=[{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}],qr=(e=Os)=>{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 Bs=["BOARD","TICKET","SWIMLANE"],j=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=v(),o=Ot().isSetup,i=t.context,a=r?.context,d=[p.SYNC,p.HELP,p.SET_VIEW,p.SET_EDITOR,p.SET_USERNAME],u=[p.NEW,p.RENAME,p.DELETE],m=[p.TAG,p.UNTAG,p.ASSIGN,p.UNASSIGN,p.CLOSE_ISSUE,p.RE_OPEN_ISSUE,p.SET_DESCRIPTION],g=[p.FILTER,p.PEEK],h={WORKSPACE:[...d,...u],BOARD:[...g,...d,...u],SWIMLANE:[...g,...d,...u],TICKET:[...d,...u,...m],FIELD:[...d,...m],FIELD_LIST:[...d,...m],TEXT:[...d]},C=a&&Bs.includes(a),I=[...h[i||"WORKSPACE"]].filter(A=>[p.RENAME,p.DELETE,p.MOVE].includes(A)?C:!0),b={[p.PEEK]:[...qr(),"now","prev","next"],[p.SYNC]:[],[p.INIT]:[],[p.SET_USERNAME]:[],[p.SET_DESCRIPTION]:["confirm"],[p.DELETE]:["confirm"],[p.RE_OPEN_ISSUE]:["confirm"],[p.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[p.CLOSE_ISSUE]:["confirm"],[p.FILTER]:["tag","assignee","description","title","clear"],[p.SET_VIEW]:["dense","wide"],[p.SET_EDITOR]:[...Hr],[p.TAG]:[...new Set([...Object.keys(Xe),...E.getExistingTags()])],[p.UNTAG]:[...Bt()?.value?.map(({name:A})=>A)??[]],[p.UNASSIGN]:[...Ut()?.value?.map(({name:A})=>A)??[]],[p.ASSIGN]:E.getExistingAssignees(),[p.HELP]:[],[p.RENAME]:[],[p.NEW]:i==="TICKET"||i==="FIELD"||i==="FIELD_LIST"?["issue","swimlane","board"]:i==="SWIMLANE"?["issue","swimlane","board"]:i==="BOARD"?["issue","swimlane","board"]:["board"],[p.NONE]:I};return o?jr()?n&&(b={[p.NONE]:[p.HELP,p.PEEK],[p.HELP]:b[p.HELP],[p.PEEK]:b[p.PEEK]}):b={[p.NONE]:[p.HELP,p.INIT],[p.HELP]:b[p.HELP],[p.INIT]:b[p.INIT]}:b={[p.NONE]:[p.HELP,p.SET_EDITOR,p.SET_USERNAME],[p.HELP]:b[p.HELP],[p.SET_EDITOR]:b[p.SET_EDITOR],[p.SET_USERNAME]:b[p.SET_USERNAME]},b[e]??[]};import Qe from"chalk";import{decodeTime as Yr}from"ulid";var Jr=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"},Xr=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())}`},Wt=e=>{try{return c("Decoded date",new Date(Yr(e)))}catch(t){return s("Decoding failed + "+t.message)}},Fn=e=>{if(!e?.id)return null;try{return Yr(e.id)}catch{return null}};var Ee=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):s("Unable to find node in breadcrumb")};import Ze from"chalk";var On={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Us=(e,t,n)=>Math.max(t,Math.min(n,e)),kn=(e,t,n)=>e+(t-e)*n,Zr=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},$s=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),u=0,m=0,g=0;a>=0&&a<1?(u=i,m=d):a>=1&&a<2?(u=d,m=i):a>=2&&a<3?(m=i,g=d):a>=3&&a<4?(m=d,g=i):a>=4&&a<5?(u=d,g=i):(u=i,g=d);let h=o-i/2;return[Math.round((u+h)*255),Math.round((m+h)*255),Math.round((g+h)*255)]},Ws=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,_s=(e,t,n)=>[Math.round(kn(e[0],t[0],n)),Math.round(kn(e[1],t[1],n)),Math.round(kn(e[2],t[2],n))],mt=e=>{let n=Zr(e)%360,r=$s(n,On.stringColor.saturation,On.stringColor.lightness);return Ws(r)},Hs=e=>{let t=On.gradient.stops,n=Us(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),a=o-i;return _s(t[i],t[i+1],a)},_t=e=>Zr(e.toLowerCase().trim())/4294967295,Qr=e=>{let t=_t(e);return Hs(t)},Ks=e=>{let[t,n,r]=Qr(e);return{normal:o=>Ze.bgRgb(t,n,r).black(o),cursor:o=>Ze.bgRgb(t,n,r).white.bold(o)}},Bn=e=>{let[t,n,r]=Qr(e);return{fg:o=>Ze.rgb(t,n,r)(o),fgCursor:o=>Ze.rgb(t,n,r).inverse(o),bg:o=>Ze.bgRgb(t,n,r).black(o),bgCursor:o=>Ze.bgRgb(t,n,r).white.bold(o)}},Un=e=>Ks(e).normal(` ${e} `),q=(e,t=Xe)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:mt(r)};var Ce={None:"none",Invalid:"invalid",Valid:"valid"};var Vs=["BOARD","TICKET","SWIMLANE"],$n=()=>{let e=v().selectedNode;return e?.context?Vs.includes(e?.context)?V():$({message:"Command not available in this context"}):$({message:"Missing target context"})},ie="<ENTER> to confirm",V=(e="",t=[])=>({message:e,validity:Ce.Valid,completionWordList:t}),$=({message:e,completionWordList:t=[]})=>({validity:Ce.Invalid,message:e,completionWordList:t}),gt=e=>e.length===0,Oe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(g=>g.startsWith(o.trim()))].sort((g,h)=>_t(g)-_t(h)).slice(0,r).map(Un),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},Wn=({modifier:e})=>{let t="confirm";return e===t?V(ie):$({message:gt(e)?`if you are certain, enter ${Un(t)}`:"",completionWordList:[t]})},js=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?V(ie):$({message:gt(n)?t:""}),zs=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?$({message:n}):V():$({message:gt(r)?t:""}),pt=({hint:e})=>({modifier:t,inputString:n})=>gt(t)&>(n)?$({message:e,completionWordList:[]}):V(ie),Gs={[p.PEEK]:e=>{let t=e.modifier;if(t==="now")return V(ie);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return V(ie);let r=$t(t);if(!t||!r)return $(n);let o=Ee(v().breadCrumb,"BOARD");if(l(o))return $({message:"Command is not applicable in this context"});let i=Wt(o.value.id);return l(i)?$({message:"Unable to peek: board id is not a valid ULID"}):Gr({date:r,horizonDate:i.value})?V(ie):$({message:Qe.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[p.INIT]:()=>V(ie),[p.FILTER]:e=>{if(e.modifier==="clear")return V();let t=a=>j(p.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return $({message:Oe({wordList:j(p.FILTER),inputString:e.inputString}),completionWordList:j(p.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?$({message:Oe({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):V():$({message:Oe({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[p.NONE]:e=>{let t=j(p.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?V():$({message:Oe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[p.NEW]:e=>zs({list:j(p.NEW),hint:Oe({wordList:j(p.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[p.SET_DESCRIPTION]:()=>V(ie),[p.HELP]:()=>V(ie),[p.RENAME]:()=>{let e=$n();return e.validity==="invalid"?e:V(ie)},[p.DELETE]:e=>{let t=$n();return t.validity==="invalid"?t:Wn(e)},[p.CLOSE_ISSUE]:e=>Wn(e),[p.RE_OPEN_ISSUE]:e=>Wn(e),[p.MOVE]:e=>{let t=$n();return t.validity==="invalid"?t:pt({hint:Oe({prefix:"hey hacker! These commands are blocked for you... ",wordList:j(p.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[p.TAG]:e=>{let t=E.getExistingTags().map(n=>` ${Qe.bgHex(q(n))(" "+n+" ")} `).slice(0,10);return pt({hint:"tag name like... "+t.join("")})(e)},[p.UNTAG]:e=>{let t=Bt();if(l(t))return $({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Qe.bgHex(q(r))(" "+r+" ")} `).slice(0,10);return n.length?pt({hint:" ... "+n.join("")})(e):$({message:"Issue has not tags",completionWordList:[]})},[p.ASSIGN]:e=>{let t=E.getExistingAssignees().map(n=>` ${Qe.bgHex(q(n))(" "+n+" ")} `).slice(0,10);return pt({hint:"assign to... "+t.join("")})(e)},[p.UNASSIGN]:e=>{let t=Ut();if(l(t))return $({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Qe.bgHex(q(r))(" "+r+" ")} `).slice(0,10);return n.length?pt({hint:"remove assignee... "+n.join("")})(e):$({message:"Issue has no assignees",completionWordList:[]})},[p.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=j(p.SET_EDITOR);return e.modifier?V(ie):$({message:Oe({wordList:t,inputString:e.inputString})})},[p.SET_USERNAME]:e=>e.inputString?V():$({message:`Enter a username. Saved in ${Qe.bgBlack("~/.epiq-global/")}`}),[p.SET_VIEW]:e=>js({list:j(p.SET_VIEW),hint:Oe({wordList:j(p.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[p.SYNC]:()=>V(ie)},eo=Object.fromEntries(Object.entries(Gs).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var to=["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 M={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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"};var no=e=>Object.values(p).includes(e),ro=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:u}=eo[n].validate(n,r,i),m=o==="command"?Object.values(p):n&&e.target==="modifier"?j(n):to;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?_r(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var oo=e=>{let t=e.trimStart(),n=Ys(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),i=Js(e),a=no(r)?r:null,d=a!==null,u=r!=="",m=e.endsWith(" "),g=a?j(a)??[]:[],h=a&&g.includes(o)?o:"",C="word";n.length<=1?C="command":n.length===2&&(C="modifier");let I=qs(t,a,h);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:u,command:a,isCommandKeyword:d,isLastWordCompleted:m,modifier:h,target:C,inputToMatch:i,inputString:I}},qs=(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},Ys=e=>e?e.split(/\s+/):[],Js=e=>e.trimEnd().split(/\s+/).at(-1)??"";var io=" ",Y={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ce.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_n=new Set,so=()=>{for(let e of _n)e()},ao=e=>(_n.add(e),()=>_n.delete(e)),Ie=e=>{let n=e(Y),r=oo(n.value),o=n.cursorPosition===n.value.length;Y={...n,commandMeta:ro(r,o)},so()},ft=({message:e,status:t})=>{let n=structuredClone(Y);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Y=n,so(),c(e,null)},Hn=e=>{Ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Kn=e=>{Ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},lo=()=>{Ie(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}})},co=()=>{Ie(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},K=e=>{Ie(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),a=i+o,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},uo=()=>{Ie(e=>({...e,commandIsPending:!0}))},mo=({addToHistory:e=!0})=>{Ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Xs()},po=()=>{Ie(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}})},go=()=>{Ie(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Xs=()=>K(()=>""),ee=()=>Y,Ht=()=>{let[e,...t]=Y.value.split(io);return t.join(io).trim()};var Zs=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Qs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",ea=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",fo=(e,t)=>{if(Qs(e,e.sequence))return x.MoveCursorLeftOfWord;if(ea(e,e.sequence))return x.MoveCursorRightOfWord;if(Zs(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={Sync:"sync",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",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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function ta(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function na(e,t,n){let r=v().currentNode.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 vo(e,t){let n=ee();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===f.COMMAND_LINE)return fo(e,n.value);let r=ta(e);if(r){let o=t===f.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return na(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var xo=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case p.INIT:return M.Init;case p.DELETE:return M.Delete;case p.SET_DESCRIPTION:return M.Edit;case p.HELP:return M.ViewHelp;case p.RE_OPEN_ISSUE:return M.ReopenIssue;case p.CLOSE_ISSUE:return M.CloseIssue;case p.TAG:return M.TagTicket;case p.UNTAG:return M.UntagTicket;case p.ASSIGN:return M.AssignUserToTicket;case p.UNASSIGN:return M.UnassignUserFromTicket;case p.RENAME:return M.Rename;case p.NEW:return M.NewItem;case p.FILTER:return M.Filter;case p.MOVE:return M.Move;case p.PEEK:return M.Peek;case p.SET_USERNAME:return M.SetUserName;case p.SET_EDITOR:return M.SetEditor;case p.SET_VIEW:return M.SetView;case p.SYNC:return M.Sync;default:return M.None}};import{ulid as W}from"ulid";import{spawnSync as ca}from"node:child_process";import ua from"node:os";import Eo from"node:path";import{ulid as ma}from"ulid";import{accessSync as ra,copyFileSync as oa,existsSync as Kt,mkdirSync as yo,readdirSync as ho,readFileSync as ia,renameSync as sa,rmSync as aa,statSync as No,unlinkSync as da,writeFileSync as la}from"node:fs";import et from"node:path";var se={writeToFile:(e,t)=>{try{let n=et.dirname(e);Kt(n)||yo(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);la(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return ia(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=se.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 Kt(e)&&No(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await ra(e),!0}catch{return!1}},mkDir:e=>yo(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=et.parse(t);for(;;){let r=et.join(t,e);try{if(Kt(r)&&No(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=et.dirname(t)}return null},readFirstJSON(e){try{if(!se.dirExists(e))return null;let t=ho(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=et.join(e,t);return se.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return se.dirExists(e)?ho(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{da(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{aa(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(et.dirname(t)),!n?.overwrite&&Kt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{sa(e,t)}catch(r){if(r?.code==="EXDEV"){oa(e,t),this.rmFile(e);return}throw r}}};function pa(){let{preferredEditor:e}=pe(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function ga(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Co(e){let t=Eo.join(ua.tmpdir(),"epiq");se.mkDir(t);let n=Eo.join(t,ma());se.writeToFile(n,e??"");let r=pa();for(let o of r){let i=ga(o,n),a=ca(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=se.readFile(n);if(d==null)return s("Unable to read edited file");let u=d.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as fa,ulid as Vt}from"ulid";var jt=fa(),Io=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=jt(),i=jt(),a=jt(),d=jt();return[{id:Vt(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:Vt(),userId:n,userName:r,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:Vt(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:Vt(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Yt from"node:fs";import Yn from"node:path";import{decodeTime as Aa}from"ulid";import{z as qn}from"zod";import ya from"node:fs";import ha from"node:path";import{decodeTime as Na,monotonicFactory as Ea}from"ulid";import{z as yt}from"zod";import Vn from"node:fs";import vt from"node:path";var jn=process.env.IS_LOCAL==="true",Be=".epiq",de=".epiq-global",zt="events",va=e=>vt.join(e,Be),xt=e=>vt.join(va(e),zt),xa=e=>{let t=vt.join(e,Be);return Vn.existsSync(t)&&Vn.statSync(t).isDirectory()},be=e=>{let t=vt.resolve(e);for(;;){if(xa(t))return c("Resolved closest .epiq root",t);let n=vt.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},bo=e=>{let t=xt(e);try{return Vn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};var So=e=>({action:e.action,payload:e.payload});var To=1,Ao=Ea(),Ca=yt.tuple([yt.string().min(1),yt.string().min(1).nullable()]),Ia=yt.looseObject({v:yt.literal(To),id:Ca}),zn=e=>{let t=Ia.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Gt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",J=()=>{let{userName:e,userId:t}=pe();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Gt(t),userName:Gt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Gn=({userId:e,userName:t})=>`${Gt(e)}.${Gt(t)}.jsonl`,ba=(e,{userId:t,userName:n})=>{let r=Gn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=ha.join(xt(e),r);return c("Successfully resolved event log path",i)},Sa=(e,t)=>{let n={[e.action]:e.payload,v:To,id:t};return zn(n)};function qt({event:e,rootDir:t=process.cwd()}){try{let n=be(t);if(l(n))return n;let r=bo(n.value);if(l(r))return r;let o=ba(n.value,{userId:e.userId,userName:e.userName});if(l(o))return o;let i=wo(n.value);if(l(i))return s(i.message);let a=i.value?Ao(Math.max(Date.now(),Na(i.value)+1)):Ao(),d=Sa(So(e),[a,i.value]);return l(d)?s(d.message):(ya.appendFileSync(o.value,`${JSON.stringify(d.value)}
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let d=
|
|
5
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import $r from"chalk";import{render as qc}from"ink";import Yc from"meow";import Xc from"react";import Hc from"chalk";import{Box as ve,Text as Ke}from"ink";import F from"react";import lt from"chalk";import{monotonicFactory as pc,ulid as we}from"ulid";import{useSyncExternalStore as lc}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function xe(e){return e.context==="TICKET"}var Dt=e=>e.context==="SWIMLANE";var Ee={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Ee.Fail,message:e,value:null}),l=(e,t)=>({status:Ee.Success,message:e,value:t}),c=e=>e.status==="fail",Fe=e=>e.status==="success";var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Ft(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var kt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Dn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Hr=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},Kr=(e,t)=>t?e.get(t)??[]:[];var Vr=new WeakMap,ks=e=>{let t=Vr.get(e);return t||(t=Hr(e),Vr.set(e,t)),t};var jr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Kr(ks(e),r).filter(i=>Ft(r,i)>=n)};var Os={hint:"",hints:[],overlap:0,remainder:""},zr=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Os;let o=jr({wordList:r,inputToMatch:e,overlapThreshold:1});return Bs(t,o)},Bs=(e,t)=>{let n=t[0]??"",r=Ft(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,g=(d&&a?o:n)+(d&&a?":":" "),h=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:h}};var Gr=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Xe=24n,Us=Xe*4n,Ot=(1n<<Us)-1n,$s=/^[0-9a-f]+$/;function qr(e){if(!e||!$s.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function Bt(e,t=Xe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function pt(e,t){if(!e&&!t)return Bt(Ot/2n,Xe);let n=e?qr(e):0n,r=t?qr(t):Ot;if(r<=n)return Bt(Ot/2n,Xe);let o=(n+r)/2n;return o===n||o===r?"":Bt(o,Xe)}function me(){return Bt(Ot/2n,Xe)}var ee={workspace:(e,t)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var U=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Yr=(e,t)=>e.findIndex(n=>n.id===t),Fn=(e,t={at:"end"})=>{if(e.length===0)return l("Resolved rank",me());switch(t.at){case"start":{let n=e[0];return n?l("Resolved rank",pt(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?l("Resolved rank",pt(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Yr(e,t.sibling);if(n<0)return s("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?l("Resolved rank",pt(r?.rank,o.rank)):s("Sibling not found")}case"after":{let n=Yr(e,t.sibling);if(n<0)return s("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?l("Resolved rank",pt(r.rank,o?.rank)):s("Sibling not found")}}};var ke=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("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 s(`No ancestor found for context: ${t}`)},On=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},kn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),E={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 s("Edit target node not found");let o=kn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return E.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=kn(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 U(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=kn(o,"move");if(a)return a;if(On(t,e))return s("Cannot move node into its own descendant");let d=U(t).filter(g=>g.id!==e),u=Fn(d,n);if(c(u))return u;let m={...o,parentNodeId:t,rank:u.value};return this.updateNode(m),l("Moved node successfully",m)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of U(m.id))a(g.id)}};a(e);let d={...structuredClone(t)};for(let u of i){if(!d[u])return s("Unable to locate node to delete");d[u]={...d[u],isDeleted:!0}}return n?(T({nodes:d}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ie(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,n){let r=E.getContributor(t),o=E.getNode(e);if(!o||!r)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(U(i.id).some(u=>u.props?.value===t))return s("Contributor already assigned");let d=this.createNodeAtPosition(ee.field(n,r.name,i.id,{value:t}));return c(d)?d:l("Assigned contributor",d.value)},createTag(e){let t=ie(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,n){let r=E.getTag(t),o=E.getNode(e);if(!r)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(U(i.id).some(u=>u.props?.value===t))return s("Tag already assigned");let d=this.createNodeAtPosition(ee.field(n,r.name,i.id,{value:t}));return c(d)?d:l("Tag added",d.value)},untag(e,t){let n=E.getTag(t),r=E.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=U(o.id).find(d=>d.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Tag removed",a)},unassign(e,t){let n=E.getContributor(t),r=E.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=U(o.id).find(d=>d.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:me()};return this.createNode(i),l("Created node",i)}let n=U(e.parentNodeId),r=Fn(n,t);if(c(r))return r;let o={...e,rank:r.value};return this.createNode(o),l("Created node",o)},createNode(e){let t=ie(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=ie(o=>({...o,nodes:{...o.nodes,[e]:n}}));return c(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=ie(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(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=>Object.values(v().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var Ut={autoSync:!1,preferredEditor:null,userName:null,userId:null},pe=()=>Ut,Je=e=>(Ut={...Ut,...e},Ut);var $t=()=>{let e=pe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Xr=()=>!Ve();var G={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"},N={accent:G.cyan,accent2:G.magenta,primary:G.white,secondary:G.grayDark,secondary2:G.grayLight,gray:G.gray,green:G.green,yellow:G.yellow,red:G.red};var y={red:G.red,yellow:G.yellow,green:G.green,blue:G.blue,magenta:G.magenta,cyan:G.cyan},Ze={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var Jr=(e,t)=>{let r=w(e.id).find(o=>o.title===t);return r?w(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Bn=e=>Jr(e,"Tags").map(t=>E.getTag(t)).filter(t=>!!t),_t=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!xe(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Bn(n)??[])},Wt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!xe(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Un(n)??[])},Un=e=>Jr(e,"Assignees").map(t=>E.getContributor(t)).filter(t=>!!t);var f={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",EXPORT:"export",NONE:""};var _s=/^(\d+)(h|d|w|mo|y)$/,Ws=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Hs=({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},Ks=(e,t=new Date)=>{let n=e.match(_s);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},Vs=e=>{let t=e.match(Ws);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,h=a?Number(a):0;return Hs({year:d,month:u,day:m,hour:g,minute:h})?new Date(d,u-1,m,g,h):null},Ht=e=>{let t=e.trim().toLowerCase();return Ks(t)??Vs(t)},Zr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,js=[{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}],Qr=(e=js)=>{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 zs=["BOARD","TICKET","SWIMLANE"],je=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],Kt=[f.NEW,f.RENAME,f.DELETE,f.MOVE],$n=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],eo=[f.FILTER,f.PEEK],Gs={WORKSPACE:[...je,...Kt],BOARD:[...eo,...je,...Kt],SWIMLANE:[...eo,...je,...Kt],TICKET:[...je,...Kt,...$n],FIELD:[...je,...$n],FIELD_LIST:[...je,...$n],TEXT:[...je]},qs=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ys=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!$t().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!Xr())return[f.HELP,f.INIT];if(n)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&zs.includes(i);return Gs[o].filter(d=>d===f.RENAME||d===f.DELETE||d===f.MOVE?a:!0)},j=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[f.NONE]:Ys(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...Qr(),"now","prev","next"],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...Gr],[f.TAG]:[...new Set([...Object.keys(Ze),...E.getExistingTags()])],[f.UNTAG]:[..._t()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...Wt()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:E.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:qs(n)}[e]??[]};import et from"chalk";import{decodeTime as to}from"ulid";var no=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"},ro=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())}`},Vt=e=>{try{return l("Decoded date",new Date(to(e)))}catch(t){return s("Decoding failed + "+t.message)}},_n=e=>{if(!e?.id)return null;try{return to(e.id)}catch{return null}};var Ce=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):s("Unable to find node in breadcrumb")};import Qe from"chalk";var Hn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Xs=(e,t,n)=>Math.max(t,Math.min(n,e)),Wn=(e,t,n)=>e+(t-e)*n,oo=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Js=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),u=0,m=0,g=0;a>=0&&a<1?(u=i,m=d):a>=1&&a<2?(u=d,m=i):a>=2&&a<3?(m=i,g=d):a>=3&&a<4?(m=d,g=i):a>=4&&a<5?(u=d,g=i):(u=i,g=d);let h=o-i/2;return[Math.round((u+h)*255),Math.round((m+h)*255),Math.round((g+h)*255)]},Zs=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Qs=(e,t,n)=>[Math.round(Wn(e[0],t[0],n)),Math.round(Wn(e[1],t[1],n)),Math.round(Wn(e[2],t[2],n))],gt=e=>{let n=oo(e)%360,r=Js(n,Hn.stringColor.saturation,Hn.stringColor.lightness);return Zs(r)},ea=e=>{let t=Hn.gradient.stops,n=Xs(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),a=o-i;return Qs(t[i],t[i+1],a)},jt=e=>oo(e.toLowerCase().trim())/4294967295,io=e=>{let t=jt(e);return ea(t)},ta=e=>{let[t,n,r]=io(e);return{normal:o=>Qe.bgRgb(t,n,r).black(o),cursor:o=>Qe.bgRgb(t,n,r).white.bold(o)}},Kn=e=>{let[t,n,r]=io(e);return{fg:o=>Qe.rgb(t,n,r)(o),fgCursor:o=>Qe.rgb(t,n,r).inverse(o),bg:o=>Qe.bgRgb(t,n,r).black(o),bgCursor:o=>Qe.bgRgb(t,n,r).white.bold(o)}},Vn=e=>ta(e).normal(` ${e} `),q=(e,t=Ze)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:gt(r)};var Ie={None:"none",Invalid:"invalid",Valid:"valid"};var na=["BOARD","TICKET","SWIMLANE"],jn=()=>{let e=v().selectedNode;return e?.context?na.includes(e?.context)?H():$({message:"Command not available in this context"}):$({message:"Missing target context"})},Z="<ENTER> to confirm",H=(e="",t=[])=>({message:e,validity:Ie.Valid,completionWordList:t}),$=({message:e,completionWordList:t=[]})=>({validity:Ie.Invalid,message:e,completionWordList:t}),vt=e=>e.length===0,Oe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(g=>g.startsWith(o.trim()))].sort((g,h)=>jt(g)-jt(h)).slice(0,r).map(Vn),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},zn=({modifier:e})=>{let t="confirm";return e===t?H(Z):$({message:vt(e)?`if you are certain, enter ${Vn(t)}`:"",completionWordList:[t]})},ra=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?H(Z):$({message:vt(n)?t:""}),oa=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?$({message:n}):H():$({message:vt(r)?t:""}),ft=({hint:e})=>({modifier:t,inputString:n})=>vt(t)&&vt(n)?$({message:e,completionWordList:[]}):H(Z),ia={[f.EXPORT]:()=>H(Z+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(Z);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return H(Z);let r=Ht(t);if(!t||!r)return $(n);let o=Ce(v().breadCrumb,"BOARD");if(c(o))return $({message:"Command is not applicable in this context"});let i=Vt(o.value.id);return c(i)?$({message:"Unable to peek: board id is not a valid ULID"}):Zr({date:r,horizonDate:i.value})?H(Z):$({message:et.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>H(Z+" and exit the application"),[f.INIT]:()=>H(Z),[f.FILTER]:e=>{if(e.modifier==="clear")return H();let t=a=>j(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return $({message:Oe({wordList:j(f.FILTER),inputString:e.inputString}),completionWordList:j(f.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?$({message:Oe({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):H():$({message:Oe({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=j(f.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?H():$({message:Oe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>oa({list:j(f.NEW),hint:Oe({wordList:j(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>H(Z),[f.HELP]:()=>H(Z),[f.RENAME]:()=>{let e=jn();return e.validity==="invalid"?e:H(Z)},[f.DELETE]:e=>{let t=jn();return t.validity==="invalid"?t:zn(e)},[f.CLOSE_ISSUE]:e=>zn(e),[f.RE_OPEN_ISSUE]:e=>zn(e),[f.MOVE]:e=>{let t=jn();return t.validity==="invalid"?t:ft({hint:Oe({prefix:"hey hacker! These commands are blocked for you... ",wordList:j(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=E.getExistingTags().map(n=>` ${et.bgHex(q(n))(" "+n+" ")} `).slice(0,10);return ft({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=_t();if(c(t))return $({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${et.bgHex(q(r))(" "+r+" ")} `).slice(0,10);return n.length?ft({hint:" ... "+n.join("")})(e):$({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=E.getExistingAssignees().map(n=>` ${et.bgHex(q(n))(" "+n+" ")} `).slice(0,10);return ft({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=Wt();if(c(t))return $({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${et.bgHex(q(r))(" "+r+" ")} `).slice(0,10);return n.length?ft({hint:"remove assignee... "+n.join("")})(e):$({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=j(f.SET_EDITOR);return e.modifier?H(Z):$({message:Oe({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?H():$({message:`Enter a username. Saved in ${et.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>ra({list:j(f.SET_VIEW),hint:Oe({wordList:j(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>H(Z)},so=Object.fromEntries(Object.entries(ia).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var ao=["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 M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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"};var co=e=>Object.values(f).includes(e),lo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:u}=so[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?j(n):ao;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?zr(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var uo=e=>{let t=e.trimStart(),n=aa(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=da(e),d=co(r)?r:null,u=d!==null,m=r!=="",g=d?j(d)??[]:[],h=d&&g.includes(o)?o:"",C="word";n.length===0||n.length===1&&!i?C="command":(n.length===1&&i||n.length===2&&!i)&&(C="modifier");let I=i?"":a,A=sa(t,d,h);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:d,isCommandKeyword:u,isLastWordCompleted:i,modifier:h,target:C,inputToMatch:I,inputString:A}},sa=(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},aa=e=>e.trim()?e.trim().split(/\s+/):[],da=e=>e.trimEnd().split(/\s+/).at(-1)??"";var mo=" ",Y={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ie.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Gn=new Set,po=()=>{for(let e of Gn)e()},go=e=>(Gn.add(e),()=>Gn.delete(e)),be=e=>{let n=e(Y),r=uo(n.value),o=n.cursorPosition===n.value.length;Y={...n,commandMeta:lo(r,o)},po()},xt=({message:e,status:t})=>{let n=structuredClone(Y);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Y=n,po(),l(e,null)},qn=e=>{be(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Yn=e=>{be(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},fo=()=>{be(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}})},vo=()=>{be(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},V=e=>{be(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),a=i+o,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},xo=()=>{be(e=>({...e,commandIsPending:!0}))},yo=({addToHistory:e=!0})=>{be(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ca()},ho=()=>{be(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}})},No=()=>{be(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ca=()=>V(()=>""),te=()=>Y,zt=()=>{let[e,...t]=Y.value.split(mo);return t.join(mo).trim()};var la=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",ua=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",ma=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Eo=(e,t)=>{if(ua(e,e.sequence))return x.MoveCursorLeftOfWord;if(ma(e,e.sequence))return x.MoveCursorRightOfWord;if(la(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={Sync:"sync",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",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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function pa(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function ga(e,t,n){let r=v().currentNode.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 Co(e,t){let n=te();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===p.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===p.COMMAND_LINE)return Eo(e,n.value);let r=pa(e);if(r){let o=t===p.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return ga(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Io=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case f.EXIT:return M.Exit;case f.EXPORT:return M.Export;case f.INIT:return M.Init;case f.DELETE:return M.Delete;case f.SET_DESCRIPTION:return M.Edit;case f.HELP:return M.ViewHelp;case f.RE_OPEN_ISSUE:return M.ReopenIssue;case f.CLOSE_ISSUE:return M.CloseIssue;case f.TAG:return M.TagTicket;case f.UNTAG:return M.UntagTicket;case f.ASSIGN:return M.AssignUserToTicket;case f.UNASSIGN:return M.UnassignUserFromTicket;case f.RENAME:return M.Rename;case f.NEW:return M.NewItem;case f.FILTER:return M.Filter;case f.MOVE:return M.Move;case f.PEEK:return M.Peek;case f.SET_USERNAME:return M.SetUserName;case f.SET_EDITOR:return M.SetEditor;case f.SET_VIEW:return M.SetView;case f.SYNC:return M.Sync;default:return M.None}};import{ulid as W}from"ulid";import{spawnSync as Ca}from"node:child_process";import Ia from"node:os";import To from"node:path";import{ulid as ba}from"ulid";import{accessSync as fa,copyFileSync as va,existsSync as Gt,mkdirSync as bo,readdirSync as So,readFileSync as xa,renameSync as ya,rmSync as ha,statSync as Ao,unlinkSync as Na,writeFileSync as Ea}from"node:fs";import tt from"node:path";var se={writeToFile:(e,t)=>{try{let n=tt.dirname(e);Gt(n)||bo(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Ea(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return xa(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=se.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 Gt(e)&&Ao(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await fa(e),!0}catch{return!1}},mkDir:e=>bo(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=tt.parse(t);for(;;){let r=tt.join(t,e);try{if(Gt(r)&&Ao(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=tt.dirname(t)}return null},readFirstJSON(e){try{if(!se.dirExists(e))return null;let t=So(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=tt.join(e,t);return se.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return se.dirExists(e)?So(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Na(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{ha(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(tt.dirname(t)),!n?.overwrite&&Gt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{ya(e,t)}catch(r){if(r?.code==="EXDEV"){va(e,t),this.rmFile(e);return}throw r}}};function Sa(){let{preferredEditor:e}=pe(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Aa(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function wo(e){let t=To.join(Ia.tmpdir(),"epiq");se.mkDir(t);let n=To.join(t,ba());se.writeToFile(n,e??"");let r=Sa();for(let o of r){let i=Aa(o,n),a=Ca(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=se.readFile(n);if(d==null)return s("Unable to read edited file");let u=d.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as Ta,ulid as qt}from"ulid";var Yt=Ta(),Ro=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=Yt(),i=Yt(),a=Yt(),d=Yt();return[{id:qt(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:qt(),userId:n,userName:r,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:qt(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:qt(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Qt from"node:fs";import tr from"node:path";import{decodeTime as $a}from"ulid";import{z as er}from"zod";import Pa from"node:fs";import La from"node:path";import{decodeTime as Da,monotonicFactory as Fa}from"ulid";import{z as ht}from"zod";import Xn from"node:fs";import nt from"node:path";var Jn=process.env.IS_LOCAL==="true",Be=".epiq",de=".epiq-global",Xt="events",wa="epiq",Mo=e=>nt.join(e,wa),Ra=e=>nt.join(e,Be),yt=e=>nt.join(Ra(e),Xt),Ma=e=>{let t=nt.join(e,Be);return Xn.existsSync(t)&&Xn.statSync(t).isDirectory()},ge=e=>{let t=nt.resolve(e);for(;;){if(Ma(t))return l("Resolved closest .epiq root",t);let n=nt.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Po=e=>{let t=yt(e);try{return Xn.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};var Lo=e=>({action:e.action,payload:e.payload});var Fo=1,Do=Fa(),ka=ht.tuple([ht.string().min(1),ht.string().min(1).nullable()]),Oa=ht.looseObject({v:ht.literal(Fo),id:ka}),Zn=e=>{let t=Oa.safeParse(e);return t.success?l("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Jt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",X=()=>{let{userName:e,userId:t}=pe();return e?t?e.trim()?l("Successfully resolved actor ID",{userId:Jt(t),userName:Jt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Qn=({userId:e,userName:t})=>`${Jt(e)}.${Jt(t)}.jsonl`,Ba=(e,{userId:t,userName:n})=>{let r=Qn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=La.join(yt(e),r);return l("Successfully resolved event log path",i)},Ua=(e,t)=>{let n={[e.action]:e.payload,v:Fo,id:t};return Zn(n)};function Zt({event:e,rootDir:t=process.cwd()}){try{let n=ge(t);if(c(n))return n;let r=Po(n.value);if(c(r))return r;let o=Ba(n.value,{userId:e.userId,userName:e.userName});if(c(o))return o;let i=ko(n.value);if(c(i))return s(i.message);let a=i.value?Do(Math.max(Date.now(),Da(i.value)+1)):Do(),d=Ua(Lo(e),[a,i.value]);return c(d)?s(d.message):(Pa.appendFileSync(o.value,`${JSON.stringify(d.value)}
|
|
3
|
+
`,"utf8"),l("Event persisted",{path:o.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}var _a=er.object({userId:er.string().min(1).default("unknown"),userName:er.string().min(1).default("unknown")}),Wa=e=>{let[t,n]=tr.basename(e,".jsonl").split("."),r=_a.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):s(`Invalid event file name ${tr.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ha=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Ka=(e,t)=>t in e,Va=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),ja=e=>{let{userId:t,userName:n,...r}=e,o=Ha(r);if(c(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Ka(r,i)?l("Decoded persisted event",Va({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},en=e=>{if(!Qt.existsSync(e))return l("Event file missing",[]);let t=Wa(e);if(c(t))return s(t.message);let n=Qt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
4
|
+
`)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let d=Zn(a);if(c(d))return s(`${d.message} in ${e}: ${i}`);r.push({...d.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function Oo(e){let t=yt(e);if(!Qt.existsSync(t))return s("No events found");let n=Qt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>tr.join(t,o)),r=[];for(let o of n){let i=en(o);if(c(i))return s(i.message);r.push(...i.value)}return l("All events loaded",za(r))}function Nt(e){let t=Oo(e);if(c(t))return s(t.message);let n=[];for(let r of t.value){let o=ja(r);if(c(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return l("Loaded merged events",n)}function ko(e=process.cwd()){let t=Oo(e);return c(t)?s(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var za=e=>{let t=new Map;for(let d of e){let u=d.id[1]??null,m=t.get(u)??[];m.push(d),t.set(u,m)}for(let d of t.values())d.sort((u,m)=>u.id[0].localeCompare(m.id[0]));let n=[],r=new Set;a(t.get(null)??[]);let o=!0;for(;o;){o=!1;for(let d=0;d<n.length;d++){let u=n[d];if(!u)continue;let m=(t.get(u.id[0])??[]).filter(g=>!r.has(g.id[0]));if(m.length!==0){n.splice(d+1,0,...m);for(let g of m)r.add(g.id[0]);o=!0,d+=m.length}}}let i=e.filter(d=>!r.has(d.id[0])).sort((d,u)=>d.id[0].localeCompare(u.id[0]));return n.push(...i),n;function a(d){for(let u of d)r.has(u.id[0])||(n.push(u),r.add(u.id[0]))}},Bo=(e,t)=>{let n=e.findIndex(r=>{try{return $a(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Uo=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};var Ga=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[rt,tn]=Ga;var L=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),qa={"init.workspace":e=>{let{id:t,name:n}=e.payload,r=ee.workspace(t,n);nr(r);let o=E.createNodeAtPosition(r);return c(o)?L(o.message??"Failed to initialize workspace",e):l("Workspace initialized",{action:e.action,result:o.value})},"add.workspace":e=>{let{id:t,name:n}=e.payload,r=ee.workspace(t,n),o=E.createNodeAtPosition(r);return c(o)?L(o.message??"Failed to add workspace",e):l("Added workspace",{action:e.action,result:o.value})},"add.board":e=>{let{id:t,name:n,parent:r}=e.payload,o=E.createNodeAtPosition(ee.board(t,n,r));return c(o)?L(o.message??"Unable to create board",e):l("Added board",{action:e.action,result:o.value})},"add.swimlane":e=>{let{id:t,name:n,parent:r}=e.payload,o=E.createNodeAtPosition(ee.swimlane(t,n,r));return c(o)?L(o.message??"Unable to create swimlane",e):l("Added swimlane",{action:e.action,result:o.value})},"add.issue":e=>{let{id:t,name:n,parent:r}=e.payload,o=E.createNodeAtPosition(ee.ticket(t,n,r));return c(o)?L(o.message??"Unable to create issue",e):l("Added issue",{action:e.action,result:o.value})},"add.field":e=>{let{id:t,name:n,parent:r,val:o}=e.payload,i=E.createNodeAtPosition(ee.field(t,n,r,{value:o},n.includes("Description")?"vertical":"horizontal"));return c(i)?L(i.message??`Unable to create field: ${n}`,e):l("Added field",{action:e.action,result:i.value})},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=E.renameNode(t,n);return c(o)?L(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=E.tombstoneNode(t);return c(n)?L(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=E.createTag({id:t,name:n});return c(r)?L(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return c(r)?L(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r}=e.payload,o=E.tag(n,r,t);return c(o)?L(o.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:o.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=E.untag(t,n);return c(r)?L(r.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r}=e.payload,o=E.assign(r,n,t);return c(o)?L(o.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:o.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=E.unassign(t,n);return c(r)?L(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,pos:r}=e.payload,o=E.moveNode({id:t,parentId:n,position:r});return c(o)?L(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=E.editValue(t,n);return c(r)?L(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t}=e.payload,n=E.getNode(t);if(!n)return L("Unable to locate issue",e);if(!xe(n))return L("Can only close issues",e);let r=E.getNode(rt);if(!r)return L("Unable to locate target swimlane",e);if(r.id===n.parentNodeId)return L("Cannot close closed issue",e);let i=E.moveNode({id:t,parentId:r.id});return c(i)?L(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:i.value})},"reopen.issue":e=>{let{id:t}=e.payload,n=E.getNode(t);if(!n)return L("Unable to locate issue",e);if(!xe(n))return L("Can only reopen issues",e);let r=E.getNode(rt);if(!r)return L("Unable to locate closed swimlane",e);if(!(n.parentNodeId===r.id))return L("Issue is not closed",e);let i=Uo(n);if(!i)return L("Unable to resolve previous parent from issue history",e);if(i===r.id)return L("Previous parent resolves to closed swimlane",e);if(!E.getNode(i))return L("Previous parent no longer exists",e);let d=E.moveNode({id:t,parentId:i});return c(d)?L(d.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:d.value})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return c(n)?L(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})}},Ya=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Xa=e=>{switch(e.action){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"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function ot(e,t=!1){let n=qa[e.action](e);if(c(n))return n;t||([...new Set(Xa(e))].forEach(a=>Ya(a,e)),ie(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?L("Invalid user ID format",e):(E.createContributor({name:o,id:r}),n)}var ze=e=>e.map(t=>ot(t));function J(e){let t=ot(e);if(t.status!==Ee.Success)return t;let n=Zt({event:e});return c(n)?n:t}function $o(e){return e.map(t=>J(t))}import vd from"node:fs";import{createHash as td}from"node:crypto";import Ct from"node:fs";import nd from"node:os";import le from"node:path";var rr=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let d=e(...i).then(u=>(c(u)&&n.delete(a),u));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import Et from"fs";import Wo from"path";import Ja from"util";var _o=1e3,Ho=()=>{let e=process.cwd(),t=ge(e);if(!c(t))return Wo.join(t.value,Be,"log","epiq.log")};function Za(){if(!Jn)return;let e=Ho();if(e===void 0||!Et.existsSync(e))return;let n=Et.readFileSync(e,"utf8").split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=_o)return;let r=n.slice(-_o).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;
|
|
8
|
-
`;
|
|
9
|
-
`);u(n?{stdout:a,stderr:g,exitCode:124}:s(g))},
|
|
7
|
+
`;Et.writeFileSync(e,r,"utf8")}function or(e,t,n=!1){if(!Jn)return;let r=Ho();if(!r)return;let o=Ja.format(...t),i=new Date,d=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
8
|
+
`;Et.mkdirSync(Wo.dirname(r),{recursive:!0}),Et.appendFileSync(r,d,"utf8"),Za()}var ae={info(...e){or("[Info]",e,!1)},debug(...e){or("->",e,!0)},error(...e){or("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=ae;import{spawn as Qa}from"node:child_process";import ir from"node:fs";import jo from"node:path";var O="epiq/events",ce="origin";var z={stage:({cwd:e,pathspec:t})=>k({args:["add",t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>k({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>k({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>k({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>k({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 k({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>k({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>k({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>k({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>k({args:["worktree","prune"],cwd:e})};var Ko=15e3,ed={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},zo=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!ir.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(s(g));return}let o=Qa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:ed}),i=!1,a="",d="",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 ${Ko}ms`].join(`
|
|
9
|
+
`);u(n?{stdout:a,stderr:g,exitCode:124}:s(g))},Ko);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{a+=g}),o.stderr.on("data",g=>{d+=g}),o.on("error",g=>{if(n){u({stdout:a,stderr:g.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
|
|
10
10
|
`)))}),o.on("close",g=>{let h=g??1;if(n){u({stdout:a,stderr:d,exitCode:h});return}if(h!==0){u(s([`git ${e.join(" ")}`,d.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
|
|
11
|
-
`)));return}u(
|
|
12
|
-
${n.message}`);let r=await k({args:["rev-parse","HEAD"],cwd:e});return
|
|
13
|
-
${r.message}`):
|
|
14
|
-
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(
|
|
15
|
-
${r.message}`);let o=await z.pullRebase({cwd:e,remote:
|
|
16
|
-
${o.message}`):
|
|
17
|
-
`+e.message);let t=
|
|
18
|
-
`+t.message):
|
|
11
|
+
`)));return}u(l("Git command succeeded",{stdout:a,stderr:d,exitCode:h}))})}),k=({args:e,cwd:t})=>zo({args:e,cwd:t,allowFail:!1}),it=({args:e,cwd:t})=>zo({args:e,cwd:t,allowFail:!0}),nn=async({cwd:e,message:t})=>{let n=await z.commit({cwd:e,message:t});if(c(n))return s(`Failed to create commit
|
|
12
|
+
${n.message}`);let r=await k({args:["rev-parse","HEAD"],cwd:e});return c(r)?s(`Commit created, but failed to read HEAD SHA
|
|
13
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},sr=async e=>{let t=await Qo(e);if(c(t))return s(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>ir.existsSync(jo.join(n,i)));return l("Checked for in-progress Git operation",o.length>0)},ar=async({repoRoot:e})=>{let n=(await it({args:["remote","get-url",ce],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},rn=async({repoRoot:e,branch:t})=>{let n=await it({args:["ls-remote","--heads",ce,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${ce}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Go=async({repoRoot:e,branch:t})=>{let n=await it({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Vo=e=>{try{return ir.realpathSync.native(e)}catch{return jo.resolve(e)}},qo=async({repoRoot:e,worktreeRoot:t})=>{let n=await k({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=Vo(t),o=n.value.stdout.split(`
|
|
14
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Vo).includes(r);return l("Checked worktree registration",o)},dr=async e=>{let t=await it({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},on=async e=>{let t=await k({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return c(t)?s(t.message):l("Resolved current branch",t.value.stdout.trim())},Yo=async e=>{let t=await k({args:["rev-parse","--short","HEAD"],cwd:e});return c(t)?s(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Xo=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),sn=async({cwd:e,branch:t})=>{let n=await rn({repoRoot:e,branch:t});if(c(n))return s(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await z.fetch({cwd:e,remote:ce,branch:t});if(c(r))return s(`Failed to fetch ${t}
|
|
15
|
+
${r.message}`);let o=await z.pullRebase({cwd:e,remote:ce,branch:t});return c(o)?s(`Failed during pull --rebase
|
|
16
|
+
${o.message}`):l("Pulled with rebase",!0)},Jo=async e=>{let t=await k({args:["status","--porcelain"],cwd:e});return c(t)?s(t.message):l("Checked state branch changes",t.value.stdout.trim().length>0)},Zo=async e=>{let t=await on(e);return c(t)?s(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var ei="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ti=e=>le.join(Be,Xt,e),rd=e=>td("sha1").update(le.resolve(e)).digest("hex").slice(0,12),ni=()=>le.join(nd.homedir(),de),ri=()=>le.join(ni(),"worktrees"),oi=e=>le.join(ri(),rd(e)),od=e=>le.join(e,Be),Ge=e=>le.join(od(e),Xt),cr=({root:e,fileName:t})=>le.join(Ge(e),t),It=e=>{try{return Ct.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},ii=()=>{let e=It(ni());if(c(e))return s(`Ensure epiq home failed.
|
|
17
|
+
`+e.message);let t=It(ri());return c(t)?s(`Ensure worktrees dir failed.
|
|
18
|
+
`+t.message):l("Ensured epiq storage",!0)},si=e=>{Ct.existsSync(e)&&(ae.debug("[sync] remove path",e),Ct.rmSync(e,{recursive:!0,force:!0}))},ai=e=>{let t=Ge(e);if(!Ct.existsSync(t))return l("Events dir missing",[]);let n=Ct.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return l("Listed event files",n)},di=(e,t)=>{for(let n of[Ge(e),Ge(t)]){let r=It(n);if(c(r))return s(r.message)}return l("Ensured state branch",void 0)},ci=async e=>{let t=await k({args:["ls-tree","--name-only","HEAD"],cwd:e});if(c(t))return s(`ensure state branch is storage only failed
|
|
19
19
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
20
|
-
`).filter(Boolean).filter(a=>a!==Be);if(r.length===0)return
|
|
21
|
-
${o.message}`);let i=await
|
|
22
|
-
`).some(d=>{let u=d.trim();return u===r||u===r+"/"})?
|
|
20
|
+
`).filter(Boolean).filter(a=>a!==Be);if(r.length===0)return l("State branch is storage-only",!1);let o=await k({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(c(o))return s(`Failed to clean storage branch
|
|
21
|
+
${o.message}`);let i=await nn({cwd:e,message:"[epiq:repair-storage-branch]"});return c(i)?s(i.message):l("Cleaned storage branch",!0)},li=rr(async(e=process.cwd())=>{let t=await k({args:["rev-parse","--show-toplevel"],cwd:e});return c(t)?s("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>le.resolve(e)),Qo=rr(async e=>{let t=await k({args:["rev-parse","--git-dir"],cwd:e});if(c(t))return s(t.message);let n=t.value.stdout.trim(),r=le.isAbsolute(n)?n:le.join(e,n);return l("Resolved git dir",r)},e=>le.resolve(e));import Ue from"node:fs";import bt from"node:path";var pi=async e=>{let t=bt.join(e,".gitignore"),n=Ue.existsSync(t)?Ue.readFileSync(t,"utf8"):"",r=".epiq";return n.split(`
|
|
22
|
+
`).some(d=>{let u=d.trim();return u===r||u===r+"/"})?l(`${r} already ignored`,!1):(n=n.trimEnd()+`
|
|
23
23
|
|
|
24
24
|
# [epiq]: hydrated state is never to be committed
|
|
25
25
|
${r}
|
|
26
26
|
`,Ue.writeFileSync(t,n+`
|
|
27
|
-
`,"utf8"),ae.info(`Added ${r} to .gitignore (epiq local cache)`),
|
|
28
|
-
${t.message}`);let n=t.value.stdout.trim(),r=await k({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return
|
|
29
|
-
${r.message}`):
|
|
30
|
-
`+t.message);if(t.value)return
|
|
31
|
-
`+n.message);if(!n.value)return
|
|
32
|
-
`+r.message);if(!r.value)return
|
|
33
|
-
${o.message}`);let i=await k({args:["branch","--track",O,`${
|
|
34
|
-
${i.message}`):
|
|
35
|
-
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return
|
|
36
|
-
`+n.message);Ue.existsSync(t)&&!Ue.existsSync(
|
|
37
|
-
${r.message}`):
|
|
38
|
-
${d.message}`)}if(o&&!Ue.existsSync(o)){ae.info("Pruning stale state branch worktree");let d=await z.worktreePrune({cwd:e});if(
|
|
39
|
-
${d.message}`)}let i=await
|
|
40
|
-
${d.message}`)}return
|
|
41
|
-
${n.message}`):
|
|
42
|
-
${o.message}`);let i=await z.setUpstream({cwd:e,branch:O,upstream:`${
|
|
43
|
-
${i.message}`):
|
|
44
|
-
${n.message}`):
|
|
45
|
-
`+n.message):
|
|
46
|
-
${n.message}`):
|
|
27
|
+
`,"utf8"),ae.info(`Added ${r} to .gitignore (epiq local cache)`),l(`${r} ignored`,!0))},gi=async e=>{if((await it({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);ae.info("Creating initial commit");let n=await z.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return c(n)?s(n.message):l("Created initial commit",!0)},ui=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",id=async e=>{let t=await on(e);if(c(t))return s(t.message);let n=await Yo(e);if(c(n))return s(n.message);let r=`[epiq:sync:${ui(t.value)}:${ui(n.value)}]`;return l("Built sync commit message",r)},mi=async e=>{ae.info(`Creating ${O}`);let t=await k({args:["commit-tree",ei,"-m","[epiq:init-state-branch]"],cwd:e});if(c(t))return s(`Failed to create state branch commit
|
|
28
|
+
${t.message}`);let n=t.value.stdout.trim(),r=await k({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return c(r)?s(`Failed to create ${O}
|
|
29
|
+
${r.message}`):l("Created state branch",!0)},sd=async({repoRoot:e})=>{let t=await Go({repoRoot:e,branch:O});if(c(t))return s(`Ensure local state branch failed
|
|
30
|
+
`+t.message);if(t.value)return l("Local state branch already exists",!1);let n=await ar({repoRoot:e});if(c(n))return s(`Ensure local state branch failed
|
|
31
|
+
`+n.message);if(!n.value)return mi(e);let r=await rn({repoRoot:e,branch:O});if(c(r))return s(`Ensure local state branch failed
|
|
32
|
+
`+r.message);if(!r.value)return mi(e);let o=await z.fetch({cwd:e,remote:ce,branch:O});if(c(o))return s(`Failed to fetch ${O} from remote
|
|
33
|
+
${o.message}`);let i=await k({args:["branch","--track",O,`${ce}/${O}`],cwd:e});return c(i)?s(`Failed to create local ${O} from remote
|
|
34
|
+
${i.message}`):l("Created local state branch from remote",!0)},ad=async({repoRoot:e,branch:t})=>{let n=await k({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=n.value.stdout.split(`
|
|
35
|
+
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},dd=async({repoRoot:e,stateBranchRoot:t})=>{let n=It(bt.dirname(t));if(c(n))return s(`Failed to create state branch worktree
|
|
36
|
+
`+n.message);Ue.existsSync(t)&&!Ue.existsSync(bt.join(t,".git"))&&(ae.info("Removing broken state branch worktree path"),si(t)),ae.info("Creating state branch worktree");let r=await z.worktreeAdd({cwd:e,worktreeRoot:t,branch:O});return c(r)?s(`Failed to create state branch worktree
|
|
37
|
+
${r.message}`):l("Created state branch worktree",!0)},cd=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ad({repoRoot:e,branch:O});if(c(n))return s(n.message);let r=bt.resolve(t),o=n.value?bt.resolve(n.value):null;if(o&&o===r&&Ue.existsSync(o))return l("State branch already checked out in expected worktree",!1);if(o&&o!==r){ae.info("Moving state branch worktree to expected location");let d=await z.worktreeRemove({cwd:e,worktreeRoot:o});if(c(d))return s(`Failed to remove existing state branch worktree
|
|
38
|
+
${d.message}`)}if(o&&!Ue.existsSync(o)){ae.info("Pruning stale state branch worktree");let d=await z.worktreePrune({cwd:e});if(c(d))return s(`Failed to prune stale worktrees
|
|
39
|
+
${d.message}`)}let i=await qo({repoRoot:e,worktreeRoot:t});if(c(i))return s(i.message);let a=Ue.existsSync(t);if(i.value&&a)return l("State branch worktree already exists",!1);if(i.value&&!a){ae.info("Pruning missing registered state branch worktree");let d=await z.worktreePrune({cwd:e});if(c(d))return s(`Failed to prune stale worktrees
|
|
40
|
+
${d.message}`)}return dd({repoRoot:e,stateBranchRoot:t})},ld=async e=>{let t=await on(e);if(c(t))return s(t.message);if(t.value===O)return l("State branch already checked out",!1);let n=await z.checkout({cwd:e,branch:O});return c(n)?s(`Failed to checkout ${O}
|
|
41
|
+
${n.message}`):l("Checked out state branch",!0)},ud=async e=>{let t=await dr(e);if(c(t))return s(t.message);if(t.value)return l("State branch upstream already configured",!1);let n=await ar({repoRoot:e});if(c(n))return s(n.message);if(!n.value)return l("No remote available for state branch upstream",!1);let r=await rn({repoRoot:e,branch:O});if(c(r))return s(r.message);if(!r.value)return l("Remote state branch missing; upstream will be configured on first push",!1);ae.info(`Configuring ${O} upstream`);let o=await z.fetch({cwd:e,remote:ce,branch:O});if(c(o))return s(`Failed to fetch ${O}
|
|
42
|
+
${o.message}`);let i=await z.setUpstream({cwd:e,branch:O,upstream:`${ce}/${O}`});return c(i)?s(`Failed to set state branch upstream
|
|
43
|
+
${i.message}`):l("Configured state branch upstream",!0)},fi=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=await z.stage({cwd:e,pathspec:ti(t)});return c(n)?s(`Failed to stage state branch own event file
|
|
44
|
+
${n.message}`):l("Staged state branch own event file",void 0)},vi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await id(e);return c(n)?s(`Create state branch sync commit failed
|
|
45
|
+
`+n.message):nn({cwd:t,message:n.value})},lr=async e=>{let t=await dr(e);if(c(t))return s(t.message);let n=t.value?await z.push({cwd:e}):await z.push({cwd:e,remote:ce,branch:O,setUpstream:!0});return c(n)?s(`Failed during state branch push
|
|
46
|
+
${n.message}`):l("Pushed state branch",!0)},xi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[ii(),await sd({repoRoot:e}),await cd({repoRoot:e,stateBranchRoot:t}),await ld(t),await ci(t),n?await ud(t):l("Skipped state branch upstream bootstrap",!1)];for(let i of o){if(c(i))return s(i.message);r=r||!!i.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import an from"node:fs";import mr from"node:path";import{decodeTime as md}from"ulid";var ur=e=>{let[t,n]=e.id;return`${t}:${n??""}`},yi=e=>{let[t]=e.id;return md(t)},pd=e=>{let{userId:t,userName:n,...r}=e;return r},gd=e=>e.length===0?"":e.map(t=>JSON.stringify(pd(t))).join(`
|
|
47
47
|
`)+`
|
|
48
|
-
`,
|
|
49
|
-
`),c("Config written",null)}catch{return s(`Unable to write ~/${de}/config.json`)}},rn=e=>{let t=Ei();if(l(t))return s("Failed to read existing config");let n={...t.value,...e};return Ci(n)},Ii=()=>{let e=ur(),t=mr();if(l(t))return s(`Unable to create ~/${de}`);if(!(se.readFile(e)!==null)){let u=Ci(sd);if(l(u))throw new Error(`Unable to create ~/${de}/config.json`)}let r=Ei();if(l(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:d}=r.value;return!i||!a?s(`User name or ID not configured in ~/${de}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:d??!1})};var Si=()=>{let{currentNode:e,selectedIndex:t}=v(),n=w(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},bi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Ai=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=w(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),c("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let a=w(i.id).findIndex(d=>d.id===o.id);if(a>=0)return D.navigate({currentNode:i,selectedIndex:a}),c("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=w(n.id);return D.navigate({currentNode:n,selectedIndex:bi(e.selectedIndex,o.length)}),c("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=w(o.id);return D.navigate({currentNode:o,selectedIndex:bi(e.selectedIndex,i.length)}),c("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};var Ti=e=>Object.values(v().tags).find(t=>t.name===e),wi=e=>Object.values(v().contributors).find(t=>t.name===e),Ri=[{systemOnly:!0,intent:M.Move,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{modifier:t}=ee().commandMeta,n=()=>{let d=$e();if(!d)return s("No pending move state");let u=d.payload.id;if(!v().nodes[u])return s("Moved node not found");let g=d.payload.parent,h=v().nodes[g];if(!h)return s("Move parent not found");let C=w(g).findIndex(I=>I.id===u);return C===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:h,selectedIndex:C}),c("Synchronized navigation to moved node",null))},r=d=>{if(l(d))return s(d.message);let u=n();return l(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=w(o.id)[i];if(!a)return T({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let d=w(a.parentNodeId),u=d.findIndex(({id:I})=>I===a.id);if(u===-1)return s("Target not found among siblings");let m=d[u-1],g=d[u+1],h=g!=null?{at:"before",sibling:g.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"};it({id:W(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,pos:h},...e.value}),T({mode:f.MOVE});let C=n();return l(C)?s(C.message):c("Move initialized",null)}if(t==="next")return T({mode:f.MOVE}),r(cr(1));if(t==="previous")return T({mode:f.MOVE}),r(cr(-1));if(t==="to-next")return T({mode:f.MOVE}),r(lr(1));if(t==="to-previous")return T({mode:f.MOVE}),r(lr(-1));if(t==="confirm"){T({mode:f.DEFAULT});let d=$e();if(!d)return s("No pending move to confirm");let u=X(d);if(l(u))return u;let m=n();return l(m)?s(m.message):(it(null),c("Moved item",null))}return t==="cancel"?(it(null),T({mode:f.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];return r?X({id:W(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.Edit,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let t=Ee(v().breadCrumb,"TICKET");if(l(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!w(n.id)[o])return s("No selected field");let a=w(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let d=a.props.value;if(typeof d!="string")return s("Selected field is not editable text");let u=Co(d);if(l(u))return s("Failed to edit field");let m=u.value;return m===d?c("No changes made",null):a.title==="Description"?X({id:W(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?X({id:W(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>j(p.FILTER).map(u=>u.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return oe(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:f.DEFAULT})),c("Viewing help",null)}},{intent:M.ViewHelp,mode:f.COMMAND_LINE,action:()=>(T({mode:f.HELP}),c("Viewing help",null))},{intent:M.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!r.parentNodeId)return s("No target parent found");if(!ve(r))return s("Cannot close in this context");let o=X({id:W(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.value});return l(o)?o:c("Viewing help",null)}},{intent:M.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):ke(r.id,"TICKET");if(l(o))return s("Cannot reopen in this context");let i=o.value,a=X({id:W(),action:"reopen.issue",payload:{id:i.id},...e.value});return l(a)?a:c("Issue reopened",null)},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.SetUserName,mode:f.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=pe(),r=Ht()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??W();if(!o||!i)return s("Unable to resolve user name or id");let a=rn({userName:o,userId:i,preferredEditor:t??""});return l(a)?a:(Je({userName:o,userId:i}),T({mode:f.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:M.Init,mode:f.COMMAND_LINE,action:()=>{let e=gr();if(l(e))return e;let{rootNodeId:t,nodes:n}=v();return D.navigate({currentNode:n[t],selectedIndex:0}),T({mode:f.DEFAULT}),c("Project initialized",null)}},{intent:M.SetEditor,mode:f.COMMAND_LINE,action:()=>{let e=Ht()?.trim();if(!e)return s("No editor provided");let t=rn({preferredEditor:e});return l(t)?t:(Je({preferredEditor:e}),T({mode:f.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:f.COMMAND_LINE,action:()=>{let e=ee().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=rn({autoSync:t});return l(n)?n:(Je({autoSync:t}),T({mode:f.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=J();if(l(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=d=>{let u=X(d);if(l(u))return u;let m=E.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let g=E.getNode(m.parentNodeId);return g?(D.navigate({currentNode:g,selectedIndex:E.getSiblings(m.parentNodeId).findIndex(({id:h})=>h===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=v(),u=E.getNode(d);return u?a({id:W(),action:"add.board",payload:{id:W(),name:t.inputString,parent:u.id},...n.value}):s("Workspace not found")}if(t.modifier==="swimlane"){let d=Ee(r,"BOARD");return l(d)?s("Unable to add swimlane in this context"):a({id:W(),action:"add.swimlane",payload:{id:W(),name:t.inputString,parent:d.value.id},...n.value})}if(t.modifier==="issue"){let d=w(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let I=Ee(r,"SWIMLANE");return l(I)?null:I.value})();if(!u)return s("Unable to add issue in this context");let m=Io({name:t.inputString,parent:u.id,user:n.value}),g=Lo(m);if(g.some(I=>l(I)))return s("Issue create failed: "+g.filter(l).map(I=>I.message).filter(Boolean).join(", "));let h=g[0];if(!h||l(h))return s("Issue creation failed");let C=m[0]?.payload.id;return C?(D.navigate({currentNode:u,selectedIndex:E.getSiblings(u.id).findIndex(({id:I})=>I===C)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.SetView,mode:f.COMMAND_LINE,action:()=>{let{commandMeta:e}=ee();return e.validity===Ce.Invalid?s("Invalid command "+Ne):(oe(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.Rename,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Ht();return o?X({id:W(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.UntagTicket,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=Ti(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=ke(i.id,"TICKET");if(l(a))return s("Unable to untag issue in this context");let d=a.value,u=E.getFieldByTitle(d.id,"Tags");if(!u)return s("Unable to locate tags field");let m=w(u.id).find(g=>g.props?.value===o.id);return m?X({id:W(),action:"untag.issue",payload:{id:m.id,target:d.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=w(i.id)[o];if(!a)return s("Invalid tag target");let d=ke(a.id,"TICKET");if(l(d))return s("Unable to tag issue in this context");let u=d.value,m=Ti(r),g;if(m)g=m.id;else{let I=W(),b=X({id:W(),action:"create.tag",payload:{id:I,name:r},userId:e.value.userId,userName:e.value.userName});if(l(b))return b;g=b.value.result.id}let h=E.getFieldByTitle(u.id,"Tags");return h?w(h.id).some(I=>I.props?.value===g)?s("Already tagged with that tag"):X({id:W(),action:"tag.issue",payload:{id:W(),target:u.id,tagId:g},...e.value}):s("Unable to locate tags field")},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=w(i.id)[o];if(!a)return s("Invalid assign target");let d=ke(a.id,"TICKET");if(l(d))return s("Unable to assign issue in this context");let u=d.value,m=wi(r),g;if(m)g=m.id;else{let I=W(),b=X({id:W(),action:"create.contributor",payload:{id:I,name:r},userId:e.value.userId,userName:e.value.userName});if(l(b))return b;g=b.value.result.id}let h=E.getFieldByTitle(u.id,"Assignees");return h?w(h.id).some(I=>I.props?.value===g)?s("Assignee already assigned"):X({id:W(),action:"assign.issue",payload:{id:W(),target:u.id,contributor:g},...e.value}):s("Unable to locate assignees field")},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:f.COMMAND_LINE,action:()=>{let e=J();if(l(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=wi(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=ke(i.id,"TICKET");if(l(a))return s("Unable to unassign in this context");let d=a.value,u=E.getFieldByTitle(d.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=w(u.id).find(g=>g.props?.value===o.id);return m?X({id:W(),action:"unassign.issue",payload:{id:m.id,target:d.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>T({mode:f.DEFAULT})},{intent:M.Sync,mode:f.COMMAND_LINE,action:async()=>{let e=Si();K(()=>""),T({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=pe();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=Ve()?gr():c("No pending default events",null);if(l(r))return s(`Unable to persist default events. ${r.message}`);let o=J();if(l(o)||!o.value)return s("Unable to resolve event log path");let i=Gn(o.value);logger.debug("[sync-command] pending defaults",Ve());let a=await fi({ownEventFileName:i});if(l(a))return T({syncStatus:{msg:a.message,status:"outOfSync"}}),s(`Unable to sync state. ${a.message}`);T({syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let d=be(process.cwd());if(l(d))throw new Error(d.message);let u=ht(d.value);if(l(u))return s("Unable to load events");je(u.value);let m=Ai(e);return l(m)?m:c("Synced",!0)}},{intent:M.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=Ee(v().breadCrumb,"BOARD");if(l(e))return e;let t=be(process.cwd());if(l(t))throw new Error(t.message);let n=ht(t.value);if(l(n))return s(n.message);let r=n.value,{modifier:o}=ee().commandMeta,i;if(o==="now"){let C=pr();if(l(C))return C;let I=je(r);return I.some(l)?s(I.map(b=>b.message).join(", ")):(T({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let C=v().eventLog.at(-2),I=Fn(C);if(I===null)return s("No previous event to peek");i=I}else if(o==="next"){let C=v().unappliedEvents.at(0),I=Fn(C);if(I===null)return s("No next event to peek");i=I}else{let C=$t(o);if(!C)return s("Invalid peek date");i=C.getTime()}let a=e.value.id,{appliedEvents:d,unappliedEvents:u}=Mo(r,i),m=pr();if(l(m))return m;let g=je(d);if(g.some(l))return s(g.map(C=>C.message).join(", "));let h=v().nodes[a];return h?(D.navigate({currentNode:h,selectedIndex:0}),T({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}}];var ld=new Set(["peek","filter","view-help"]),ue=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return s("No command to confirm");if(!e&&n===Ce.Invalid)return s("Invalid command");let i=xo(t);if(uo(),v().readOnly&&!ld.has(i))return ft({status:Ne.Fail,message:"Command not available in readonly state",value:null});let a=Ri.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return ft({status:Ne.Fail,message:"Command not found",value:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return l(d)?ft(d):(mo({addToHistory:!e}),a.onSuccess?.(),ft(d))};var on=[{intent:x.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(T({mode:f.COMMAND_LINE}),K(()=>"move cancel"),ue({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(T({mode:f.COMMAND_LINE}),K(()=>"move start"),ue({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:f.MOVE,action:()=>(T({mode:f.COMMAND_LINE}),K(()=>"move confirm"),ue({isForceExecutedBySystem:!0}))}],sn=[{intent:x.MovePreviousItem,mode:f.MOVE,action:()=>$e()?(T({mode:f.COMMAND_LINE}),K(()=>"move previous"),ue({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:f.MOVE,action:()=>$e()?(T({mode:f.COMMAND_LINE}),K(()=>"move next"),ue({isForceExecutedBySystem:!0})):s("No pending move")}],Mi=[{intent:x.MoveToNextContainer,mode:f.MOVE,action:()=>$e()?(T({mode:f.COMMAND_LINE}),K(()=>"move to-next"),ue({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:f.MOVE,action:()=>$e()?(T({mode:f.COMMAND_LINE}),K(()=>"move to-previous"),ue({isForceExecutedBySystem:!0})):s("No pending move")}];var Pi={[P.WORKSPACE]:[...on,...sn],[P.BOARD]:[...on,...sn],[P.SWIMLANE]:[...on,...sn,...Mi],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Li=[{intent:x.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(T({mode:f.COMMAND_LINE}),K(()=>`${p.NEW} `),c("Adding new item",null))},{intent:x.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(T({mode:f.COMMAND_LINE}),K(()=>`${p.DELETE} `),c("Deleting item",null))},{intent:x.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(T({mode:f.COMMAND_LINE}),K(()=>""),c("Entering command line mode",null))},{intent:x.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),c("Entering context",null))},{intent:x.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:x.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:x.NavNextItem,mode:f.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:f.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:x.Edit,mode:f.DEFAULT,action:()=>(T({mode:f.COMMAND_LINE}),K(()=>"edit"),ue(),c("Fired command",!0))},{intent:x.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(T({viewMode:"dense"}),c("View set",null))},{intent:x.SetViewWide,mode:f.DEFAULT,action:()=>(T({viewMode:"wide"}),c("View set",null))}];var cd=500,ud=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Di=e=>{let t=ud(e);t&&K(n=>(n+t).slice(0,cd))};var Fi=[{intent:x.ViewHelp,mode:f.DEFAULT,action:()=>(T({mode:f.HELP}),c("Viewing help",null))},{intent:x.Exit,mode:f.HELP,action:()=>(T({mode:f.DEFAULT}),c("Exiting help",null))},{intent:x.Confirm,mode:f.COMMAND_LINE,action:()=>(ue(),c("Executing command",null))},{intent:x.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(Hn(-1),c("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(Hn(1),c("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(Kn("left"),c("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(Kn("right"),c("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(T({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>(K((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:x.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(Di(t??""),c("Capturing input",null))},{intent:x.EraseInput,mode:f.COMMAND_LINE,action:()=>(lo(),c("Erasing input",null))},{intent:x.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(co(),c("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(po(),c("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(go(),c("Getting next command from history",null))}];import md from"chalk";var an=": for command line",ki="q to exit",Oi=`${md.hex(N.accent)("m")} to confirm`,fr={[P.WORKSPACE]:[an],[P.BOARD]:[an],[P.BOARD+f.COMMAND_LINE]:[an],[P.SWIMLANE]:[an],[P.TICKET+f.HELP]:[ki],[P.SWIMLANE+f.HELP]:[ki],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[Oi],[P.TICKET+f.MOVE]:[Oi]};var dn=e=>e.trim().toLocaleLowerCase(),pd=(e,t)=>{let n=E.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},gd=e=>{let{tags:t}=v(),n=E.getFieldByTitle(e,"Tags");return n?U(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},fd=e=>{let{contributors:t}=v(),n=E.getFieldByTitle(e,"Assignees");return n?U(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Bi=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return dn(e.title??"").includes(n);case"description":return dn(pd(e.id,"Description")).includes(n);case"tag":return gd(e.id).map(dn).some(d=>d.includes(n));case"assignee":return fd(e.id).map(dn).some(d=>d.includes(n));default:return!0}};function Ui(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var $i=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 ln,vr,xr=new Set,Wi=()=>{for(let e of xr)e()},xd=e=>(xr.add(e),()=>xr.delete(e));function _i(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let d=o[t];if(!d)return s("Unable to derive state, currentNode not found");let u=Ui(t,o,r);if(l(u))return logger.error(u.message),u;let m=u.value,{context:g}=d,h=fr[g+n]??fr[g]??[],C=[...Li,...Pi[g]??[],...Fi],I=$i(C),b=yd(o,i),A=b[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:d,breadCrumb:m,availableHints:h,availableActions:C,actionIndex:I,selectedNode:A,renderedChildrenIndex:b})}var v=()=>(ln||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),ln);function Jn(e){vr=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=_i(t);return l(n)?n:(ln=n.value,Wi(),c("State initialized",null))}function oe(e){let t=v(),n=e(t),r=_i(n);return l(r)?s(r.message??"Unable to update state"):(ln=r.value,Wi(),c("State updated",null))}var T=e=>oe(t=>({...t,...e}));var _=()=>vd(xd,v,v),yd=(e,t)=>{let n={};for(let r of Object.values(e))ve(r)&&t.length>0&&!t.every(o=>Bi(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 a=e[o.id],d=e[i.id];return!a||!d?0:a.rank.localeCompare(d.rank)});return n},w=e=>v()?.renderedChildrenIndex[e]??[],pr=()=>vr?Jn(vr):s("Cannot reset state: no initial workspace found");var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=w(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:w(r.id).length?0:-1})},enterParentNode(){let{currentNode: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=w(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Hi(1),navigateToPreviousItem:()=>Hi(-1),navigateToNextContainer:()=>Ki(1),navigateToPreviousContainer:()=>Ki(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{T({currentNodeId:e.id,selectedIndex:t})}},Hi=e=>{let t=v(),n=w(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Ki=e=>{let{currentNode: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=w(o.id),a=i.findIndex(C=>C.id===t.id);if(a<0)return;let d=i.at(a+e)??i.at(0);if(!d)return;let u=w(d.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),h=u.length?g:-1;D.navigate({currentNode:d,selectedIndex:h})};var Ae="system",Te="ACTOR",St=hd(),we=null;function Nd(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=w(e.id),[n]=t?w(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function Ed(){let e=Nd();D.navigate(e)}function Cd(){let e=St(),t=St(),n=St(),r=St(),o=St();return[{id:Se(),userId:Ae,userName:Te,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:Se(),userId:Ae,userName:Te,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:Se(),userId:Ae,userName:Te,action:"add.board",payload:{id:Xt,name:"Closed",parent:e}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:tt,name:"Closed",parent:Xt}},{id:Se(),userId:Ae,userName:Te,action:"lock.node",payload:{id:Xt}},{id:Se(),userId:Ae,userName:Te,action:"lock.node",payload:{id:tt}}]}function Ve(){return we!==null}function gr(){if(!we||we.length===0)return we=null,c("No pending default events to persist",null);let e=we.map(t=>qt({event:t})).filter(l);return e.length>0?s([st.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${st.dim.gray(`${n+1}.`)} ${st.dim(t.message)}`),`
|
|
48
|
+
`,fd=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(ur(r),r);return[...n.values()].sort((r,o)=>{let i=yi(r)-yi(o);return i!==0?i:ur(r).localeCompare(ur(o))})},pr=({sourceFile:e,targetFile:t})=>{let n=en(e);if(c(n))return s(n.message);let r=en(t);if(c(r))return s(r.message);let o=fd(r.value,n.value),i=gd(o);return(an.existsSync(t)?an.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(an.mkdirSync(mr.dirname(t),{recursive:!0}),an.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},gr=({repoRoot:e,stateBranchRoot:t})=>{let n=ai(t);if(c(n))return s(n.message);let r=Ge(t),o=Ge(e),i=!1;for(let a of n.value){let d=mr.join(r,a),u=mr.join(o,a),m=pr({sourceFile:d,targetFile:u});if(c(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var Ni=async(e=process.cwd())=>{let t=await Ei({cwd:e,ensureUpstream:!1});if(c(t))return t;let{repoRoot:n,stateBranchRoot:r}=t.value,o=await sn({cwd:r,branch:O});if(c(o))return s(o.message);let i=gr({repoRoot:n,stateBranchRoot:r});return c(i)?s(i.message):l("Synced state branch",{repoRoot:n,stateBranchRoot:r})},xd=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=cr({root:e,fileName:n}),o=cr({root:t,fileName:n});return vd.existsSync(r)?pr({sourceFile:r,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},Ei=async({cwd:e,ensureUpstream:t})=>{let n=await li(e);if(c(n))return s(n.message);let r=n.value,o=oi(r),i=await pi(r);if(c(i))return s("Sync aborted. Unable to gitignore hydrated events");let a=await sr(r);if(c(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let d=await gi(r);if(c(d))return s(d.message);let u=await xi({repoRoot:r,stateBranchRoot:o,ensureUpstream:t});if(c(u))return s(u.message);let m=await sr(o);if(c(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let g=di(r,o);return c(g)?s(g.message):l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:o,bootstrapped:u.value})},hi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=xd({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(c(r))return s(r.message);let o=await Jo(t);if(c(o))return s(o.message);if(!r.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await fi({stateBranchRoot:t,ownEventFileName:n});if(c(i))return s(i.message);let a=await vi({repoRoot:e,stateBranchRoot:t});return c(a)?s(a.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Ci=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");let n=await Ei({cwd:e,ensureUpstream:!0});if(c(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await Zo(r);if(c(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let d=!1,u,m=!1,g=!1,h=!1,C=await sn({cwd:o,branch:O});if(c(C))return s(C.message);m=C.value;let I=gr({repoRoot:r,stateBranchRoot:o});if(c(I))return s(I.message);h=I.value;let A=await hi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(c(A))return s(A.message);if(d=A.value.createdCommit,u=A.value.commitSha,d||i){let S=await lr(o),b=S;if(c(S)&&Xo(S.message)){let R=await sn({cwd:o,branch:O});if(c(R))return s(R.message);let B=await hi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(c(B))return s(B.message);B.value.createdCommit&&(d=!0,u=B.value.commitSha),b=await lr(o)}if(c(b))return s(b.message);g=b.value,logger.debug("[sync] pushed to state branch",g)}else logger.debug("[sync] no commit created, skipped push");if(d){let S=await k({args:["rev-parse","HEAD"],cwd:o});if(c(S))return s(S.message);u=S.value.stdout.trim()}return l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:u,pulled:m,pushed:g,hydrated:h,bootstrapped:i})};import{ulid as Ii}from"ulid";var st=null,$e=()=>structuredClone(st),at=e=>st=e,bi=()=>{let{currentNode:e,selectedIndex:t}=v(),r=w(e.id)[t];return r?l("Resolved selected child",r):s("Target node not found")};function fr(e){let t=bi();if(c(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=U(o.id),a=i.findIndex(({id:C})=>C===n.id);if(a<0)return s("Current node not found among siblings");let d=i[a+e];if(!d)return s("Missing sibling node");let u=X();if(c(u))return s("Unable to resolve user ID");let{userId:m,userName:g}=u.value;if(at({id:Ii(),userId:m,userName:g,action:"move.node",payload:{id:t.value.id,parent:d.id,pos:{at:"end"}}}),!st)return s("Could not materialize move state");let h=ot(st,!0);return c(h)?h:l("Node moved successfully",h.value)}function vr(e){let t=bi();if(c(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=U(n.id)[r+e];if(!i)return s("Missing sibling node");let a=X();if(c(a))return s("Unable to resolve user ID");let{userId:d,userName:u}=a.value;if(at({id:Ii(),userId:d,userName:u,action:"move.node",payload:{id:t.value.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:i.id}}}),!st)return s("Could not materialize move state");let m=ot(st,!0);return c(m)?m:l("Node moved successfully",m.value)}import yd from"node:os";import Si from"node:path";import{z as St}from"zod";var hd={userId:"",userName:"",preferredEditor:"",autoSync:!1},Ai=St.object({preferredEditor:St.string().optional(),userName:St.string().optional(),userId:St.string().optional(),autoSync:St.boolean().optional()}).strict(),Nd="config.json",Ti=()=>Si.join(yd.homedir(),de),xr=()=>Si.join(Ti(),Nd),yr=()=>{try{return se.mkDir(Ti()),l(`Ensured ~/${de} exists`,null)}catch{return s(`Unable to create ~/${de}`)}},Ed=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${de}/config.json JSON`)}let n=Ai.safeParse(t??{});return n.success?l("Parsed config",n.data):s(`Invalid ~/${de}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},wi=()=>{let e=yr();if(c(e))return s(e.message);let t=xr(),n=se.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Ed(n)},Ri=e=>{let t=yr();if(c(t))return s(t.message);let n=Ai.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=xr();try{return se.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
49
|
+
`),l("Config written",null)}catch{return s(`Unable to write ~/${de}/config.json`)}},dn=e=>{let t=wi();if(c(t))return s("Failed to read existing config");let n={...t.value,...e};return Ri(n)},Mi=()=>{let e=xr(),t=yr();if(c(t))return s(`Unable to create ~/${de}`);if(!(se.readFile(e)!==null)){let u=Ri(hd);if(c(u))throw new Error(`Unable to create ~/${de}/config.json`)}let r=wi();if(c(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:d}=r.value;return!i||!a?s(`User name or ID not configured in ~/${de}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:d??!1})};var Li=()=>{let{currentNode:e,selectedIndex:t}=v(),n=w(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},Pi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Di=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=w(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),l("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let a=w(i.id).findIndex(d=>d.id===o.id);if(a>=0)return D.navigate({currentNode:i,selectedIndex:a}),l("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=w(n.id);return D.navigate({currentNode:n,selectedIndex:Pi(e.selectedIndex,o.length)}),l("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=w(o.id);return D.navigate({currentNode:o,selectedIndex:Pi(e.selectedIndex,i.length)}),l("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),l("Restored navigation to root",null))};import Gi from"node:fs";import Yd from"node:path";import Xd from"react";import{Box as Gd}from"ink";import gn from"react";import{Box as Er,Text as Dd}from"ink";import ye from"react";import{Text as Fi}from"ink";import ki,{useEffect as Oi,useState as Cd}from"react";var Bi={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},ne=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=_(),r=Bi[n]??Bi.default,[o,i]=Cd(0);if(Oi(()=>{i(0)},[r]),Oi(()=>{if(!e)return;let d=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return ki.createElement(Fi,null,t);let a=r[o]??r[0]??t;return ki.createElement(Fi,{color:N.accent,dimColor:o===1},a)};import{Box as hr,Text as Id}from"ink";import cn from"react";var ln=({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)),a=Math.max(1,Math.ceil(r)),d=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-d),g=o?Math.min(m,Math.max(0,u-d+1)):Math.min(m,Math.floor(u/d)*d),h=g+d,C=e.slice(g,h),I=e.length>d,A=i,S=I?Math.max(1,Math.floor(d/e.length*A)):A,b=Math.max(0,A-S),R=Math.max(1,e.length-d),B=I?Math.floor(g/R*b):0;return cn.createElement(hr,{flexDirection:"row",height:i,width:"100%"},cn.createElement(hr,{flexDirection:"column",flexGrow:1,height:i},C),cn.createElement(hr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((Le,De)=>cn.createElement(Id,{key:De,color:I&&De>=B&&De<B+S?N.accent:N.secondary},I?"\u2502":" "))))};import{Box as un,Text as Md}from"ink";import qe from"react";import{Text as bd}from"ink";import Sd from"react";var Ad=e=>e.toLowerCase().trim(),Td=(e,t=Ze)=>{let n=Ad(e);return t[n]?t[n]:gt(n)},dt=({id:e,isSelected:t})=>{let n=E.getContributor(e);if(n)return Sd.createElement(bd,{underline:t,color:Td(n.name)},"@"+n.name)};import{Text as wd}from"ink";import Rd from"react";var ct=({id:e,isSelected:t})=>{let n=E.getTag(e);if(n)return Rd.createElement(wd,{underline:t,backgroundColor:q(n.name),color:N.primary}," "+n.name+" ")};var Ui=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=kt(Dn(t.title),r),i=Bn(t),a=Un(t);return qe.createElement(un,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?N.accent:N.secondary,justifyContent:"space-between"},qe.createElement(un,{borderBottom:!0},qe.createElement(un,{paddingLeft:1,flexDirection:"column"},qe.createElement(Md,{color:N.primary},o))),qe.createElement(un,{flexDirection:"row",paddingLeft:1},i.map(d=>qe.createElement(ct,{key:d.id,id:d.id})),a.map(d=>qe.createElement(dt,{key:d.id,id:d.id}))))};import Pd from"chalk";import{Box as At,Text as Nr}from"ink";import Se from"react";var Ld=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,$i=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=w(t.id),a=S=>{let b=i.find(R=>R.title===S);return b?w(b.id).map(R=>typeof R.props?.value=="string"?R.props.value:"").filter(R=>!!R):[]},d=a("Tags").map(S=>E.getTag(S)).filter(S=>!!S),u=a("Assignees").map(S=>E.getContributor(S)).filter(S=>!!S),m=1,g=d.length*(1+m),h=u.length*(2+m),C=d.map(S=>Se.createElement(At,{key:S.id,paddingRight:m},Se.createElement(Nr,{color:q(S.name)},"\u25A0"))),I=u.map(S=>Se.createElement(At,{key:S.id,paddingRight:m},Se.createElement(Nr,{color:gt(S.name)},"@"+S.name.at(0)))),A=n?N.accent:o===p.MOVE?N.secondary:N.primary;return Se.createElement(At,{borderBottom:!0,justifyContent:"space-between"},Se.createElement(At,null,Se.createElement(ne,{isSelected:n,placeholder:Pd.dim.gray(r+1+" ")}),Se.createElement(Nr,{wrap:"truncate",color:A},Ld(t.title,e-g-h-14))),Se.createElement(At,null,C,I))};var Fd=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:u}=_(),m=u[e.id]??[],g=`${e.title} (${m.length})`,h=3,C=o?1:4,I=r-h-(o?2:1),A=ye.createElement(Er,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ye.createElement(ne,{isSelected:t}),ye.createElement(Dd,{bold:!0,color:t?N.accent:N.primary},g," ",e.readonly?"\u{1F512}":"")),S=(b,R)=>{let B=i&&a===R;return o?ye.createElement($i,{key:b.id,index:R,width:n,ticket:b,isSelected:B,mode:d}):ye.createElement(Ui,{key:b.id,width:n,ticket:b,isSelected:B})};return ye.createElement(Er,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:r},A,ye.createElement(Er,{padding:o?1:0},m.length>0&&ye.createElement(ln,{selectedIndex:a,height:I,itemHeight:C},m.map(S)),ye.createElement(ne,{isSelected:i&&a===-1})))},_i=ye.memo(Fd);import{Box as br,Text as jd}from"ink";import _e,{useEffect as Sr,useMemo as Vi}from"react";import fe from"chalk";import Wi from"string-width";import{decodeTime as kd}from"ulid";var Od=(e,t)=>e+" ".repeat(Math.max(0,t-Wi(e))),Bd=(e,t)=>" ".repeat(Math.max(0,t-Wi(e)))+e,Ud=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),$d=e=>{switch(e.action){case"move.node":{let t=E.getNode(e.payload.parent),n=t?fe.dim.bgBlack(` ${t.title} `):"unknown",r=e.payload.pos;if(!r)return`to ${n}`;switch(r.at){case"start":return`to ${n} ${fe.dim("(to top of list)")}`;case"end":return`to ${n} ${fe.dim("(to bottom of list)")}`;case"before":return`to ${n} ${fe.dim("(up in list)")}`;case"after":return`to ${n} ${fe.dim("(down in list)")}`}}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?fe.bgHex(q(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?fe.bgHex(q(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?fe.hex(q(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?fe.hex(q(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""}},_d=e=>{let t=no(kd(e));return fe.gray(Bd(t,8))},Wd=12,Hd=e=>Od(`${e}`,Wd),Hi=e=>{let t=_d(e.id),n=Hd(e.userName),r=Ud(e.action),o=$d(e),i=fe.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as mn,Text as Kd}from"ink";import Ae from"react";var Ki=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=_(),{title:o}=t,i=w(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return E.getContributor(d)?.id;if(o==="Tags")return E.getTag(d)?.id}).filter(a=>!!a);return Ae.createElement(mn,{alignItems:"center",paddingTop:1},Ae.createElement(mn,{minWidth:12},Ae.createElement(ne,{isSelected:n}),Ae.createElement(Kd,{color:n?N.accent:N.secondary2},o,":")),Ae.createElement(mn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,d)=>{let u=r.id===t.id&&d===e;return Ae.createElement(mn,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Ae.createElement(ne,{isSelected:u}),o==="Assignees"?Ae.createElement(dt,{isSelected:u,id:a}):o==="Tags"?Ae.createElement(ct,{isSelected:u,id:a}):null)})))};import{Box as pn,Text as Cr}from"ink";import Te,{useEffect as Vd}from"react";var Ir=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:d}=_(),u=C=>String(C).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Vd(()=>{let C=[];return m.forEach((I,A)=>{let S=ee.text({id:`${A}`,name:`Line ${A+1}`,parentNodeId:e,props:{value:I},readonly:!0}),b=E.createNodeAtPosition(S);Fe(b)&&C.push(b.value.id)}),()=>C.forEach(E.deleteNode)},[e,n]);let g="\u2029",h=m.map((C,I)=>{let A=d.id===e&&a===I;return Te.createElement(pn,{key:`${e}-${I}`},Te.createElement(Cr,{color:A?N.primary:N.secondary2,dimColor:!A},`${I+1} `.padStart(5,"\xA0")),Te.createElement(Cr,{backgroundColor:A?"gray":""},u(C.length?kt(C,i-10):g)))});return Te.createElement(pn,{flexDirection:"column",paddingTop:1},Te.createElement(pn,null,Te.createElement(ne,{isSelected:o}),Te.createElement(Cr,{color:o?N.accent:N.secondary2},t)),Te.createElement(pn,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Te.createElement(ln,{scrollByOne:!0,children:h,height:r-2,selectedIndex:a,itemHeight:1})))};var zd=e=>`${e}::log`,ji=e=>e==="Assignees"||e==="Tags",zi=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=_(),o=process.stdout.columns||120,i=Vi(()=>zd(e.id),[e.id]),a=Vi(()=>[...e.log].reverse().map(Hi).join(`
|
|
50
|
+
`),[e.log]);Sr(()=>{if(E.getNode(i))return;let R={...ee.field(i,"Log",e.id,{value:a}),readonly:!0,childRenderAxis:"vertical"};return E.createNodeAtPosition(R),()=>{E.deleteNode(i)}},[i,e.id,a]),Sr(()=>{let b=E.getNode(i);b&&b.props.value!==a&&E.updateNode({...b,props:{...b.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let d=r.id===e.id,u=r.id===i||r.parentNodeId===i;Sr(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=w(e.id);if(u){let b=E.getNode(i),B=t-3;return _e.createElement(br,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},b?_e.createElement(Ir,{id:b.id,label:"Event log",text:b.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let g=m.reduce((b,R)=>ji(R.title)||R.id===i?b+1:b,0),h=2,C=g*1,A=t-3-C-h,S=(b,R)=>ji(b.title)?_e.createElement(Ki,{key:b.id,parent:b,selected:R,selectedIndex:n}):b.id===i?_e.createElement(br,{key:b.id,paddingTop:1},_e.createElement(ne,{isSelected:R}),_e.createElement(jd,{backgroundColor:N.secondary,color:R?N.accent:N.primary}," History \u203A\u203A ")):b.title==="Description"?_e.createElement(Ir,{label:"Description (press e to edit)",key:b.id,id:b.id,text:b.props.value??"",selected:R,maxWidth:o,height:A}):null;return _e.createElement(br,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((b,R)=>S(b,d&&n===R)))};var qd=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:d})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,g=u===P.BOARD||u===P.SWIMLANE,h=u===P.TICKET?t:r.find(b=>b.context===P.TICKET),C=Math.floor(d/3),I=Math.floor(d/Math.max(e.length,1)),A=Math.min(I,C),S=i==="dense";return gn.createElement(Gd,{flexDirection:"row",height:a},g&&e.map((b,R)=>{let B=t.id===b.id,Le=B?n:-1,De=t.context===P.BOARD&&n===R;return gn.createElement(_i,{key:b.id,height:a,width:A,swimlane:b,isSelected:De,isDense:S,isFocused:B,listSelectedIndex:Le,mode:o})}),m&&h&&gn.createElement(zi,{height:a,ticket:h}))},fn=gn.memo(qd);import{render as Jd}from"ink";import{Writable as Zd}from"node:stream";var Tt=e=>String(e).padStart(2,"0"),Qd=e=>{let t=e.getUTCFullYear(),n=Tt(e.getUTCMonth()+1),r=Tt(e.getUTCDate()),o=Tt(e.getUTCHours()),i=Tt(e.getUTCMinutes()),a=Tt(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},ec=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",tc=async(e,{width:t,height:n})=>{let r="",o=new Zd({write(a,d,u){let m=nc(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Jd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},nc=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),qi=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=v(),a=n.find(R=>R.context==="BOARD");if(!a)return s("No board found to export");let d=120,u=40,m=await tc(Xd.createElement(fn,{height:u,width:d,swimlanes:(i[a.id]??[]).filter(R=>R!==void 0&&Dt(R)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:d,height:u});if(!m)return s("Failed to render board export");let g=ge(process.cwd());if(c(g))return s("Unable to export, epiq root not found");let h=new Date,C=Qd(h),I=`board_${ec(a.title)}_${C}.md`,A=Mo(g.value);Gi.mkdirSync(A,{recursive:!0});let S=Yd.join(A,I),b=`# Board - ${a.title}
|
|
51
|
+
Date: ${h.toISOString()}
|
|
52
|
+
|
|
53
|
+
\`\`\`text
|
|
54
|
+
${m}
|
|
55
|
+
\`\`\`
|
|
56
|
+
`;return Gi.writeFileSync(S,b,"utf8"),l("Exported board layout",S)};var Yi=e=>Object.values(v().tags).find(t=>t.name===e),Xi=e=>Object.values(v().contributors).find(t=>t.name===e),Ji=[{systemOnly:!0,intent:M.Move,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t}=te().commandMeta,n=()=>{let d=$e();if(!d)return s("No pending move state");let u=d.payload.id;if(!v().nodes[u])return s("Moved node not found");let g=d.payload.parent,h=v().nodes[g];if(!h)return s("Move parent not found");let C=w(g).findIndex(I=>I.id===u);return C===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:h,selectedIndex:C}),l("Synchronized navigation to moved node",null))},r=d=>{if(c(d))return s(d.message);let u=n();return c(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=w(o.id)[i];if(!a)return T({mode:p.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let d=w(a.parentNodeId),u=d.findIndex(({id:I})=>I===a.id);if(u===-1)return s("Target not found among siblings");let m=d[u-1],g=d[u+1],h=g!=null?{at:"before",sibling:g.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"};at({id:W(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,pos:h},...e.value}),T({mode:p.MOVE});let C=n();return c(C)?s(C.message):l("Move initialized",null)}if(t==="next")return T({mode:p.MOVE}),r(vr(1));if(t==="previous")return T({mode:p.MOVE}),r(vr(-1));if(t==="to-next")return T({mode:p.MOVE}),r(fr(1));if(t==="to-previous")return T({mode:p.MOVE}),r(fr(-1));if(t==="confirm"){T({mode:p.DEFAULT});let d=$e();if(!d)return s("No pending move to confirm");let u=J(d);if(c(u))return u;let m=n();return c(m)?s(m.message):(at(null),l("Moved item",null))}return t==="cancel"?(at(null),T({mode:p.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];return r?J({id:W(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.Edit,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let t=Ce(v().breadCrumb,"TICKET");if(c(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!w(n.id)[o])return s("No selected field");let a=w(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let d=a.props.value;if(typeof d!="string")return s("Selected field is not editable text");let u=wo(d);if(c(u))return s("Failed to edit field");let m=u.value;return m===d?l("No changes made",null):a.title==="Description"?J({id:W(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?J({id:W(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.Filter,mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=te().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>j(f.FILTER).map(u=>u.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return ie(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:p.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:p.COMMAND_LINE,action:()=>(T({mode:p.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!r.parentNodeId)return s("No target parent found");if(!xe(r))return s("Cannot close in this context");let o=J({id:W(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.value});return c(o)?o:l("Viewing help",null)}},{intent:M.ReopenIssue,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):ke(r.id,"TICKET");if(c(o))return s("Cannot reopen in this context");let i=o.value,a=J({id:W(),action:"reopen.issue",payload:{id:i.id},...e.value});return c(a)?a:l("Issue reopened",null)},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.SetUserName,mode:p.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=pe(),r=zt()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??W();if(!o||!i)return s("Unable to resolve user name or id");let a=dn({userName:o,userId:i,preferredEditor:t??""});return c(a)?a:(Je({userName:o,userId:i}),T({mode:p.DEFAULT}),l(`Username set to "${r}"`,null))}},{intent:M.Init,mode:p.COMMAND_LINE,action:()=>{let e=Tr();if(c(e))return e;let{rootNodeId:t,nodes:n}=v();return D.navigate({currentNode:n[t],selectedIndex:0}),T({mode:p.DEFAULT}),l("Project initialized",null)}},{intent:M.SetEditor,mode:p.COMMAND_LINE,action:()=>{let e=zt()?.trim();if(!e)return s("No editor provided");let t=dn({preferredEditor:e});return c(t)?t:(Je({preferredEditor:e}),T({mode:p.DEFAULT}),l(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:p.COMMAND_LINE,action:()=>{let e=te().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=dn({autoSync:t});return c(n)?n:(Je({autoSync:t}),T({mode:p.DEFAULT}),l(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:p.COMMAND_LINE,action:(e,t)=>{let n=X();if(c(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=d=>{let u=J(d);if(c(u))return u;let m=E.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let g=E.getNode(m.parentNodeId);return g?(D.navigate({currentNode:g,selectedIndex:E.getSiblings(m.parentNodeId).findIndex(({id:h})=>h===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=v(),u=E.getNode(d);return u?a({id:W(),action:"add.board",payload:{id:W(),name:t.inputString,parent:u.id},...n.value}):s("Workspace not found")}if(t.modifier==="swimlane"){let d=Ce(r,"BOARD");return c(d)?s("Unable to add swimlane in this context"):a({id:W(),action:"add.swimlane",payload:{id:W(),name:t.inputString,parent:d.value.id},...n.value})}if(t.modifier==="issue"){let d=w(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let I=Ce(r,"SWIMLANE");return c(I)?null:I.value})();if(!u)return s("Unable to add issue in this context");let m=Ro({name:t.inputString,parent:u.id,user:n.value}),g=$o(m);if(g.some(I=>c(I)))return s("Issue create failed: "+g.filter(c).map(I=>I.message).filter(Boolean).join(", "));let h=g[0];if(!h||c(h))return s("Issue creation failed");let C=m[0]?.payload.id;return C?(D.navigate({currentNode:u,selectedIndex:E.getSiblings(u.id).findIndex(({id:I})=>I===C)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.SetView,mode:p.COMMAND_LINE,action:()=>{let{commandMeta:e}=te();return e.validity===Ie.Invalid?s("Invalid command "+Ee):(ie(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),l("View set",null))},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.Rename,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=w(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=zt();return o?J({id:W(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.UntagTicket,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=Yi(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=ke(i.id,"TICKET");if(c(a))return s("Unable to untag issue in this context");let d=a.value,u=E.getFieldByTitle(d.id,"Tags");if(!u)return s("Unable to locate tags field");let m=w(u.id).find(g=>g.props?.value===o.id);return m?J({id:W(),action:"untag.issue",payload:{id:m.id,target:d.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.TagTicket,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=w(i.id)[o];if(!a)return s("Invalid tag target");let d=ke(a.id,"TICKET");if(c(d))return s("Unable to tag issue in this context");let u=d.value,m=Yi(r),g;if(m)g=m.id;else{let I=W(),A=J({id:W(),action:"create.tag",payload:{id:I,name:r},userId:e.value.userId,userName:e.value.userName});if(c(A))return A;g=A.value.result.id}let h=E.getFieldByTitle(u.id,"Tags");return h?w(h.id).some(I=>I.props?.value===g)?s("Already tagged with that tag"):J({id:W(),action:"tag.issue",payload:{id:W(),target:u.id,tagId:g},...e.value}):s("Unable to locate tags field")},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.AssignUserToTicket,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=w(i.id)[o];if(!a)return s("Invalid assign target");let d=ke(a.id,"TICKET");if(c(d))return s("Unable to assign issue in this context");let u=d.value,m=Xi(r),g;if(m)g=m.id;else{let I=W(),A=J({id:W(),action:"create.contributor",payload:{id:I,name:r},userId:e.value.userId,userName:e.value.userName});if(c(A))return A;g=A.value.result.id}let h=E.getFieldByTitle(u.id,"Assignees");return h?w(h.id).some(I=>I.props?.value===g)?s("Assignee already assigned"):J({id:W(),action:"assign.issue",payload:{id:W(),target:u.id,contributor:g},...e.value}):s("Unable to locate assignees field")},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:p.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=Xi(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=ke(i.id,"TICKET");if(c(a))return s("Unable to unassign in this context");let d=a.value,u=E.getFieldByTitle(d.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=w(u.id).find(g=>g.props?.value===o.id);return m?J({id:W(),action:"unassign.issue",payload:{id:m.id,target:d.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>T({mode:p.DEFAULT})},{intent:M.Sync,mode:p.COMMAND_LINE,action:async()=>{let e=Li();V(()=>""),T({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=pe();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=Ve()?Tr():l("No pending default events",null);if(c(r))return s(`Unable to persist default events. ${r.message}`);let o=X();if(c(o)||!o.value)return s("Unable to resolve event log path");let i=Qn(o.value);logger.debug("[sync-command] pending defaults",Ve());let a=await Ci({ownEventFileName:i});if(c(a))return T({syncStatus:{msg:a.message,status:"outOfSync"}}),s(`Unable to sync state. ${a.message}`);T({syncStatus:{msg:"Synced",status:"synced"},mode:p.DEFAULT});let d=ge(process.cwd());if(c(d))throw new Error(d.message);let u=Nt(d.value);if(c(u))return s("Unable to load events");ze(u.value);let m=Di(e);return c(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:p.COMMAND_LINE,action:async()=>{let e=Ce(v().breadCrumb,"BOARD");if(c(e))return e;let t=ge(process.cwd());if(c(t))throw new Error(t.message);let n=Nt(t.value);if(c(n))return s(n.message);let r=n.value,{modifier:o}=te().commandMeta,i;if(o==="now"){let C=Ar();if(c(C))return C;let I=ze(r);return I.some(c)?s(I.map(A=>A.message).join(", ")):(T({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let C=v().eventLog.at(-2),I=_n(C);if(I===null)return s("No previous event to peek");i=I}else if(o==="next"){let C=v().unappliedEvents.at(0),I=_n(C);if(I===null)return s("No next event to peek");i=I}else{let C=Ht(o);if(!C)return s("Invalid peek date");i=C.getTime()}let a=e.value.id,{appliedEvents:d,unappliedEvents:u}=Bo(r,i),m=Ar();if(c(m))return m;let g=ze(d);if(g.some(c))return s(g.map(C=>C.message).join(", "));let h=v().nodes[a];return h?(D.navigate({currentNode:h,selectedIndex:0}),T({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:p.COMMAND_LINE,action:async()=>{let e=await qi();return c(e)?e:(T({mode:p.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:p.COMMAND_LINE,action:async()=>(D.exit(),l("Exit successful",!0))}];var rc=new Set(["peek","filter","view-help"]),ue=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=te();if(!t)return s("No command to confirm");if(!e&&n===Ie.Invalid)return s("Invalid command");let i=Io(t);if(xo(),v().readOnly&&!rc.has(i))return xt({status:Ee.Fail,message:"Command not available in readonly state",value:null});let a=Ji.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return xt({status:Ee.Fail,message:"Command not found",value:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return c(d)?xt(d):(yo({addToHistory:!e}),a.onSuccess?.(),xt(d))};var vn=[{intent:x.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(T({mode:p.COMMAND_LINE}),V(()=>"move cancel"),ue({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:p.DEFAULT,description:"[m] move init/confirm",action:()=>(T({mode:p.COMMAND_LINE}),V(()=>"move start"),ue({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:p.MOVE,action:()=>(T({mode:p.COMMAND_LINE}),V(()=>"move confirm"),ue({isForceExecutedBySystem:!0}))}],xn=[{intent:x.MovePreviousItem,mode:p.MOVE,action:()=>$e()?(T({mode:p.COMMAND_LINE}),V(()=>"move previous"),ue({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:p.MOVE,action:()=>$e()?(T({mode:p.COMMAND_LINE}),V(()=>"move next"),ue({isForceExecutedBySystem:!0})):s("No pending move")}],Zi=[{intent:x.MoveToNextContainer,mode:p.MOVE,action:()=>$e()?(T({mode:p.COMMAND_LINE}),V(()=>"move to-next"),ue({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:p.MOVE,action:()=>$e()?(T({mode:p.COMMAND_LINE}),V(()=>"move to-previous"),ue({isForceExecutedBySystem:!0})):s("No pending move")}];var Qi={[P.WORKSPACE]:[...vn,...xn],[P.BOARD]:[...vn,...xn],[P.SWIMLANE]:[...vn,...xn,...Zi],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var es=[{intent:x.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(T({mode:p.COMMAND_LINE}),V(()=>`${f.NEW} `),l("Adding new item",null))},{intent:x.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(T({mode:p.COMMAND_LINE}),V(()=>`${f.DELETE} `),l("Deleting item",null))},{intent:x.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(T({mode:p.COMMAND_LINE}),V(()=>""),l("Entering command line mode",null))},{intent:x.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),l("Entering context",null))},{intent:x.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),l("Exiting context",null))},{intent:x.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:x.NavNextItem,mode:p.DEFAULT,action:()=>(D.navigateToNextItem(),l("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(D.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:p.DEFAULT,action:()=>(D.navigateToNextContainer(),l("Navigating to next container",null))},{intent:x.Edit,mode:p.DEFAULT,action:()=>(T({mode:p.COMMAND_LINE}),V(()=>"edit"),ue(),l("Fired command",!0))},{intent:x.SetViewDense,mode:p.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(T({viewMode:"dense"}),l("View set",null))},{intent:x.SetViewWide,mode:p.DEFAULT,action:()=>(T({viewMode:"wide"}),l("View set",null))}];var oc=500,ic=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ts=e=>{let t=ic(e);t&&V(n=>(n+t).slice(0,oc))};var ns=[{intent:x.ViewHelp,mode:p.DEFAULT,action:()=>(T({mode:p.HELP}),l("Viewing help",null))},{intent:x.Exit,mode:p.HELP,action:()=>(T({mode:p.DEFAULT}),l("Exiting help",null))},{intent:x.Confirm,mode:p.COMMAND_LINE,action:()=>(ue(),l("Executing command",null))},{intent:x.MoveCursorLeft,mode:p.COMMAND_LINE,action:()=>(qn(-1),l("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:p.COMMAND_LINE,action:()=>(qn(1),l("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:p.COMMAND_LINE,action:()=>(Yn("left"),l("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:p.COMMAND_LINE,action:()=>(Yn("right"),l("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(T({mode:p.DEFAULT}),l("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:p.COMMAND_LINE,action:()=>(V((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:x.CaptureInput,mode:p.COMMAND_LINE,action:(e,{sequence:t})=>(ts(t??""),l("Capturing input",null))},{intent:x.EraseInput,mode:p.COMMAND_LINE,action:()=>(fo(),l("Erasing input",null))},{intent:x.EraseInputWord,mode:p.COMMAND_LINE,action:()=>(vo(),l("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(ho(),l("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(No(),l("Getting next command from history",null))}];import sc from"chalk";var yn=": for command line",rs="q to exit",os=`${sc.hex(N.accent)("m")} to confirm`,wr={[P.WORKSPACE]:[yn],[P.BOARD]:[yn],[P.BOARD+p.COMMAND_LINE]:[yn],[P.SWIMLANE]:[yn],[P.TICKET+p.HELP]:[rs],[P.SWIMLANE+p.HELP]:[rs],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+p.MOVE]:[os],[P.TICKET+p.MOVE]:[os]};var hn=e=>e.trim().toLocaleLowerCase(),ac=(e,t)=>{let n=E.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},dc=e=>{let{tags:t}=v(),n=E.getFieldByTitle(e,"Tags");return n?U(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},cc=e=>{let{contributors:t}=v(),n=E.getFieldByTitle(e,"Assignees");return n?U(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},is=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return hn(e.title??"").includes(n);case"description":return hn(ac(e.id,"Description")).includes(n);case"tag":return dc(e.id).map(hn).some(d=>d.includes(n));case"assignee":return cc(e.id).map(hn).some(d=>d.includes(n));default:return!0}};function ss(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var as=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Nn,Rr,Mr=new Set,ds=()=>{for(let e of Mr)e()},uc=e=>(Mr.add(e),()=>Mr.delete(e));function cs(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let d=o[t];if(!d)return s("Unable to derive state, currentNode not found");let u=ss(t,o,r);if(c(u))return logger.error(u.message),u;let m=u.value,{context:g}=d,h=wr[g+n]??wr[g]??[],C=[...es,...Qi[g]??[],...ns],I=as(C),A=mc(o,i),S=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:d,breadCrumb:m,availableHints:h,availableActions:C,actionIndex:I,selectedNode:S,renderedChildrenIndex:A})}var v=()=>(Nn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Nn);function nr(e){Rr=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:p.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=cs(t);return c(n)?n:(Nn=n.value,ds(),l("State initialized",null))}function ie(e){let t=v(),n=e(t),r=cs(n);return c(r)?s(r.message??"Unable to update state"):(Nn=r.value,ds(),l("State updated",null))}var T=e=>ie(t=>({...t,...e}));var _=()=>lc(uc,v,v),mc=(e,t)=>{let n={};for(let r of Object.values(e))xe(r)&&t.length>0&&!t.every(o=>is(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 a=e[o.id],d=e[i.id];return!a||!d?0:a.rank.localeCompare(d.rank)});return n},w=e=>v()?.renderedChildrenIndex[e]??[],Ar=()=>Rr?nr(Rr):s("Cannot reset state: no initial workspace found");var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=w(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:w(r.id).length?0:-1})},enterParentNode(){let{currentNode: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=w(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>ls(1),navigateToPreviousItem:()=>ls(-1),navigateToNextContainer:()=>us(1),navigateToPreviousContainer:()=>us(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{T({currentNodeId:e.id,selectedIndex:t})}},ls=e=>{let t=v(),n=w(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},us=e=>{let{currentNode: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=w(o.id),a=i.findIndex(C=>C.id===t.id);if(a<0)return;let d=i.at(a+e)??i.at(0);if(!d)return;let u=w(d.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),h=u.length?g:-1;D.navigate({currentNode:d,selectedIndex:h})};var Re="system",Me="ACTOR",wt=pc(),Pe=null;function gc(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=w(e.id),[n]=t?w(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function fc(){let e=gc();D.navigate(e)}function vc(){let e=wt(),t=wt(),n=wt(),r=wt(),o=wt();return[{id:we(),userId:Re,userName:Me,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:we(),userId:Re,userName:Me,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:we(),userId:Re,userName:Me,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:we(),userId:Re,userName:Me,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t}},{id:we(),userId:Re,userName:Me,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:we(),userId:Re,userName:Me,action:"add.board",payload:{id:tn,name:"Closed",parent:e}},{id:we(),userId:Re,userName:Me,action:"add.swimlane",payload:{id:rt,name:"Closed",parent:tn}},{id:we(),userId:Re,userName:Me,action:"lock.node",payload:{id:tn}},{id:we(),userId:Re,userName:Me,action:"lock.node",payload:{id:rt}}]}function Ve(){return Pe!==null}function Tr(){if(!Pe||Pe.length===0)return Pe=null,l("No pending default events to persist",null);let e=Pe.map(t=>Zt({event:t})).filter(c);return e.length>0?s([lt.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${lt.dim.gray(`${n+1}.`)} ${lt.dim(t.message)}`),`
|
|
50
57
|
`].join(`
|
|
51
|
-
`)):(
|
|
58
|
+
`)):(Pe=null,l("Persisted pending default events",null))}function ms(e){let t;e.some(r=>r.action==="init.workspace")?(Pe=null,t=ze(e)):(Pe=vc(),t=ze([...Pe]));let n=t.filter(c);return n.length>0?s([lt.bold.red("Materializing failed"),"",...n.map((r,o)=>`${lt.dim.gray(`${o+1}.`)} ${lt.dim(r.message)}`),`
|
|
52
59
|
`].join(`
|
|
53
60
|
|
|
54
61
|
See complete log:
|
|
55
62
|
|
|
56
63
|
`)+e.map(r=>JSON.stringify(r)).join(`
|
|
57
|
-
`)):(Ed(),c("State booted successfully",null))}import{Box as Wd}from"ink";import Nr from"react";import Tt from"chalk";import{Box as yr,Text as ji}from"ink";import At,{useEffect as Id,useMemo as bd,useState as Sd}from"react";var zi=Tt.gray,Ad=Tt.inverse,Td=Tt.inverse.gray,wd={hint:"",hints:[],overlap:0,remainder:""},qi=({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}},Rd=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=q(t);return{bg:r=>Tt.bgHex(n).black(r),bgCursor:r=>Tt.bgHex(n).inverse.black(r)}}return Bn(t)},Md=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=qi({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},Gi=()=>({value:Y.value,cursorPosition:Y.cursorPosition,commandIsPending:Y.commandIsPending,autoCompletion:Y.commandMeta.autoCompletion??wd,infoMessage:Y.commandMeta.infoMessage,validationStatus:Y.commandMeta.validity,command:Y.commandMeta.command,inputString:Y.commandMeta.inputString,modifier:Y.commandMeta.modifier}),Pd=(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,Yi=({width:e})=>{let[t,n]=Sd(Gi());Id(()=>{let h=()=>{let I=Gi();n(b=>Pd(b,I)?b:I)},C=ao(h);return h(),()=>{C()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:d,command:u,modifier:m}=t,g=bd(()=>{let h=Math.max(0,Math.min(o,r.length)),C=qi({value:r,command:u}),I=Md({value:r,command:u,modifier:m}),b=u?Bn(u):null,A=Rd({command:u,modifier:m}),S=(ne,re)=>{let An=C&&re>=C.start&&re<C.end,Tn=I&&re>=I.start&&re<I.end;return An&&b?b.fg(ne):Tn&&A?A.bg(ne):ne},R=(ne,re)=>{let An=C&&re>=C.start&&re<C.end,Tn=I&&re>=I.start&&re<I.end;return An&&b?b.fgCursor(ne):Tn&&A?A.bgCursor(ne):Ad(ne)},B=r.slice(0,h),Le=r[h]??" ",De=h<r.length?r.slice(h+1):"",As=Array.from(B).map((ne,re)=>S(ne,re)).join(""),Fr=R(Le,h),kr=Array.from(De).map((ne,re)=>S(ne,h+1+re)).join("");if(d.hint){let ne=d.hint[d.overlap]??Le;Fr=Td(ne),kr=zi(d.remainder.slice(1)+De)}return zi(":")+As+Fr+kr},[r,o,d,u,m]);return At.createElement(yr,{flexDirection:"column",justifyContent:"flex-start"},At.createElement(yr,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},At.createElement(yr,null,At.createElement(ji,null,g),i&&At.createElement(ji,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import Ji from"chalk";import{Box as Ld,Text as hr}from"ink";import cn,{useEffect as Dd,useState as Fd}from"react";var kd=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Xi=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)}},Od=({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)}`},Bd=(e,t,n)=>{let r=Xi(e),o=Xi(t);return Od({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Ud=(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],a=e[Math.min(r+1,e.length-1)];return Bd(i,a,o)},$d=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Zi=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=_(),[o,i]=Fd(0);Dd(()=>{if(n!=="syncing"){i(0);return}let S=setInterval(()=>{i(R=>R+1)},50);return()=>clearInterval(S)},[n]);let a=[],d=0;for(let S of t){let B=(a.length>0?" | ":"").length+S.length;if(d+B>e-4)break;a.push(S),d+=B}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),g=n==="syncing"?Ud(kd,(Math.sin(o*.12)+1)/2):N.secondary,h=Ji.hex(g??"fff"),C=Ji.hex(N.secondary2),I=h(`\u256D${"\u2500".repeat(m)}\u256E`),b=h(`\u2570${"\u2500".repeat(m)}\u256F`),A=`${h("\u2502")}${C($d(` ${u} `,m))}${h("\u2502")}`;return cn.createElement(Ld,{flexDirection:"column",width:e},cn.createElement(hr,null,I),cn.createElement(hr,null,A),cn.createElement(hr,null,b))};var un=({width:e,mode:t,availableHints:n})=>{let r=_(),o=[],i=0;for(let a of n){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return Nr.createElement(Wd,null,t===f.COMMAND_LINE&&r.syncStatus.status!=="syncing"?Nr.createElement(Yi,{width:e}):Nr.createElement(Zi,{width:e,mode:t,availableHints:n}))};import{Box as at,Text as Qi}from"ink";import We from"react";var es=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),We.createElement(at,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},We.createElement(at,{flexDirection:"column",width:e},v().mode===f.HELP?t.map(([n,r],o)=>We.createElement(at,{paddingLeft:1,key:o,flexDirection:"row"},We.createElement(at,{key:o,flexDirection:"row",paddingBottom:o?0:1},We.createElement(at,{width:20,justifyContent:"flex-end"},We.createElement(Qi,{color:o?N.accent:N.secondary},n)),We.createElement(at,{flexGrow:1,width:40,paddingLeft:2},We.createElement(Qi,{color:o?N.primary:N.secondary},r))))):null))};import os from"chalk";import{Box as pn,Text as Ge}from"ink";import Z from"react";import{Box as Er,Text as Gd}from"ink";import ct from"react";import{Text as _d}from"ink";import Hd from"react";var Kd=e=>e.toLowerCase().trim(),Vd=(e,t=Xe)=>{let n=Kd(e);return t[n]?t[n]:mt(n)},dt=({id:e,isSelected:t})=>{let n=E.getContributor(e);if(n)return Hd.createElement(_d,{underline:t,color:Vd(n.name)},"@"+n.name)};import{Text as jd}from"ink";import zd from"react";var lt=({id:e,isSelected:t})=>{let n=E.getTag(e);if(n)return zd.createElement(jd,{underline:t,backgroundColor:q(n.name),color:N.primary}," "+n.name+" ")};var qd=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",ts=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=U(n.id)[r],a=ke(i?.id??n.id,"TICKET"),d=Fe(a)?a.value:void 0,u=d?.id?U(d.id):[],m=A=>{let S=u.find(R=>R.title===A);return S?U(S.id).map(R=>typeof R.props?.value=="string"?R.props.value:"").filter(R=>!!R):[]},g=m("Tags"),h=m("Assignees"),C=d?.parentNodeId?!Pn(n.id,d?.parentNodeId)&&o==="dense":!1,I=t.map((A,S)=>{let R=S===t.length-1,B=U(A.id),Le=R?B?.[r]?.title:void 0;return`${S?" / ":""}${A.title??""}${Le?` \u25B8 ${Le}`:""}`}).join(""),b=qd(I,e);return ct.createElement(Er,null,ct.createElement(Gd,{color:N.secondary2},b),C?g.map(A=>ct.createElement(Er,{key:A,paddingLeft:2},ct.createElement(lt,{id:A}))):null,C?h.map(A=>ct.createElement(Er,{key:A,paddingLeft:2},ct.createElement(dt,{id:A}))):null)};import{Box as Yd,Text as ns}from"ink";import mn from"react";var Jd=({filters:e})=>mn.createElement(Yd,{columnGap:1},mn.createElement(ns,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>mn.createElement(ns,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),rs=mn.memo(Jd);function gn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=_(),{userName:i,preferredEditor:a}=pe(),d=40,u=process.stdout.columns-d-8,m=r.at(-1)?.id,g=Wt(m??""),h=Fe(g)?Xr(g.value):"INVALID DATE";return Z.createElement(pn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Z.createElement(Ge,null," "):Z.createElement(pn,{paddingLeft:1},e.length>0?Z.createElement(rs,{filters:e}):Z.createElement(ts,{width:u})),n==="live"?Z.createElement(pn,{columnGap:1,paddingRight:2,"max-width":d,overflow:"hidden",justifyContent:"flex-end"},Z.createElement(is,{icon:"@",value:i}),Z.createElement(is,{icon:"\u276F",value:a})):"",n==="peek"?Z.createElement(pn,{paddingLeft:1},Z.createElement(Ge,{backgroundColor:N.yellow}," Readonly "),Z.createElement(Ge,{color:N.yellow}," "+o.length+" edits ago at "),Z.createElement(Ge,{backgroundColor:N.yellow,color:N.accent}," "+h+" "),Z.createElement(Ge,{color:N.yellow},". Resume with "),Z.createElement(Ge,{backgroundColor:N.yellow}," :peek now ")):"")}function is({icon:e,value:t}){return Z.createElement(Ge,null,os.dim(e)+os.hex(N.accent)(` ${t??"-"} `))}import{Box as yl,Text as hl}from"ink";import Rt from"react";import{Box as fn,Text as Cr}from"ink";import _e from"react";import{Text as ss}from"ink";import as,{useEffect as ds,useState as Xd}from"react";var ls={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},te=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=_(),r=ls[n]??ls.default,[o,i]=Xd(0);if(ds(()=>{i(0)},[r]),ds(()=>{if(!e)return;let d=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return as.createElement(ss,null,t);let a=r[o]??r[0]??t;return as.createElement(ss,{color:N.accent,dimColor:o===1},a)};function Ir(){let e=_(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?w(t?.id):[];return _e.createElement(fn,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},_e.createElement(fn,{padding:1,paddingTop:0,paddingBottom:0},_e.createElement(Cr,null,"Select a board:")),_e.createElement(fn,{padding:1,flexDirection:"column"},a.map((d,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,h=w(d.id).flatMap(({id:C})=>U(C)).length;return _e.createElement(fn,{key:d.id??u},_e.createElement(Cr,{color:m?N.accent:N.secondary2},_e.createElement(te,{isSelected:m})),_e.createElement(Cr,{color:m?N.accent:N.secondary2},d.title," (",h," issues)",d.readonly?" \u{1F512}":""))})))}import{Box as vl}from"ink";import En from"react";import{Box as Ar,Text as nl}from"ink";import xe from"react";import{Box as br,Text as Zd}from"ink";import vn from"react";var xn=({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)),a=Math.max(1,Math.ceil(r)),d=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-d),g=o?Math.min(m,Math.max(0,u-d+1)):Math.min(m,Math.floor(u/d)*d),h=g+d,C=e.slice(g,h),I=e.length>d,b=i,A=I?Math.max(1,Math.floor(d/e.length*b)):b,S=Math.max(0,b-A),R=Math.max(1,e.length-d),B=I?Math.floor(g/R*S):0;return vn.createElement(br,{flexDirection:"row",height:i,width:"100%"},vn.createElement(br,{flexDirection:"column",flexGrow:1,height:i},C),vn.createElement(br,{flexDirection:"column",width:1,height:b},Array.from({length:b}).map((Le,De)=>vn.createElement(Zd,{key:De,color:I&&De>=B&&De<B+A?N.accent:N.secondary},I?"\u2502":" "))))};import{Box as yn,Text as Qd}from"ink";import qe from"react";var cs=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Lt(wn(t.title),r),i=Ln(t),a=Dn(t);return qe.createElement(yn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?N.accent:N.secondary,justifyContent:"space-between"},qe.createElement(yn,{borderBottom:!0},qe.createElement(yn,{paddingLeft:1,flexDirection:"column"},qe.createElement(Qd,{color:N.primary},o))),qe.createElement(yn,{flexDirection:"row",paddingLeft:1},i.map(d=>qe.createElement(lt,{key:d.id,id:d.id})),a.map(d=>qe.createElement(dt,{key:d.id,id:d.id}))))};import el from"chalk";import{Box as wt,Text as Sr}from"ink";import Re from"react";var tl=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,us=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=w(t.id),a=A=>{let S=i.find(R=>R.title===A);return S?w(S.id).map(R=>typeof R.props?.value=="string"?R.props.value:"").filter(R=>!!R):[]},d=a("Tags").map(A=>E.getTag(A)).filter(A=>!!A),u=a("Assignees").map(A=>E.getContributor(A)).filter(A=>!!A),m=1,g=d.length*(1+m),h=u.length*(2+m),C=d.map(A=>Re.createElement(wt,{key:A.id,paddingRight:m},Re.createElement(Sr,{color:q(A.name)},"\u25A0"))),I=u.map(A=>Re.createElement(wt,{key:A.id,paddingRight:m},Re.createElement(Sr,{color:mt(A.name)},"@"+A.name.at(0)))),b=n?N.accent:o===f.MOVE?N.secondary:N.primary;return Re.createElement(wt,{borderBottom:!0,justifyContent:"space-between"},Re.createElement(wt,null,Re.createElement(te,{isSelected:n,placeholder:el.dim.gray(r+1+" ")}),Re.createElement(Sr,{wrap:"truncate",color:b},tl(t.title,e-g-h-14))),Re.createElement(wt,null,C,I))};var rl=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:u}=_(),m=u[e.id]??[],g=`${e.title} (${m.length})`,h=3,C=o?1:4,I=r-h-(o?2:1),b=xe.createElement(Ar,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},xe.createElement(te,{isSelected:t}),xe.createElement(nl,{bold:!0,color:t?N.accent:N.primary},g," ",e.readonly?"\u{1F512}":"")),A=(S,R)=>{let B=i&&a===R;return o?xe.createElement(us,{key:S.id,index:R,width:n,ticket:S,isSelected:B,mode:d}):xe.createElement(cs,{key:S.id,width:n,ticket:S,isSelected:B})};return xe.createElement(Ar,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:r},b,xe.createElement(Ar,{padding:o?1:0},m.length>0&&xe.createElement(xn,{selectedIndex:a,height:I,itemHeight:C},m.map(A)),xe.createElement(te,{isSelected:i&&a===-1})))},ms=xe.memo(rl);import{Box as Rr,Text as gl}from"ink";import He,{useEffect as Mr,useMemo as vs}from"react";import ge from"chalk";import ps from"string-width";import{decodeTime as ol}from"ulid";var il=(e,t)=>e+" ".repeat(Math.max(0,t-ps(e))),sl=(e,t)=>" ".repeat(Math.max(0,t-ps(e)))+e,al=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),dl=e=>{switch(e.action){case"move.node":{let t=E.getNode(e.payload.parent),n=t?ge.dim.bgBlack(` ${t.title} `):"unknown",r=e.payload.pos;if(!r)return`to ${n}`;switch(r.at){case"start":return`to ${n} ${ge.dim("(to top of list)")}`;case"end":return`to ${n} ${ge.dim("(to bottom of list)")}`;case"before":return`to ${n} ${ge.dim("(up in list)")}`;case"after":return`to ${n} ${ge.dim("(down in list)")}`}}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?ge.bgHex(q(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?ge.bgHex(q(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?ge.hex(q(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?ge.hex(q(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""}},ll=e=>{let t=Jr(ol(e));return ge.gray(sl(t,8))},cl=12,ul=e=>il(`${e}`,cl),gs=e=>{let t=ll(e.id),n=ul(e.userName),r=al(e.action),o=dl(e),i=ge.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as hn,Text as ml}from"ink";import Me from"react";var fs=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=_(),{title:o}=t,i=w(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return E.getContributor(d)?.id;if(o==="Tags")return E.getTag(d)?.id}).filter(a=>!!a);return Me.createElement(hn,{alignItems:"center",paddingTop:1},Me.createElement(hn,{minWidth:12},Me.createElement(te,{isSelected:n}),Me.createElement(ml,{color:n?N.accent:N.secondary2},o,":")),Me.createElement(hn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,d)=>{let u=r.id===t.id&&d===e;return Me.createElement(hn,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Me.createElement(te,{isSelected:u}),o==="Assignees"?Me.createElement(dt,{isSelected:u,id:a}):o==="Tags"?Me.createElement(lt,{isSelected:u,id:a}):null)})))};import{Box as Nn,Text as Tr}from"ink";import Pe,{useEffect as pl}from"react";var wr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:d}=_(),u=C=>String(C).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];pl(()=>{let C=[];return m.forEach((I,b)=>{let A=Q.text({id:`${b}`,name:`Line ${b+1}`,parentNodeId:e,props:{value:I},readonly:!0}),S=E.createNodeAtPosition(A);Fe(S)&&C.push(S.value.id)}),()=>C.forEach(E.deleteNode)},[e,n]);let g="\u2029",h=m.map((C,I)=>{let b=d.id===e&&a===I;return Pe.createElement(Nn,{key:`${e}-${I}`},Pe.createElement(Tr,{color:b?N.primary:N.secondary2,dimColor:!b},`${I+1} `.padStart(5,"\xA0")),Pe.createElement(Tr,{backgroundColor:b?"gray":""},u(C.length?Lt(C,i-10):g)))});return Pe.createElement(Nn,{flexDirection:"column",paddingTop:1},Pe.createElement(Nn,null,Pe.createElement(te,{isSelected:o}),Pe.createElement(Tr,{color:o?N.accent:N.secondary2},t)),Pe.createElement(Nn,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Pe.createElement(xn,{scrollByOne:!0,children:h,height:r-2,selectedIndex:a,itemHeight:1})))};var fl=e=>`${e}::log`,xs=e=>e==="Assignees"||e==="Tags",ys=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=_(),o=process.stdout.columns||120,i=vs(()=>fl(e.id),[e.id]),a=vs(()=>[...e.log].reverse().map(gs).join(`
|
|
58
|
-
`),[e.log]);Mr(()=>{if(E.getNode(i))return;let R={...Q.field(i,"Log",e.id,{value:a}),readonly:!0,childRenderAxis:"vertical"};return E.createNodeAtPosition(R),()=>{E.deleteNode(i)}},[i,e.id,a]),Mr(()=>{let S=E.getNode(i);S&&S.props.value!==a&&E.updateNode({...S,props:{...S.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let d=r.id===e.id,u=r.id===i||r.parentNodeId===i;Mr(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=w(e.id);if(u){let S=E.getNode(i),B=t-3;return He.createElement(Rr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S?He.createElement(wr,{id:S.id,label:"Event log",text:S.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let g=m.reduce((S,R)=>xs(R.title)||R.id===i?S+1:S,0),h=2,C=g*1,b=t-3-C-h,A=(S,R)=>xs(S.title)?He.createElement(fs,{key:S.id,parent:S,selected:R,selectedIndex:n}):S.id===i?He.createElement(Rr,{key:S.id,paddingTop:1},He.createElement(te,{isSelected:R}),He.createElement(gl,{backgroundColor:N.secondary,color:R?N.accent:N.primary}," History \u203A\u203A ")):S.title==="Description"?He.createElement(wr,{label:"Description (press e to edit)",key:S.id,id:S.id,text:S.props.value??"",selected:R,maxWidth:o,height:b}):null;return He.createElement(Rr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((S,R)=>A(S,d&&n===R)))};var xl=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:d})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,g=u===P.BOARD||u===P.SWIMLANE,h=u===P.TICKET?t:r.find(S=>S.context===P.TICKET),C=Math.floor(d/3),I=Math.floor(d/Math.max(e.length,1)),b=Math.min(I,C),A=i==="dense";return En.createElement(vl,{flexDirection:"row",height:a},g&&e.map((S,R)=>{let B=t.id===S.id,Le=B?n:-1,De=t.context===P.BOARD&&n===R;return En.createElement(ms,{key:S.id,height:a,width:b,swimlane:S,isSelected:De,isDense:A,isFocused:B,listSelectedIndex:Le,mode:o})}),m&&h&&En.createElement(ys,{height:a,ticket:h}))},hs=En.memo(xl);var Nl=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:d}=_(),u=n.find(({context:C})=>C==="BOARD"),h=i-1-3;return Rt.createElement(yl,{flexDirection:"row"},e.context==="WORKSPACE"?Rt.createElement(Ir,null):u?Rt.createElement(hs,{height:h,width:a,swimlanes:(d[u.id]??[]).filter(C=>C!==void 0&&Or(C)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Rt.createElement(hl,null))},Ns=Rt.memo(Nl);import{Box as Mt,Text as ye}from"ink";import H from"react";var Cn=({isDone:e,command:t,value:n})=>H.createElement(Mt,null,H.createElement(ye,{color:N.accent,dimColor:e},e?" \u2714 ":" "),H.createElement(ye,{dimColor:e},"Type "),H.createElement(ye,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),n&&H.createElement(H.Fragment,null,H.createElement(ye,{dimColor:e}," "),H.createElement(ye,{color:N.secondary,dimColor:e},"<"+n+">")));function Pr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,d=n?r?null:":config:editor":":config:username";return H.createElement(Mt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},H.createElement(ye,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),H.createElement(ye,null,"Lets get you started - its a breeze."),H.createElement(ye,{color:N.secondary2},"And remember, you can always get help with"," ",H.createElement(ye,{color:N.accent},":help"),"."),!a&&H.createElement(ye,{color:N.secondary2},d===":config:username"?"First, choose your username.":"Nice. One more step."),H.createElement(Mt,{flexDirection:"column"},n&&H.createElement(Mt,{marginBottom:1},H.createElement(Cn,{isDone:!0,command:":config:username",value:o})),!n&&H.createElement(Cn,{isDone:!1,command:":config:username"}),n&&!r&&H.createElement(Cn,{isDone:!1,command:":config:editor"}),a&&H.createElement(Mt,null,H.createElement(Cn,{isDone:!0,command:":config:editor",value:i}))))}var Cl=({width:e,height:t})=>F.createElement(fe,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},F.createElement(Ke,{color:N.accent,bold:!0},"Initialize project"),F.createElement(Ke,null,`This folder is not an ${El.hex(N.accent)("epiq")} project yet.`),F.createElement(Ke,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",F.createElement(Ke,{color:N.primary,backgroundColor:N.secondary}," .epiq/ ")," ","directory in this repository."),F.createElement(fe,{marginTop:1,flexDirection:"column"},F.createElement(fe,null,F.createElement(Ke,{color:N.accent}," "),F.createElement(Ke,{color:N.primary},"Type "),F.createElement(Ke,{backgroundColor:N.secondary}," :init "))),F.createElement(fe,{marginTop:1},F.createElement(Ke,{color:N.secondary2},"(This will create the local epiq project files)")));function Lr({width:e,height:t}){let n=_(),r=n.filters;if(n.mode===f.HELP)return F.createElement(fe,{flexDirection:"column"},F.createElement(es,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:d,preferredEditor:u}=Ot(),m=!o,g=o&&Ve();if(m)return F.createElement(fe,{flexDirection:"column"},F.createElement(fe,{flexDirection:"column"},F.createElement(gn,{hideBreadCrumb:!0,filters:r}),F.createElement(Pr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:d??"",preferredEditor:u??""})),F.createElement(un,{width:e,mode:n.mode,availableHints:n.availableHints}));if(g)return F.createElement(fe,{flexDirection:"column"},F.createElement(fe,{flexDirection:"column"},F.createElement(gn,{hideBreadCrumb:!0,filters:r}),F.createElement(Cl,{height:t,width:e})),F.createElement(un,{width:e,mode:n.mode,availableHints:n.availableHints}));let h=Ee(v().breadCrumb??[],"BOARD");if(Fe(h)){let C=h.value.id,I=w(C).length,b=3,A=Math.floor(e/b),S=Math.floor(e/Math.max(I,1));e=Math.min(S,A)*Math.max(I,b)}return F.createElement(fe,{flexDirection:"column"},F.createElement(fe,{flexDirection:"column"},F.createElement(gn,{filters:r}),F.createElement(Ns,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),F.createElement(un,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Il from"readline";var In,bn,he,bl=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.InitCommandLine,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Es=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=vo(e,n);if(!o||r&&!bl.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Sl=()=>async function(t,n){n.name!=="escape"&&(he&&(clearTimeout(he),he=void 0),await Es(n))},Al=()=>async function(t){if(t.length===1&&t[0]===27){he&&clearTimeout(he),he=setTimeout(()=>{Es({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),he=void 0},25);return}he&&(clearTimeout(he),he=void 0)};function Cs(){In&&process.stdin.removeListener("keypress",In),bn&&process.stdin.removeListener("data",bn),In=Sl(),bn=Al(),Il.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",bn),process.stdin.on("keypress",In)}wl(`${Dr.bold("Epiq CLI")}
|
|
64
|
+
`)):(fc(),l("State booted successfully",null))}import{Box as Fc}from"ink";import Dr from"react";import Mt from"chalk";import{Box as Pr,Text as ps}from"ink";import Rt,{useEffect as xc,useMemo as yc,useState as hc}from"react";var gs=Mt.gray,Nc=Mt.inverse,Ec=Mt.inverse.gray,Cc={hint:"",hints:[],overlap:0,remainder:""},vs=({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}},Ic=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=q(t);return{bg:r=>Mt.bgHex(n).black(r),bgCursor:r=>Mt.bgHex(n).inverse.black(r)}}return Kn(t)},bc=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=vs({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},fs=()=>({value:Y.value,cursorPosition:Y.cursorPosition,commandIsPending:Y.commandIsPending,autoCompletion:Y.commandMeta.autoCompletion??Cc,infoMessage:Y.commandMeta.infoMessage,validationStatus:Y.commandMeta.validity,command:Y.commandMeta.command,inputString:Y.commandMeta.inputString,modifier:Y.commandMeta.modifier}),Sc=(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,xs=({width:e})=>{let[t,n]=hc(fs());xc(()=>{let h=()=>{let I=fs();n(A=>Sc(A,I)?A:I)},C=go(h);return h(),()=>{C()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:d,command:u,modifier:m}=t,g=yc(()=>{let h=Math.max(0,Math.min(o,r.length)),C=vs({value:r,command:u}),I=bc({value:r,command:u,modifier:m}),A=u?Kn(u):null,S=Ic({command:u,modifier:m}),b=(re,oe)=>{let Pn=C&&oe>=C.start&&oe<C.end,Ln=I&&oe>=I.start&&oe<I.end;return Pn&&A?A.fg(re):Ln&&S?S.bg(re):re},R=(re,oe)=>{let Pn=C&&oe>=C.start&&oe<C.end,Ln=I&&oe>=I.start&&oe<I.end;return Pn&&A?A.fgCursor(re):Ln&&S?S.bgCursor(re):Nc(re)},B=r.slice(0,h),Le=r[h]??" ",De=h<r.length?r.slice(h+1):"",Fs=Array.from(B).map((re,oe)=>b(re,oe)).join(""),_r=R(Le,h),Wr=Array.from(De).map((re,oe)=>b(re,h+1+oe)).join("");if(d.hint){let re=d.hint[d.overlap]??Le;_r=Ec(re),Wr=gs(d.remainder.slice(1)+De)}return gs(":")+Fs+_r+Wr},[r,o,d,u,m]);return Rt.createElement(Pr,{flexDirection:"column",justifyContent:"flex-start"},Rt.createElement(Pr,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},Rt.createElement(Pr,null,Rt.createElement(ps,null,g),i&&Rt.createElement(ps,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import ys from"chalk";import{Box as Ac,Text as Lr}from"ink";import En,{useEffect as Tc,useState as wc}from"react";var Rc=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],hs=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)}},Mc=({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)}`},Pc=(e,t,n)=>{let r=hs(e),o=hs(t);return Mc({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Lc=(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],a=e[Math.min(r+1,e.length-1)];return Pc(i,a,o)},Dc=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Ns=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=_(),[o,i]=wc(0);Tc(()=>{if(n!=="syncing"){i(0);return}let b=setInterval(()=>{i(R=>R+1)},50);return()=>clearInterval(b)},[n]);let a=[],d=0;for(let b of t){let B=(a.length>0?" | ":"").length+b.length;if(d+B>e-4)break;a.push(b),d+=B}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),g=n==="syncing"?Lc(Rc,(Math.sin(o*.12)+1)/2):N.secondary,h=ys.hex(g??"fff"),C=ys.hex(N.secondary2),I=h(`\u256D${"\u2500".repeat(m)}\u256E`),A=h(`\u2570${"\u2500".repeat(m)}\u256F`),S=`${h("\u2502")}${C(Dc(` ${u} `,m))}${h("\u2502")}`;return En.createElement(Ac,{flexDirection:"column",width:e},En.createElement(Lr,null,I),En.createElement(Lr,null,S),En.createElement(Lr,null,A))};var Cn=({width:e,mode:t,availableHints:n})=>{let r=_(),o=[],i=0;for(let a of n){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return Dr.createElement(Fc,null,t===p.COMMAND_LINE&&r.syncStatus.status!=="syncing"?Dr.createElement(xs,{width:e}):Dr.createElement(Ns,{width:e,mode:t,availableHints:n}))};import{Box as ut,Text as Es}from"ink";import We from"react";var Cs=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),We.createElement(ut,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},We.createElement(ut,{flexDirection:"column",width:e},v().mode===p.HELP?t.map(([n,r],o)=>We.createElement(ut,{paddingLeft:1,key:o,flexDirection:"row"},We.createElement(ut,{key:o,flexDirection:"row",paddingBottom:o?0:1},We.createElement(ut,{width:20,justifyContent:"flex-end"},We.createElement(Es,{color:o?N.accent:N.secondary},n)),We.createElement(ut,{flexGrow:1,width:40,paddingLeft:2},We.createElement(Es,{color:o?N.primary:N.secondary},r))))):null))};import As from"chalk";import{Box as bn,Text as Ye}from"ink";import Q from"react";import{Box as Fr,Text as kc}from"ink";import mt from"react";var Oc=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Is=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=U(n.id)[r],a=ke(i?.id??n.id,"TICKET"),d=Fe(a)?a.value:void 0,u=d?.id?U(d.id):[],m=S=>{let b=u.find(R=>R.title===S);return b?U(b.id).map(R=>typeof R.props?.value=="string"?R.props.value:"").filter(R=>!!R):[]},g=m("Tags"),h=m("Assignees"),C=d?.parentNodeId?!On(n.id,d?.parentNodeId)&&o==="dense":!1,I=t.map((S,b)=>{let R=b===t.length-1,B=U(S.id),Le=R?B?.[r]?.title:void 0;return`${b?" / ":""}${S.title??""}${Le?` \u25B8 ${Le}`:""}`}).join(""),A=Oc(I,e);return mt.createElement(Fr,null,mt.createElement(kc,{color:N.secondary2},A),C?g.map(S=>mt.createElement(Fr,{key:S,paddingLeft:2},mt.createElement(ct,{id:S}))):null,C?h.map(S=>mt.createElement(Fr,{key:S,paddingLeft:2},mt.createElement(dt,{id:S}))):null)};import{Box as Bc,Text as bs}from"ink";import In from"react";var Uc=({filters:e})=>In.createElement(Bc,{columnGap:1},In.createElement(bs,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>In.createElement(bs,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ss=In.memo(Uc);function Sn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=_(),{userName:i,preferredEditor:a}=pe(),d=40,u=process.stdout.columns-d-8,m=r.at(-1)?.id,g=Vt(m??""),h=Fe(g)?ro(g.value):"INVALID DATE";return Q.createElement(bn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Q.createElement(Ye,null," "):Q.createElement(bn,{paddingLeft:1},e.length>0?Q.createElement(Ss,{filters:e}):Q.createElement(Is,{width:u})),n==="live"?Q.createElement(bn,{columnGap:1,paddingRight:2,"max-width":d,overflow:"hidden",justifyContent:"flex-end"},Q.createElement(Ts,{icon:"@",value:i}),Q.createElement(Ts,{icon:"\u276F",value:a})):"",n==="peek"?Q.createElement(bn,{paddingLeft:1},Q.createElement(Ye,{backgroundColor:N.yellow}," Readonly "),Q.createElement(Ye,{color:N.yellow}," "+o.length+" edits ago at "),Q.createElement(Ye,{backgroundColor:N.yellow,color:N.accent}," "+h+" "),Q.createElement(Ye,{color:N.yellow},". Resume with "),Q.createElement(Ye,{backgroundColor:N.yellow}," :peek now ")):"")}function Ts({icon:e,value:t}){return Q.createElement(Ye,null,As.dim(e)+As.hex(N.accent)(` ${t??"-"} `))}import{Box as $c,Text as _c}from"ink";import Pt from"react";import{Box as An,Text as kr}from"ink";import He from"react";function Or(){let e=_(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?w(t?.id):[];return He.createElement(An,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},He.createElement(An,{padding:1,paddingTop:0,paddingBottom:0},He.createElement(kr,null,"Select a board:")),He.createElement(An,{padding:1,flexDirection:"column"},a.map((d,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,h=w(d.id).flatMap(({id:C})=>U(C)).length;return He.createElement(An,{key:d.id??u},He.createElement(kr,{color:m?N.accent:N.secondary2},He.createElement(ne,{isSelected:m})),He.createElement(kr,{color:m?N.accent:N.secondary2},d.title," (",h," issues)",d.readonly?" \u{1F512}":""))})))}var Wc=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:d}=_(),u=n.find(({context:C})=>C==="BOARD"),h=i-1-3;return Pt.createElement($c,{flexDirection:"row"},e.context==="WORKSPACE"?Pt.createElement(Or,null):u?Pt.createElement(fn,{height:h,width:a,swimlanes:(d[u.id]??[]).filter(C=>C!==void 0&&Dt(C)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Pt.createElement(_c,null))},ws=Pt.memo(Wc);import{Box as Lt,Text as he}from"ink";import K from"react";var Tn=({isDone:e,command:t,value:n})=>K.createElement(Lt,null,K.createElement(he,{color:N.accent,dimColor:e},e?" \u2714 ":" "),K.createElement(he,{dimColor:e},"Type "),K.createElement(he,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),n&&K.createElement(K.Fragment,null,K.createElement(he,{dimColor:e}," "),K.createElement(he,{color:N.secondary,dimColor:e},"<"+n+">")));function Br({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,d=n?r?null:":config:editor":":config:username";return K.createElement(Lt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},K.createElement(he,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),K.createElement(he,null,"Lets get you started - its a breeze."),K.createElement(he,{color:N.secondary2},"And remember, you can always get help with"," ",K.createElement(he,{color:N.accent},":help"),"."),!a&&K.createElement(he,{color:N.secondary2},d===":config:username"?"First, choose your username.":"Nice. One more step."),K.createElement(Lt,{flexDirection:"column"},n&&K.createElement(Lt,{marginBottom:1},K.createElement(Tn,{isDone:!0,command:":config:username",value:o})),!n&&K.createElement(Tn,{isDone:!1,command:":config:username"}),n&&!r&&K.createElement(Tn,{isDone:!1,command:":config:editor"}),a&&K.createElement(Lt,null,K.createElement(Tn,{isDone:!0,command:":config:editor",value:i}))))}var Kc=({width:e,height:t})=>F.createElement(ve,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},F.createElement(Ke,{color:N.accent,bold:!0},"Initialize project"),F.createElement(Ke,null,`This folder is not an ${Hc.hex(N.accent)("epiq")} project yet.`),F.createElement(Ke,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",F.createElement(Ke,{color:N.primary,backgroundColor:N.secondary}," .epiq/ ")," ","directory in this repository."),F.createElement(ve,{marginTop:1,flexDirection:"column"},F.createElement(ve,null,F.createElement(Ke,{color:N.accent}," "),F.createElement(Ke,{color:N.primary},"Type "),F.createElement(Ke,{backgroundColor:N.secondary}," :init "))),F.createElement(ve,{marginTop:1},F.createElement(Ke,{color:N.secondary2},"(This will create the local epiq project files)")));function Ur({width:e,height:t}){let n=_(),r=n.filters;if(n.mode===p.HELP)return F.createElement(ve,{flexDirection:"column"},F.createElement(Cs,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:d,preferredEditor:u}=$t(),m=!o,g=o&&Ve();if(m)return F.createElement(ve,{flexDirection:"column"},F.createElement(ve,{flexDirection:"column"},F.createElement(Sn,{hideBreadCrumb:!0,filters:r}),F.createElement(Br,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:d??"",preferredEditor:u??""})),F.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(g)return F.createElement(ve,{flexDirection:"column"},F.createElement(ve,{flexDirection:"column"},F.createElement(Sn,{hideBreadCrumb:!0,filters:r}),F.createElement(Kc,{height:t,width:e})),F.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}));let h=Ce(v().breadCrumb??[],"BOARD");if(Fe(h)){let C=h.value.id,I=w(C).length,A=3,S=Math.floor(e/A),b=Math.floor(e/Math.max(I,1));e=Math.min(b,S)*Math.max(I,A)}return F.createElement(ve,{flexDirection:"column"},F.createElement(ve,{flexDirection:"column"},F.createElement(Sn,{filters:r}),F.createElement(ws,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),F.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Vc from"readline";var wn,Rn,Ne,jc=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.InitCommandLine,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Rs=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Co(e,n);if(!o||r&&!jc.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},zc=()=>async function(t,n){n.name!=="escape"&&(Ne&&(clearTimeout(Ne),Ne=void 0),await Rs(n))},Gc=()=>async function(t){if(t.length===1&&t[0]===27){Ne&&clearTimeout(Ne),Ne=setTimeout(()=>{Rs({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ne=void 0},25);return}Ne&&(clearTimeout(Ne),Ne=void 0)};function Ms(){wn&&process.stdin.removeListener("keypress",wn),Rn&&process.stdin.removeListener("data",Rn),wn=zc(),Rn=Gc(),Vc.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Rn),process.stdin.on("keypress",wn)}Yc(`${$r.bold("Epiq CLI")}
|
|
59
65
|
|
|
60
|
-
${
|
|
61
|
-
${
|
|
66
|
+
${$r.dim("Boot in directory:")}
|
|
67
|
+
${$r.cyan("$ epiq")}
|
|
62
68
|
|
|
63
|
-
`,{importMeta:import.meta,flags:{init:{type:"string"}}});var
|
|
69
|
+
`,{importMeta:import.meta,flags:{init:{type:"string"}}});var Ps=process.stdout.columns||120,Ls=process.stdout.rows||20,Mn=null,Jc=e=>{if(!Mn){Mn=qc(e);return}Mn.rerender(e)},Ds=()=>{Jc(Xc.createElement(Ur,{width:Ps,height:Ls}))},Zc=()=>{let e=ge(process.cwd());if(c(e))throw Error(e.message);let t=Nt(e.value);if(c(t)){if(t.message.includes("No events found"))return logger.info("No events found, starting with empty state"),[];throw new Error(t.message)}return t.value},Qc=e=>{let t=ms(e);if(c(t))throw new Error(`Failed to boot state: ${t.message}`)};async function el(){let e=Mi();c(e)||Je(e.value),await Ni();let t=Zc();Qc(t),Ds(),Ms()}process.stdout.on("resize",()=>{Ps=process.stdout.columns||120,Ls=process.stdout.rows||20,Mn&&Ds()});(async()=>(console.clear(),await el()))();
|