epiq 0.3.8 → 0.3.9
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 +63 -0
- package/dist/mcp.js +52 -33
- package/package.json +6 -6
- package/readme.md +3 -3
- package/dist/cli.js +0 -45
package/dist/index.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
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"),c("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 Ta=qn.object({userId:qn.string().min(1).default("unknown"),userName:qn.string().min(1).default("unknown")}),wa=e=>{let[t,n]=Yn.basename(e,".jsonl").split("."),r=Ta.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Yn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ra=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"):c("Resolved persisted action",t[0])},Ma=(e,t)=>t in e,Pa=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),La=e=>{let{userId:t,userName:n,...r}=e,o=Ra(r);if(l(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Ma(r,i)?c("Decoded persisted event",Pa({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")},Jt=e=>{if(!Yt.existsSync(e))return c("Event file missing",[]);let t=wa(e);if(l(t))return s(t.message);let n=Yt.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(l(d))return s(`${d.message} in ${e}: ${i}`);r.push({...d.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function Ro(e){let t=xt(e);if(!Yt.existsSync(t))return s("No events found");let n=Yt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Yn.join(t,o)),r=[];for(let o of n){let i=Jt(o);if(l(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Da(r))}function ht(e){let t=Ro(e);if(l(t))return s(t.message);let n=[];for(let r of t.value){let o=La(r);if(l(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function wo(e=process.cwd()){let t=Ro(e);return l(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Da=e=>{if(e.length===0)return[];let t=new Map;for(let u of e){let m=u.id[1]??null;t.has(m)||t.set(m,[]),t.get(m).push(u)}for(let u of t.values())u.sort((m,g)=>m.id[0].localeCompare(g.id[0]));let n=[],r=new Set,o=t.get(null)??[];d(o);let i=!0;for(;i;){i=!1;for(let u=0;u<n.length;u++){let m=n[u].id[0],g=(t.get(m)??[]).filter(h=>!r.has(h.id[0]));if(g.length!==0){n.splice(u+1,0,...g);for(let h of g)r.add(h.id[0]);i=!0,u+=g.length}}}let a=e.filter(u=>!r.has(u.id[0])).sort((u,m)=>u.id[0].localeCompare(m.id[0]));return n.push(...a),n;function d(u){for(let m of u)r.has(m.id[0])||(n.push(m),r.add(m.id[0]))}},Mo=(e,t)=>{let n=e.findIndex(r=>{try{return Aa(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Po=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 Fa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[tt,Xt]=Fa;var L=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ka={"init.workspace":e=>{let{id:t,name:n}=e.payload,r=Q.workspace(t,n);Jn(r);let o=E.createNodeAtPosition(r);return l(o)?L(o.message??"Failed to initialize workspace",e):c("Workspace initialized",{action:e.action,result:o.value})},"add.workspace":e=>{let{id:t,name:n}=e.payload,r=Q.workspace(t,n),o=E.createNodeAtPosition(r);return l(o)?L(o.message??"Failed to add workspace",e):c("Added workspace",{action:e.action,result:o.value})},"add.board":e=>{let{id:t,name:n,parent:r}=e.payload,o=E.createNodeAtPosition(Q.board(t,n,r));return l(o)?L(o.message??"Unable to create board",e):c("Added board",{action:e.action,result:o.value})},"add.swimlane":e=>{let{id:t,name:n,parent:r}=e.payload,o=E.createNodeAtPosition(Q.swimlane(t,n,r));return l(o)?L(o.message??"Unable to create swimlane",e):c("Added swimlane",{action:e.action,result:o.value})},"add.issue":e=>{let{id:t,name:n,parent:r}=e.payload,o=E.createNodeAtPosition(Q.ticket(t,n,r));return l(o)?L(o.message??"Unable to create issue",e):c("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(Q.field(t,n,r,{value:o},n.includes("Description")?"vertical":"horizontal"));return l(i)?L(i.message??`Unable to create field: ${n}`,e):c("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 l(o)?L(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=E.tombstoneNode(t);return l(n)?L(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=E.createTag({id:t,name:n});return l(r)?L(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return l(r)?L(r.message??"Unable to create contributor",e):c("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 l(o)?L(o.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:o.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=E.untag(t,n);return l(r)?L(r.message??"Unable to untag ",e):c("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 l(o)?L(o.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:o.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=E.unassign(t,n);return l(r)?L(r.message??"Unable to unassign issue",e):c("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 l(o)?L(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=E.editValue(t,n);return l(r)?L(r.message??"Unable to edit description",e):c("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(!ve(n))return L("Can only close issues",e);let r=E.getNode(tt);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 l(i)?L(i.message??"Unable to close issue",e):c("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(!ve(n))return L("Can only reopen issues",e);let r=E.getNode(tt);if(!r)return L("Unable to locate closed swimlane",e);if(!(n.parentNodeId===r.id))return L("Issue is not closed",e);let i=Po(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 l(d)?L(d.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:d.value})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return l(n)?L(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})}},Oa=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Ba=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 nt(e,t=!1){let n=ka[e.action](e);if(l(n))return n;t||([...new Set(Ba(e))].forEach(a=>Oa(a,e)),oe(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 je=e=>e.map(t=>nt(t));function X(e){let t=nt(e);if(t.status!==Ne.Success)return t;let n=qt({event:e});return l(n)?n:t}function Lo(e){return e.map(t=>X(t))}import rd from"node:fs";import{createHash as Ha}from"node:crypto";import Et from"node:fs";import Ka from"node:os";import ce from"node:path";var Xn=(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=>(l(u)&&n.delete(a),u));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import Nt from"fs";import Fo from"path";import Ua from"util";var Do=1e3,ko=()=>{let e=process.cwd(),t=be(e);if(!l(t))return Fo.join(t.value,Be,"log","epiq.log")};function $a(){if(!jn)return;let e=ko();if(e===void 0||!Nt.existsSync(e))return;let n=Nt.readFileSync(e,"utf8").split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Do)return;let r=n.slice(-Do).join(`
|
|
6
|
+
`)+`
|
|
7
|
+
`;Nt.writeFileSync(e,r,"utf8")}function Zn(e,t,n=!1){if(!jn)return;let r=ko();if(!r)return;let o=Ua.format(...t),i=new Date,d=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
8
|
+
`;Nt.mkdirSync(Fo.dirname(r),{recursive:!0}),Nt.appendFileSync(r,d,"utf8"),$a()}var ae={info(...e){Zn("[Info]",e,!1)},debug(...e){Zn("->",e,!0)},error(...e){Zn("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=ae;import{spawn as Wa}from"node:child_process";import Qn from"node:fs";import Uo from"node:path";var O="epiq/events",le="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 Oo=15e3,_a={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},$o=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Qn.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=Wa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:_a}),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 ${Oo}ms`].join(`
|
|
9
|
+
`);u(n?{stdout:a,stderr:g,exitCode:124}:s(g))},Oo);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
|
+
`)))}),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(c("Git command succeeded",{stdout:a,stderr:d,exitCode:h}))})}),k=({args:e,cwd:t})=>$o({args:e,cwd:t,allowFail:!1}),rt=({args:e,cwd:t})=>$o({args:e,cwd:t,allowFail:!0}),Zt=async({cwd:e,message:t})=>{let n=await z.commit({cwd:e,message:t});if(l(n))return s(`Failed to create commit
|
|
12
|
+
${n.message}`);let r=await k({args:["rev-parse","HEAD"],cwd:e});return l(r)?s(`Commit created, but failed to read HEAD SHA
|
|
13
|
+
${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},er=async e=>{let t=await zo(e);if(l(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=>Qn.existsSync(Uo.join(n,i)));return c("Checked for in-progress Git operation",o.length>0)},tr=async({repoRoot:e})=>{let n=(await rt({args:["remote","get-url",le],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Qt=async({repoRoot:e,branch:t})=>{let n=await rt({args:["ls-remote","--heads",le,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${le}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Wo=async({repoRoot:e,branch:t})=>{let n=await rt({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Bo=e=>{try{return Qn.realpathSync.native(e)}catch{return Uo.resolve(e)}},_o=async({repoRoot:e,worktreeRoot:t})=>{let n=await k({args:["worktree","list","--porcelain"],cwd:e});if(l(n))return s(n.message);let r=Bo(t),o=n.value.stdout.split(`
|
|
14
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Bo).includes(r);return c("Checked worktree registration",o)},nr=async e=>{let t=await rt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},en=async e=>{let t=await k({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return l(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ho=async e=>{let t=await k({args:["rev-parse","--short","HEAD"],cwd:e});return l(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Ko=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),tn=async({cwd:e,branch:t})=>{let n=await Qt({repoRoot:e,branch:t});if(l(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await z.fetch({cwd:e,remote:le,branch:t});if(l(r))return s(`Failed to fetch ${t}
|
|
15
|
+
${r.message}`);let o=await z.pullRebase({cwd:e,remote:le,branch:t});return l(o)?s(`Failed during pull --rebase
|
|
16
|
+
${o.message}`):c("Pulled with rebase",!0)},Vo=async e=>{let t=await k({args:["status","--porcelain"],cwd:e});return l(t)?s(t.message):c("Checked state branch changes",t.value.stdout.trim().length>0)},jo=async e=>{let t=await en(e);return l(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var Go="4b825dc642cb6eb9a060e54bf8d69288fbee4904",qo=e=>ce.join(Be,zt,e),Va=e=>Ha("sha1").update(ce.resolve(e)).digest("hex").slice(0,12),Yo=()=>ce.join(Ka.homedir(),de),Jo=()=>ce.join(Yo(),"worktrees"),Xo=e=>ce.join(Jo(),Va(e)),ja=e=>ce.join(e,Be),ze=e=>ce.join(ja(e),zt),rr=({root:e,fileName:t})=>ce.join(ze(e),t),Ct=e=>{try{return Et.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},Zo=()=>{let e=Ct(Yo());if(l(e))return s(`Ensure epiq home failed.
|
|
17
|
+
`+e.message);let t=Ct(Jo());return l(t)?s(`Ensure worktrees dir failed.
|
|
18
|
+
`+t.message):c("Ensured epiq storage",!0)},Qo=e=>{Et.existsSync(e)&&(ae.debug("[sync] remove path",e),Et.rmSync(e,{recursive:!0,force:!0}))},ei=e=>{let t=ze(e);if(!Et.existsSync(t))return c("Events dir missing",[]);let n=Et.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},ti=(e,t)=>{for(let n of[ze(e),ze(t)]){let r=Ct(n);if(l(r))return s(r.message)}return c("Ensured state branch",void 0)},ni=async e=>{let t=await k({args:["ls-tree","--name-only","HEAD"],cwd:e});if(l(t))return s(`ensure state branch is storage only failed
|
|
19
|
+
`+t.message);let r=t.value.stdout.trim().split(`
|
|
20
|
+
`).filter(Boolean).filter(a=>a!==Be);if(r.length===0)return c("State branch is storage-only",!1);let o=await k({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(l(o))return s(`Failed to clean storage branch
|
|
21
|
+
${o.message}`);let i=await Zt({cwd:e,message:"[epiq:repair-storage-branch]"});return l(i)?s(i.message):c("Cleaned storage branch",!0)},ri=Xn(async(e=process.cwd())=>{let t=await k({args:["rev-parse","--show-toplevel"],cwd:e});return l(t)?s("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>ce.resolve(e)),zo=Xn(async e=>{let t=await k({args:["rev-parse","--git-dir"],cwd:e});if(l(t))return s(t.message);let n=t.value.stdout.trim(),r=ce.isAbsolute(n)?n:ce.join(e,n);return c("Resolved git dir",r)},e=>ce.resolve(e));import Ue from"node:fs";import It from"node:path";var si=async e=>{let t=It.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+"/"})?c(`${r} already ignored`,!1):(n=n.trimEnd()+`
|
|
23
|
+
|
|
24
|
+
# [epiq]: hydrated state is never to be committed
|
|
25
|
+
${r}
|
|
26
|
+
`,Ue.writeFileSync(t,n+`
|
|
27
|
+
`,"utf8"),ae.info(`Added ${r} to .gitignore (epiq local cache)`),c(`${r} ignored`,!0))},ai=async e=>{if((await rt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ae.info("Creating initial commit");let n=await z.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return l(n)?s(n.message):c("Created initial commit",!0)},oi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",za=async e=>{let t=await en(e);if(l(t))return s(t.message);let n=await Ho(e);if(l(n))return s(n.message);let r=`[epiq:sync:${oi(t.value)}:${oi(n.value)}]`;return c("Built sync commit message",r)},ii=async e=>{ae.info(`Creating ${O}`);let t=await k({args:["commit-tree",Go,"-m","[epiq:init-state-branch]"],cwd:e});if(l(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 l(r)?s(`Failed to create ${O}
|
|
29
|
+
${r.message}`):c("Created state branch",!0)},Ga=async({repoRoot:e})=>{let t=await Wo({repoRoot:e,branch:O});if(l(t))return s(`Ensure local state branch failed
|
|
30
|
+
`+t.message);if(t.value)return c("Local state branch already exists",!1);let n=await tr({repoRoot:e});if(l(n))return s(`Ensure local state branch failed
|
|
31
|
+
`+n.message);if(!n.value)return ii(e);let r=await Qt({repoRoot:e,branch:O});if(l(r))return s(`Ensure local state branch failed
|
|
32
|
+
`+r.message);if(!r.value)return ii(e);let o=await z.fetch({cwd:e,remote:le,branch:O});if(l(o))return s(`Failed to fetch ${O} from remote
|
|
33
|
+
${o.message}`);let i=await k({args:["branch","--track",O,`${le}/${O}`],cwd:e});return l(i)?s(`Failed to create local ${O} from remote
|
|
34
|
+
${i.message}`):c("Created local state branch from remote",!0)},qa=async({repoRoot:e,branch:t})=>{let n=await k({args:["worktree","list","--porcelain"],cwd:e});if(l(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 c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Ya=async({repoRoot:e,stateBranchRoot:t})=>{let n=Ct(It.dirname(t));if(l(n))return s(`Failed to create state branch worktree
|
|
36
|
+
`+n.message);Ue.existsSync(t)&&!Ue.existsSync(It.join(t,".git"))&&(ae.info("Removing broken state branch worktree path"),Qo(t)),ae.info("Creating state branch worktree");let r=await z.worktreeAdd({cwd:e,worktreeRoot:t,branch:O});return l(r)?s(`Failed to create state branch worktree
|
|
37
|
+
${r.message}`):c("Created state branch worktree",!0)},Ja=async({repoRoot:e,stateBranchRoot:t})=>{let n=await qa({repoRoot:e,branch:O});if(l(n))return s(n.message);let r=It.resolve(t),o=n.value?It.resolve(n.value):null;if(o&&o===r&&Ue.existsSync(o))return c("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(l(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(l(d))return s(`Failed to prune stale worktrees
|
|
39
|
+
${d.message}`)}let i=await _o({repoRoot:e,worktreeRoot:t});if(l(i))return s(i.message);let a=Ue.existsSync(t);if(i.value&&a)return c("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(l(d))return s(`Failed to prune stale worktrees
|
|
40
|
+
${d.message}`)}return Ya({repoRoot:e,stateBranchRoot:t})},Xa=async e=>{let t=await en(e);if(l(t))return s(t.message);if(t.value===O)return c("State branch already checked out",!1);let n=await z.checkout({cwd:e,branch:O});return l(n)?s(`Failed to checkout ${O}
|
|
41
|
+
${n.message}`):c("Checked out state branch",!0)},Za=async e=>{let t=await nr(e);if(l(t))return s(t.message);if(t.value)return c("State branch upstream already configured",!1);let n=await tr({repoRoot:e});if(l(n))return s(n.message);if(!n.value)return c("No remote available for state branch upstream",!1);let r=await Qt({repoRoot:e,branch:O});if(l(r))return s(r.message);if(!r.value)return c("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:le,branch:O});if(l(o))return s(`Failed to fetch ${O}
|
|
42
|
+
${o.message}`);let i=await z.setUpstream({cwd:e,branch:O,upstream:`${le}/${O}`});return l(i)?s(`Failed to set state branch upstream
|
|
43
|
+
${i.message}`):c("Configured state branch upstream",!0)},di=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=await z.stage({cwd:e,pathspec:qo(t)});return l(n)?s(`Failed to stage state branch own event file
|
|
44
|
+
${n.message}`):c("Staged state branch own event file",void 0)},li=async({repoRoot:e,stateBranchRoot:t})=>{let n=await za(e);return l(n)?s(`Create state branch sync commit failed
|
|
45
|
+
`+n.message):Zt({cwd:t,message:n.value})},or=async e=>{let t=await nr(e);if(l(t))return s(t.message);let n=t.value?await z.push({cwd:e}):await z.push({cwd:e,remote:le,branch:O,setUpstream:!0});return l(n)?s(`Failed during state branch push
|
|
46
|
+
${n.message}`):c("Pushed state branch",!0)},ci=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[Zo(),await Ga({repoRoot:e}),await Ja({repoRoot:e,stateBranchRoot:t}),await Xa(t),await ni(t),n?await Za(t):c("Skipped state branch upstream bootstrap",!1)];for(let i of o){if(l(i))return s(i.message);r=r||!!i.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import nn from"node:fs";import sr from"node:path";import{decodeTime as Qa}from"ulid";var ir=e=>{let[t,n]=e.id;return`${t}:${n??""}`},ui=e=>{let[t]=e.id;return Qa(t)},ed=e=>{let{userId:t,userName:n,...r}=e;return r},td=e=>e.length===0?"":e.map(t=>JSON.stringify(ed(t))).join(`
|
|
47
|
+
`)+`
|
|
48
|
+
`,nd=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(ir(r),r);return[...n.values()].sort((r,o)=>{let i=ui(r)-ui(o);return i!==0?i:ir(r).localeCompare(ir(o))})},ar=({sourceFile:e,targetFile:t})=>{let n=Jt(e);if(l(n))return s(n.message);let r=Jt(t);if(l(r))return s(r.message);let o=nd(r.value,n.value),i=td(o);return(nn.existsSync(t)?nn.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(nn.mkdirSync(sr.dirname(t),{recursive:!0}),nn.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},dr=({repoRoot:e,stateBranchRoot:t})=>{let n=ei(t);if(l(n))return s(n.message);let r=ze(t),o=ze(e),i=!1;for(let a of n.value){let d=sr.join(r,a),u=sr.join(o,a),m=ar({sourceFile:d,targetFile:u});if(l(m))return s(m.message);i=i||m.value}return c("Hydrated event files from state branch",i)};var pi=async(e=process.cwd())=>{let t=await gi({cwd:e,ensureUpstream:!1});if(l(t))return t;let{repoRoot:n,stateBranchRoot:r}=t.value,o=await tn({cwd:r,branch:O});if(l(o))return s(o.message);let i=dr({repoRoot:n,stateBranchRoot:r});return l(i)?s(i.message):c("Synced state branch",{repoRoot:n,stateBranchRoot:r})},od=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=rr({root:e,fileName:n}),o=rr({root:t,fileName:n});return rd.existsSync(r)?ar({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},gi=async({cwd:e,ensureUpstream:t})=>{let n=await ri(e);if(l(n))return s(n.message);let r=n.value,o=Xo(r),i=await si(r);if(l(i))return s("Sync aborted. Unable to gitignore hydrated events");let a=await er(r);if(l(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 ai(r);if(l(d))return s(d.message);let u=await ci({repoRoot:r,stateBranchRoot:o,ensureUpstream:t});if(l(u))return s(u.message);let m=await er(o);if(l(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=ti(r,o);return l(g)?s(g.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:o,bootstrapped:u.value})},mi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=od({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(l(r))return s(r.message);let o=await Vo(t);if(l(o))return s(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let i=await di({stateBranchRoot:t,ownEventFileName:n});if(l(i))return s(i.message);let a=await li({repoRoot:e,stateBranchRoot:t});return l(a)?s(a.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},fi=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 gi({cwd:e,ensureUpstream:!0});if(l(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await jo(r);if(l(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 tn({cwd:o,branch:O});if(l(C))return s(C.message);m=C.value;let I=dr({repoRoot:r,stateBranchRoot:o});if(l(I))return s(I.message);h=I.value;let b=await mi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(l(b))return s(b.message);if(d=b.value.createdCommit,u=b.value.commitSha,d||i){let A=await or(o),S=A;if(l(A)&&Ko(A.message)){let R=await tn({cwd:o,branch:O});if(l(R))return s(R.message);let B=await mi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(l(B))return s(B.message);B.value.createdCommit&&(d=!0,u=B.value.commitSha),S=await or(o)}if(l(S))return s(S.message);g=S.value,logger.debug("[sync] pushed to state branch",g)}else logger.debug("[sync] no commit created, skipped push");if(d){let A=await k({args:["rev-parse","HEAD"],cwd:o});if(l(A))return s(A.message);u=A.value.stdout.trim()}return c("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 vi}from"ulid";var ot=null,$e=()=>structuredClone(ot),it=e=>ot=e,xi=()=>{let{currentNode:e,selectedIndex:t}=v(),r=w(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};function lr(e){let t=xi();if(l(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=J();if(l(u))return s("Unable to resolve user ID");let{userId:m,userName:g}=u.value;if(it({id:vi(),userId:m,userName:g,action:"move.node",payload:{id:t.value.id,parent:d.id,pos:{at:"end"}}}),!ot)return s("Could not materialize move state");let h=nt(ot,!0);return l(h)?h:c("Node moved successfully",h.value)}function cr(e){let t=xi();if(l(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=U(n.id)[r+e];if(!i)return s("Missing sibling node");let a=J();if(l(a))return s("Unable to resolve user ID");let{userId:d,userName:u}=a.value;if(it({id:vi(),userId:d,userName:u,action:"move.node",payload:{id:t.value.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:i.id}}}),!ot)return s("Could not materialize move state");let m=nt(ot,!0);return l(m)?m:c("Node moved successfully",m.value)}import id from"node:os";import yi from"node:path";import{z as bt}from"zod";var sd={userId:"",userName:"",preferredEditor:"",autoSync:!1},hi=bt.object({preferredEditor:bt.string().optional(),userName:bt.string().optional(),userId:bt.string().optional(),autoSync:bt.boolean().optional()}).strict(),ad="config.json",Ni=()=>yi.join(id.homedir(),de),ur=()=>yi.join(Ni(),ad),mr=()=>{try{return se.mkDir(Ni()),c(`Ensured ~/${de} exists`,null)}catch{return s(`Unable to create ~/${de}`)}},dd=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${de}/config.json JSON`)}let n=hi.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${de}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ei=()=>{let e=mr();if(l(e))return s(e.message);let t=ur(),n=se.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):dd(n)},Ci=e=>{let t=mr();if(l(t))return s(t.message);let n=hi.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=ur();try{return se.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
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)}`),`
|
|
50
|
+
`].join(`
|
|
51
|
+
`)):(we=null,c("Persisted pending default events",null))}function Vi(e){let t;e.some(r=>r.action==="init.workspace")?(we=null,t=je(e)):(we=Cd(),t=je([...we]));let n=t.filter(l);return n.length>0?s([st.bold.red("Materializing failed"),"",...n.map((r,o)=>`${st.dim.gray(`${o+1}.`)} ${st.dim(r.message)}`),`
|
|
52
|
+
`].join(`
|
|
53
|
+
|
|
54
|
+
See complete log:
|
|
55
|
+
|
|
56
|
+
`)+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")}
|
|
59
|
+
|
|
60
|
+
${Dr.dim("Boot in directory:")}
|
|
61
|
+
${Dr.cyan("$ epiq")}
|
|
62
|
+
|
|
63
|
+
`,{importMeta:import.meta,flags:{init:{type:"string"}}});var Is=process.stdout.columns||120,bs=process.stdout.rows||20,Sn=null,Ml=e=>{if(!Sn){Sn=Tl(e);return}Sn.rerender(e)},Ss=()=>{Ml(Rl.createElement(Lr,{width:Is,height:bs}))},Pl=()=>{let e=be(process.cwd());if(l(e))throw Error(e.message);let t=ht(e.value);if(l(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},Ll=e=>{let t=Vi(e);if(l(t))throw new Error(`Failed to boot state: ${t.message}`)};async function Dl(){let e=Ii();l(e)||Je(e.value),await pi();let t=Pl();Ll(t),Ss(),Cs()}process.stdout.on("resize",()=>{Is=process.stdout.columns||120,bs=process.stdout.rows||20,Sn&&Ss()});(async()=>(console.clear(),await Dl()))();
|