epiq 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +113 -113
- package/dist/index.js +100 -100
- package/dist/mcp.js +114 -86
- package/package.json +1 -1
- package/readme.md +18 -143
package/dist/index.js
CHANGED
|
@@ -1,116 +1,116 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`);return i===-1?"":s.slice(i+1)}finally{
|
|
5
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
2
|
+
import mn from"chalk";import{render as iP}from"ink";import aP from"meow";import lP from"react";import ax from"chalk";import cI from"node:crypto";var Zn={Success:"success",Fail:"fail"},l=e=>({status:Zn.Fail,message:e,value:null}),d=(e,t)=>({status:Zn.Success,message:e,value:t}),a=e=>e.status==="fail",ve=e=>e.status==="success";var Dn="EPIQ_USER_NAME",Oi="EPIQ_USER_ID",Am="0123456789ABCDEFGHJKMNPQRSTVWXYZ",dI=26,sc=80,ic=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Fi=e=>e.trim().length>0&&e.length<=sc,lo=e=>e.trim().toLowerCase(),uI=e=>{let t=cI.createHash("sha256").update(`epiq:actor:${lo(e)}`).digest(),n="";for(let r=0;r<dI;r++)n+=Am[(t[r]??0)%Am.length];return n},co=(e,t=process.env)=>{let n=(t[Dn]??"").trim(),r=(t[Oi]??"").trim();return n?Fi(n)?!r&&e.userId&&e.userName&&lo(e.userName)===lo(n)?d("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!ic(r)?l(`${Oi} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?l(`${Oi} is the configured user's own id; using it under a different name would rename them on the board`):d("Resolved actor from environment",{userId:r||uI(n),userName:r?n:lo(n)}):l(`${Dn} must be 1-${sc} characters of text`):r?l(`${Oi} is set without ${Dn}`):d("No actor override",null)},ac=(e,t,n=process.env)=>{let r=e.trim();if(!Fi(r))return l(`${t} must be 1-${sc} characters of text`);let o=(n[Dn]??"").trim();return o&&lo(o)!==lo(r)?l(`${t} names ${r}, but ${Dn} names ${o}`):(o||(n[Dn]=r),d("Applied actor name argument",o||r))};import GI from"node:path";import{z as Qt}from"zod";var uo=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},mo=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e));import fs from"node:fs";import fn from"node:path";import er from"node:fs";import Et from"node:path";import as from"node:fs";import{ulid as mI}from"ulid";import{z as _i}from"zod";var pI="__epiq_state__",fI=_i.object({projectId:_i.string().min(1),stateBranch:_i.string().min(1),createdAt:_i.iso.datetime()}),ji=()=>({projectId:mI(),stateBranch:pI,createdAt:new Date().toISOString()}),Mt=e=>{let t=po(e);if(!as.existsSync(t))return l("Missing .epiq/project.json");try{let n=as.readFileSync(t,"utf8"),r=JSON.parse(n),o=fI.safeParse(r);return o.success?d("Read project.json",o.data):l(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return l(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},pn=e=>{let t=Mt(e);return a(t)?l(t.message):d("Read projectId",t.value.projectId)},lc=({repoRoot:e,fileContents:t})=>{let n=Mr(e),r=po(e);try{if(as.mkdirSync(n,{recursive:!0}),as.existsSync(r)){let o=Mt(e);return a(o)?l(o.message):d("Project already initialized",null)}return as.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),d("Created project.json",null)}catch(o){return l(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import gI from"node:os";import hI from"node:path";var Yt=".epiq-global",Bn=()=>process.env.EPIQ_GLOBAL_DIR??hI.join(gI.homedir(),Yt);var cc=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(a(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Xt from"fs";import fc from"path";import yI from"util";var Tm=500,gc=4*1024*1024,dc=16*1024,vI=50,uc=0,wm=()=>process.env.EPIQ_MCP==="true",bI=()=>{let e=process.cwd(),t=$i(e);return a(t)?wm()?fc.join(Bn(),"epiq-mcp.log"):void 0:fc.join(t.value,gt,"log","epiq.log")},xI=(e,t)=>{let n=Xt.statSync(e).size;if(n<=t)return Xt.readFileSync(e,"utf8");let r=Xt.openSync(e,"r");try{let o=Buffer.alloc(t);Xt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
4
|
+
`);return i===-1?"":s.slice(i+1)}finally{Xt.closeSync(r)}};function II(e){if(!Xt.existsSync(e))return;let t=Xt.statSync(e).size,n=xI(e,gc).split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=gc&&n.length<=Tm)return;let r=n.slice(-Tm).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;
|
|
8
|
-
`;try{
|
|
9
|
-
`);
|
|
10
|
-
`)))}),o.on("close",f=>{let g=f??1;if(n){
|
|
11
|
-
`)));return}d(
|
|
12
|
-
${s}`:""}`));return}let
|
|
7
|
+
`;Xt.writeFileSync(e,r,"utf8")}var EI=e=>{if(e.length<=dc)return e;let t=e.length-dc;return`${e.slice(0,dc)} \u2026 [${t} more chars]`};function mc(e,t,n=!1){let r=bI();if(!r)return;let o=EI(yI.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
8
|
+
`;try{Xt.mkdirSync(fc.dirname(r),{recursive:!0}),Xt.appendFileSync(r,c,"utf8"),uc++,(uc>=vI||Xt.statSync(r).size>gc)&&(uc=0,II(r))}catch{}}var pc=()=>wm()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ee={info(...e){let t=pc();(t==="info"||t==="debug")&&mc("[Info]",e,!1)},debug(...e){pc()==="debug"&&mc("[Debug]",e,!0)},error(...e){let t=pc();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;mc("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ee;import{spawn as Pm}from"node:child_process";import Lt from"node:fs";import It from"node:path";var Ce={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>U({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>U({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>U({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>U({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>U({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return U({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>U({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>U({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>U({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>U({args:["worktree","prune"],cwd:e})};var ke=e=>{let t=re(e);if(a(t))return l("Unable to resolve epiq project root");let n=Mt(t.value);return a(n)?l("Unable to read project.json"):d("Resolved state branch",n.value.stateBranch)},Pt="origin";var hc=1e4,SI=12e4,RI=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),CI=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&RI.has(t)?SI:hc},NI=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(It.delimiter))if(t)for(let n of e){let r=It.join(t,n);try{if(!Lt.statSync(r).isFile())continue;return Lt.accessSync(r,Lt.constants.X_OK),r}catch{continue}}return"git"},Lm=NI(),km={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Dm=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Lt.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(l(f));return}let o=Pm(Lm,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:km}),s=!1,i="",c="",u=f=>{s||(s=!0,clearTimeout(m),r(f))},p=CI(e),m=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${p}ms`].join(`
|
|
9
|
+
`);u(n?{stdout:i,stderr:f,exitCode:124}:l(f))},p);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{i+=f}),o.stderr.on("data",f=>{c+=f}),o.on("error",f=>{if(n){u({stdout:i,stderr:f.message,exitCode:1});return}u(l([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
10
|
+
`)))}),o.on("close",f=>{let g=f??1;if(n){u({stdout:i,stderr:c,exitCode:g});return}if(g!==0){u(l([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
11
|
+
`)));return}u(d("Git command succeeded",{stdout:i,stderr:c,exitCode:g}))})}),U=({args:e,cwd:t})=>Dm({args:e,cwd:t,allowFail:!1}),Le=({args:e,cwd:t})=>Dm({args:e,cwd:t,allowFail:!0}),Ui=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let r=Pm(Lm,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:km}),o=[],s="",i=!1,c=p=>{i||(i=!0,clearTimeout(u),n(p))},u=setTimeout(()=>{r.kill("SIGTERM"),c(l(`git cat-file --batch timed out after ${hc}ms`))},hc);r.stdout.on("data",p=>o.push(p)),r.stderr.setEncoding("utf8"),r.stderr.on("data",p=>{s+=p}),r.on("error",p=>c(l(p.message))),r.on("close",p=>{if(p!==0){c(l(`git cat-file --batch exited ${p}${s?`
|
|
12
|
+
${s}`:""}`));return}let m=Buffer.concat(o),f=new Map,g=0;for(let h of e){let x=m.indexOf(10,g);if(x===-1){c(l(`git cat-file --batch output ended before a header for ${h}`));return}let b=m.toString("utf8",g,x);g=x+1;let R=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(b);if(!R||!R[1]){c(l(`Unexpected git cat-file --batch header: "${b}"`));return}let S=Number(R[1]);f.set(h,m.toString("utf8",g,g+S)),g+=S+1}c(d("Read blobs",f))}),r.stdin.write(e.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`),r.stdin.end()}),
|
|
15
|
-
${r.message}`);let o=await
|
|
16
|
-
${o.message}`):
|
|
17
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
18
|
-
${t.stderr.trim()}`):
|
|
19
|
-
${o.message}`);let s=await
|
|
20
|
-
${s.message}`);let i=await
|
|
21
|
-
`+r.message);let o=
|
|
22
|
-
`+o.message):
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
14
|
+
`),r.stdin.end()}),go=async({cwd:e,message:t,pathspec:n})=>{let r=await Ce.commit({cwd:e,message:t,pathspec:n});if(a(r))return l(`Failed to create commit
|
|
15
|
+
${r.message}`);let o=await U({args:["rev-parse","HEAD"],cwd:e});return a(o)?l(`Commit created, but failed to read HEAD SHA
|
|
16
|
+
${o.message}`):d("Created commit and resolved SHA",o.value.stdout.trim())},ls=async e=>{let t=await U({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return l(t.message);let n=t.value.stdout.trim();return d("Resolved git dir",It.isAbsolute(n)?n:It.resolve(e,n))},yc=async e=>{let t=await ls(e);if(a(t))return l(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Lt.existsSync(It.join(n,s)))return d("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(Lt.existsSync(It.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},Bm=async e=>{let t=await yc(e);return a(t)?l(t.message):d("Checked for in-progress Git operation",t.value!==null)},On=async({repoRoot:e})=>{let n=(await Le({args:["remote","get-url",Pt],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},cs=async({repoRoot:e,branch:t})=>{let n=await Le({args:["ls-remote","--heads",Pt,t],cwd:e});return n.exitCode!==0?l(n.stderr.trim()||`Unable to inspect remote branch ${Pt}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},Hi=async({repoRoot:e,branch:t})=>{let n=await Le({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?d("Local branch exists",!0):n.exitCode===1?d("Local branch missing",!1):l(n.stderr.trim()||`Unable to inspect branch ${t}`)},fo=e=>{try{return Lt.realpathSync.native(e)}catch{return It.resolve(e)}},Om=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return l(n.message);let r=fo(t),o=n.value.stdout.split(`
|
|
17
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(fo).includes(r);return d("Checked worktree registration",o)},vc=async e=>{let t=await Le({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Wi=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?l(t.message):d("Resolved current branch",t.value.stdout.trim())},Fm=async e=>{let t=await U({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?l(t.message):d("Resolved short HEAD sha",t.value.stdout.trim())},_m=e=>e.includes("fetch first")||e.includes("non-fast-forward"),jm=async e=>{let t=await Le({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Lt.existsSync(It.join(n,"rebase-merge"))||Lt.existsSync(It.join(n,"rebase-apply")):!1},AI=3,TI=120,wI=e=>new Promise(t=>setTimeout(t,e)),MI=async(e,t)=>{let n=await Ce.rebaseOnto({cwd:e,ref:t});for(let r=1;r<AI;r+=1){if(!a(n)||await jm(e))return n;await wI(TI),n=await Ce.rebaseOnto({cwd:e,ref:t})}return n},$m=async(e,{preserve:t=[]}={})=>{let n=await ls(e);if(a(n))return l(n.message);let r=n.value,o=[];for(let s of Lt.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{Lt.rmSync(It.join(r,s),{force:!0}),o.push(s)}catch{}return d("Cleared stale git lock files",o)},Um=async(e,t)=>{let n=await Le({cwd:e,args:["rev-parse","--git-common-dir"]});if(n.exitCode!==0)return l(`Unable to resolve the common git directory at ${e}`);let r=It.resolve(e,n.stdout.trim()),o=It.join(r,"refs","heads"),s=It.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${It.sep}`))return l(`Refusing to clear a ref lock outside ${o}`);if(!Lt.existsSync(s))return d("No ref lock to clear",!1);try{Lt.rmSync(s,{force:!0})}catch{return d("Ref lock could not be cleared",!1)}return d("Cleared a stale ref lock",!0)},bc=async e=>{if(!await jm(e))return d("No rebase to abort",!1);let t=await Le({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?l(`Failed to abort the rebase in progress at ${e}
|
|
18
|
+
${t.stderr.trim()}`):d("Aborted stale rebase",!0)},Mm=async e=>{let t=await Le({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},ds=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),PI=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),us=async({cwd:e,branch:t})=>{let n=await bc(e);if(a(n))return l(n.message);let r=await Mm(e),o=await Ce.fetch({cwd:e,remote:Pt,branch:t});if(a(o))return PI(o.message)?d("Remote branch missing, skipped pull",!1):l(`Failed to fetch ${t}
|
|
19
|
+
${o.message}`);let s=await MI(e,`${Pt}/${t}`);if(a(s))return l(`Failed during rebase
|
|
20
|
+
${s.message}`);let i=await Mm(e),c=r!==null&&i!==null&&r!==i;return d(c?"Pulled with rebase":"Already up to date",c)},Hm=async e=>{let t=await Le({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?d("No upstream to compare against",!1):d("Compared against upstream",Number(t.stdout.trim())>0)},Wm=async e=>{let t=await Le({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?l(t.stderr.trim()||"Unable to inspect the worktree for changes"):d("Inspected worktree for changes",t.stdout.trim().length>0)},Gm=async(e,t)=>{let n=await Le({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?d("No staged changes",!1):n.exitCode===1?d("Has staged changes",!0):l(n.stderr.trim()||"Unable to inspect staged changes")};var Vm=async e=>{let t=await Wi(e);return a(t)?l(t.message):d("Checked detached HEAD state",t.value==="HEAD")};var qm="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ym=e=>Et.join(gt,Fn,e),Xm=()=>Et.join(gt,Ec),Jm=Bn,Pr=()=>Et.join(Jm(),"worktrees"),me=({repoRoot:e})=>{let t=pn(e);return a(t)?l(t.message):d("Resolved state branch root",Et.join(Pr(),t.value))},LI=e=>Et.join(e,gt),zm=e=>Et.join(LI(e),Fn);var ms=e=>{try{return er.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return l(t instanceof Error?t.message:String(t))}},ps=()=>{let e=Jm(),t=Pr(),n=!er.existsSync(e)||!er.existsSync(t),r=ms(e);if(a(r))return l(`Ensure epiq home failed.
|
|
21
|
+
`+r.message);let o=ms(t);return a(o)?l(`Ensure worktrees dir failed.
|
|
22
|
+
`+o.message):d("Ensured epiq storage",n)},Qm=e=>{er.existsSync(e)&&(ee.debug("[sync] remove path",e),er.rmSync(e,{recursive:!0,force:!0}))};var kI=`*.jsonl merge=union
|
|
23
|
+
`,DI=`*~pending*.jsonl
|
|
24
|
+
`,xc=()=>Et.join(gt,Fn,".gitattributes"),Ic=()=>Et.join(gt,Fn,".gitignore"),Km=(e,t)=>{try{er.readFileSync(e,"utf8")!==t&&er.writeFileSync(e,t)}catch{er.writeFileSync(e,t)}},Zm=(e,t)=>{for(let n of[zm(e),zm(t)]){let r=ms(n);if(a(r))return l(r.message)}return Km(Et.join(t,xc()),kI),Km(Et.join(t,Ic()),DI),d("Ensured state branch",void 0)},ep=async e=>{let t=await U({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return l(`ensure state branch is storage only failed
|
|
25
25
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
26
|
-
`).filter(Boolean).filter(i=>i!==gt);if(r.length===0)return
|
|
27
|
-
${o.message}`);let s=await
|
|
28
|
-
`),u("Config written",null)}catch{return c(`Unable to write ~/${Vt}/config.json`)}},Bt=e=>{let t=pn();if(a(t))return c("Failed to read existing config");let n={...t.value,...e};return Qm(n)},ht=()=>{let e=gc(),t=hc();if(a(t))return c(`Unable to create ~/${Vt}`);if(!(ot.readFile(e)!==null)){let b=Qm(AI);if(a(b))throw new Error(`Unable to create ~/${Vt}/config.json`)}let r=pn();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:d,autoSyncDebounceMs:m,attachmentMaxKb:p,logLevel:f,viewMode:g}=r.value,y=lo({userId:i,userName:s});if(a(y))return c(y.message);let x=y.value??{userId:i,userName:s};return!x.userName||!x.userId?c(`User name or ID not configured in ~/${Vt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,u("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:d??!1,autoSyncIntervalMs:m??1e4,attachmentMaxKb:p??null,viewMode:g??"dense"}))};import{useSyncExternalStore as MI}from"react";var fs={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},yc=new Set,PI=()=>{for(let e of yc)e()},V=()=>fs,Zm=()=>MI(e=>(yc.add(e),()=>{yc.delete(e)}),()=>fs),je=e=>(fs={...fs,...e},PI(),fs);import{spawn as LI}from"node:child_process";import vc from"node:process";var bc=e=>{let t=vc.platform==="darwin"?"open":vc.platform==="win32"?"cmd":"xdg-open",n=vc.platform==="win32"?["/c","start","",e]:[e];LI(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Wb,stat as dw}from"node:fs/promises";import{createHash as uw}from"node:crypto";import Er from"chalk";import Rv from"string-width";import{decodeTime as ep}from"ulid";var Hi=1440*60*1e3,gs=(e,t=Date.now())=>e>t+Hi?t:e,Be=e=>gs(ep(e)),ho=e=>{let t=Date.now()+Hi,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},yo=e=>{try{return u("Decoded date",new Date(Be(e)))}catch(t){return c("Decoding failed + "+t.message)}},er=e=>{if(!e?.id)return null;try{return ep(e.id)}catch{return null}};import vo from"chalk";var at={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},h={accent:at.cyan,accent2:at.magenta,primary:at.white,secondary:at.grayDark,secondary2:at.grayLight,gray:at.gray,green:at.green,yellow:at.yellow,red:at.red};var L={red:at.red,yellow:at.yellow,green:at.green,blue:at.blue,magenta:at.magenta,cyan:at.cyan},Wi={urgent:L.red,critical:L.red,important:L.red,blocker:L.red,asap:L.red,immediate:L.red,fail:L.red,failure:L.red,broken:L.red,bug:L.red,error:L.red,incident:L.red,outage:L.red,production:L.red,crash:L.red,security:L.red,warning:L.yellow,warn:L.yellow,risky:L.yellow,risk:L.yellow,attention:L.yellow,pending:L.yellow,review:L.yellow,"needs-review":L.yellow,qa:L.yellow,testing:L.yellow,test:L.yellow,validate:L.yellow,verification:L.yellow,staging:L.yellow,check:L.yellow,"follow-up":L.yellow,followup:L.yellow,waiting:L.yellow,blocked:L.yellow,hold:L.yellow,done:L.green,complete:L.green,completed:L.green,success:L.green,ok:L.green,stable:L.green,resolved:L.green,fixed:L.green,closed:L.green,merged:L.green,released:L.green,deployed:L.green,approved:L.green,verified:L.green,working:L.green,healthy:L.green,pass:L.green,passing:L.green,info:L.blue,information:L.blue,note:L.blue,docs:L.blue,documentation:L.blue,doc:L.blue,guide:L.blue,help:L.blue,explanation:L.blue,detail:L.blue,details:L.blue,context:L.blue,design:L.blue,discussion:L.blue,proposal:L.blue,idea:L.blue,feature:L.magenta,enhancement:L.magenta,improvement:L.magenta,refactor:L.magenta,refactoring:L.magenta,cleanup:L.magenta,optimize:L.magenta,optimization:L.magenta,perf:L.magenta,performance:L.magenta,upgrade:L.magenta,migration:L.magenta,modernize:L.magenta,debt:L.magenta,todo:L.cyan,next:L.cyan,planned:L.cyan,plan:L.cyan,future:L.cyan,backlog:L.cyan,investigate:L.cyan,explore:L.cyan,prototype:L.cyan};var Ic={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},tp=(e,t,n)=>Math.max(t,Math.min(n,e)),xc=(e,t,n)=>e+(t-e)*n,np=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kI=e=>e.toLowerCase().trim(),DI=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),d=0,m=0,p=0;i>=0&&i<1?(d=s,m=l):i>=1&&i<2?(d=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(d=l,p=s):(d=s,p=l);let f=o-s/2;return[Math.round((d+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},rp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var BI=(e,t,n)=>{let r=tp(n,0,1);return[Math.round(xc(e[0],t[0],r)),Math.round(xc(e[1],t[1],r)),Math.round(xc(e[2],t[2],r))]};var OI=(e,t,n)=>BI(e,t,n),Ec=e=>{let t=np(e)%360,n=DI(t,Ic.stringColor.saturation,Ic.stringColor.lightness);return rp(n)},qe=(e,t=Wi)=>{let n=kI(e??"");return n&&t[n]?t[n]:Ec(n)};var op=e=>{let t=Ic.gradient.stops,n=tp(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return OI(t[s],t[s+1],i)},Gi=e=>rp(op(e)),Vi=e=>np(e.toLowerCase().trim())/4294967295,sp=e=>{let t=Vi(e);return op(t)},FI=e=>{let[t,n,r]=sp(e);return{normal:o=>vo.bgRgb(t,n,r).black(o),cursor:o=>vo.bgRgb(t,n,r).white.bold(o)}},Sc=e=>{let[t,n,r]=sp(e);return{fg:o=>vo.rgb(t,n,r)(o),fgCursor:o=>vo.rgb(t,n,r).inverse(o),bg:o=>vo.bgRgb(t,n,r).black(o),bgCursor:o=>vo.bgRgb(t,n,r).white.bold(o)}},zi=e=>FI(e).normal(` ${e} `);var _I="Unknown",Ki=(e,t)=>t?.length?t:e?.length?e:_I,Ye=(e,t)=>{let n=Ki(e,t);return{id:e?.length?e:n,name:n,color:qe(n)}};var bo="removed",yt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):c("Unable to find node in breadcrumb")},ip=["png","jpg","gif","webp"];var et=e=>e.trim().toLowerCase(),tr=e=>{let t=et(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},hs=(e,t)=>`${et(e)} ${t}`,Rc=e=>!e.tombstoned,ys=(e,t)=>{let n=et(t),r=new Set;for(let o of Object.values(e))Rc(o)&&o.email===n&&r.add(o.contributor);return[...r]},fn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Rc(r)&&r.contributor===t&&n.add(r.email);return[...n]},ap=e=>{let t=new Map;for(let r of Object.values(e)){if(!Rc(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var qi=(e,t)=>e===t.authorId||e===t.contributor;var ie={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Cc(e){return e.context===ie.WORKSPACE}function _(e){return e.context===ie.TICKET}function nr(e){return e.context===ie.TEXT}function lt(e){return e.context===ie.FIELD}function vs(e){return e.context===ie.FIELD_LIST}var gn=e=>e.context===ie.SWIMLANE,rr=e=>e.context===ie.BOARD,bs=e=>e.context===ie.COMMENT;import{useSyncExternalStore as lA}from"react";var I={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var lp=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",cp=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dp=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",up=(e,t)=>{if(cp(e,e.sequence))return E.MoveCursorLeftOfWord;if(dp(e,e.sequence))return E.MoveCursorRightOfWord;if(lp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.GetLastCommandFromHistory;case"down":return E.GetNextCommandFromHistory;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}},mp=(e,t)=>{if(cp(e,e.sequence))return E.MoveCursorLeftOfWord;if(dp(e,e.sequence))return E.MoveCursorRightOfWord;if(lp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.NavPreviousItem;case"down":return E.NavNextItem;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}};import pp from"string-width";function Yi(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",$I=/\u001B\[[0-9;]*m/,Nc="\x1B[0m",UI=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),_n=(e,t)=>{if(t<=0)return"";if(pp(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if($I.test(l)){o+=l,i=l!==Nc&&l!=="\x1B[m";continue}for(let d of UI(l)){let m=pp(d);if(s+m>r)return`${o}...${i?Nc:""}`;o+=d,s+=m}}return`${o}...${i?Nc:""}`},Re=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),fp=e=>e.charAt(0).toUpperCase()+e.slice(1);var gp=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},hp=(e,t)=>t?e.get(t)??[]:[];var yp=new WeakMap,jI=e=>{let t=yp.get(e);return t||(t=gp(e),yp.set(e,t)),t};var vp=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return hp(jI(e),r).filter(s=>Yi(r,s.toLowerCase())>=n)};var HI={hint:"",hints:[],overlap:0,remainder:""},xp=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?bp("",[l]):HI}let i=vp({wordList:o,inputToMatch:e,overlapThreshold:1});return bp(t,i)},bp=(e,t)=>{let n=t[0]??"",r=Yi(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,p=(l&&i?o:n)+(l&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import xs from"node:fs";import Is from"node:path";import{z as xo}from"zod";var Xi="recent-projects.json",WI=20,GI=xo.object({projectId:xo.string().min(1),root:xo.string().min(1),lastOpenedAt:xo.number().finite()}),VI=xo.object({projects:xo.array(GI)}),Ep=()=>Is.join(Dn(),Xi),Io=e=>Is.basename(e)||e,Ip=e=>{let t=Is.resolve(e);try{return xs.realpathSync(t)}catch{return t}},Sp=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Rp=e=>{if(!ps(e.root))return!1;let t=dn(e.root);return!a(t)&&t.value===e.projectId},Cp=()=>{let e=Ep();if(!xs.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(xs.readFileSync(e,"utf8"))}catch(r){return c(`Invalid ${Xi}: ${r instanceof Error?r.message:String(r)}`)}let n=VI.safeParse(t);return n.success?u("Read recent projects",n.data.projects):c(`Invalid ${Xi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},zI=e=>{let t=Ep();try{xs.mkdirSync(Is.dirname(t),{recursive:!0}),xs.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
29
|
-
`,"utf8")}catch(n){return c(`Unable to write ${Xi}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},$n=({exclude:e}={})=>{let t=Cp();if(a(t))return t;let n=e===void 0?null:Ip(e);return u("Listed recent projects",t.value.filter(r=>n===null||Ip(r.root)!==n).filter(Rp).sort(Sp))},Ji=({root:e,now:t=Date.now()})=>{let n=Is.resolve(e),r=dn(n);if(a(r))return c(r.message);let o=r.value,s=Cp(),i=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(d=>d.projectId!==o&&d.root!==n)].filter(Rp).sort(Sp).slice(0,WI);return zI(l)};var Ac=null,Np=e=>{Ac=e},Ap=e=>Ac?Ac(e):[];var Tp=[],Eo=e=>{Tp=e},So=()=>Tp;var Un=()=>{let e=V(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=wp(),s=o.length>0?null:Tc(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Tc=()=>{let e=me(process.cwd());if(a(e))return null;let t=dn(e.value);return a(t)?null:t.value||null},wp=()=>{let{userId:e}=V();return e?Ap(e):[]},Mp=()=>wp().length>0;var wc=()=>{let e=me(process.cwd());if(a(e))return!1;let t=Tt(e.value);return be(t)},Pp=e=>e===!0?"on":e===!1?"off":null,Lp=e=>e==="on"?!0:e==="off"?!1:null,kp=()=>{let e=Un();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!wc())return"init";if(!e.isSetEmails){let{gitEmail:t}=V(),n=So()[0]??t;return n&&tr(n)?`config emails ${n}`:"config emails "}return null};var KI=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,Qi]=KI;var qI=e=>e.props.tags??[],YI=e=>e.props.assignees??[],hn=e=>qI(e).map(t=>N.getTag(t)).filter(t=>!!t),yn=e=>YI(e).map(t=>N.getContributor(t)).filter(t=>!!t),Zi=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",hn(n))},ea=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",yn(n))};var C={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""};var XI=/^(\d+)(h|d|w|mo|y)$/,JI=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,QI=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},ZI=(e,t=new Date)=>{let n=e.match(XI);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},eE=e=>{let t=e.match(JI);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),d=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return QI({year:l,month:d,day:m,hour:p,minute:f})?new Date(l,d-1,m,p,f):null},Lr=e=>{let t=e.trim().toLowerCase();return ZI(t)??eE(t)};var Dp=/^(\d+)(s|m)?$/,ta=e=>{let t=e.trim().toLowerCase().match(Dp);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},na=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Dp.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Bp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,tE=[{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}],Mc=(e=tE)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var nE=["BOARD","TICKET","SWIMLANE","COMMENT"],ve={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Xe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},rE=[ve.EDITOR,ve.VIEW,ve.USERNAME,ve.EMAILS,ve.EMAILS_UNCLAIM,ve.AUTOSYNC,ve.SYNC_DEBOUNCE_MS,ve.ATTACHMENT_MAX_KB,ve.LOG_LEVEL],oE=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Mt.TITLE,Mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Mt.TITLE];case"COMMENT":return[Mt.COMMENT];default:return[]}},Lc=[String(3e3),"5000","15000","30000","60000"],kc=["250","500","1000"],_p=["10s","20s","30s","45s"],kr=[C.EXIT,C.SYNC,C.HELP,C.EXPORT,C.CONFIG,C.YANK],ra=[C.NEW,C.EDIT,C.DELETE,C.MOVE],Pc=[C.TAG,C.UNTAG,C.ASSIGN,C.UNASSIGN,C.CLOSE_ISSUE,C.RE_OPEN_ISSUE,C.EDIT,C.COMMENT],Op=[C.FILTER,C.PEEK,C.REPLAY],sE={WORKSPACE:[...kr,...ra],BOARD:[...Op,...kr,...ra],SWIMLANE:[...Op,...kr,...ra],TICKET:[...kr,...ra,...Pc],FIELD:[...kr,...Pc],FIELD_LIST:[...kr,...Pc],TEXT:[...kr],COMMENT:[C.EDIT,C.DELETE,C.YANK]},iE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Es=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&_(n)),Fp=e=>e.parentNodeId===ye,aE=({selectedNode:e,breadCrumb:t})=>{let n=oE(e?.context);return Es({breadCrumb:t,selectedNode:e})?n.includes(Mt.DESCRIPTION)?n:[...n,Mt.DESCRIPTION]:n},lE=({selectedNode:e,breadCrumb:t})=>{let n=Es({breadCrumb:t,selectedNode:e});return n?[Xe.REF,Xe.TITLE,...n.props?.description?.trim()?[Xe.DESCRIPTION]:[],...hn(n).length>0?[Xe.TAGS]:[],...yn(n).length>0?[Xe.ASSIGNEES]:[]]:e?[Xe.REF,Xe.TITLE]:[]},Dc=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},cE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Un();if(!r)return[C.HELP,C.CONFIG];if(!wc())return[C.HELP,C.INIT,C.OPEN];if(t)return[C.HELP,C.PEEK,C.REPLAY,C.EXPORT,C.CONFIG,C.YANK];let o=e?.context,s=o&&nE.includes(o),i=[...new Set([...n,e].map(d=>d?.context).flatMap(d=>d?sE[d]:[]))],l=Es({breadCrumb:n,selectedNode:e});return i.filter(d=>d===C.MOVE?!1:d===C.YANK?!!(l??e):d===C.EDIT?s||!!l:d===C.DELETE?s:d===C.UNTAG?!!(l&&hn(l).length>0):d===C.UNASSIGN?!!(l&&yn(l).length>0):d===C.RE_OPEN_ISSUE?!!(l&&Fp(l)):d===C.CLOSE_ISSUE?!!(l&&!Fp(l)):!0)},Oe=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[C.NONE]:cE({breadCrumb:o,readOnly:r,selectedNode:n}),[C.EXIT]:["confirm"],[C.EXPORT]:[],[C.SYNC]:[],[C.INIT]:[],[C.OPEN]:e===C.OPEN?Dc():[],[C.HELP]:[],[C.PEEK]:[...Mc(),"now","prev","next"],[C.REPLAY]:[...Mc()],[C.EDIT]:aE({selectedNode:n,breadCrumb:o}),[C.YANK]:lE({selectedNode:n,breadCrumb:o}),[C.COMMENT]:[],[C.DELETE]:["confirm"],[C.RE_OPEN_ISSUE]:["confirm"],[C.CLOSE_ISSUE]:["confirm"],[C.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[C.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[C.TAG]:[...new Set([...Object.keys(Wi),...N.getExistingTags()])],[C.UNTAG]:[...Zi()?.value?.map(({name:l})=>l)??[]],[C.UNASSIGN]:[...ea()?.value?.map(({name:l})=>l)??[]],[C.ASSIGN]:N.getExistingAssignees(),[C.NEW]:iE(s),[C.CONFIG]:[...rE]}[e]??[]};import Qp from"chalk";var $p=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import fE from"zod";import dE from"node:crypto";import Ss from"node:fs";import Hp from"node:path";var Up="/media/",jp=e=>`${Up}${e}`,Bc=(e,t)=>`})`;var vn=500,uE=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Br=(e,t)=>`${e}.${t}`,mE=e=>uE.test(e),Wp=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?u("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?u("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?u("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?u("Sniffed image type","webp"):c(`Unsupported image format. Allowed: ${ip.join(", ")}`),Gp=e=>dE.createHash("sha256").update(e).digest("hex"),pE=(e,t=vn)=>{if(e.length===0)return c("Attachment is empty");if(e.length>t*1024)return c(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Wp(e);return a(n)?n:u("Validated attachment data",{hash:Gp(e),ext:n.value,bytes:e.length})},Vp=(e,t,n=vn)=>{let r=pE(t,n);if(a(r))return r;let o=ms(e),s=Hp.join(o,Br(r.value.hash,r.value.ext));try{Ss.existsSync(s)||(Ss.mkdirSync(o,{recursive:!0}),Ss.writeFileSync(s,t))}catch(i){return c(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},zp=(e,t,n=vn)=>{if(!mE(t))return c("Invalid attachment file name");let r=Hp.join(ms(e),t);if(!Ss.existsSync(r))return c("Attachment blob not found");let o;try{o=Ss.readFileSync(r)}catch(d){return c(`Unable to read attachment blob: ${d instanceof Error?d.message:String(d)}`)}if(o.length>n*1024)return c(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(Gp(o)!==s)return c("Attachment blob does not match its content hash");let l=Wp(o);return a(l)?l:l.value!==i?c("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var Rs=50,Cs=5e3,Kp=()=>{let e=ae().commandMeta.inputString,t=fE.coerce.number().int().min(Rs).max(Cs).safeParse(e);if(!t.success)return c(`Attachment size cap must be ${Rs}-${Cs} KB (default ${vn})`);let n=Bt({attachmentMaxKb:t.data});return a(n)?n:(je({attachmentMaxKb:t.data}),u(`Attachment size cap set to ${t.data} KB`,null))};var ct=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as gE}from"node:crypto";var hE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",yE=e=>{let t=gE("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=hE[Number(n>>s&31n)]}return r},qp=new Map,Pe=(e,t)=>{let n=`${e}:virtual:${t}`,r=qp.get(n);if(r!==void 0)return r;let o=yE(n);return qp.set(n,o),o};import Yp from"chalk";var Ce=e=>Yp.dim(e),He=e=>Yp.hex(h.primary)(e),We=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>Vi(f)-Vi(g)).slice(0,r).map(f=>zi(f)).join(" ");return p?`${Ce(e)}${p}${Ce(n)}`:""};var bn={None:"none",Invalid:"invalid",Valid:"valid"};var vE=["BOARD","TICKET","SWIMLANE"],Xp=()=>{let e=v().selectedNode;if(!e?.context)return z({message:Ce("Missing target context")});if(vE.includes(e.context))return le();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Pe(t?.parentNodeId??"","comments"))return le()}return z({message:Ce("Command not available in this context")})},fe="<ENTER> to confirm",bE=()=>{let{userId:e}=V(),t=xe();return!e||a(t)?[]:fn(t.value.emailLinks,e)},le=(e="",t=[],n=!0)=>({message:n?Ce(e):e,validity:bn.Valid,completionWordList:t}),z=({message:e,completionWordList:t=[]})=>({validity:bn.Invalid,message:e,completionWordList:t}),Co=e=>e.length===0,Jp=(e,t)=>{let n=yt(v().breadCrumb,"BOARD");if(a(n))return z({message:He("Command is not applicable in this context")});let r=yo(n.value.id);return a(r)?z({message:He(`Unable to ${t}: board id is not a valid ULID`)}):Bp({date:e,horizonDate:r.value})?null:z({message:He(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},oa=e=>` ${Qp.hex("#000").bgHex(qe(e))(` ${e} `)} `,Oc=({modifier:e})=>{let t="confirm";return e===t?le(fe):z({message:Co(e)?Ce("if you are certain, enter ")+zi(t):"",completionWordList:[t]})},xE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?z({message:Ce(n)}):le():z({message:Co(r)?t:"",completionWordList:[...e]}),Ro=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Co(n)&&Co(r)?z({message:e,completionWordList:[]}):le(t??fe),IE=({modifier:e,inputString:t})=>{let n=Dc();return!Co(e)||!Co(t)?le(fe):z({message:n.length?Ce("number from the list, or a path"):Ce("path to an epiq project"),completionWordList:n})},EE=({modifier:e,inputString:t})=>{let n=Oe(C.CONFIG);if(!n.includes(e))return z({message:We({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ve.EDITOR:{let r=[...$p];return t.trim()?r.includes(t.trim())?le(fe):z({message:We({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):z({message:We({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ve.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?le(fe):z({message:We({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ve.USERNAME:{let r=V().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(m=>m.startsWith(s)),d=i.length===1&&i[0]===s?"":We({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?d?le(`${d} ${Ce(fe)}`,o,!1):le(fe,o):z({message:d||He("Enter a user name. Saved in ")+Qp.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ve.EMAILS:{let r=V().gitEmail,o=So(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),d=(x,b)=>z({message:We({prefix:x,wordList:i,noOfHints:3,inputString:b,minLengthForHints:0}),completionWordList:i});if(!l)return le(`${fe} to see your addresses, or name one`,i);let m=l.split(/[,\s]+/).filter(Boolean),p=m[m.length-1]??"",f=x=>x==="none"||s.includes(x.toLowerCase()),g=x=>i.some(b=>b.startsWith(x.toLowerCase())),y=m.filter(x=>!f(x)&&!g(x));return y.length>0?z({message:He(`no address here matches ${y.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(p)?le(fe):d("",p)}case ve.EMAILS_UNCLAIM:{let r=bE(),o=t.trim();return r.length===0?z({message:He("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?le(fe):z({message:We({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ve.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?le(fe):z({message:We({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ve.AUTOSYNC:{let r=["on","off"],o=V().autoSync;if(!r.includes(t.trim())){let s=Pp(o);return z({message:We({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return le(fe)}case ve.ATTACHMENT_MAX_KB:{let r=V().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Rs||o>Cs){let s=We({prefix:" examples: ",wordList:kc,minLengthForHints:0,inputString:t});return z({message:He(`provide a size cap in KB (${Rs}-${Cs}). current: ${r??vn} KB.`)+s,completionWordList:kc})}return le(fe)}case ve.SYNC_DEBOUNCE_MS:{let r=V().autoSyncIntervalMs,o=co(t);if(!t.trim()||o===null){let s=We({prefix:" examples: ",wordList:Lc,minLengthForHints:0,inputString:t});return z({message:He(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Lc})}return le(fe)}default:return z({message:He("Unknown config option"),completionWordList:n})}},SE=({modifier:e,inputString:t})=>{let n=Oe(C.EDIT);if(!n.length)return z({message:He("Command not available in this context")});if(!n.includes(e)){let r=We({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return z({message:r||He("Unknown edit option"),completionWordList:n})}switch(e){case Mt.COMMENT:return t.trim()?le(fe):z({message:Ce("write a comment...")});case Mt.TITLE:return le(fe);case Mt.DESCRIPTION:{let{preferredEditor:r}=V();return r?le(Ce("<ENTER> to edit in ")+r):z({message:"No editor selected"})}default:return z({message:He("Unknown edit option"),completionWordList:n})}},RE=({modifier:e})=>{let t=Oe(C.YANK);return t.length?t.includes(e)?le(fe+Ce(" and copy to clipboard")):z({message:We({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):z({message:He("Nothing selected to copy from")})},CE={[C.EXPORT]:()=>le(fe+Ce(", and create export markdown file")),[C.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return le(fe);let n={message:Ce("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Lr(r);if(!r||!o)return z(n);let s=Jp(o,"peek");return s||le(fe)},[C.REPLAY]:e=>{let{dateInput:t,durationInput:n}=na(e.modifier,e.inputString),r={message:Ce("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Lr(t);if(!t||!o)return z(r);let s=Jp(o,"replay");return s||(n&&ta(n)===null?z({message:He("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):le("<ENTER> to replay board history",n?_p:[]))},[C.EXIT]:()=>le(fe+Ce(" and exit the application")),[C.INIT]:()=>le(fe),[C.OPEN]:IE,[C.PALETTE]:()=>le(fe),[C.FILTER]:e=>{if(e.modifier==="clear")return le(fe);let t=s=>Oe(C.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return z({message:We({wordList:Oe(C.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Oe(C.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?z({message:We({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):le():z({message:We({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[C.NONE]:e=>{let t=Oe(C.NONE);return z({message:We({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[C.NEW]:e=>xE({list:Oe(C.NEW),hint:We({wordList:Oe(C.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[C.HELP]:()=>le(fe),[C.EDIT]:SE,[C.COMMENT]:e=>{let t=Ro({hint:Ce(`write a comment (max ${4e3} char)...`),onOk:Ce(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===bn.Invalid?t:e.inputString.length>4e3?le(He("max input exceeded")):t},[C.CONFIG]:EE,[C.YANK]:RE,[C.DELETE]:e=>{let t=Xp();return t.validity==="invalid"?t:Oc(e)},[C.CLOSE_ISSUE]:e=>Oc(e),[C.RE_OPEN_ISSUE]:e=>Oc(e),[C.MOVE]:e=>{let t=Xp();return t.validity==="invalid"?t:Ro({hint:We({prefix:"hey hacker! These commands are blocked for you... ",wordList:Oe(C.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[C.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(oa).join("");return Ro({hint:n.length?Ce("create tag or reuse:")+n+Ce(""):Ce("create tag ...")})(e)},[C.UNTAG]:e=>{let t=Zi();if(a(t))return z({message:He("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(oa).slice(0,10);return n.length?Ro({hint:Ce(" ... ")+n.join("")})(e):z({message:He("Issue has no tags"),completionWordList:[]})},[C.ASSIGN]:e=>{let t=N.getExistingAssignees().map(oa).slice(0,10);return Ro({hint:Ce("assignees... ")+t.join("")})(e)},[C.UNASSIGN]:e=>{let t=ea();if(a(t))return z({message:He("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(oa).slice(0,10);return n.length?Ro({hint:Ce("remove assignee... ")+n.join("")})(e):z({message:He("Issue has no assignees"),completionWordList:[]})},[C.SYNC]:()=>le(fe)},Zp=Object.fromEntries(Object.entries(CE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var sa=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var NE=3,AE=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),TE=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},wE=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=NE&&!AE.has(t)&&!/^\d+$/.test(t)),ME=e=>{let t=new Map;for(let s of TE(e))for(let i of wE(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=sa.filter(s=>!r.has(s));return[...n,...o]},ef=sa,tf=-1,nf=()=>{let e=xe();if(a(e))return sa;let t=e.value,n=t.eventLog.length;return n!==tf&&(ef=ME(t),tf=n),ef};var rf=e=>Object.values(C).includes(e),of=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:d}=Zp[n].validate(n,r,s),m=n!==C.PEEK&&n!==C.REPLAY,p=o==="command"||o==="modifier"?Oe(n):m?nf():[],{mode:f}=v(),g=f===I.COMMAND_LINE?i??"":"",y=[...d,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?xp(e,y,d):{hint:"",hints:[],remainder:"",overlap:0}}};var sf=e=>{let t=e.trimStart(),n=LE(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=kE(e),l=rf(r)?r:null,d=l!==null,m=r!=="",p=l?Oe(l)??[]:[],f=l&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let y=s?"":i,x=PE(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:d,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:y,inputString:x}},PE=(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},LE=e=>e.trim()?e.trim().split(/\s+/):[],kE=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as DE}from"react";var No=e=>e===Fc||e===":",Fc=" ",As=40,dt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:bn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_c=new Set,af=()=>{for(let e of _c)e()},$c=e=>(_c.add(e),()=>_c.delete(e)),Ft=e=>{let n=e(dt),r=sf(n.value),o=n.cursorPosition===n.value.length;dt={...n,commandMeta:of(r,o)},af()},Ts=({message:e,status:t})=>{let n=structuredClone(dt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,dt=n,af(),u(e,null)},Uc=e=>{Ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},jc=e=>{Ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&No(n[o-1]);)o--;for(;o>0&&!No(n[o-1]);)o--}else{for(;o<n.length&&!No(n[o]);)o++;for(;o<n.length&&No(n[o]);)o++}return{...t,cursorPosition:o}})},lf=()=>{Ft(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},cf=()=>{Ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&No(t[r-1]);)r--;for(;r>0&&!No(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},ia=e=>{Ft(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},df=()=>{Ft(e=>({...e,commandIsPending:!0}))},Q=e=>{Ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},uf=({addToHistory:e=!0,line:t})=>{Ft(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,As):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},mf=e=>{Ft(t=>({...t,commandHistory:e.slice(0,As),commandHistoryIndex:-1}))},pf=()=>{Ft(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},ff=()=>{Ft(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},gf=()=>{Ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ae=()=>dt,hf=()=>DE($c,ae,ae),aa=()=>{let[e,...t]=dt.value.split(Fc);return t.join(Fc).trim()};var E={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},BE=e=>e.shift===!0,OE={[E.NavPreviousItem]:E.NavPreviousItemJump,[E.NavNextItem]:E.NavNextItemJump,[E.MovePreviousItem]:E.MovePreviousItemJump,[E.MoveNextItem]:E.MoveNextItemJump};function FE(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function _E(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function $E(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function yf(e,t){let n=ae();if(e.sequence==="?"&&t!==I.PALETTE)return E.InitCommandPalette;if(e.sequence===":"&&t!==I.COMMAND_LINE)return E.InitCommandLine;if(t===I.MOVE)switch(e.name){case"m":case"return":return E.ConfirmMove}if(t===I.COMMAND_LINE)return up(e,n.value);if(t===I.PALETTE)return mp(e,n.value);let r=FE(e)||_E(e);if(r)return UE(r,t,BE(e));if(e.ctrl&&e.name==="c")return E.Exit;switch(e.name){case"r":return E.EditTitle;case"e":return E.EditDescription;case"n":return E.AddItem;case"m":return E.InitMove;case"d":return E.Delete;case"y":return E.Yank;case"o":return E.OpenInEditor;case"s":return E.MarkDiffLine;case"c":return E.CommentOnDiffLine;case"return":return E.Confirm;case"space":return E.Confirm;case"v":return V().viewMode==="wide"?E.SetViewDense:E.SetViewWide;case"q":case"escape":return E.Exit;default:return null}}function UE(e,t,n=!1){let r=t===I.MOVE?{prevItem:E.MovePreviousItem,nextItem:E.MoveNextItem,prevContainer:E.MoveToPreviousContainer,nextContainer:E.MoveToNextContainer}:{prevItem:E.NavPreviousItem,nextItem:E.NavNextItem,prevContainer:E.NavToPreviousContainer,nextContainer:E.NavToNextContainer},o=$E(v().contextNode.childRenderAxis,e,r);return!o||!n?o:OE[o]??o}import{ulid as WE}from"ulid";var ws=24n,jE=ws*4n,Xt=(1n<<jE)-1n,HE=/^[0-9a-f]+$/;function vf(e){return!e||!HE.test(e)?c(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Pt(e,t=ws){if(e<0n)return c("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function vt(e,t){if(!e&&!t)return Pt(Xt/2n,ws);let n=e?vf(e):u("Resolved lower bound",0n);if(a(n))return n;let r=t?vf(t):u("Resolved upper bound",Xt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return c("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?c("No rank space available between neighbors"):Pt(i,ws)}function bf(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Xt*BigInt(r+1)/(t+1n),s=Pt(o,ws);if(a(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var D=({userId:e})=>({userId:e}),xf=e=>({action:e.action,payload:e.payload});var Hc=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user","link.contributor.email","unlink.contributor.email"];var SD=new Set(Hc);var Wc=(e,t)=>{let n=Ie(e),r=bf(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return c("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:WE(),action:"rebalance.children",payload:{parent:e,ranks:o},...D(t)})};import{z as Or}from"zod";var If=1,Ef=Or.tuple([Or.string().min(1),Or.string().min(1).nullable()]),GE=Or.looseObject({v:Or.literal(If),id:Ef}),FD=Or.looseObject({v:Or.number().int().positive(),id:Ef}),VE=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),zE=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Sf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return c("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return c("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return c("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?c("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?c("Invalid persisted event envelope: id.1"):u("Parsed persisted event envelope",VE(e)?zE(e):e)};var KE=[1];var qE=new Set(KE),Gc=e=>qE.has(e),Rf=e=>{let t=GE.safeParse(e);return t.success?u("Parsed persisted event",t.data):c(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Vc=(e,t)=>{let n={[e.action]:e.payload,v:If,id:t};return Rf(n)};import ks from"node:fs";import pa from"node:path";import{decodeTime as rS}from"ulid";import{z as Qc}from"zod";import zc from"node:fs";import YE from"node:path";var Ms=e=>e?.code==="ENOENT",Kc=3,qc=e=>zc.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),xn=e=>{let t=Et(e);for(let n=1;;n++){if(!zc.existsSync(t))return"none";let r=[],o=!1;for(let s of qc(t))try{let{size:i,mtimeMs:l}=zc.statSync(YE.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!Ms(i))throw i;if(n<Kc){o=!0;break}}if(!o)return r.join("|")}},Cf=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Yc=(e,t,n)=>{let r=Cf(t),o=xn(e),s=Cf(o);for(let[i,l]of s)if(i!==n&&r.get(i)!==l)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},or=null,Nf=e=>or&&or.root===e?or.signature:null,Af=(e,t)=>{or={root:e,signature:t}},Tf=(e,t)=>{if(!or||or.root!==e)return;let n=Yc(e,or.signature,t);or=n===null?null:{root:e,signature:n}};import Ge from"node:fs";import Fr from"node:path";import{ulid as XE}from"ulid";var ca="~pending",Xc=/~pending(-[0-9a-z]+)*$/i,Mf=/-f(\d+)$/,Pf=e=>{let t=e.indexOf(".");return t===-1?`${e}${ca}`:e.slice(0,t)+ca+e.slice(t)},da=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},JE=e=>{let[t,n]=da(e);return Xc.test(t)?t.replace(Xc,"")+n:null},Jc=e=>e.replace(Xc,""),_r=e=>e.endsWith(".jsonl")&&JE(e)!==null,Ps=e=>Jc(da(e)[0]),Lf=e=>{let[t]=da(e),n=Mf.exec(t);return n&&_r(e)?Number(n[1]):null},QE=e=>Pf(e).replace(ca,`${ca}-${XE().toLowerCase()}`),ZE=(e,t)=>{let[n,r]=da(e);return`${n.replace(Mf,"")}-f${t}${r}`},kf=(e,t)=>Fr.join(Et(e),Pf(t)),eS=(e,t)=>Math.max(0,Ge.statSync(e).size-(Lf(t)??0)),Df=e=>{let t=Et(e);try{return Ge.existsSync(t)?Ge.readdirSync(t).filter(_r).some(n=>eS(Fr.join(t,n),n)>0):!1}catch{return!0}},tS=3,Bf=(e,t)=>{for(let n=1;;n++){let r=Ge.openSync(e,"a"),o;try{Ge.writeSync(r,t),o=Ge.fstatSync(r).ino}finally{Ge.closeSync(r)}let s;try{s=Ge.statSync(e).ino}catch{s=null}if(s===o||n>=tS)return}},nS=e=>{let t;try{t=Ge.openSync(e,"r")}catch{return!0}try{let{size:n}=Ge.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ge.readSync(t,r,0,1,n-1),r[0]===10}finally{Ge.closeSync(t)}},la=10,wf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(la)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ge.appendFileSync(e,Buffer.concat([Buffer.from(nS(e)?"":`
|
|
30
|
-
`),o,Buffer.from(o[o.length-1]===
|
|
31
|
-
`)]));let s=0;for(let i of o)i===
|
|
32
|
-
`).entries()){let g=f.trim();if(!g)continue;let
|
|
33
|
-
`),i&&(i.current=g);let b=nd.basename(p);return e.advanceEdgeRef(s,b,g),Tf(s,b),u("Event persisted",{path:p,entry:x.value})}catch(d){let m=d instanceof Error?d.message:"Unknown persist error";return c(`Failed to persist event: ${m}`)}}return{mintEventId:n,persist:r}};var Xf=(e,t,n)=>{function r(s,i,l){let d=n.mintEventId(i,l);if(a(d))return c(d.message);let m={...s,id:d.value[0]},p=t.materialize(m);if(p.status!==Qn.Success)return p;let f=n.persist({event:m,rootDir:i,edge:l,id:d.value});return a(f)?f:p}function o(s,i){if(s.length===0||!s[0])return c("No events provided");let l=e.write.readOnlyReason();if(l)return c(l);let d=e.replay.batch(()=>{let m={},p=e.write.beforeWrite(s[0],y=>r(y,i,m));if(a(p))return c(p.message);let f=s.map(y=>r(y,i,m)),g=f.filter(a);return g.length>0?c("Materialize and persist failed: "+g.map(y=>y.message).join(", ")):u("Materialization succeeded",f.map(y=>y.value))});return a(d)?c(d.message):d.value??c("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var Jf=e=>{let t=Gf(e),n=Wf(e),r=Yf(n),o=Xf(e,t,r);return{...t,...n,...r,...o}};import{z as Z}from"zod";var K=Z.string().min(1),Jt=Z.string(),ar=Z.string(),ha=Z.looseObject({id:K}),rd=Z.looseObject({id:K,name:Jt,parent:K,rank:ar}),IS={"init.workspace":Z.looseObject({id:K,name:Jt,rank:ar}),"add.workspace":Z.looseObject({id:K,name:Jt,rank:ar}),"add.board":rd,"add.swimlane":rd,"add.issue":rd,"add.field":Z.looseObject({id:K,name:Jt,parent:K,rank:ar}),"edit.title":Z.looseObject({id:K,name:Jt}),"delete.node":ha,"lock.node":ha,"move.node":Z.looseObject({id:K,parent:K,rank:ar}),"edit.description":Z.looseObject({id:K,md:Z.string()}),"close.issue":Z.looseObject({id:K,parent:K,rank:ar}),"reopen.issue":Z.looseObject({id:K,parent:K,rank:ar}),"create.tag":Z.looseObject({id:K,name:Jt}),"tombstone.tag":ha,"restore.tag":Z.looseObject({id:K,name:Jt}),"create.contributor":Z.looseObject({id:K,name:Jt}),"rename.contributor":Z.looseObject({id:K,name:Jt}),"tombstone.contributor":ha,"restore.contributor":Z.looseObject({id:K,name:Jt}),"link.contributor.user":Z.looseObject({contributor:K}),"link.contributor.email":Z.looseObject({contributor:K,email:K}),"unlink.contributor.email":Z.looseObject({contributor:K,email:K}),"add.issue.assignee":Z.looseObject({id:K,assignee:K}),"remove.issue.assignee":Z.looseObject({id:K,assignee:K}),"add.issue.tag":Z.looseObject({id:K,tag:K}),"remove.issue.tag":Z.looseObject({id:K,tag:K}),"add.issue.comment":Z.looseObject({id:K,issue:K,md:Z.string()}),"edit.issue.comment":Z.looseObject({id:K,issue:K,md:Z.string()}),"delete.issue.comment":Z.looseObject({id:K,issue:K}),"add.issue.attachment":Z.looseObject({id:K,issue:K,hash:Z.string().min(1),ext:Z.string().min(1),name:Jt,bytes:Z.number()}),"delete.issue.attachment":Z.looseObject({id:K,issue:K}),"rebalance.children":Z.looseObject({parent:K,ranks:Z.record(Z.string(),ar)})},Qf=(e,t)=>{let r=IS[e].safeParse(t);return r.success?u("Payload is readable",void 0):c(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as ES}from"ulid";var Zf=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let{userId:n,userName:r}=V();if(!r||n!==e.userId)return u("Not this actor own write",void 0);let o=N.getContributor(e.userId),s={id:ES(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return u("Contributor name is current",void 0);let i=t(s);return a(i)?c(i.message):u("Contributor name recorded",void 0)};var Te={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var H=e=>e.slice(-7).toUpperCase(),ya=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?H(e).includes(n):!0};var Ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:ie.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:H(e)},context:ie.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:ie.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:H(e)},context:ie.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:ie.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:ie.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Ds=(e,t,n)=>N.getNode(e)?$(`a node with id ${e} already exists`,n):t===e?$("a node cannot be its own parent",n):null,eg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ne.workspace(t,n,r),s=Bs(o);if(a(s))return ga(s.message,e);let i=N.createNode(o);return a(i)?$(i.message??"Failed to initialize workspace",e):Cc(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ds(t,void 0,e);if(o)return o;let s=N.createNode(Ne.workspace(t,n,r));return a(s)?$(s.message??"Failed to add workspace",e):Cc(s.value)?u("Added workspace",{action:e.action,result:s.value}):c("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.board(t,n,r,o));return a(i)?$(i.message??"Unable to create board",e):rr(i.value)?u("Added board",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.swimlane(t,n,r,o));return a(i)?$(i.message??"Unable to create swimlane",e):gn(i.value)?u("Added swimlane",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.ticket(t,n,r,o));return a(i)?$(i.message??"Unable to create issue",e):_(i.value)?u("Added issue",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Ds(t,r,e);if(i)return i;let l=N.createNode(Ne.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Te.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?$(l.message??`Unable to create field: ${n}`,e):lt(l.value)?u("Added field",{action:e.action,result:l.value}):c("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return $(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?$(o.message??"Unable to edit title",e):u("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?$(n.message??"Unable to delete node",e):u("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return a(r)?$(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=N.tombstoneTag(t);return a(n)?$(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=N.restoreTag(t,n);return a(r)?$(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return a(r)?$(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=N.renameContributor(t,n);return a(r)?$(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=N.tombstoneContributor(t);return a(n)?$(n.message??"Unable to remove contributor",e):u("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=N.restoreContributor(t,n);return a(r)?$(r.message??"Unable to restore contributor",e):u("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.tag(t,n);return a(r)?$(r.message??"Unable to tag issue",e):u("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.untag(t,n);return a(r)?$(r.message??"Unable to untag issue",e):u("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.assign(t,n);return a(r)?$(r.message??"Unable to assign issue",e):u("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.unassign(t,n);return a(r)?$(r.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?$(o.message??"Failed to move node",e):u("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return a(r)?$(r.message??"Unable to edit description",e):u("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return $("Unable to locate issue",e);if(!_(o))return $("Can only close issues",e);let s=N.getNode(ye);if(!s)return $("Unable to locate target swimlane",e);if(n!==s.id)return $("Close target must be closed swimlane",e);let i=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?$(i.message??"Unable to close issue",e):u("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return $("Unable to locate issue",e);if(!_(o))return $("Can only reopen issues",e);let s=N.getNode(ye);if(!s)return $("Unable to locate closed swimlane",e);if(n===s.id)return $("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return $("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?$(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?$(n.message??"Unable to lock node",e):u("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=N.getNode(r);if(!s)return $(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return $(`Node ${r} is not child of ${t}`,e);let i=N.updateNode({...s,rank:o});if(a(i))return $(i.message??"Unable to rebalance child",e)}return u("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=N.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return a(s)?$(s.message??"Unable to add comment",e):u("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=N.getComment(t);if(!o)return $("Unable to locate comment",e);if(o.issue!==n)return $("Comment does not belong to issue",e);let s=N.editComment(t,r);return a(s)?$(s.message??"Unable to edit comment",e):u("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=N.getComment(t);if(!r)return $("Unable to locate comment",e);if(r.issue!==n)return $("Comment does not belong to issue",e);let o=N.deleteComment(t);return a(o)?$(o.message??"Unable to delete comment",e):u("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,l=N.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(l)?$(l.message??"Unable to add attachment",e):u("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=N.getAttachment(t);if(!r)return $("Unable to locate attachment",e);if(r.issue!==n)return $("Attachment does not belong to issue",e);let o=N.deleteAttachment(t);return a(o)?$(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!tr(n))return $(`not an email address: ${n}`,e);let r=N.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?$(r.message??"Unable to link email",e):u("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=N.unlinkContributorEmail(n,t,e.userId);return a(r)?$(r.message??"Unable to unlink email",e):u("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=N.linkUserId({contributorId:t,userId:e.userId});return a(n)?$(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};var tg=e=>{let t=N.getNode(e);if(!t||!_(t)||t.isDeleted)return null;let n=og(t);return a(n)?n:null},ng=e=>{if(!sd())return null;for(let t of e){let n=tg(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=tg(r);if(o)return o}return null},SS=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},RS=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},od=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return RS(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},CS=e=>{Fe(t=>({...t,eventLog:[...t.eventLog,e]}))},jn=null,NS=e=>{for(let[t,n]of e.nodeLog){let r=N.getNode(t);r&&N.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Fe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),ng([...e.virtualNodeIds])},rg={isInitialized:()=>_t(),batch:e=>va(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(od(e))];if(t){jn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=jn.nodeLog.get(o);s?s.push(e):jn.nodeLog.set(o,[e])}if(sd()){jn.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&jn.virtualNodeIds.add(s)}}return n||jn.appLog.push(e),null}return n||(r.forEach(o=>SS(o,e)),CS(e)),ng(r)},flush(){if(!jn)return null;let e=jn;return jn=null,NS(e)}};var pe=()=>{let{userName:e,userId:t}=V();return e?t?Xl(t)?ki(e)?u("Successfully resolved actor ID",{userId:t,userName:e}):c("Invalid user name in config"):c("Invalid user ID in config"):c("User ID not configured"):c("User name not configured")};var AS={genesis:"init.workspace",actions:Hc,readPayload:Qf,apply:eg,replay:rg,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:Zf}},TS=Jf(AS),{materialize:Os,materializeAll:Qt,fromPersistedEvent:WO,decodeReconstructedEvents:GO,loadMergedEventsWithUnreadable:Zt,loadEventActors:sg,loadActorNames:lr,loadMergedEvents:cr,loadMergedEventsBefore:ba,getEdgeRef:VO,advanceEdgeRef:zO,clearEdgeCache:KO,getSortedEvents:qO,loadEffectiveEventTimes:xa,mintEventId:YO,persist:ig,materializeAndPersist:XO,materializeAndPersistAll:B}=TS;var $r=e=>e.trim().toLocaleLowerCase(),id=(e,t)=>$r(e).includes($r(t));var wS=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},MS=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},ag=null,lg=new Map,PS=()=>{let e=v().eventLog??[];if(e===ag)return lg;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return ag=e,lg=t,t},LS=e=>{let{contributors:t}=v(),n=PS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},cg=(e,t)=>{let n=$r(t.value);if(!n)return!0;switch(t.target){case"title":return id(e.title??"",n);case"description":return id(e.props.description??"",n);case"tag":return wS(e).map($r).some(o=>o.includes(n));case"assignee":return MS(e).map($r).some(o=>o.includes(n));case"actor":return LS(e).map($r).some(o=>o.includes(n));case"ref":return ya(e.id,t.value);default:return!0}};var ad=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,kS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,dg=(e,t)=>Object.values(e).filter(n=>kS(n,t)).sort(ad),ug=(e,t)=>{let n={};for(let r of Object.values(e)){if(_(r)&&t.length>0&&!t.every(s=>cg(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(ad);return n},mg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(ad);return n};var pg=e=>Ia(Ie(e),{at:"end"}),Ia=(e,t={at:"end"})=>{let n=o=>a(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(vt(void 0,void 0));let r=()=>n(vt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(vt(void 0,o.rank)):c("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(vt(o.rank,void 0)):c("Unable to resolve last sibling")}case"before":{let o=fg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(vt(i?.rank,s.rank))}case"after":{let o=fg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(vt(s.rank,i?.rank))}}},Ie=e=>{let t=v();if(!hg()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return dg(t.nodes,e)},fg=(e,t)=>e.findIndex(n=>n.id===t),gg=(e,t,n={at:"end"})=>Ia(Ie(t).filter(r=>r.id!==e),n),Sn=(e,t,n,r,o)=>{let s=gg(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=Wc(e,r);if(a(i))return i;let l=B([i.value],o);if(a(l))return l;let d=gg(t,e,n);return a(d)?d:d.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",d.value.rank)},Hn=(e,t,n)=>{let r=pg(e);if(a(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=Wc(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let i=pg(e);return a(i)?i:i.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var Fs=5,U={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=de(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:de(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=de(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>yg(1),navigateToPreviousItem:()=>yg(-1),jumpToNextItem:()=>vg(Fs),jumpToPreviousItem:()=>vg(-Fs),navigateToNextContainer:()=>bg(1),navigateToPreviousContainer:()=>bg(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},yg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=de(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},vg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=de(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);U.navigate({selectedIndex:s,contextNode:n})},bg=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=de(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let d=de(l.id),m=Math.max(0,d.length-1),p=Math.min(Math.max(0,r),m),f=d.length?p:-1;U.navigate({contextNode:l,selectedIndex:f})};var Ig=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Eg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},DS=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&<(t)&&t.childRenderAxis==="vertical"},Ea=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Ie(r.id);return U.navigate({contextNode:r,selectedIndex:Ig(t,o.length)}),!0},Sg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ea(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Ie(o.id).findIndex(l=>l.id===n.id);return i>=0?(U.navigate({contextNode:o,selectedIndex:i}),!0):Sg(o.id)},xg=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Sg(n))return!0;n=t[n]?.parentNodeId}return!1},BS=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Rg=e=>{let{nodes:t,rootNodeId:n}=v();if(DS(e.contextNodeId)&&Ea(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(BS(e.selectedNodeId)&&e.selectedNodeId&&xg(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Ea(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Ea(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(xg(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return c("Unable to restore navigation");let o=Ie(r.id);return U.navigate({contextNode:r,selectedIndex:Ig(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as OS,ulid as Rn}from"ulid";var _s=OS();function FS(){let e=xe();if(a(e))return c("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return c("No workspace found in event log");let[r]=de(n.id),[o]=r?de(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function _S(){let e=FS();return a(e)?e:U.navigate(e.value)}function Cg({userId:e,userName:t}){let n=_s(),r=_s(),o=_s(),s=_s(),i=_s(),l=vt(void 0,void 0);if(a(l))return l;let d=vt(void 0,void 0);if(a(d))return d;let m=vt(d.value,void 0);if(a(m))return m;let p=vt(void 0,void 0);if(a(p))return p;let f=vt(p.value,void 0);if(a(f))return f;let g=vt(f.value,void 0);if(a(g))return g;let y=vt(void 0,void 0);return a(y)?y:u("Created default events",[{id:Rn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Rn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Rn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:d.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Rn(),userId:e,action:"add.board",payload:{id:Qi,name:"Closed",parent:n,rank:m.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:Qi,rank:y.value}},{id:Rn(),userId:e,action:"lock.node",payload:{id:Qi}},{id:Rn(),userId:e,action:"lock.node",payload:{id:ye}}])}var $S=()=>{let e=xe();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},US=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");se.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");se.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function en(e,t=[]){if($S())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Bs(s);return a(i)?i:(w({hasProjectDefinition:!1,mode:I.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return c("Initialized Epiq project has no workspace init event");let n=Qt(e),{fatal:r,skipped:o}=In(n);return r.length>0?c(`Materializing failed:
|
|
26
|
+
`).filter(Boolean).filter(i=>i!==gt);if(r.length===0)return d("State branch is storage-only",!1);let o=await U({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return l(`Failed to clean storage branch
|
|
27
|
+
${o.message}`);let s=await go({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?l(s.message):d("Cleaned storage branch",!0)},Jt=cc(async(e=process.cwd())=>{let t=await U({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?l("Not inside a Git repository"):d("Resolved repo root",t.value.stdout.trim())},e=>Et.resolve(e)),aL=cc(async e=>{let t=await U({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return l(t.message);let n=t.value.stdout.trim(),r=Et.isAbsolute(n)?n:Et.join(e,n);return d("Resolved git dir",r)},e=>Et.resolve(e));var fL=process.env.IS_LOCAL==="true",gt=".epiq",Fn="events",Ec="media",BI="project.json",Mr=e=>fn.join(e,gt),po=e=>fn.join(Mr(e),BI),St=e=>fn.join(Mr(e),Fn),gs=e=>fn.join(Mr(e),Ec),tp=e=>fn.join(e,gt),OI=e=>{let t=fn.join(e,gt);return fs.existsSync(t)&&fs.statSync(t).isDirectory()},hs=e=>{let t=po(e);return fs.existsSync(t)&&fs.statSync(t).isFile()},$i=e=>{let t=fn.resolve(e);for(;;){if(OI(t))return d("Resolved closest .epiq root",t);let n=fn.dirname(t);if(n===t)return l("No .epiq directory found in any parent");t=n}},Sc="No .epiq/project.json found in any parent",re=e=>{let t=fn.resolve(e);for(;;){if(hs(t))return d("Resolved closest epiq project root",t);let n=fn.dirname(t);if(n===t)return l(Sc);t=n}},np=e=>{let t=St(e);try{return fs.mkdirSync(t,{recursive:!0}),d("Resolved events dir",t)}catch(n){return l(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ie=async()=>{let e=await Jt(process.cwd());if(a(e))return e;let t=me({repoRoot:e.value});return a(t)?t:d("Resolved persist root",t.value)};import{accessSync as FI,copyFileSync as _I,existsSync as Gi,mkdirSync as rp,readdirSync as op,readFileSync as jI,renameSync as $I,rmSync as UI,statSync as sp,unlinkSync as HI,writeFileSync as WI}from"node:fs";import ho from"node:path";var Rc=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ot={writeToFile:(e,t)=>{try{let n=ho.dirname(e);Gi(n)||rp(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);WI(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return jI(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ot.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 Gi(e)&&sp(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await FI(e),!0}catch{return!1}},mkDir:e=>rp(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ho.parse(t);for(;;){let r=ho.join(t,e);try{if(Gi(r)&&sp(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ho.dirname(t)}return null},readFirstJSON(e){try{if(!ot.dirExists(e))return null;let t=op(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ho.join(e,t);return ot.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ot.dirExists(e)?op(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{HI(e)}catch(t){(!Rc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{UI(e,{recursive:!0,force:!0})}catch(t){(!Rc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ho.dirname(t)),!n?.overwrite&&Gi(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{$I(e,t)}catch(r){if(Rc(r)&&r.code==="EXDEV"){_I(e,t),this.rmFile(e);return}throw r}}};var VI={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},ap=Qt.object({logLevel:Qt.enum(["info","error","debug"]),preferredEditor:Qt.string().optional(),userName:Qt.string().optional(),userId:Qt.string().optional(),autoSync:Qt.boolean().nullable().optional(),autoSyncDebounceMs:Qt.number().optional(),attachmentMaxKb:Qt.number().optional(),viewMode:Qt.enum(["dense","wide"]).optional(),declinedEmailBoards:Qt.array(Qt.string()).optional()}).partial(),zI="config.json",lp=Bn,Cc=()=>GI.join(lp(),zI),Nc=()=>{try{return ot.mkDir(lp()),d(`Ensured ~/${Yt} exists`,null)}catch{return l(`Unable to create ~/${Yt}`)}},KI=e=>{let t;try{t=JSON.parse(e)}catch{return l(`Invalid ~/${Yt}/config.json JSON`)}let n=ap.safeParse(t??{});return n.success?d("Parsed config",n.data):l(`Invalid ~/${Yt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},gn=()=>{let e=Nc();if(a(e))return l(e.message);let t=Cc(),n=ot.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):KI(n)},cp=e=>{let t=Nc();if(a(t))return l(t.message);let n=ap.safeParse(e);if(!n.success)return l(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Cc();try{return ot.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
28
|
+
`),d("Config written",null)}catch{return l(`Unable to write ~/${Yt}/config.json`)}},jt=e=>{let t=gn();if(a(t))return l("Failed to read existing config");let n={...t.value,...e};return cp(n)},ht=()=>{let e=Cc(),t=Nc();if(a(t))return l(`Unable to create ~/${Yt}`);if(!(ot.readFile(e)!==null)){let b=cp(VI);if(a(b))throw new Error(`Unable to create ~/${Yt}/config.json`)}let r=gn();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:c,autoSync:u,autoSyncDebounceMs:p,attachmentMaxKb:m,logLevel:f,viewMode:g}=r.value,h=co({userId:i,userName:s});if(a(h))return l(h.message);let x=h.value??{userId:i,userName:s};return!x.userName||!x.userId?l(`User name or ID not configured in ~/${Yt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:c??[],logLevel:f??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:u??!1,autoSyncIntervalMs:p??1e4,attachmentMaxKb:m??null,viewMode:g??"dense"}))};import{useSyncExternalStore as qI}from"react";var ys={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},Ac=new Set,YI=()=>{for(let e of Ac)e()},V=()=>ys,dp=()=>qI(e=>(Ac.add(e),()=>{Ac.delete(e)}),()=>ys),je=e=>(ys={...ys,...e},YI(),ys);import{spawn as XI}from"node:child_process";import Tc from"node:process";var wc=e=>{let t=Tc.platform==="darwin"?"open":Tc.platform==="win32"?"cmd":"xdg-open",n=Tc.platform==="win32"?["/c","start","",e]:[e];XI(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as sx,stat as Lw}from"node:fs/promises";import{createHash as kw}from"node:crypto";import Sr from"chalk";import Fv from"string-width";import{decodeTime as up}from"ulid";var Vi=1440*60*1e3,vs=(e,t=Date.now())=>e>t+Vi?t:e,De=e=>vs(up(e)),yo=e=>{let t=Date.now()+Vi,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},vo=e=>{try{return d("Decoded date",new Date(De(e)))}catch(t){return l("Decoding failed + "+t.message)}},tr=e=>{if(!e?.id)return null;try{return up(e.id)}catch{return null}};import bo from"chalk";var it={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:it.cyan,accent2:it.magenta,primary:it.white,secondary:it.grayDark,secondary2:it.grayLight,gray:it.gray,green:it.green,yellow:it.yellow,red:it.red};var L={red:it.red,yellow:it.yellow,green:it.green,blue:it.blue,magenta:it.magenta,cyan:it.cyan},zi={urgent:L.red,critical:L.red,important:L.red,blocker:L.red,asap:L.red,immediate:L.red,fail:L.red,failure:L.red,broken:L.red,bug:L.red,error:L.red,incident:L.red,outage:L.red,production:L.red,crash:L.red,security:L.red,warning:L.yellow,warn:L.yellow,risky:L.yellow,risk:L.yellow,attention:L.yellow,pending:L.yellow,review:L.yellow,"needs-review":L.yellow,qa:L.yellow,testing:L.yellow,test:L.yellow,validate:L.yellow,verification:L.yellow,staging:L.yellow,check:L.yellow,"follow-up":L.yellow,followup:L.yellow,waiting:L.yellow,blocked:L.yellow,hold:L.yellow,done:L.green,complete:L.green,completed:L.green,success:L.green,ok:L.green,stable:L.green,resolved:L.green,fixed:L.green,closed:L.green,merged:L.green,released:L.green,deployed:L.green,approved:L.green,verified:L.green,working:L.green,healthy:L.green,pass:L.green,passing:L.green,info:L.blue,information:L.blue,note:L.blue,docs:L.blue,documentation:L.blue,doc:L.blue,guide:L.blue,help:L.blue,explanation:L.blue,detail:L.blue,details:L.blue,context:L.blue,design:L.blue,discussion:L.blue,proposal:L.blue,idea:L.blue,feature:L.magenta,enhancement:L.magenta,improvement:L.magenta,refactor:L.magenta,refactoring:L.magenta,cleanup:L.magenta,optimize:L.magenta,optimization:L.magenta,perf:L.magenta,performance:L.magenta,upgrade:L.magenta,migration:L.magenta,modernize:L.magenta,debt:L.magenta,todo:L.cyan,next:L.cyan,planned:L.cyan,plan:L.cyan,future:L.cyan,backlog:L.cyan,investigate:L.cyan,explore:L.cyan,prototype:L.cyan};var Pc={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Lc=(e,t,n)=>Math.max(t,Math.min(n,e)),Mc=(e,t,n)=>e+(t-e)*n,pp=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},JI=e=>e.toLowerCase().trim(),QI=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,p=0,m=0;i>=0&&i<1?(u=s,p=c):i>=1&&i<2?(u=c,p=s):i>=2&&i<3?(p=s,m=c):i>=3&&i<4?(p=c,m=s):i>=4&&i<5?(u=c,m=s):(u=s,m=c);let f=o-s/2;return[Math.round((u+f)*255),Math.round((p+f)*255),Math.round((m+f)*255)]},kc=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,mp=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},fp=(e,t,n)=>{let r=Lc(n,0,1);return[Math.round(Mc(e[0],t[0],r)),Math.round(Mc(e[1],t[1],r)),Math.round(Mc(e[2],t[2],r))]};var ZI=(e,t,n)=>fp(e,t,n),Dc=e=>{let t=pp(e)%360,n=QI(t,Pc.stringColor.saturation,Pc.stringColor.lightness);return kc(n)},ze=(e,t=zi)=>{let n=JI(e??"");return n&&t[n]?t[n]:Dc(n)};var gp=e=>{let t=Pc.gradient.stops,n=Lc(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return ZI(t[s],t[s+1],i)},hp=(e,t)=>{if(e.length===0)return"#000000";if(e.length===1)return e[0];let n=e.length-1,r=Lc(t,0,1)*n,o=Math.min(Math.floor(r),n-1);return kc(fp(mp(e[o]),mp(e[o+1]),r-o))},Ki=e=>kc(gp(e)),qi=e=>pp(e.toLowerCase().trim())/4294967295,yp=e=>{let t=qi(e);return gp(t)},eE=e=>{let[t,n,r]=yp(e);return{normal:o=>bo.bgRgb(t,n,r).black(o),cursor:o=>bo.bgRgb(t,n,r).white.bold(o)}},Bc=e=>{let[t,n,r]=yp(e);return{fg:o=>bo.rgb(t,n,r)(o),fgCursor:o=>bo.rgb(t,n,r).inverse(o),bg:o=>bo.bgRgb(t,n,r).black(o),bgCursor:o=>bo.bgRgb(t,n,r).white.bold(o)}},Yi=e=>eE(e).normal(` ${e} `);var tE="Unknown",Xi=(e,t)=>t?.length?t:e?.length?e:tE,Ke=(e,t)=>{let n=Xi(e,t);return{id:e?.length?e:n,name:n,color:ze(n)}};var xo="removed",yt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?d("Found node",n):l("Unable to find node in breadcrumb")},vp=["png","jpg","gif","webp"];var Ze=e=>e.trim().toLowerCase(),nr=e=>{let t=Ze(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},bs=(e,t)=>`${Ze(e)} ${t}`,Oc=e=>!e.tombstoned,xs=(e,t)=>{let n=Ze(t),r=new Set;for(let o of Object.values(e))Oc(o)&&o.email===n&&r.add(o.contributor);return[...r]},hn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Oc(r)&&r.contributor===t&&n.add(r.email);return[...n]},bp=e=>{let t=new Map;for(let r of Object.values(e)){if(!Oc(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var Ji=(e,t)=>e===t.authorId||e===t.contributor;var oe={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Fc(e){return e.context===oe.WORKSPACE}function _(e){return e.context===oe.TICKET}function rr(e){return e.context===oe.TEXT}function at(e){return e.context===oe.FIELD}function Is(e){return e.context===oe.FIELD_LIST}var yn=e=>e.context===oe.SWIMLANE,or=e=>e.context===oe.BOARD,Es=e=>e.context===oe.COMMENT;import{useSyncExternalStore as AA}from"react";var I={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var xp=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Ip=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Ep=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Sp=(e,t)=>{if(Ip(e,e.sequence))return E.MoveCursorLeftOfWord;if(Ep(e,e.sequence))return E.MoveCursorRightOfWord;if(xp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.GetLastCommandFromHistory;case"down":return E.GetNextCommandFromHistory;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}},Rp=(e,t)=>{if(Ip(e,e.sequence))return E.MoveCursorLeftOfWord;if(Ep(e,e.sequence))return E.MoveCursorRightOfWord;if(xp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.NavPreviousItem;case"down":return E.NavNextItem;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}};import Cp from"string-width";function Qi(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var _n=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",nE=/\u001B\[[0-9;]*m/,_c="\x1B[0m",rE=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),jn=(e,t)=>{if(t<=0)return"";if(Cp(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(nE.test(c)){o+=c,i=c!==_c&&c!=="\x1B[m";continue}for(let u of rE(c)){let p=Cp(u);if(s+p>r)return`${o}...${i?_c:""}`;o+=u,s+=p}}return`${o}...${i?_c:""}`},Ee=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Np=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ap=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},Tp=(e,t)=>t?e.get(t)??[]:[];var wp=new WeakMap,oE=e=>{let t=wp.get(e);return t||(t=Ap(e),wp.set(e,t)),t};var Mp=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Tp(oE(e),r).filter(s=>Qi(r,s.toLowerCase())>=n)};var sE={hint:"",hints:[],overlap:0,remainder:""},Lp=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[c]=s;return s.length===1&&c&&!r.trim()?Pp("",[c]):sE}let i=Mp({wordList:o,inputToMatch:e,overlapThreshold:1});return Pp(t,i)},Pp=(e,t)=>{let n=t[0]??"",r=Qi(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,m=(c&&i?o:n)+(c&&i?":":" "),f=m.slice(r);return{hint:m,hints:t,overlap:r,remainder:f}};import Ss from"node:fs";import Rs from"node:path";import{z as Io}from"zod";var Zi="recent-projects.json",iE=20,aE=Io.object({projectId:Io.string().min(1),root:Io.string().min(1),lastOpenedAt:Io.number().finite()}),lE=Io.object({projects:Io.array(aE)}),Dp=()=>Rs.join(Bn(),Zi),Eo=e=>Rs.basename(e)||e,kp=e=>{let t=Rs.resolve(e);try{return Ss.realpathSync(t)}catch{return t}},Bp=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Op=e=>{if(!hs(e.root))return!1;let t=pn(e.root);return!a(t)&&t.value===e.projectId},Fp=()=>{let e=Dp();if(!Ss.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(Ss.readFileSync(e,"utf8"))}catch(r){return l(`Invalid ${Zi}: ${r instanceof Error?r.message:String(r)}`)}let n=lE.safeParse(t);return n.success?d("Read recent projects",n.data.projects):l(`Invalid ${Zi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},cE=e=>{let t=Dp();try{Ss.mkdirSync(Rs.dirname(t),{recursive:!0}),Ss.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
29
|
+
`,"utf8")}catch(n){return l(`Unable to write ${Zi}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},$n=({exclude:e}={})=>{let t=Fp();if(a(t))return t;let n=e===void 0?null:kp(e);return d("Listed recent projects",t.value.filter(r=>n===null||kp(r.root)!==n).filter(Op).sort(Bp))},ea=({root:e,now:t=Date.now()})=>{let n=Rs.resolve(e),r=pn(n);if(a(r))return l(r.message);let o=r.value,s=Fp(),i=a(s)?[]:s.value,c=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(Op).sort(Bp).slice(0,iE);return cE(c)};var jc=null,_p=e=>{jc=e},jp=e=>jc?jc(e):[];var $p=[],So=e=>{$p=e},Ro=()=>$p;var Un=()=>{let e=V(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=Up(),s=o.length>0?null:$c(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),c=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&c,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:c,claimedEmails:o,emailSetupDeclined:i}},$c=()=>{let e=re(process.cwd());if(a(e))return null;let t=pn(e.value);return a(t)?null:t.value||null},Up=()=>{let{userId:e}=V();return e?jp(e):[]},Hp=()=>Up().length>0;var Uc=()=>{let e=re(process.cwd());if(a(e))return!1;let t=Mt(e.value);return ve(t)},Wp=e=>e===!0?"on":e===!1?"off":null,Gp=e=>e==="on"?!0:e==="off"?!1:null,Vp=()=>{let e=Un();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!Uc())return"init";if(!e.isSetEmails){let{gitEmail:t}=V(),n=Ro()[0]??t;return n&&nr(n)?`config emails ${n}`:"config emails "}return null};var dE=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,ta]=dE;var uE=e=>e.props.tags??[],mE=e=>e.props.assignees??[],vn=e=>uE(e).map(t=>N.getTag(t)).filter(t=>!!t),bn=e=>mE(e).map(t=>N.getContributor(t)).filter(t=>!!t),na=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?l("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",vn(n))},ra=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?l("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",bn(n))};var C={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""};var pE=/^(\d+)(h|d|w|mo|y)$/,fE=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,gE=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},hE=(e,t=new Date)=>{let n=e.match(pE);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},yE=e=>{let t=e.match(fE);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),p=Number(o),m=s?Number(s):0,f=i?Number(i):0;return gE({year:c,month:u,day:p,hour:m,minute:f})?new Date(c,u-1,p,m,f):null},Lr=e=>{let t=e.trim().toLowerCase();return hE(t)??yE(t)};var zp=/^(\d+)(s|m)?$/,oa=e=>{let t=e.trim().toLowerCase().match(zp);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},sa=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&zp.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Kp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,vE=[{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}],Hc=(e=vE)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var bE=["BOARD","TICKET","SWIMLANE","COMMENT"],ye={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},kt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},qe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},xE=[ye.EDITOR,ye.VIEW,ye.USERNAME,ye.EMAILS,ye.EMAILS_UNCLAIM,ye.AUTOSYNC,ye.SYNC_DEBOUNCE_MS,ye.ATTACHMENT_MAX_KB,ye.LOG_LEVEL],IE=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[kt.TITLE,kt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[kt.TITLE];case"COMMENT":return[kt.COMMENT];default:return[]}},Gc=[String(3e3),"5000","15000","30000","60000"],Vc=["250","500","1000"],Xp=["10s","20s","30s","45s"],kr=[C.EXIT,C.SYNC,C.HELP,C.EXPORT,C.CONFIG,C.YANK],ia=[C.NEW,C.EDIT,C.DELETE,C.MOVE],Wc=[C.TAG,C.UNTAG,C.ASSIGN,C.UNASSIGN,C.CLOSE_ISSUE,C.RE_OPEN_ISSUE,C.EDIT,C.COMMENT],qp=[C.FILTER,C.PEEK,C.REPLAY],EE={WORKSPACE:[...kr,...ia],BOARD:[...qp,...kr,...ia],SWIMLANE:[...qp,...kr,...ia],TICKET:[...kr,...ia,...Wc],FIELD:[...kr,...Wc],FIELD_LIST:[...kr,...Wc],TEXT:[...kr],COMMENT:[C.EDIT,C.DELETE,C.YANK]},SE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Cs=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&_(n)),Yp=e=>e.parentNodeId===he,RE=({selectedNode:e,breadCrumb:t})=>{let n=IE(e?.context);return Cs({breadCrumb:t,selectedNode:e})?n.includes(kt.DESCRIPTION)?n:[...n,kt.DESCRIPTION]:n},CE=({selectedNode:e,breadCrumb:t})=>{let n=Cs({breadCrumb:t,selectedNode:e});return n?[qe.REF,qe.TITLE,...n.props?.description?.trim()?[qe.DESCRIPTION]:[],...vn(n).length>0?[qe.TAGS]:[],...bn(n).length>0?[qe.ASSIGNEES]:[]]:e?[qe.REF,qe.TITLE]:[]},zc=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},NE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Un();if(!r)return[C.HELP,C.CONFIG];if(!Uc())return[C.HELP,C.INIT,C.OPEN];if(t)return[C.HELP,C.PEEK,C.REPLAY,C.EXPORT,C.CONFIG,C.YANK];let o=e?.context,s=o&&bE.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?EE[u]:[]))],c=Cs({breadCrumb:n,selectedNode:e});return i.filter(u=>u===C.MOVE?!1:u===C.YANK?!!(c??e):u===C.EDIT?s||!!c:u===C.DELETE?s:u===C.UNTAG?!!(c&&vn(c).length>0):u===C.UNASSIGN?!!(c&&bn(c).length>0):u===C.RE_OPEN_ISSUE?!!(c&&Yp(c)):u===C.CLOSE_ISSUE?!!(c&&!Yp(c)):!0)},Be=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[C.NONE]:NE({breadCrumb:o,readOnly:r,selectedNode:n}),[C.EXIT]:["confirm"],[C.EXPORT]:[],[C.SYNC]:[],[C.INIT]:[],[C.OPEN]:e===C.OPEN?zc():[],[C.HELP]:[],[C.PEEK]:[...Hc(),"now","prev","next"],[C.REPLAY]:[...Hc()],[C.EDIT]:RE({selectedNode:n,breadCrumb:o}),[C.YANK]:CE({selectedNode:n,breadCrumb:o}),[C.COMMENT]:[],[C.DELETE]:["confirm"],[C.RE_OPEN_ISSUE]:["confirm"],[C.CLOSE_ISSUE]:["confirm"],[C.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[C.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[C.TAG]:[...new Set([...Object.keys(zi),...N.getExistingTags()])],[C.UNTAG]:[...na()?.value?.map(({name:c})=>c)??[]],[C.UNASSIGN]:[...ra()?.value?.map(({name:c})=>c)??[]],[C.ASSIGN]:N.getExistingAssignees(),[C.NEW]:SE(s),[C.CONFIG]:[...xE]}[e]??[]};import uf from"chalk";var Jp=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import PE from"zod";import AE from"node:crypto";import Ns from"node:fs";import ef from"node:path";var Qp="/media/",Zp=e=>`${Qp}${e}`,Kc=(e,t)=>`})`;var xn=500,TE=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Br=(e,t)=>`${e}.${t}`,wE=e=>TE.test(e),tf=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?d("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?d("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?d("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?d("Sniffed image type","webp"):l(`Unsupported image format. Allowed: ${vp.join(", ")}`),nf=e=>AE.createHash("sha256").update(e).digest("hex"),ME=(e,t=xn)=>{if(e.length===0)return l("Attachment is empty");if(e.length>t*1024)return l(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=tf(e);return a(n)?n:d("Validated attachment data",{hash:nf(e),ext:n.value,bytes:e.length})},rf=(e,t,n=xn)=>{let r=ME(t,n);if(a(r))return r;let o=gs(e),s=ef.join(o,Br(r.value.hash,r.value.ext));try{Ns.existsSync(s)||(Ns.mkdirSync(o,{recursive:!0}),Ns.writeFileSync(s,t))}catch(i){return l(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",r.value)},of=(e,t,n=xn)=>{if(!wE(t))return l("Invalid attachment file name");let r=ef.join(gs(e),t);if(!Ns.existsSync(r))return l("Attachment blob not found");let o;try{o=Ns.readFileSync(r)}catch(u){return l(`Unable to read attachment blob: ${u instanceof Error?u.message:String(u)}`)}if(o.length>n*1024)return l(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(nf(o)!==s)return l("Attachment blob does not match its content hash");let c=tf(o);return a(c)?c:c.value!==i?l("Attachment blob content does not match its extension"):d("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var As=50,Ts=5e3,sf=()=>{let e=se().commandMeta.inputString,t=PE.coerce.number().int().min(As).max(Ts).safeParse(e);if(!t.success)return l(`Attachment size cap must be ${As}-${Ts} KB (default ${xn})`);let n=jt({attachmentMaxKb:t.data});return a(n)?n:(je({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))};var lt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as LE}from"node:crypto";var kE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",DE=e=>{let t=LE("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=kE[Number(n>>s&31n)]}return r},af=new Map,Me=(e,t)=>{let n=`${e}:virtual:${t}`,r=af.get(n);if(r!==void 0)return r;let o=DE(n);return af.set(n,o),o};import lf from"chalk";var Se=e=>lf.dim(e),$e=e=>lf.hex(y.primary)(e),Ue=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let m=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>qi(f)-qi(g)).slice(0,r).map(f=>Yi(f)).join(" ");return m?`${Se(e)}${m}${Se(n)}`:""};var In={None:"none",Invalid:"invalid",Valid:"valid"};var BE=["BOARD","TICKET","SWIMLANE"],cf=()=>{let e=v().selectedNode;if(!e?.context)return z({message:Se("Missing target context")});if(BE.includes(e.context))return ie();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Me(t?.parentNodeId??"","comments"))return ie()}return z({message:Se("Command not available in this context")})},fe="<ENTER> to confirm",OE=()=>{let{userId:e}=V(),t=de();return!e||a(t)?[]:hn(t.value.emailLinks,e)},ie=(e="",t=[],n=!0)=>({message:n?Se(e):e,validity:In.Valid,completionWordList:t}),z=({message:e,completionWordList:t=[]})=>({validity:In.Invalid,message:e,completionWordList:t}),No=e=>e.length===0,df=(e,t)=>{let n=yt(v().breadCrumb,"BOARD");if(a(n))return z({message:$e("Command is not applicable in this context")});let r=vo(n.value.id);return a(r)?z({message:$e(`Unable to ${t}: board id is not a valid ULID`)}):Kp({date:e,horizonDate:r.value})?null:z({message:$e(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},aa=e=>` ${uf.hex("#000").bgHex(ze(e))(` ${e} `)} `,qc=({modifier:e})=>{let t="confirm";return e===t?ie(fe):z({message:No(e)?Se("if you are certain, enter ")+Yi(t):"",completionWordList:[t]})},FE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?z({message:Se(n)}):ie():z({message:No(r)?t:"",completionWordList:[...e]}),Co=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>No(n)&&No(r)?z({message:e,completionWordList:[]}):ie(t??fe),_E=({modifier:e,inputString:t})=>{let n=zc();return!No(e)||!No(t)?ie(fe):z({message:n.length?Se("number from the list, or a path"):Se("path to an epiq project"),completionWordList:n})},jE=({modifier:e,inputString:t})=>{let n=Be(C.CONFIG);if(!n.includes(e))return z({message:Ue({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ye.EDITOR:{let r=[...Jp];return t.trim()?r.includes(t.trim())?ie(fe):z({message:Ue({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):z({message:Ue({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?ie(fe):z({message:Ue({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.USERNAME:{let r=V().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(p=>p.startsWith(s)),u=i.length===1&&i[0]===s?"":Ue({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?u?ie(`${u} ${Se(fe)}`,o,!1):ie(fe,o):z({message:u||$e("Enter a user name. Saved in ")+uf.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ye.EMAILS:{let r=V().gitEmail,o=Ro(),s=o.length>0||!r?o:[r],i=[...s,"none"],c=t.trim(),u=(x,b)=>z({message:Ue({prefix:x,wordList:i,noOfHints:3,inputString:b,minLengthForHints:0}),completionWordList:i});if(!c)return ie(`${fe} to see your addresses, or name one`,i);let p=c.split(/[,\s]+/).filter(Boolean),m=p[p.length-1]??"",f=x=>x==="none"||s.includes(x.toLowerCase()),g=x=>i.some(b=>b.startsWith(x.toLowerCase())),h=p.filter(x=>!f(x)&&!g(x));return h.length>0?z({message:$e(`no address here matches ${h.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?ie(fe):u("",m)}case ye.EMAILS_UNCLAIM:{let r=OE(),o=t.trim();return r.length===0?z({message:$e("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?ie(fe):z({message:Ue({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ye.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?ie(fe):z({message:Ue({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ye.AUTOSYNC:{let r=["on","off"],o=V().autoSync;if(!r.includes(t.trim())){let s=Wp(o);return z({message:Ue({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return ie(fe)}case ye.ATTACHMENT_MAX_KB:{let r=V().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<As||o>Ts){let s=Ue({prefix:" examples: ",wordList:Vc,minLengthForHints:0,inputString:t});return z({message:$e(`provide a size cap in KB (${As}-${Ts}). current: ${r??xn} KB.`)+s,completionWordList:Vc})}return ie(fe)}case ye.SYNC_DEBOUNCE_MS:{let r=V().autoSyncIntervalMs,o=uo(t);if(!t.trim()||o===null){let s=Ue({prefix:" examples: ",wordList:Gc,minLengthForHints:0,inputString:t});return z({message:$e(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Gc})}return ie(fe)}default:return z({message:$e("Unknown config option"),completionWordList:n})}},$E=({modifier:e,inputString:t})=>{let n=Be(C.EDIT);if(!n.length)return z({message:$e("Command not available in this context")});if(!n.includes(e)){let r=Ue({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return z({message:r||$e("Unknown edit option"),completionWordList:n})}switch(e){case kt.COMMENT:return t.trim()?ie(fe):z({message:Se("write a comment...")});case kt.TITLE:return ie(fe);case kt.DESCRIPTION:{let{preferredEditor:r}=V();return r?ie(Se("<ENTER> to edit in ")+r):z({message:"No editor selected"})}default:return z({message:$e("Unknown edit option"),completionWordList:n})}},UE=({modifier:e})=>{let t=Be(C.YANK);return t.length?t.includes(e)?ie(fe+Se(" and copy to clipboard")):z({message:Ue({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):z({message:$e("Nothing selected to copy from")})},HE={[C.EXPORT]:()=>ie(fe+Se(", and create export markdown file")),[C.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ie(fe);let n={message:Se("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Lr(r);if(!r||!o)return z(n);let s=df(o,"peek");return s||ie(fe)},[C.REPLAY]:e=>{let{dateInput:t,durationInput:n}=sa(e.modifier,e.inputString),r={message:Se("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Lr(t);if(!t||!o)return z(r);let s=df(o,"replay");return s||(n&&oa(n)===null?z({message:$e("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ie("<ENTER> to replay board history",n?Xp:[]))},[C.EXIT]:()=>ie(fe+Se(" and exit the application")),[C.INIT]:()=>ie(fe),[C.OPEN]:_E,[C.PALETTE]:()=>ie(fe),[C.FILTER]:e=>{if(e.modifier==="clear")return ie(fe);let t=s=>Be(C.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return z({message:Ue({wordList:Be(C.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Be(C.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?z({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):ie():z({message:Ue({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[C.NONE]:e=>{let t=Be(C.NONE);return z({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[C.NEW]:e=>FE({list:Be(C.NEW),hint:Ue({wordList:Be(C.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[C.HELP]:()=>ie(fe),[C.EDIT]:$E,[C.COMMENT]:e=>{let t=Co({hint:Se(`write a comment (max ${4e3} char)...`),onOk:Se(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===In.Invalid?t:e.inputString.length>4e3?ie($e("max input exceeded")):t},[C.CONFIG]:jE,[C.YANK]:UE,[C.DELETE]:e=>{let t=cf();return t.validity==="invalid"?t:qc(e)},[C.CLOSE_ISSUE]:e=>qc(e),[C.RE_OPEN_ISSUE]:e=>qc(e),[C.MOVE]:e=>{let t=cf();return t.validity==="invalid"?t:Co({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:Be(C.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[C.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(aa).join("");return Co({hint:n.length?Se("create tag or reuse:")+n+Se(""):Se("create tag ...")})(e)},[C.UNTAG]:e=>{let t=na();if(a(t))return z({message:$e("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(aa).slice(0,10);return n.length?Co({hint:Se(" ... ")+n.join("")})(e):z({message:$e("Issue has no tags"),completionWordList:[]})},[C.ASSIGN]:e=>{let t=N.getExistingAssignees().map(aa).slice(0,10);return Co({hint:Se("assignees... ")+t.join("")})(e)},[C.UNASSIGN]:e=>{let t=ra();if(a(t))return z({message:$e("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(aa).slice(0,10);return n.length?Co({hint:Se("remove assignee... ")+n.join("")})(e):z({message:$e("Issue has no assignees"),completionWordList:[]})},[C.SYNC]:()=>ie(fe)},mf=Object.fromEntries(Object.entries(HE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var la=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var WE=3,GE=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),VE=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},zE=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=WE&&!GE.has(t)&&!/^\d+$/.test(t)),KE=e=>{let t=new Map;for(let s of VE(e))for(let i of zE(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=la.filter(s=>!r.has(s));return[...n,...o]},pf=la,ff=-1,gf=()=>{let e=de();if(a(e))return la;let t=e.value,n=t.eventLog.length;return n!==ff&&(pf=KE(t),ff=n),pf};var hf=e=>Object.values(C).includes(e),yf=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=mf[n].validate(n,r,s),p=n!==C.PEEK&&n!==C.REPLAY,m=o==="command"||o==="modifier"?Be(n):p?gf():[],{mode:f}=v(),g=f===I.COMMAND_LINE?i??"":"",h=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Lp(e,h,u):{hint:"",hints:[],remainder:"",overlap:0}}};var vf=e=>{let t=e.trimStart(),n=YE(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=XE(e),c=hf(r)?r:null,u=c!==null,p=r!=="",m=c?Be(c)??[]:[],f=c&&m.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let h=s?"":i,x=qE(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:p,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:h,inputString:x}},qE=(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},YE=e=>e.trim()?e.trim().split(/\s+/):[],XE=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as JE}from"react";var Ao=e=>e===Yc||e===":",Yc=" ",Ms=40,ct={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:In.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Xc=new Set,bf=()=>{for(let e of Xc)e()},Jc=e=>(Xc.add(e),()=>Xc.delete(e)),Ut=e=>{let n=e(ct),r=vf(n.value),o=n.cursorPosition===n.value.length;ct={...n,commandMeta:yf(r,o)},bf()},Ps=({message:e,status:t})=>{let n=structuredClone(ct);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ct=n,bf(),d(e,null)},Qc=e=>{Ut(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Zc=e=>{Ut(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ao(n[o-1]);)o--;for(;o>0&&!Ao(n[o-1]);)o--}else{for(;o<n.length&&!Ao(n[o]);)o++;for(;o<n.length&&Ao(n[o]);)o++}return{...t,cursorPosition:o}})},xf=()=>{Ut(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}})},If=()=>{Ut(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ao(t[r-1]);)r--;for(;r>0&&!Ao(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},ca=e=>{Ut(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Ef=()=>{Ut(e=>({...e,commandIsPending:!0}))},J=e=>{Ut(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Sf=({addToHistory:e=!0,line:t})=>{Ut(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,Ms):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Rf=e=>{Ut(t=>({...t,commandHistory:e.slice(0,Ms),commandHistoryIndex:-1}))},Cf=()=>{Ut(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},Nf=()=>{Ut(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}})},Af=()=>{Ut(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},se=()=>ct,Tf=()=>JE(Jc,se,se),da=()=>{let[e,...t]=ct.value.split(Yc);return t.join(Yc).trim()};var E={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},QE=e=>e.shift===!0,ZE={[E.NavPreviousItem]:E.NavPreviousItemJump,[E.NavNextItem]:E.NavNextItemJump,[E.MovePreviousItem]:E.MovePreviousItemJump,[E.MoveNextItem]:E.MoveNextItemJump};function eS(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function tS(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function nS(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function wf(e,t){let n=se();if(e.sequence==="?"&&t!==I.PALETTE)return E.InitCommandPalette;if(e.sequence===":"&&t!==I.COMMAND_LINE)return E.InitCommandLine;if(t===I.MOVE)switch(e.name){case"m":case"return":return E.ConfirmMove}if(t===I.COMMAND_LINE)return Sp(e,n.value);if(t===I.PALETTE)return Rp(e,n.value);let r=eS(e)||tS(e);if(r)return rS(r,t,QE(e));if(e.ctrl&&e.name==="c")return E.Exit;switch(e.name){case"r":return E.EditTitle;case"e":return E.EditDescription;case"n":return E.AddItem;case"m":return E.InitMove;case"d":return E.Delete;case"y":return E.Yank;case"o":return E.OpenInEditor;case"s":return E.MarkDiffLine;case"c":return E.CommentOnDiffLine;case"return":return E.Confirm;case"space":return E.Confirm;case"v":return V().viewMode==="wide"?E.SetViewDense:E.SetViewWide;case"q":case"escape":return E.Exit;default:return null}}function rS(e,t,n=!1){let r=t===I.MOVE?{prevItem:E.MovePreviousItem,nextItem:E.MoveNextItem,prevContainer:E.MoveToPreviousContainer,nextContainer:E.MoveToNextContainer}:{prevItem:E.NavPreviousItem,nextItem:E.NavNextItem,prevContainer:E.NavToPreviousContainer,nextContainer:E.NavToNextContainer},o=nS(v().contextNode.childRenderAxis,e,r);return!o||!n?o:ZE[o]??o}import{ulid as iS}from"ulid";var Ls=24n,oS=Ls*4n,Zt=(1n<<oS)-1n,sS=/^[0-9a-f]+$/;function Mf(e){return!e||!sS.test(e)?l(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function Dt(e,t=Ls){if(e<0n)return l("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function vt(e,t){if(!e&&!t)return Dt(Zt/2n,Ls);let n=e?Mf(e):d("Resolved lower bound",0n);if(a(n))return n;let r=t?Mf(t):d("Resolved upper bound",Zt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return l("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?l("No rank space available between neighbors"):Dt(i,Ls)}function Pf(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Zt*BigInt(r+1)/(t+1n),s=Dt(o,Ls);if(a(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var D=({userId:e})=>({userId:e}),Lf=e=>({action:e.action,payload:e.payload});var ed=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user","link.contributor.email","unlink.contributor.email"];var GD=new Set(ed);var td=(e,t)=>{let n=be(e),r=Pf(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return l("Unable to assign rebalance rank");o[i.id]=c}return d("Created rebalance event",{id:iS(),action:"rebalance.children",payload:{parent:e,ranks:o},...D(t)})};import{z as Or}from"zod";var kf=1,Df=Or.tuple([Or.string().min(1),Or.string().min(1).nullable()]),aS=Or.looseObject({v:Or.literal(kf),id:Df}),oB=Or.looseObject({v:Or.number().int().positive(),id:Df}),lS=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),cS=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Bf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return l("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return l("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return l("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?l("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?l("Invalid persisted event envelope: id.1"):d("Parsed persisted event envelope",lS(e)?cS(e):e)};var dS=[1];var uS=new Set(dS),nd=e=>uS.has(e),Of=e=>{let t=aS.safeParse(e);return t.success?d("Parsed persisted event",t.data):l(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},rd=(e,t)=>{let n={[e.action]:e.payload,v:kf,id:t};return Of(n)};import Os from"node:fs";import ya from"node:path";import{decodeTime as xS}from"ulid";import{z as dd}from"zod";import od from"node:fs";import mS from"node:path";var ks=e=>e?.code==="ENOENT",sd=3,id=e=>od.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),et=e=>{let t=St(e);for(let n=1;;n++){if(!od.existsSync(t))return"none";let r=[],o=!1;for(let s of id(t))try{let{size:i,mtimeMs:c}=od.statSync(mS.join(t,s));r.push(`${s}:${i}:${c}`)}catch(i){if(!ks(i))throw i;if(n<sd){o=!0;break}}if(!o)return r.join("|")}},Ff=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),ad=(e,t,n)=>{let r=Ff(t),o=et(e),s=Ff(o);for(let[i,c]of s)if(i!==n&&r.get(i)!==c)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},sr=null,ua=e=>sr&&sr.root===e?sr.signature:null,To=(e,t)=>{sr={root:e,signature:t}},_f=(e,t)=>{if(!sr||sr.root!==e)return;let n=ad(e,sr.signature,t);sr=n===null?null:{root:e,signature:n}};import He from"node:fs";import Fr from"node:path";import{ulid as pS}from"ulid";var pa="~pending",ld=/~pending(-[0-9a-z]+)*$/i,$f=/-f(\d+)$/,Uf=e=>{let t=e.indexOf(".");return t===-1?`${e}${pa}`:e.slice(0,t)+pa+e.slice(t)},fa=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},fS=e=>{let[t,n]=fa(e);return ld.test(t)?t.replace(ld,"")+n:null},cd=e=>e.replace(ld,""),_r=e=>e.endsWith(".jsonl")&&fS(e)!==null,Ds=e=>cd(fa(e)[0]),Hf=e=>{let[t]=fa(e),n=$f.exec(t);return n&&_r(e)?Number(n[1]):null},gS=e=>Uf(e).replace(pa,`${pa}-${pS().toLowerCase()}`),hS=(e,t)=>{let[n,r]=fa(e);return`${n.replace($f,"")}-f${t}${r}`},Wf=(e,t)=>Fr.join(St(e),Uf(t)),yS=(e,t)=>Math.max(0,He.statSync(e).size-(Hf(t)??0)),Gf=e=>{let t=St(e);try{return He.existsSync(t)?He.readdirSync(t).filter(_r).some(n=>yS(Fr.join(t,n),n)>0):!1}catch{return!0}},vS=3,Vf=(e,t)=>{for(let n=1;;n++){let r=He.openSync(e,"a"),o;try{He.writeSync(r,t),o=He.fstatSync(r).ino}finally{He.closeSync(r)}let s;try{s=He.statSync(e).ino}catch{s=null}if(s===o||n>=vS)return}},bS=e=>{let t;try{t=He.openSync(e,"r")}catch{return!0}try{let{size:n}=He.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return He.readSync(t,r,0,1,n-1),r[0]===10}finally{He.closeSync(t)}},ma=10,jf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(ma)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};He.appendFileSync(e,Buffer.concat([Buffer.from(bS(e)?"":`
|
|
30
|
+
`),o,Buffer.from(o[o.length-1]===ma?"":`
|
|
31
|
+
`)]));let s=0;for(let i of o)i===ma&&s++;return o[o.length-1]!==ma&&s++,{bytes:r,lines:s}},ga=(e,t)=>{let n=St(e);if(!He.existsSync(n))return d("No events directory",0);try{let r=Ds(t),o=He.readdirSync(n).filter(c=>_r(c)&&Ds(c)===r),s=Fr.join(n,t),i=0;for(let c of o){let u=Hf(c);if(u!==null){let g=Fr.join(n,c),h=He.readFileSync(g).subarray(u);i+=jf(s,h,!0).lines,He.rmSync(g,{force:!0});continue}let p=/~pending-/i.test(c)?c:gS(t),m=Fr.join(n,p);p!==c&&He.renameSync(Fr.join(n,c),m);let f=jf(s,He.readFileSync(m));i+=f.lines,He.renameSync(m,Fr.join(n,hS(p,f.bytes)))}return d("Folded pending logs",i)}catch(r){return l(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};var va="unknown",IS=dd.object({userId:dd.string().min(1).default(va),userName:dd.string().min(1).default(va)}),Yf=new Set(["id","v","userId","userName"]),ha=e=>{let t=Object.entries(e).filter(([o])=>!Yf.has(o));if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},ES=/^[0-9a-hjkmnp-tv-z]{26}$/i,SS=e=>ES.test(e)?e.toUpperCase():e,Xf=e=>{let t=ya.basename(e,".jsonl"),n=t.indexOf("."),r=cd(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=IS.safeParse({userId:SS(r),userName:o});return s.success?d("Parsed event file actor",s.data):l(`Invalid event file name ${ya.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},RS=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?l(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?l("Invalid persisted event: action key is missing or invalid"):d("Resolved persisted action",t[0])},CS=(e,t)=>t in e,ir=new Map,NS=3e5,AS=512,Bs=0,ud=e=>e.entries.length+e.quarantined.length,TS=(e,t,n,r)=>{let o=ir.get(e);o&&(Bs-=ud(o));let s={stamp:t,entries:n,quarantined:r};ir.delete(e),ir.set(e,s),Bs+=ud(s);for(let[i,c]of ir){if(Bs<=NS&&ir.size<=AS)break;i!==e&&(ir.delete(i),Bs-=ud(c))}},wS=()=>{ir.clear(),Bs=0},MS=2n,zf=1000000n,PS=e=>{try{let{size:t,mtimeNs:n}=Os.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*zf-n>MS*zf}}catch{return null}},Jf=(e,t)=>{let n=Xf(e);if(a(n))return l(n.message);let r=PS(e),o=r?ir.get(e):void 0;if(r&&o&&o.stamp===r.value){if(t)for(let m of o.quarantined)t.push(m);return d("Parsed persisted events file",[...o.entries])}let s;try{s=Os.readFileSync(e,"utf8")}catch(m){if(ks(m))return d("Event file missing",null);throw m}let i=[],c=ya.basename(e),u=[],p=(m,f)=>{u.push({eventId:null,reason:"corrupt-line",detail:`${c}:${m} (${f})`,targetNodeId:null})};for(let[m,f]of s.split(`
|
|
32
|
+
`).entries()){let g=f.trim();if(!g)continue;let h;try{h=JSON.parse(g)}catch{p(m+1,"invalid JSON");continue}let x=Bf(h);if(a(x)){p(m+1,x.message);continue}i.push({...x.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let m of u)t.push(m);return r?.settled&&TS(e,r.value,i,u),d("Parsed persisted events file",[...i])},Kf=(e,t)=>e<t?-1:e>t?1:0,md=(e,t)=>{let n=Kf(e.id[0],t.id[0]);return n!==0?n:Kf(JSON.stringify(e),JSON.stringify(t))},qf=(e,t)=>{let n=new Map,r=new Map;for(let m of e){let f=m.id[0],g=m.id[1]??null;n.set(f,m);let h=r.get(g)??[];h.push(m),r.set(g,h)}for(let m of r.values())m.sort(md);let o=[],s=new Set,i=m=>{let f=[m];for(;f.length>0;){let g=f.pop(),h=g.id[0];if(s.has(h))continue;o.push(g),s.add(h);let x=r.get(h)??[];for(let b=x.length-1;b>=0;b--)f.push(x[b])}},c=(r.get(null)??[]).filter(m=>{let f=Object.keys(m).filter(g=>!Yf.has(g));return f.length===1&&f[0]===t});for(let m of c)i(m);let u=e.filter(m=>{let f=m.id[0],g=m.id[1]??null;return s.has(f)?!1:g===null||!n.has(g)}).sort(md);for(let m of u)i(m);let p=e.filter(m=>!s.has(m.id[0])).sort(md);for(let m of p)i(m);return o},pd=e=>yo(e.map(t=>{try{return xS(t.id[0])}catch{return null}})),Qf=(e,t)=>{let n=new Set,r=[],o=[],s=pd(e);for(let i=0;i<e.length;i++){let c=e[i],u=c.id[0],p=c.id[1],m=s[i]??null;!(m!==null&&m<t)||p&&n.has(p)?(n.add(u),o.push(c)):r.push(c)}return{appliedEvents:r,unappliedEvents:o}},Zf=e=>{let t=new Set(e.actions),n=S=>t.has(S),r=S=>{let{userId:A,userName:T,...P}=S,M=RS(P);if(a(M))return l(M.message);let O=M.value,W=S.id?.[0];return W?CS(P,O)?d("Decoded persisted event",{id:W,action:O,payload:P[O],userId:A}):l(`Persisted event is missing payload for action: ${O}`):l("Persisted event is missing id")},o=(S,A)=>{let T=[],P=new Map,M=new Map;for(let O of S){if(!nd(O.v)){M.set(O.v,(M.get(O.v)??0)+1),A?.push({eventId:O.id[0],reason:"unsupported-schema-version",detail:`v${O.v}`,targetNodeId:ha(O)});continue}let W=r(O);if(a(W)){A?.push({eventId:O.id[0],reason:"invalid-payload",detail:W.message,targetNodeId:ha(O)});continue}let Y=W.value.action;if(!n(Y)){P.set(Y,(P.get(Y)??0)+1),A?.push({eventId:O.id[0],reason:"unknown-action",detail:Y,targetNodeId:ha(O)});continue}let xe=e.readPayload(Y,W.value.payload);if(a(xe)){A?.push({eventId:O.id[0],reason:"invalid-payload",detail:xe.message,targetNodeId:ha(O)});continue}T.push(W.value)}if(P.size>0){let O=[...P.entries()].map(([W,Y])=>`${W} (x${Y})`).join(", ");ee.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${O}. Upgrade to apply them.`)}if(M.size>0){let O=[...M.entries()].map(([W,Y])=>`v${W} (x${Y})`).join(", ");ee.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${O}. Upgrade to apply them.`)}return d("Decoded reconstructed events",T)},s=null;function i(S,A){let T=St(S),P=et(S);if(!Os.existsSync(T))return d("No events found",[]);let M=[],O=[];for(let Y=1;;Y++){M=[],O=[];let xe=!1;for(let F of id(T)){let X=Jf(ya.join(T,F),O);if(a(X))return l(X.message);if(X.value===null){if(Y<sd){xe=!0;break}continue}for(let Ve of X.value)M.push(Ve)}if(!xe)break}if(A)for(let Y of O)A.push(Y);let W=qf(M,e.genesis);return s={root:S,signature:P,edge:W.at(-1)?.id?.[0]??null},d("All events loaded",W)}function c(S){let A=[],T=i(S,A);if(a(T))return l(T.message);let P=o(T.value,A);return a(P)?l(P.message):d("Loaded merged events",{events:P.value,unreadable:A})}function u(S){let A=i(S);return a(A)?l(A.message):d("Loaded event actors",A.value.map(({userId:T,userName:P})=>({userId:T,userName:P})))}function p(S){let A=new Map,T=St(S),P;try{if(!Os.existsSync(T))return A;P=Os.readdirSync(T)}catch{return A}let M=new Set;for(let W of P){if(!W.endsWith(".jsonl"))continue;let Y=Xf(W);if(a(Y))continue;let{userId:xe,userName:F}=Y.value;if(!xe||!F||F===va)continue;let X=A.get(xe);X!==void 0&&X!==F&&M.add(xe),A.set(xe,F)}if(M.size===0)return A;let O=u(S);if(a(O))return A;for(let{userId:W,userName:Y}of O.value)M.has(W)&&(!Y||Y===va||A.set(W,Y));return A}function m(S){let A=c(S);return a(A)?l(A.message):d("Loaded merged events",A.value.events)}function f(S,A){let T=i(S);if(a(T))return l(T.message);let{appliedEvents:P,unappliedEvents:M}=Qf(T.value,A),O=o(P);if(a(O))return l(O.message);let W=o(M);return a(W)?l(W.message):d("Loaded merged events before time",{appliedEvents:O.value,unappliedEvents:W.value})}function g(S=process.cwd()){let A=et(S);if(s&&s.root===S&&s.signature===A)return d("Loaded edge reference, unchanged",s.edge);let T=i(S);return a(T)?l(T.message):d("Loaded edge reference",T.value.at(-1)?.id?.[0]??null)}function h(S,A,T){if(!s||s.root!==S)return;let P=ad(S,s.signature,A);s=P===null?null:{root:S,signature:P,edge:T}}function x(){s=null,wS()}let b=S=>qf(S,e.genesis);function R(S){let A=i(S);if(a(A))return l(A.message);let T=pd(A.value);return d("Loaded effective event times",new Map(A.value.map((P,M)=>[P.id[0],T[M]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:c,loadEventActors:u,loadActorNames:p,loadMergedEvents:m,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:h,clearEdgeCache:x,getSortedEvents:b,loadEffectiveEventTimes:R}};var ba=(e,t)=>l(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),j=(e,t)=>({...ba(e,t),convergence:!0}),wo=e=>a(e)&&e.convergence===!0,En=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!wo(n)),skipped:t.filter(wo)}},Sn=e=>{e.length!==0&&ee.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},LS=e=>e.userId?.length?null:ba("Invalid user ID format",e),eg=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return l(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return j(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return j("the state is already initialized",o);t.genesisApplied=!0}let c;try{c=i(o)}catch(m){return j(`threw while materializing (${m instanceof Error?m.message:String(m)})`,o)}if(a(c))return c;let u=LS(o);if(u)return u;let p=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return p||c}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let c=!1;try{let u=o.map(p=>n(p));if(i){c=!0;let p=e.replay.flush();if(p)return o.map(()=>p)}return u}finally{i&&(t=null,c||e.replay.flush())}});return a(s)?o.map(()=>l(s.message)):s.value}}};import ng from"node:fs";import fd from"node:path";import{decodeTime as kS,monotonicFactory as DS}from"ulid";var tg=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";var BS=0xffffffffffff,OS=Vi,FS=e=>{let t=Date.now(),n;try{n=kS(e)}catch{return t}return n>=BS?t:n>t+OS?(ee.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},ar=({userId:e})=>`${tg(e)}.jsonl`,rg=(e,t)=>{let n;try{if(!ng.existsSync(e))return[t];n=ng.readdirSync(e)}catch{return[t]}let r=Ds(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||_r(s)?!1:Ds(s)===r).sort(),t]},og=(e,{userId:t})=>{let n=ar({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return l(`Invalid event log file name: ${n}`);let o=fd.join(St(e),n);return d("Successfully resolved event log path",o)},sg=e=>{let t=DS();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let u=e.getEdgeRef(o);if(a(u))return l(u.message);i=u.value}let c=i?t(FS(i)):t();return d("Minted event id",[c,i])}function r({event:o,rootDir:s,edge:i,id:c}){try{let u=np(s);if(a(u))return u;let p=og(s,{userId:o.userId});if(a(p))return p;let m=Wf(s,fd.basename(p.value)),f=c?d("Minted event id",c):n(s,i);if(a(f))return l(f.message);let[g,h]=f.value,x=rd(Lf(o),[g,h]);if(a(x))return l(x.message);Vf(m,`${JSON.stringify(x.value)}
|
|
33
|
+
`),i&&(i.current=g);let b=fd.basename(m);return e.advanceEdgeRef(s,b,g),_f(s,b),d("Event persisted",{path:m,entry:x.value})}catch(u){let p=u instanceof Error?u.message:"Unknown persist error";return l(`Failed to persist event: ${p}`)}}return{mintEventId:n,persist:r}};var ig=(e,t,n)=>{function r(s,i,c){let u=n.mintEventId(i,c);if(a(u))return l(u.message);let p={...s,id:u.value[0]},m=t.materialize(p);if(m.status!==Zn.Success)return m;let f=n.persist({event:p,rootDir:i,edge:c,id:u.value});return a(f)?f:m}function o(s,i){if(s.length===0||!s[0])return l("No events provided");let c=e.write.readOnlyReason();if(c)return l(c);let u=e.replay.batch(()=>{let p={},m=e.write.beforeWrite(s[0],h=>r(h,i,p));if(a(m))return l(m.message);let f=s.map(h=>r(h,i,p)),g=f.filter(a);return g.length>0?l("Materialize and persist failed: "+g.map(h=>h.message).join(", ")):d("Materialization succeeded",f.map(h=>h.value))});return a(u)?l(u.message):u.value??l("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var ag=e=>{let t=eg(e),n=Zf(e),r=sg(n),o=ig(e,t,r);return{...t,...n,...r,...o}};import{z as Q}from"zod";var K=Q.string().min(1),en=Q.string(),lr=Q.string(),xa=Q.looseObject({id:K}),gd=Q.looseObject({id:K,name:en,parent:K,rank:lr}),_S={"init.workspace":Q.looseObject({id:K,name:en,rank:lr}),"add.workspace":Q.looseObject({id:K,name:en,rank:lr}),"add.board":gd,"add.swimlane":gd,"add.issue":gd,"add.field":Q.looseObject({id:K,name:en,parent:K,rank:lr}),"edit.title":Q.looseObject({id:K,name:en}),"delete.node":xa,"lock.node":xa,"move.node":Q.looseObject({id:K,parent:K,rank:lr}),"edit.description":Q.looseObject({id:K,md:Q.string()}),"close.issue":Q.looseObject({id:K,parent:K,rank:lr}),"reopen.issue":Q.looseObject({id:K,parent:K,rank:lr}),"create.tag":Q.looseObject({id:K,name:en}),"tombstone.tag":xa,"restore.tag":Q.looseObject({id:K,name:en}),"create.contributor":Q.looseObject({id:K,name:en}),"rename.contributor":Q.looseObject({id:K,name:en}),"tombstone.contributor":xa,"restore.contributor":Q.looseObject({id:K,name:en}),"link.contributor.user":Q.looseObject({contributor:K}),"link.contributor.email":Q.looseObject({contributor:K,email:K}),"unlink.contributor.email":Q.looseObject({contributor:K,email:K}),"add.issue.assignee":Q.looseObject({id:K,assignee:K}),"remove.issue.assignee":Q.looseObject({id:K,assignee:K}),"add.issue.tag":Q.looseObject({id:K,tag:K}),"remove.issue.tag":Q.looseObject({id:K,tag:K}),"add.issue.comment":Q.looseObject({id:K,issue:K,md:Q.string()}),"edit.issue.comment":Q.looseObject({id:K,issue:K,md:Q.string()}),"delete.issue.comment":Q.looseObject({id:K,issue:K}),"add.issue.attachment":Q.looseObject({id:K,issue:K,hash:Q.string().min(1),ext:Q.string().min(1),name:en,bytes:Q.number()}),"delete.issue.attachment":Q.looseObject({id:K,issue:K}),"rebalance.children":Q.looseObject({parent:K,ranks:Q.record(Q.string(),lr)})},lg=(e,t)=>{let r=_S[e].safeParse(t);return r.success?d("Payload is readable",void 0):l(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as jS}from"ulid";var cg=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return d("Contributor write already in flight",void 0);let{userId:n,userName:r}=V();if(!r||n!==e.userId)return d("Not this actor own write",void 0);let o=N.getContributor(e.userId),s={id:jS(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return d("Contributor name is current",void 0);let i=t(s);return a(i)?l(i.message):d("Contributor name recorded",void 0)};var Ne={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var H=e=>e.slice(-7).toUpperCase(),Ia=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?H(e).includes(n):!0};var Re={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:oe.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:H(e)},context:oe.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:oe.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:oe.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:oe.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:H(e)},context:oe.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:oe.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:oe.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Fs=(e,t,n)=>N.getNode(e)?j(`a node with id ${e} already exists`,n):t===e?j("a node cannot be its own parent",n):null,dg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Re.workspace(t,n,r),s=_s(o);if(a(s))return ba(s.message,e);let i=N.createNode(o);return a(i)?j(i.message??"Failed to initialize workspace",e):Fc(i.value)?d("Workspace initialized",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Fs(t,void 0,e);if(o)return o;let s=N.createNode(Re.workspace(t,n,r));return a(s)?j(s.message??"Failed to add workspace",e):Fc(s.value)?d("Added workspace",{action:e.action,result:s.value}):l("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Fs(t,r,e);if(s)return s;let i=N.createNode(Re.board(t,n,r,o));return a(i)?j(i.message??"Unable to create board",e):or(i.value)?d("Added board",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Fs(t,r,e);if(s)return s;let i=N.createNode(Re.swimlane(t,n,r,o));return a(i)?j(i.message??"Unable to create swimlane",e):yn(i.value)?d("Added swimlane",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Fs(t,r,e);if(s)return s;let i=N.createNode(Re.ticket(t,n,r,o));return a(i)?j(i.message??"Unable to create issue",e):_(i.value)?d("Added issue",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Fs(t,r,e);if(i)return i;let c=N.createNode(Re.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Ne.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?j(c.message??`Unable to create field: ${n}`,e):at(c.value)?d("Added field",{action:e.action,result:c.value}):l("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return j(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?j(o.message??"Unable to edit title",e):d("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?j(n.message??"Unable to delete node",e):d("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return a(r)?j(r.message??"Unable to create tag",e):d("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=N.tombstoneTag(t);return a(n)?j(n.message??"Unable to delete tag",e):d("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=N.restoreTag(t,n);return a(r)?j(r.message??"Unable to restore tag",e):d("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return a(r)?j(r.message??"Unable to create contributor",e):d("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=N.renameContributor(t,n);return a(r)?j(r.message??"Unable to rename contributor",e):d("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=N.tombstoneContributor(t);return a(n)?j(n.message??"Unable to remove contributor",e):d("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=N.restoreContributor(t,n);return a(r)?j(r.message??"Unable to restore contributor",e):d("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.tag(t,n);return a(r)?j(r.message??"Unable to tag issue",e):d("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.untag(t,n);return a(r)?j(r.message??"Unable to untag issue",e):d("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.assign(t,n);return a(r)?j(r.message??"Unable to assign issue",e):d("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.unassign(t,n);return a(r)?j(r.message??"Unable to unassign issue",e):d("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?j(o.message??"Failed to move node",e):d("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return a(r)?j(r.message??"Unable to edit description",e):d("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return j("Unable to locate issue",e);if(!_(o))return j("Can only close issues",e);let s=N.getNode(he);if(!s)return j("Unable to locate target swimlane",e);if(n!==s.id)return j("Close target must be closed swimlane",e);let i=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?j(i.message??"Unable to close issue",e):d("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return j("Unable to locate issue",e);if(!_(o))return j("Can only reopen issues",e);let s=N.getNode(he);if(!s)return j("Unable to locate closed swimlane",e);if(n===s.id)return j("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return j("Reopen parent no longer exists",e);let c=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(c)?j(c.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?j(n.message??"Unable to lock node",e):d("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=N.getNode(r);if(!s)return j(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return j(`Node ${r} is not child of ${t}`,e);let i=N.updateNode({...s,rank:o});if(a(i))return j(i.message??"Unable to rebalance child",e)}return d("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=N.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return a(s)?j(s.message??"Unable to add comment",e):d("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=N.getComment(t);if(!o)return j("Unable to locate comment",e);if(o.issue!==n)return j("Comment does not belong to issue",e);let s=N.editComment(t,r);return a(s)?j(s.message??"Unable to edit comment",e):d("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=N.getComment(t);if(!r)return j("Unable to locate comment",e);if(r.issue!==n)return j("Comment does not belong to issue",e);let o=N.deleteComment(t);return a(o)?j(o.message??"Unable to delete comment",e):d("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=N.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(c)?j(c.message??"Unable to add attachment",e):d("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=N.getAttachment(t);if(!r)return j("Unable to locate attachment",e);if(r.issue!==n)return j("Attachment does not belong to issue",e);let o=N.deleteAttachment(t);return a(o)?j(o.message??"Unable to delete attachment",e):d("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!nr(n))return j(`not an email address: ${n}`,e);let r=N.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?j(r.message??"Unable to link email",e):d("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=N.unlinkContributorEmail(n,t,e.userId);return a(r)?j(r.message??"Unable to unlink email",e):d("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=N.linkUserId({contributorId:t,userId:e.userId});return a(n)?j(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};var ug=e=>{let t=N.getNode(e);if(!t||!_(t)||t.isDeleted)return null;let n=fg(t);return a(n)?n:null},mg=e=>{if(!yd())return null;for(let t of e){let n=ug(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=ug(r);if(o)return o}return null},$S=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},US=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},hd=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return US(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},HS=e=>{Oe(t=>({...t,eventLog:[...t.eventLog,e]}))},Hn=null,WS=e=>{for(let[t,n]of e.nodeLog){let r=N.getNode(t);r&&N.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Oe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),mg([...e.virtualNodeIds])},pg={isInitialized:()=>Rt(),batch:e=>Ea(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(hd(e))];if(t){Hn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=Hn.nodeLog.get(o);s?s.push(e):Hn.nodeLog.set(o,[e])}if(yd()){Hn.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&Hn.virtualNodeIds.add(s)}}return n||Hn.appLog.push(e),null}return n||(r.forEach(o=>$S(o,e)),HS(e)),mg(r)},flush(){if(!Hn)return null;let e=Hn;return Hn=null,WS(e)}};var pe=()=>{let{userName:e,userId:t}=V();return e?t?ic(t)?Fi(e)?d("Successfully resolved actor ID",{userId:t,userName:e}):l("Invalid user name in config"):l("Invalid user ID in config"):l("User ID not configured"):l("User name not configured")};var GS={genesis:"init.workspace",actions:ed,readPayload:lg,apply:dg,replay:pg,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:cg}},VS=ag(GS),{materialize:js,materializeAll:tn,fromPersistedEvent:dF,decodeReconstructedEvents:uF,loadMergedEventsWithUnreadable:nn,loadEventActors:gg,loadActorNames:cr,loadMergedEvents:dr,loadMergedEventsBefore:Sa,getEdgeRef:mF,advanceEdgeRef:pF,clearEdgeCache:fF,getSortedEvents:gF,loadEffectiveEventTimes:Ra,mintEventId:hF,persist:hg,materializeAndPersist:yF,materializeAndPersistAll:B}=VS;var jr=e=>e.trim().toLocaleLowerCase(),vd=(e,t)=>jr(e).includes(jr(t));var zS=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},KS=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},yg=null,vg=new Map,qS=()=>{let e=v().eventLog??[];if(e===yg)return vg;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return yg=e,vg=t,t},YS=e=>{let{contributors:t}=v(),n=qS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},bg=(e,t)=>{let n=jr(t.value);if(!n)return!0;switch(t.target){case"title":return vd(e.title??"",n);case"description":return vd(e.props.description??"",n);case"tag":return zS(e).map(jr).some(o=>o.includes(n));case"assignee":return KS(e).map(jr).some(o=>o.includes(n));case"actor":return YS(e).map(jr).some(o=>o.includes(n));case"ref":return Ia(e.id,t.value);default:return!0}};var bd=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,XS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,xg=(e,t)=>Object.values(e).filter(n=>XS(n,t)).sort(bd),Ig=(e,t)=>{let n={};for(let r of Object.values(e)){if(_(r)&&t.length>0&&!t.every(s=>bg(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(bd);return n},Eg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(bd);return n};var Sg=e=>Ca(be(e),{at:"end"}),Ca=(e,t={at:"end"})=>{let n=o=>a(o)?d("Rank space exhausted",{rank:"",needsRebalance:!0}):d("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(vt(void 0,void 0));let r=()=>n(vt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(vt(void 0,o.rank)):l("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(vt(o.rank,void 0)):l("Unable to resolve last sibling")}case"before":{let o=Rg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(vt(i?.rank,s.rank))}case"after":{let o=Rg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(vt(s.rank,i?.rank))}}},be=e=>{let t=v();if(!Ng()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return xg(t.nodes,e)},Rg=(e,t)=>e.findIndex(n=>n.id===t),Cg=(e,t,n={at:"end"})=>Ca(be(t).filter(r=>r.id!==e),n),Rn=(e,t,n,r,o)=>{let s=Cg(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=td(e,r);if(a(i))return i;let c=B([i.value],o);if(a(c))return c;let u=Cg(t,e,n);return a(u)?u:u.value.needsRebalance?l("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},Wn=(e,t,n)=>{let r=Sg(e);if(a(r))return r;if(!r.value.needsRebalance)return d("Resolved rank",r.value.rank);let o=td(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let i=Sg(e);return a(i)?i:i.value.needsRebalance?l("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)};var $s=5,$={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=le(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||$.navigate({contextNode:o,selectedIndex:le(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=le(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;$.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ag(1),navigateToPreviousItem:()=>Ag(-1),jumpToNextItem:()=>Tg($s),jumpToPreviousItem:()=>Tg(-$s),navigateToNextContainer:()=>wg(1),navigateToPreviousContainer:()=>wg(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},Ag=e=>{let{selectedIndex:t,contextNode:n}=v(),r=le(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;$.navigate({selectedIndex:s,contextNode:n})},Tg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=le(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);$.navigate({selectedIndex:s,contextNode:n})},wg=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=le(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=le(c.id),p=Math.max(0,u.length-1),m=Math.min(Math.max(0,r),p),f=u.length?m:-1;$.navigate({contextNode:c,selectedIndex:f})};var Pg=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Lg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},JS=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&at(t)&&t.childRenderAxis==="vertical"},Na=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=be(r.id);return $.navigate({contextNode:r,selectedIndex:Pg(t,o.length)}),!0},kg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Na(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=be(o.id).findIndex(c=>c.id===n.id);return i>=0?($.navigate({contextNode:o,selectedIndex:i}),!0):kg(o.id)},Mg=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),kg(n))return!0;n=t[n]?.parentNodeId}return!1},QS=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Dg=e=>{let{nodes:t,rootNodeId:n}=v();if(JS(e.contextNodeId)&&Na(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(QS(e.selectedNodeId)&&e.selectedNodeId&&Mg(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(Na(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&Na(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(Mg(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return l("Unable to restore navigation");let o=be(r.id);return $.navigate({contextNode:r,selectedIndex:Pg(e.selectedIndex,o.length)}),d("Restored navigation to root",null)};import{monotonicFactory as ZS,ulid as Cn}from"ulid";var Us=ZS();function eR(){let e=de();if(a(e))return l("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return l("No workspace found in event log");let[r]=le(n.id),[o]=r?le(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return d("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?d("Resolved boot nav target",{contextNode:r,selectedIndex:0}):d("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function tR(){let e=eR();return a(e)?e:$.navigate(e.value)}function Bg({userId:e,userName:t}){let n=Us(),r=Us(),o=Us(),s=Us(),i=Us(),c=vt(void 0,void 0);if(a(c))return c;let u=vt(void 0,void 0);if(a(u))return u;let p=vt(u.value,void 0);if(a(p))return p;let m=vt(void 0,void 0);if(a(m))return m;let f=vt(m.value,void 0);if(a(f))return f;let g=vt(f.value,void 0);if(a(g))return g;let h=vt(void 0,void 0);return a(h)?h:d("Created default events",[{id:Cn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Cn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Cn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:m.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Cn(),userId:e,action:"add.board",payload:{id:ta,name:"Closed",parent:n,rank:p.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:he,name:"Closed",parent:ta,rank:h.value}},{id:Cn(),userId:e,action:"lock.node",payload:{id:ta}},{id:Cn(),userId:e,action:"lock.node",payload:{id:he}}])}var nR=()=>{let e=de();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},rR=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");ee.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");ee.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function rn(e,t=[]){if(nR())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Re.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=_s(s);return a(i)?i:(w({hasProjectDefinition:!1,mode:I.DEFAULT}),d("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return l("Initialized Epiq project has no workspace init event");let n=tn(e),{fatal:r,skipped:o}=En(n);return r.length>0?l(`Materializing failed:
|
|
34
34
|
${r.map(s=>s.message).join(`
|
|
35
|
-
`)}`):(
|
|
36
|
-
`,"utf8"),
|
|
37
|
-
`);var
|
|
38
|
-
`).filter(t=>t.trim().length>0)
|
|
39
|
-
`);
|
|
40
|
-
`:""}${
|
|
35
|
+
`)}`):(Sn(o),tR(),w({hasProjectDefinition:!0}),rR(t),d("State booted successfully",null))}import{WebSocket as oR}from"ws";var Aa=new Set,Og=e=>{Aa.add(e),e.on("close",()=>{Aa.delete(e)}),e.on("error",()=>{Aa.delete(e)})},$r=e=>{let t=JSON.stringify(e);for(let n of Aa)n.readyState===oR.OPEN&&n.send(t)};var Ta=e=>{Rt()&&(w({syncStatus:e}),$r({type:"sync-status",payload:e}))},Mo=(e="Syncing...")=>{Ta({status:"syncing",msg:e})},Ur=(e="Synced")=>{Ta({status:"synced",msg:e})},xd=e=>{Ta({status:"failed",msg:e})},wa=e=>{Ta({status:"offline",msg:e})},We=e=>(xd(e),l(e));var on=(e,t)=>(logger.error(`[boot:${e}] ${t}`),l(`[boot:${e}] ${t}`)),Po=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},ge=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t);import rh from"node:fs";import Gn from"node:fs";import Vn from"node:path";import Ma from"node:fs";import Fg from"node:path";var dt=".epiq/project.json",_g=e=>Fg.join(e,dt),sR=e=>{if(!Ma.existsSync(_g(e)))return d("State branch carries no identity yet",null);let t=Mt(e);return a(t)?l(`On the state branch: ${t.message}`):d("Read the state branch identity",t.value)},Id=(e,t)=>{try{let n=_g(e);return Ma.mkdirSync(Fg.dirname(n),{recursive:!0}),Ma.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
36
|
+
`,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return l(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},iR=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${dt} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${dt} > ${dt}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
37
|
+
`);var jg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Ma.existsSync(po(e)))return d("No project file to compare","no-checkout-file");let r=Mt(e);if(a(r))return l(r.message);let o=sR(t);if(a(o))return l(o.message);if(o.value===null){let s=Id(t,r.value);return a(s)?l(s.message):d("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?l(iR({checkout:r.value,branch:o.value,stateBranch:n})):d("The checkout and the state branch agree","matched")};import Nn from"node:fs";import Hs from"node:path";var Lo=e=>e.split(`
|
|
38
|
+
`).filter(t=>t.trim().length>0),$g=e=>{let t=Hs.join(e,gt,Fn);try{if(!Nn.existsSync(t))return d("No events directory",[]);let n=Nn.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>Lo(Nn.readFileSync(Hs.join(t,r),"utf8")).length>0);return d("Looked for stranded event logs",n)}catch(n){return l(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Ug=e=>Hs.join(e,gt,Fn),Hg=e=>{let t=Ug(e),n=new Map;try{if(!Nn.existsSync(t))return n;for(let r of Nn.readdirSync(t))if(r.endsWith(".jsonl")&&!_r(r))try{n.set(r,Lo(Nn.readFileSync(Hs.join(t,r),"utf8")))}catch(o){if(!ks(o))throw o}}catch{return n}return n},aR=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Wg=(e,t)=>{if(t.size===0)return[];let n=Ug(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Hs.join(n,o);try{let c=Nn.existsSync(i)?Nn.readFileSync(i,"utf8"):null,u=new Set(c===null?[]:Lo(c)),p=s.filter(f=>!u.has(f)).filter(aR);if(p.length===0)continue;Nn.mkdirSync(n,{recursive:!0});let m=c!==null&&c.length>0&&!c.endsWith(`
|
|
39
|
+
`);Nn.appendFileSync(i,`${m?`
|
|
40
|
+
`:""}${p.join(`
|
|
41
41
|
`)}
|
|
42
|
-
`,"utf8"),r.push(`${o} (${
|
|
43
|
-
`),
|
|
44
|
-
`));
|
|
45
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
46
|
-
${o.message}`):
|
|
47
|
-
`+n.message);if(n.value)return
|
|
48
|
-
`+r.message);let o=r.value,s=o?await
|
|
49
|
-
`+s.message);let i=s.value;if(o&&i){let
|
|
50
|
-
${
|
|
51
|
-
${
|
|
52
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return
|
|
53
|
-
`+r.message);if(
|
|
54
|
-
`));
|
|
55
|
-
${o.message}`):
|
|
56
|
-
`));if(s&&s!==o){let
|
|
57
|
-
`));
|
|
58
|
-
${
|
|
59
|
-
${
|
|
60
|
-
${
|
|
61
|
-
${o.message}`):
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
${s.message}`):
|
|
65
|
-
${r.message}`):
|
|
66
|
-
${n.message}`):
|
|
67
|
-
`+r.message):
|
|
68
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},Ug=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ue(e);if(a(o))return o;let s=o.value,i=[ds(),await Us({repoRoot:e,stateBranchName:s}),await dr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await ZS({stateBranchRoot:t,stateBranchName:s}),await Wm(t),n?await eR({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(a(l))return c(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import Po from"node:fs";import md from"node:os";import tR from"node:path";var pd="epiq-sync.lock",jg=600*1e3,nR=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},rR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},oR=e=>e?e.hostname!==md.hostname()||rR(e.pid)?Date.now()-e.startedAt>jg?"stale":null:"dead":"stale",Wg=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ud=e=>{try{return nR(Po.readFileSync(e,"utf8"))}catch{return null}},Hg=(e,t)=>{let n={pid:process.pid,hostname:md.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Po.writeFileSync(r,JSON.stringify(n)),Po.linkSync(r,e),!0}catch{return!1}finally{try{Po.rmSync(r,{force:!0})}catch{}}},sR=async({worktreeRoot:e,operation:t})=>{let n=await _i(e);if(a(n))return c(n.message);let r=tR.join(n.value,pd),o=()=>{try{let d=ud(r);d&&d.pid===process.pid&&Po.rmSync(r)}catch{}};if(Hg(r,t))return u("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=ud(r),i=oR(s);if(i===null)return u("Sync lock is held",{acquired:!1,heldBy:s});se.info(`Breaking an abandoned sync lock: ${s?Wg(s):"unreadable lock file"}`);try{Po.rmSync(r,{force:!0})}catch{}if(Hg(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let l=ud(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:l??{pid:-1,hostname:md.hostname(),startedAt:Date.now(),operation:"unknown"}})},Hs=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await sR({worktreeRoot:e,operation:t});if(a(r))return c(r.message);if(!r.value.acquired)return se.info(`Skipping ${t}: the state worktree is held by ${Wg(r.value.heldBy)}`),u("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return u("Ran under the sync lock",await n(o))}finally{s()}};var iR=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ge("getRepoRootDir",await qt(t));if(a(r))return c(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ge("getStateBranchRoot",he({repoRoot:o}));if(a(s))return c(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&Vg.existsSync(i)){let p=await Mm(i,{preserve:[pd]});if(a(p))return c(p.message);p.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:p.value,stateBranchRoot:i});let f=ge("abortRebaseIfPresent(stateBranchRoot)",await cc(i));if(a(f))return c(f.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=ge("bootstrapStateBranchStorage",await Ug({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(l))return c(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let d=ge("getInProgressGitOperation(stateBranchRoot)",await ac(i));if(a(d))return c(d.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:d.value}),d.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),c(`Cannot sync while there is a ${d.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let m=ge("ensureStateBranchLayout",Hm(o,i));return a(m)?c(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),u("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},aR=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=[];for(let m of Kf(Et(t),n)){let p=ge("stageStateBranchOwnEventFile",await Aa({stateBranchRoot:t,eventFileName:m}));if(a(p))return c(p.message);r.push(p.value)}let o=ge("stageStateBranchMediaFiles",await Fg({stateBranchRoot:t}));if(a(o))return c(o.message);let s=ge("stageStateBranchEventConfig",await _g({stateBranchRoot:t}));if(a(s))return c(s.message);let i=[...r,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=ge("hasStagedChanges(after stage)",await km(t,i));if(a(l))return c(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let d=ge("createStateBranchSyncCommit",await $g({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(d)?c(d.message):(logger.debug("[sync] created sync commit",d.value),u("Committed own event file",{createdCommit:!0,commitSha:d.value}))},fd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ca(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Gg=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),c("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),c("Own event file must end with .jsonl");To();let r=ge("ensureSyncReady",await iR({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return Ve(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=ge("isDetachedHead(stateBranchRoot)",await Dm(s));if(a(l))return Ve(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return Ve("Cannot run :sync while the state branch is in detached HEAD state");let d=!1,m,p=!1,f=!1,g=ge("getStateBranch",Ue(o));if(a(g))return Ve(g.message);let y=g.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:s});let x=ge("flushPendingLogs",ua(s,t));a(x)&&logger.error(`[sync] ${x.message}`);let b=ge("commitOwnEventFileToStateBranch",await aR({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(b))return Ve(b.message);d=b.value.createdCommit,m=b.value.commitSha;let R=ge("hasRemote",await Bn({repoRoot:s}));if(a(R))return Ve(R.message);if(!R.value)return fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i},"no remote");let S=ge("pullBranchRebaseIfPresent",await ls({cwd:s,branch:y}));if(a(S))return as(S.message)?fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):Ve(S.message);p=S.value;let T=ge("isAheadOfUpstream",await Pm(s));if(a(T))return Ve(T.message);if(d||i||T.value){logger.info("[sync] pushing state branch",{createdCommit:d,bootstrapped:i,stateBranchRoot:s});let A=ge("pushStateBranch",await js({stateBranchRoot:s,repoRoot:o}));if(a(A)&&Tm(A.message)){let P=ge("pullBranchRebaseIfPresent(retry)",await ls({cwd:s,branch:y}));if(a(P))return Ve(P.message);p=p||P.value,A=ge("pushStateBranch(retry)",await js({stateBranchRoot:s,repoRoot:o}))}if(a(A))return as(A.message)?fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):Ve(A.message);f=A.value}if(d){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let A=ge("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:s}));if(a(A))return Ve(A.message);m=A.value.stdout.trim(),logger.debug("[sync] final sync commit sha",m)}return jr(f?"Synced and pushed":p||d?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,pulled:p,pushed:f,bootstrapped:i,offline:!1})},Ta=async(e,t)=>{let n=Lg(e);try{return await t()}finally{let r=kg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},wa=async e=>{let t=e.cwd??process.cwd(),n=await qt(t);if(a(n))return Ve(n.message);let r=he({repoRoot:n.value});if(a(r))return Ve(r.message);let o=r.value;if(!Vg.existsSync(o))return Gg(e,"clean");let s=await Hs({worktreeRoot:o,operation:"sync",fn:i=>Ta(o,()=>Gg(e,i))});return a(s)?Ve(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Nn=null,Ma=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Nn,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),Nn)return logger.debug("[sync] syncAndReloadState joining existing promise"),Nn;logger.debug("[sync] syncAndReloadState creating promise"),Nn=lR();try{let e=await Nn;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),a(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Nn||c(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),Nn=null}},lR=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=zg();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(Nn)return Nn;logger.debug("[sync] syncAndReloadState:start");let t=ge("resolveActorId",pe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),c("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=ir(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ge("syncEpiqWithRemote",await wa({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),Ve(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=gd(o);return a(i)?i:(w({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},gd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ge("loadMergedEvents",Zt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),c(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=zg();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:n.message,syncStatus:v().syncStatus}),n;let r=Eg(),o=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ge("bootStateFromEventLog",en(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),c(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ge("restoreNavigationAnchor",Rg(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(s)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),s):u("Reloaded state from event log",null)},zg=()=>v().mode===I.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),c("Will not re-materialize if not in default mode, to not lose edit data"));var Kg=0,hd,yd=!1,Ws=!1,vd=()=>{if(yd)return!0;let e=xe();return a(e)?!1:e.value.syncStatus.status==="syncing"},cR=()=>{let e=uo(V().autoSyncIntervalMs),t=Date.now()-Kg;return Math.max(0,e-t)},qg=()=>{hd||(hd=setTimeout(async()=>{if(hd=void 0,!!_t()){if(vd()){Ws=!0;return}Ws=!1,await dR()}},cR()))},dR=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return c("Cannot auto-sync while peeking");if(!_t())return c("Cannot auto-sync before state is initialized");if(vd())return Ws=!0,c("Sync already in progress");yd=!0,Kg=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ma()}finally{yd=!1,Ws&&qg()}},Pa=()=>{_t()&&(Ws=!0,!vd()&&qg())};var La=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case C.EXIT:return G.Exit;case C.EXPORT:return G.Export;case C.INIT:return G.Init;case C.OPEN:return G.OpenProject;case C.DELETE:return G.Delete;case C.EDIT:return G.Edit;case C.COMMENT:return G.Comment;case C.HELP:return G.ViewHelp;case C.RE_OPEN_ISSUE:return G.ReopenIssue;case C.CLOSE_ISSUE:return G.CloseIssue;case C.TAG:return G.TagTicket;case C.UNTAG:return G.UntagTicket;case C.ASSIGN:return G.AssignUserToTicket;case C.UNASSIGN:return G.UnassignUserFromTicket;case C.NEW:return G.NewItem;case C.FILTER:return G.Filter;case C.MOVE:return G.Move;case C.PEEK:return G.Peek;case C.REPLAY:return G.Replay;case C.CONFIG:return G.Config;case C.YANK:return G.Yank;case C.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import ay from"node:fs";import tN from"node:path";import nN from"react";import{Box as ZC}from"ink";import Ya from"react";import TR from"chalk";import{Box as Id,Text as wR}from"ink";import An from"react";import{Text as Yg}from"ink";import Xg,{useEffect as Jg,useState as uR}from"react";var Qg={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},St=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=oe(),r=Qg[n]??Qg.default,[o,s]=uR(0);if(Jg(()=>{s(0)},[r]),Jg(()=>{if(!e)return;let l=setInterval(()=>{s(d=>(d+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Xg.createElement(Yg,null,t);let i=r[o]??r[0]??t;return Xg.createElement(Yg,{color:h.accent,dimColor:o===1},i)};import{Box as bd,Text as mR}from"ink";import ka from"react";var pR=(e,t,n,r)=>{let o=d=>Math.max(1,e[d]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},mt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),d=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/l)),p=Math.max(0,e.length-m),{start:f,end:g}=o?pR(o,e.length,d,i):s?{start:Math.min(p,Math.max(0,d-m+1)),end:Math.min(p,Math.max(0,d-m+1))+m}:{start:Math.min(p,Math.floor(d/m)*m),end:Math.min(p,Math.floor(d/m)*m)+m},y=Math.max(1,g-f),x=e.slice(f,g),b=e.length>y,R=i,S=b?Math.max(1,Math.floor(y/e.length*R)):R,T=Math.max(0,R-S),A=Math.max(1,e.length-y),P=b?Math.floor(f/A*T):0;return ka.createElement(bd,{flexDirection:"row",height:i,width:"100%"},ka.createElement(bd,{flexDirection:"column",flexGrow:1,height:i},x),ka.createElement(bd,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((M,O)=>ka.createElement(mR,{key:O,color:b&&O>=P&&O<P+S?h.accent:h.secondary},b?"\u2502":" "))))};import{Box as Do,Text as Bo}from"ink";import Rt from"react";var Zg,xd,fR=()=>{let{eventLog:e=[]}=v();if(xd&&Zg===e)return xd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Zg=e,xd=t,t},Da=e=>fR().has(e);import{Text as gR}from"ink";import hR from"react";var ur=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Fn(o,n);return hR.createElement(gR,{underline:t,color:qe(o)},"@"+s,Da(e)?"":"\u2197")};import{Text as yR}from"ink";import vR from"react";var Lo=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getTag(e);if(!r)return;let o=n===void 0?r.name:Fn(r.name,n);return vR.createElement(yR,{underline:t,backgroundColor:qe(r.name),color:h.secondary}," "+o+" ")};import{useEffect as bR,useState as xR}from"react";var IR=80,eh=1400,Ba=new Set,Gs=null,ER=e=>(Ba.add(e),Gs||(Gs=setInterval(()=>{for(let t of Ba)t()},IR)),()=>{Ba.delete(e),Ba.size===0&&Gs&&(clearInterval(Gs),Gs=null)}),SR=()=>{let e=Date.now()%eh/eh;return e<.5?e*2:(1-e)*2},ko=e=>{let[,t]=xR(0);return bR(()=>{if(e)return ER(()=>t(n=>n+1))},[e]),Gi(SR())};var RR=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),Fn(e.slice(o).trim(),n)]},th=3,CR=2,NR=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},nh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=ko(r),s=e-4,i=s-7-1,[l,d]=RR(Re(t.title),i,s),m=d?null:Fn(Re(t.props.description),s)||null,p=hn(t),f=yn(t).map(S=>({...S,name:S.name})),g=Math.max(1,s-th),y=N.getCommentsByIssue(t.id),x=y.length?String(y.length).length+2+1:0,{shown:b,hidden:R}=NR([...p.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,g)+th})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,g)+CR+(Da(S.id)?0:1)}))],s-x);return Rt.createElement(Do,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?h.accent:h.secondary,justifyContent:"space-between"},Rt.createElement(Do,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Rt.createElement(Do,{justifyContent:"space-between"},Rt.createElement(Bo,{color:h.primary},l),Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},H(t.id))),d&&Rt.createElement(Bo,{color:h.primary},d),m&&Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},m)),Rt.createElement(Do,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Rt.createElement(Do,{flexDirection:"row"},b.map(S=>Rt.createElement(Do,{paddingRight:1,key:S.id},S.isTag?Rt.createElement(Lo,{id:S.id,maxWidth:g}):Rt.createElement(ur,{id:S.id,maxWidth:g}))),R>0&&Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},"+",R)),y.length>0&&Rt.createElement(Bo,{color:h.accent},"[",y.length,"]")))};import{Box as Hr,Text as Vs}from"ink";import Lt from"react";var AR=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,rh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=ko(s),d=(r.props.tags??[]).map(M=>N.getTag(M)).filter(M=>!!M),m=(r.props.assignees??[]).map(M=>N.getContributor(M)).map(M=>M&&{...M,name:M.name}).filter(M=>!!M),p=1,f=d.length*(1+p),g=m.length*(2+p),y=d.map(M=>Lt.createElement(Hr,{key:M.id,paddingRight:p},Lt.createElement(Vs,{color:qe(M.name)},"\u25A0"))),x=m.map(M=>Lt.createElement(Hr,{key:M.id,paddingRight:p},Lt.createElement(Vs,{color:Ec(M.name)},"@"+M.name.at(0)))),b=s?l:o?h.accent:i===I.MOVE?h.secondary:h.primary,R=N.getCommentsByIssue(r.id),S=R.length?String(R.length).length+2+p:0,T=R.length?Lt.createElement(Hr,{paddingRight:p},Lt.createElement(Vs,{color:h.accent},"[",R.length,"]")):null,A=f+g+S,P=Math.max(1,n-t-A-(A>0?1:0));return Lt.createElement(Hr,{justifyContent:"space-between"},Lt.createElement(Hr,null,Lt.createElement(Hr,{width:t},o?Lt.createElement(St,{isSelected:!0}):Lt.createElement(Vs,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Lt.createElement(Vs,{wrap:"truncate",color:b},AR(r.title,P))),Lt.createElement(Hr,null,y,x,T))};var MR=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:d,replay:m}=oe(),p=d[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,y=ko(g),x=`${e.title} ${TR.hex(h.secondary2).dim("("+p.length+")")}`,b=3,R=o?1:5,S=s&&i===-1,T=n-3-(o?1:0)-(S?2:0),A=Math.max(2,String(p.length).length+1),P=r-b-1,M=An.createElement(Id,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},An.createElement(St,{isSelected:t}),An.createElement(wR,{bold:!0,color:g?y:t?h.accent:h.primary},x," ",e.readonly?"\u{1F512}":"")),O=(W,X)=>{let Ee=s&&i===X;if(!_(W))return null;let F=f?.has(W.id)??!1;return o?An.createElement(rh,{key:W.id,index:X,labelWidth:A,width:T,ticket:W,isSelected:Ee,isFlashing:F,mode:l}):An.createElement(nh,{key:W.id,width:T,ticket:W,isSelected:Ee,isFlashing:F})};return An.createElement(Id,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},M,An.createElement(Id,null,p.length>0&&An.createElement(mt,{selectedIndex:i,height:P,itemHeight:R},p.map(O)),S&&An.createElement(St,{isSelected:!0})))},oh=An.memo(MR);import{Box as Wo,Text as KC}from"ink";import Ct,{useMemo as Go}from"react";var sh=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},ih=(e,t,n)=>Ne.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var ah=e=>e.action==="add.issue.comment";import{Box as Oo,Text as Vn}from"ink";import pt,{useEffect as PR,useMemo as LR,useRef as kR}from"react";import{decodeTime as lh}from"ulid";var pr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Oa=e=>String(e).padStart(2,"0"),Fa=e=>`${e.getFullYear()}-${Oa(e.getMonth()+1)}-${Oa(e.getDate())} ${Oa(e.getHours())}:${Oa(e.getMinutes())}`;var DR=e=>Pe(e,"attachments"),BR=e=>N.getAttachmentsByIssue(e.id).sort((t,n)=>lh(t.id)-lh(n.id)),ch=e=>{for(let t of e)N.deleteNode(t.id)},OR=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),FR=(e,t)=>{let n=N.getNode(DR(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>OR(o,s,n.id)).map(o=>N.createNode(o)).filter(be).map(({value:o})=>o).filter(lt);return t.length>0&&v().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},_R=e=>`${Math.max(1,Math.round(e/1024))} KB`;function dh({ticket:e,width:t,height:n}){let r=LR(()=>BR(e),[e]),o=kR([]);PR(()=>(ch(o.current),o.current=FR(e,r),()=>{ch(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=oe(),l=Math.max(1,n-4),d=Math.max(12,t-32);return r.length===0?pt.createElement(Oo,{flexDirection:"column",width:t,height:n,padding:1},pt.createElement(Vn,{color:h.primary},"No attachments yet."),pt.createElement(Oo,{paddingTop:1},pt.createElement(Vn,{color:h.primary},"Attach images from the browser GUI"),pt.createElement(Vn,{color:h.accent}," epiq gui "),pt.createElement(Vn,{color:h.primary},"by dropping or pasting them."))):pt.createElement(Oo,{flexDirection:"column",width:t,height:n},pt.createElement(Oo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},pt.createElement(Vn,{color:h.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),pt.createElement(mt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>d?m.name.slice(0,d-1)+"\u2026":m.name;return pt.createElement(Oo,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},pt.createElement(Vn,{color:h.accent},f?"\u276F ":" "),pt.createElement(Oo,{paddingLeft:1},pt.createElement(Vn,{color:h.secondary2},`#${p+1} `),pt.createElement(Vn,{color:f?h.accent:h.primary},g),pt.createElement(Vn,{color:h.secondary2}," "+_R(m.bytes)+" "+pr(Be(m.id)))))})))}import{Box as fr,Text as gr}from"ink";import Je,{useEffect as KR,useMemo as Rh,useRef as qR}from"react";import{decodeTime as Ch}from"ulid";var mh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Ed=e=>e.replace(mh,""),$R=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,uh=e=>e==="additions"||e==="deletions",zs=e=>{let t=mh.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!uh(r.side)||!uh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var ph=/```\n([\s\S]*?)\n?```\s*$/,fh=e=>ph.exec(e)?.[1]??null,UR=/`[^`\n]+`[^\n]*\n?$/,gh=e=>Ed(e).replace(ph,"").replace(UR,"").trim(),hh=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Sd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${hh(e)}`;var jR=e=>{let t=e.split(`
|
|
42
|
+
`,"utf8"),r.push(`${o} (${p.length})`)}catch{continue}}return r},lR=(e,t)=>{let n=new Set(Lo(t));return Lo(e).filter(r=>!n.has(r))},cR=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
43
|
+
`),Gg=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Le({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return d("No committed log to compare against",void 0);let o=lR(r.stdout,n);return o.length>0?l(cR(t,o,Lo(r.stdout).length)):d("Event log only grew",void 0)};var dR="[epiq:init-repo]",zg=async e=>{let t=await Le({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return d("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return l(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
44
|
+
`));ee.info("Creating initial commit");let r=await U({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return l(r.message);let o=await U({args:["commit-tree",r.value.stdout.trim(),"-m",dR],cwd:e});if(a(o))return l(o.message);let s=await U({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?l(s.message):d("Created initial commit",!0)},Vg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",uR=async e=>{let t=await Wi(e);if(a(t))return l(t.message);let n=await Fm(e);return a(n)?l(n.message):d("Built sync commit message",`[sync|branch:${Vg(t.value)}:sha:${Vg(n.value)}]`)},Ed=async({repoRoot:e,stateBranchName:t})=>{ee.info(`Creating ${t}`);let n=await U({args:["commit-tree",qm,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return l(`Failed to create state branch commit
|
|
45
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await U({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?l(`Failed to create ${t}
|
|
46
|
+
${o.message}`):d("Created state branch",!0)},Ws=async({repoRoot:e,stateBranchName:t})=>{let n=await Hi({repoRoot:e,branch:t});if(a(n))return l(`Ensure local state branch failed
|
|
47
|
+
`+n.message);if(n.value)return d("Local state branch already exists",!1);let r=await On({repoRoot:e});if(a(r))return l(`Ensure local state branch failed
|
|
48
|
+
`+r.message);let o=r.value,s=o?await cs({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(a(s))return l(`Ensure local state branch failed
|
|
49
|
+
`+s.message);let i=s.value;if(o&&i){let c=await Ce.fetch({cwd:e,remote:Pt,branch:t});if(a(c))return l(`Failed to fetch ${t} from remote
|
|
50
|
+
${c.message}`)}if(i){let c=await U({args:["branch","--track",t,`${Pt}/${t}`],cwd:e});return a(c)?l(`Failed to create local ${t} from remote
|
|
51
|
+
${c.message}`):d("Created local state branch from remote",!0)}return Ed({repoRoot:e,stateBranchName:t})},mR=async({repoRoot:e,branch:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return l(n.message);let r=n.value.stdout.split(`
|
|
52
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return d("Found worktree for branch",o)}return d("No worktree found for branch",null)},pR=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=ms(Vn.dirname(t));if(a(r))return l(`Failed to create state branch worktree
|
|
53
|
+
`+r.message);if(Gn.existsSync(t)&&!Gn.existsSync(Vn.join(t,".git"))){let s=$g(t);if(a(s))return l(s.message);if(s.value.length>0)return l([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
54
|
+
`));ee.info("Removing broken state branch worktree path"),Qm(t)}ee.info("Creating state branch worktree");let o=await Ce.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?l(`Failed to create state branch worktree
|
|
55
|
+
${o.message}`):d("Created state branch worktree",!0)},ur=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await gR({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(r))return r;let o=jg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(o)?l(o.message):(o.value==="stamped"&&ee.info("Stamped the state branch with this project\u2019s identity"),r)},fR=(e,t)=>{let n=fo(Pr());return Vn.dirname(e)===n&&Vn.dirname(t)===n},gR=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await mR({repoRoot:e,branch:n});if(a(r))return l(r.message);let o=fo(t),s=r.value?fo(r.value):null;if(s&&s===o&&Gn.existsSync(s))return d("State branch already checked out in expected worktree",!1);if(s&&s!==o&&fR(s,o))return l([`The state branch ${n} is checked out under project ${Vn.basename(s)}, but this checkout names project ${Vn.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${dt} here`,`with \`git show ${n}:${dt}\`, and keep the branch's.`].join(`
|
|
56
|
+
`));if(s&&s!==o){let u=await Wm(s);if(a(u))return l(u.message);if(u.value||Gf(s))return l([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
57
|
+
`));ee.info("Moving state branch worktree to expected location");let p=await Ce.worktreeRemove({cwd:e,worktreeRoot:s});if(a(p))return l(`Failed to remove existing state branch worktree
|
|
58
|
+
${p.message}`)}if(s&&!Gn.existsSync(s)){ee.info("Pruning stale state branch worktree");let u=await Ce.worktreePrune({cwd:e});if(a(u))return l(`Failed to prune stale worktrees
|
|
59
|
+
${u.message}`)}let i=await Om({repoRoot:e,worktreeRoot:t});if(a(i))return l(i.message);let c=Gn.existsSync(t);if(i.value&&c)return d("State branch worktree already exists",!1);if(i.value&&!c){ee.info("Pruning missing registered state branch worktree");let u=await Ce.worktreePrune({cwd:e});if(a(u))return l(`Failed to prune stale worktrees
|
|
60
|
+
${u.message}`)}return pR({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},hR=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Wi(e);if(a(n))return l(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Le({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ee.info("Aborted stale state branch rebase");let o=await Ce.checkout({cwd:e,branch:t});return a(o)?l(`Failed to checkout ${t}
|
|
61
|
+
${o.message}`):d("Checked out state branch",!0)},yR=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vc(t);if(a(n))return l(n.message);if(n.value)return d("State branch upstream already configured",!1);let r=await On({repoRoot:t});if(a(r))return l(r.message);if(!r.value)return d("No remote available for state branch upstream",!1);let o=ke(e);if(a(o))return o;let s=o.value,i=await cs({repoRoot:t,branch:s});if(a(i))return l(i.message);if(!i.value)return d("Remote state branch missing; upstream will be configured on first push",!1);ee.info(`Configuring ${s} upstream`);let c=await Ce.fetch({cwd:t,remote:Pt,branch:s});if(a(c))return l(`Failed to fetch ${s}
|
|
62
|
+
${c.message}`);let u=await Ce.setUpstream({cwd:t,branch:s,upstream:`${Pt}/${s}`});return a(u)?l(`Failed to set state branch upstream
|
|
63
|
+
${u.message}`):d("Configured state branch upstream",!0)},Pa=async({stateBranchRoot:e,eventFileName:t})=>{let n=Ym(t),r=Vn.join(e,n);if(!Gn.existsSync(r))return d("No event file to stage",null);let o=await Gg({stateBranchRoot:e,relativePath:n,workingContent:Gn.readFileSync(r,"utf8")});if(a(o))return l(o.message);let s=await Ce.stage({cwd:e,pathspec:[n]});return a(s)?l(`Failed to stage state branch event file
|
|
64
|
+
${s.message}`):d("Staged state branch event file",n)},Kg=async({stateBranchRoot:e})=>{let t=Xm(),n=Vn.join(e,t);if(!Gn.existsSync(n))return d("No media directory to stage",null);let r=await Ce.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?l(`Failed to stage state branch media files
|
|
65
|
+
${r.message}`):d("Staged state branch media files",t)},qg=async({stateBranchRoot:e})=>{let t=[xc(),Ic(),dt].filter(r=>Gn.existsSync(Vn.join(e,r)));if(t.length===0)return d("No event log config to stage",[]);let n=await Ce.stage({cwd:e,pathspec:t});return a(n)?l(`Failed to stage event log config
|
|
66
|
+
${n.message}`):d("Staged event log config",t)},Yg=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await uR(e);return a(r)?l(`Create state branch sync commit failed
|
|
67
|
+
`+r.message):go({cwd:t,message:r.value,pathspec:n})},Gs=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vc(t);if(a(n))return l(n.message);let r=ke(e);if(a(r))return r;let o=r.value,s=n.value?await Ce.push({cwd:t}):await Ce.push({cwd:t,remote:Pt,branch:o,setUpstream:!0});if(a(s))return l(`Failed during state branch push
|
|
68
|
+
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return d(i?"Pushed state branch":"Remote already up to date",i)},Xg=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=ke(e);if(a(o))return o;let s=o.value,i=[ps(),await Ws({repoRoot:e,stateBranchName:s}),await ur({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await hR({stateBranchRoot:t,stateBranchName:s}),await ep(t),n?await yR({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(a(c))return l(c.message);r=r||!!c.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import Hr from"node:fs";import Sd from"node:os";import Zg from"node:path";var Da="epiq-sync.lock",Jg=600*1e3,vR=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},bR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},eh=e=>e?e.hostname!==Sd.hostname()||bR(e.pid)?Date.now()-e.startedAt>Jg?"stale":null:"dead":"stale",xR=e=>{let t=Zg.join(e,Da);return Hr.existsSync(t)?eh(ka(t))===null:!1},La=new Map,IR=e=>{let t=La.get(e);if(t)return t;let n=ls(e).then(r=>a(r)?null:r.value,()=>null);return La.set(e,n),n.then(r=>{r===null&&La.get(e)===n&&La.delete(e)}),n},Ba=async e=>{let t=await IR(e);return t!==null&&xR(t)},th=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ka=e=>{try{return vR(Hr.readFileSync(e,"utf8"))}catch{return null}},Qg=(e,t)=>{let n={pid:process.pid,hostname:Sd.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Hr.writeFileSync(r,JSON.stringify(n)),Hr.linkSync(r,e),!0}catch{return!1}finally{try{Hr.rmSync(r,{force:!0})}catch{}}},ER=async({worktreeRoot:e,operation:t})=>{let n=await ls(e);if(a(n))return l(n.message);let r=Zg.join(n.value,Da),o=()=>{try{let u=ka(r);u&&u.pid===process.pid&&Hr.rmSync(r)}catch{}};if(Qg(r,t))return d("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=ka(r),i=eh(s);if(i===null)return d("Sync lock is held",{acquired:!1,heldBy:s});ee.info(`Breaking an abandoned sync lock: ${s?th(s):"unreadable lock file"}`);try{Hr.rmSync(r,{force:!0})}catch{}if(Qg(r,t))return d("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let c=ka(r);return d("Sync lock taken by another process",{acquired:!1,heldBy:c??{pid:-1,hostname:Sd.hostname(),startedAt:Date.now(),operation:"unknown"}})},Vs=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await ER({worktreeRoot:e,operation:t});if(a(r))return l(r.message);if(!r.value.acquired)return ee.info(`Skipping ${t}: the state worktree is held by ${th(r.value.heldBy)}`),d("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return d("Ran under the sync lock",await n(o))}finally{s()}};var SR=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ge("getRepoRootDir",await Jt(t));if(a(r))return l(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ge("getStateBranchRoot",me({repoRoot:o}));if(a(s))return l(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&rh.existsSync(i)){let m=await $m(i,{preserve:[Da]});if(a(m))return l(m.message);m.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:m.value,stateBranchRoot:i});let f=ke(o);if(a(f))return l(f.message);let g=await Um(i,f.value);if(a(g))return l(g.message);g.value&&logger.info("[sync] cleared a ref lock left by a dead process",{branch:f.value,stateBranchRoot:i});let h=ge("abortRebaseIfPresent(stateBranchRoot)",await bc(i));if(a(h))return l(h.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let c=ge("bootstrapStateBranchStorage",await Xg({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(c))return l(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=ge("getInProgressGitOperation(stateBranchRoot)",await yc(i));if(a(u))return l(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),l(`Cannot sync while there is a ${u.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let p=ge("ensureStateBranchLayout",Zm(o,i));return a(p)?l(p.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:c.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:c.value}))},RR=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=[];for(let p of rg(St(t),n)){let m=ge("stageStateBranchOwnEventFile",await Pa({stateBranchRoot:t,eventFileName:p}));if(a(m))return l(m.message);r.push(m.value)}let o=ge("stageStateBranchMediaFiles",await Kg({stateBranchRoot:t}));if(a(o))return l(o.message);let s=ge("stageStateBranchEventConfig",await qg({stateBranchRoot:t}));if(a(s))return l(s.message);let i=[...r,o.value,...s.value].filter(p=>p!==null);if(i.length===0)return d("Nothing to stage",{createdCommit:!1});let c=ge("hasStagedChanges(after stage)",await Gm(t,i));if(a(c))return l(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=ge("createStateBranchSyncCommit",await Yg({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(u)?l(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},Rd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return wa(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},nh=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),l("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),l("Own event file must end with .jsonl");Mo();let r=ge("ensureSyncReady",await SR({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return We(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,c=ge("isDetachedHead(stateBranchRoot)",await Vm(s));if(a(c))return We(c.message);if(logger.debug("[sync] detached state branch check result",{detached:c.value}),c.value)return We("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,p,m=!1,f=!1,g=ge("getStateBranch",ke(o));if(a(g))return We(g.message);let h=g.value;logger.debug("[sync] resolved state branch",{stateBranch:h,stateBranchRoot:s});let x=ge("flushPendingLogs",ga(s,t));a(x)&&logger.error(`[sync] ${x.message}`);let b=ge("commitOwnEventFileToStateBranch",await RR({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(b))return We(b.message);u=b.value.createdCommit,p=b.value.commitSha;let R=ge("hasRemote",await On({repoRoot:s}));if(a(R))return We(R.message);if(!R.value)return Rd({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i},"no remote");let S=ge("pullBranchRebaseIfPresent",await us({cwd:s,branch:h}));if(a(S))return ds(S.message)?Rd({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):We(S.message);m=S.value;let A=ge("isAheadOfUpstream",await Hm(s));if(a(A))return We(A.message);if(u||i||A.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let T=ge("pushStateBranch",await Gs({stateBranchRoot:s,repoRoot:o}));if(a(T)&&_m(T.message)){let P=ge("pullBranchRebaseIfPresent(retry)",await us({cwd:s,branch:h}));if(a(P))return We(P.message);m=m||P.value,T=ge("pushStateBranch(retry)",await Gs({stateBranchRoot:s,repoRoot:o}))}if(a(T))return ds(T.message)?Rd({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):We(T.message);f=T.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let T=ge("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:s}));if(a(T))return We(T.message);p=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",p)}return Ur(f?"Synced and pushed":m||u?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),d("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,pulled:m,pushed:f,bootstrapped:i,offline:!1})},Oa=async(e,t)=>{let n=Hg(e);try{return await t()}finally{let r=Wg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},Fa=async e=>{let t=e.cwd??process.cwd(),n=await Jt(t);if(a(n))return We(n.message);let r=me({repoRoot:n.value});if(a(r))return We(r.message);let o=r.value;if(!rh.existsSync(o))return nh(e,"clean");let s=await Vs({worktreeRoot:o,operation:"sync",fn:i=>Oa(o,()=>nh(e,i))});return a(s)?We(s.message):s.value===null?d("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var ko=null,_a=async()=>(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ko,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),ko?(logger.debug("[sync] syncAndReloadState joining existing promise"),ko):(logger.debug("[sync] syncAndReloadState creating promise"),ko=CR().finally(()=>{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),ko=null}),ko)),CR=async()=>{let e;try{e=await NR(),logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:e.message,statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg})}catch(n){let r=n instanceof Error?n.message:String(n);logger.error("[sync] syncAndReloadState promise threw",{message:r,error:n}),e=l(r)}let t=de();return a(e)&&!a(t)&&t.value.syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({syncStatus:{msg:e.message,status:"failed"}})),e},NR=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=oh();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;logger.debug("[sync] syncAndReloadState:start");let t=ge("resolveActorId",pe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),l("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=ar(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ge("syncEpiqWithRemote",await Fa({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),We(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=zs(o);return a(i)?i:(w({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),d("Synced",!0))},zs=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=et(e),n=ge("loadMergedEvents",nn(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(n),message:(a(n),n.message),count:a(n)?void 0:n.value.events.length}),a(n))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),l(`Unable to load events. ${n.message}`);logger.debug("[sync] loaded merged events after sync",{count:n.value.events.length});let r=oh();if(r)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:r.message,syncStatus:v().syncStatus}),r;let o=Lg(),s=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:n.value.events.length});let c=de(),u=!a(c)&&c.value.timeMode==="live",p=ge("bootStateFromEventLog",rn(n.value.events,n.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),l(`Unable to boot synced state. ${p.message}`);u&&To(e,t)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:s}),logger.debug("[sync] restoreNavigationAnchor:start");let i=ge("restoreNavigationAnchor",Dg(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(i),message:a(i)?i.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(i)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),i):d("Reloaded state from event log",null)},oh=()=>v().mode===I.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),l("Will not re-materialize if not in default mode, to not lose edit data"));var sh=0,Cd,Nd=!1,Ks=!1,Ad=()=>{if(Nd)return!0;let e=de();return a(e)?!1:e.value.syncStatus.status==="syncing"},AR=()=>{let e=mo(V().autoSyncIntervalMs),t=Date.now()-sh;return Math.max(0,e-t)},ih=()=>{Cd||(Cd=setTimeout(async()=>{if(Cd=void 0,!!Rt()){if(Ad()){Ks=!0;return}Ks=!1,await TR()}},AR()))},TR=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return l("Cannot auto-sync while peeking");if(!Rt())return l("Cannot auto-sync before state is initialized");if(Ad())return Ks=!0,l("Sync already in progress");Nd=!0,sh=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await _a()}finally{Nd=!1,Ks&&ih()}},ja=()=>{Rt()&&(Ks=!0,!Ad()&&ih())};var $a=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case C.EXIT:return G.Exit;case C.EXPORT:return G.Export;case C.INIT:return G.Init;case C.OPEN:return G.OpenProject;case C.DELETE:return G.Delete;case C.EDIT:return G.Edit;case C.COMMENT:return G.Comment;case C.HELP:return G.ViewHelp;case C.RE_OPEN_ISSUE:return G.ReopenIssue;case C.CLOSE_ISSUE:return G.CloseIssue;case C.TAG:return G.TagTicket;case C.UNTAG:return G.UntagTicket;case C.ASSIGN:return G.AssignUserToTicket;case C.UNASSIGN:return G.UnassignUserFromTicket;case C.NEW:return G.NewItem;case C.FILTER:return G.Filter;case C.MOVE:return G.Move;case C.PEEK:return G.Peek;case C.REPLAY:return G.Replay;case C.CONFIG:return G.Config;case C.YANK:return G.Yank;case C.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import by from"node:fs";import bN from"node:path";import xN from"react";import{Box as yN}from"ink";import rl from"react";import zR from"chalk";import{Box as Md,Text as KR}from"ink";import An from"react";import{Text as ah}from"ink";import lh,{useEffect as ch,useState as wR}from"react";var dh={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},Ct=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=ne(),r=dh[n]??dh.default,[o,s]=wR(0);if(ch(()=>{s(0)},[r]),ch(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return lh.createElement(ah,null,t);let i=r[o]??r[0]??t;return lh.createElement(ah,{color:y.accent,dimColor:o===1},i)};import{Box as Td,Text as MR}from"ink";import Ua from"react";var PR=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=o(n);for(;i<t&&c+o(i)<=r;)c+=o(i),i++;for(;s>0&&c+o(s-1)<=r;)s--,c+=o(s);return{start:s,end:i}},ut=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),p=Math.max(1,Math.floor(i/c)),m=Math.max(0,e.length-p),{start:f,end:g}=o?PR(o,e.length,u,i):s?{start:Math.min(m,Math.max(0,u-p+1)),end:Math.min(m,Math.max(0,u-p+1))+p}:{start:Math.min(m,Math.floor(u/p)*p),end:Math.min(m,Math.floor(u/p)*p)+p},h=Math.max(1,g-f),x=e.slice(f,g),b=e.length>h,R=i,S=b?Math.max(1,Math.floor(h/e.length*R)):R,A=Math.max(0,R-S),T=Math.max(1,e.length-h),P=b?Math.floor(f/T*A):0;return Ua.createElement(Td,{flexDirection:"row",height:i,width:"100%"},Ua.createElement(Td,{flexDirection:"column",flexGrow:1,height:i},x),Ua.createElement(Td,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((M,O)=>Ua.createElement(MR,{key:O,color:b&&O>=P&&O<P+S?y.accent:y.secondary},b?"\u2502":" "))))};import{Box as Oo,Text as Fo}from"ink";import Nt from"react";var uh,wd,LR=()=>{let{eventLog:e=[]}=v();if(wd&&uh===e)return wd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return uh=e,wd=t,t},Ha=e=>LR().has(e);import{Text as kR}from"ink";import DR from"react";var mr=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:_n(o,n);return DR.createElement(kR,{underline:t,color:ze(o)},"@"+s,Ha(e)?"":"\u2197")};import{Text as BR}from"ink";import OR from"react";var Do=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getTag(e);if(!r)return;let o=n===void 0?r.name:_n(r.name,n);return OR.createElement(BR,{underline:t,backgroundColor:ze(r.name),color:y.secondary}," "+o+" ")};import{useEffect as FR,useState as _R}from"react";var jR=80,mh=1400,Wa=new Set,qs=null,$R=e=>(Wa.add(e),qs||(qs=setInterval(()=>{for(let t of Wa)t()},jR)),()=>{Wa.delete(e),Wa.size===0&&qs&&(clearInterval(qs),qs=null)}),UR=()=>{let e=Date.now()%mh/mh;return e<.5?e*2:(1-e)*2},Bo=e=>{let[,t]=_R(0);return FR(()=>{if(e)return $R(()=>t(n=>n+1))},[e]),Ki(UR())};var HR=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),_n(e.slice(o).trim(),n)]},ph=3,WR=2,GR=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,c=i>0?String(i).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},fh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Bo(r),s=e-4,i=s-7-1,[c,u]=HR(Ee(t.title),i,s),p=u?null:_n(Ee(t.props.description),s)||null,m=vn(t),f=bn(t).map(S=>({...S,name:S.name})),g=Math.max(1,s-ph),h=N.getCommentsByIssue(t.id),x=h.length?String(h.length).length+2+1:0,{shown:b,hidden:R}=GR([...m.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,g)+ph})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,g)+WR+(Ha(S.id)?0:1)}))],s-x);return Nt.createElement(Oo,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},Nt.createElement(Oo,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Nt.createElement(Oo,{justifyContent:"space-between"},Nt.createElement(Fo,{color:y.primary},c),Nt.createElement(Fo,{color:y.secondary2,dimColor:!0},H(t.id))),u&&Nt.createElement(Fo,{color:y.primary},u),p&&Nt.createElement(Fo,{color:y.secondary2,dimColor:!0},p)),Nt.createElement(Oo,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Nt.createElement(Oo,{flexDirection:"row"},b.map(S=>Nt.createElement(Oo,{paddingRight:1,key:S.id},S.isTag?Nt.createElement(Do,{id:S.id,maxWidth:g}):Nt.createElement(mr,{id:S.id,maxWidth:g}))),R>0&&Nt.createElement(Fo,{color:y.secondary2,dimColor:!0},"+",R)),h.length>0&&Nt.createElement(Fo,{color:y.accent},"[",h.length,"]")))};import{Box as Wr,Text as Ys}from"ink";import Bt from"react";var VR=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,gh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let c=Bo(s),u=(r.props.tags??[]).map(M=>N.getTag(M)).filter(M=>!!M),p=(r.props.assignees??[]).map(M=>N.getContributor(M)).map(M=>M&&{...M,name:M.name}).filter(M=>!!M),m=1,f=u.length*(1+m),g=p.length*(2+m),h=u.map(M=>Bt.createElement(Wr,{key:M.id,paddingRight:m},Bt.createElement(Ys,{color:ze(M.name)},"\u25A0"))),x=p.map(M=>Bt.createElement(Wr,{key:M.id,paddingRight:m},Bt.createElement(Ys,{color:Dc(M.name)},"@"+M.name.at(0)))),b=s?c:o?y.accent:i===I.MOVE?y.secondary:y.primary,R=N.getCommentsByIssue(r.id),S=R.length?String(R.length).length+2+m:0,A=R.length?Bt.createElement(Wr,{paddingRight:m},Bt.createElement(Ys,{color:y.accent},"[",R.length,"]")):null,T=f+g+S,P=Math.max(1,n-t-T-(T>0?1:0));return Bt.createElement(Wr,{justifyContent:"space-between"},Bt.createElement(Wr,null,Bt.createElement(Wr,{width:t},o?Bt.createElement(Ct,{isSelected:!0}):Bt.createElement(Ys,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Bt.createElement(Ys,{wrap:"truncate",color:b},VR(r.title,P))),Bt.createElement(Wr,null,h,x,A))};var qR=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:p}=ne(),m=u[e.id]??[],f=p?new Set(p.flashNodeIds):null,g=f?.has(e.id)??!1,h=Bo(g),x=`${e.title} ${zR.hex(y.secondary2).dim("("+m.length+")")}`,b=3,R=o?1:5,S=s&&i===-1,A=n-3-(o?1:0)-(S?2:0),T=Math.max(2,String(m.length).length+1),P=r-b-1,M=An.createElement(Md,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},An.createElement(Ct,{isSelected:t}),An.createElement(KR,{bold:!0,color:g?h:t?y.accent:y.primary},x," ",e.readonly?"\u{1F512}":"")),O=(W,Y)=>{let xe=s&&i===Y;if(!_(W))return null;let F=f?.has(W.id)??!1;return o?An.createElement(gh,{key:W.id,index:Y,labelWidth:T,width:A,ticket:W,isSelected:xe,isFlashing:F,mode:c}):An.createElement(fh,{key:W.id,width:A,ticket:W,isSelected:xe,isFlashing:F})};return An.createElement(Md,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},M,An.createElement(Md,null,m.length>0&&An.createElement(ut,{selectedIndex:i,height:P,itemHeight:R},m.map(O)),S&&An.createElement(Ct,{isSelected:!0})))},hh=An.memo(qR);import{Box as Vo,Text as uN}from"ink";import At,{useMemo as zo}from"react";var yh=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},vh=(e,t,n)=>Re.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var bh=e=>e.action==="add.issue.comment";import{Box as _o,Text as zn}from"ink";import mt,{useEffect as YR,useMemo as XR,useRef as JR}from"react";import{decodeTime as xh}from"ulid";var fr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Ga=e=>String(e).padStart(2,"0"),Va=e=>`${e.getFullYear()}-${Ga(e.getMonth()+1)}-${Ga(e.getDate())} ${Ga(e.getHours())}:${Ga(e.getMinutes())}`;var QR=e=>Me(e,"attachments"),ZR=e=>N.getAttachmentsByIssue(e.id).sort((t,n)=>xh(t.id)-xh(n.id)),Ih=e=>{for(let t of e)N.deleteNode(t.id)},eC=(e,t,n)=>Re.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),tC=(e,t)=>{let n=N.getNode(QR(e.id));if(!n||!at(n))return[];let r=t.map((o,s)=>eC(o,s,n.id)).map(o=>N.createNode(o)).filter(ve).map(({value:o})=>o).filter(at);return t.length>0&&v().selectedIndex<0&&$.navigate({contextNode:n,selectedIndex:0}),r},nC=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Eh({ticket:e,width:t,height:n}){let r=XR(()=>ZR(e),[e]),o=JR([]);YR(()=>(Ih(o.current),o.current=tC(e,r),()=>{Ih(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=ne(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?mt.createElement(_o,{flexDirection:"column",width:t,height:n,padding:1},mt.createElement(zn,{color:y.primary},"No attachments yet."),mt.createElement(_o,{paddingTop:1},mt.createElement(zn,{color:y.primary},"Attach images from the browser GUI"),mt.createElement(zn,{color:y.accent}," epiq gui "),mt.createElement(zn,{color:y.primary},"by dropping or pasting them."))):mt.createElement(_o,{flexDirection:"column",width:t,height:n},mt.createElement(_o,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},mt.createElement(zn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),mt.createElement(ut,{height:c,itemHeight:2,selectedIndex:s},r.map((p,m)=>{let f=m===s,g=p.name.length>u?p.name.slice(0,u-1)+"\u2026":p.name;return mt.createElement(_o,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},mt.createElement(zn,{color:y.accent},f?"\u276F ":" "),mt.createElement(_o,{paddingLeft:1},mt.createElement(zn,{color:y.secondary2},`#${m+1} `),mt.createElement(zn,{color:f?y.accent:y.primary},g),mt.createElement(zn,{color:y.secondary2}," "+nC(p.bytes)+" "+fr(De(p.id)))))})))}import{Box as gr,Text as hr}from"ink";import Ye,{useEffect as uC,useMemo as Oh,useRef as mC}from"react";import{decodeTime as Fh}from"ulid";var Rh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Pd=e=>e.replace(Rh,""),rC=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,Sh=e=>e==="additions"||e==="deletions",Xs=e=>{let t=Rh.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!Sh(r.side)||!Sh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var Ch=/```\n([\s\S]*?)\n?```\s*$/,Nh=e=>Ch.exec(e)?.[1]??null,oC=/`[^`\n]+`[^\n]*\n?$/,Ah=e=>Pd(e).replace(Ch,"").replace(oC,"").trim(),Th=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Ld=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Th(e)}`;var sC=e=>{let t=e.split(`
|
|
69
69
|
`),n=t.filter(r=>r.trim()!=="").reduce((r,o)=>{let s=/^[ \t]*/.exec(o)?.[0].length??0;return r===null?s:Math.min(r,s)},null);return n?t.map(r=>r.slice(n)).join(`
|
|
70
|
-
`):e},
|
|
71
|
-
`)};var
|
|
72
|
-
`),t);let o=
|
|
73
|
-
`).map(
|
|
74
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:
|
|
75
|
-
`),[m,
|
|
76
|
-
`).filter(
|
|
77
|
-
`)){if(
|
|
78
|
-
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},
|
|
79
|
-
`)){if(i.startsWith("diff --git ")){n=s();let
|
|
80
|
-
`)}}};import{existsSync as
|
|
81
|
-
`).map(o=>o.trim()).filter(Boolean);return r.length===0?c("No changed files found for this commit"):u("Listed changed files",r)},wC=async(e,t,n)=>{let r=await TC(e,t);if(a(r))return c(r.message);let o=r.value;if(o.length>NC)return c(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Ys("commit-diffs",t);if(a(s))return c(s.message);let i=s.value,l=await Promise.all(o.map(async(g,y)=>{let[x,b]=await Promise.all([zh(e,`${t}~1`,g),zh(e,t,g)]),R=Wa.basename(g),S=Wa.join(i,String(y),"before",R),T=Wa.join(i,String(y),"after",R);return Fd(S)||(ot.writeToFile(S,x),await _d(S,292)),Fd(T)||(ot.writeToFile(T,b),await _d(T,292)),{beforePath:S,afterPath:T}})),[d,...m]=l;if(!d)return c("No changed files found for this commit");let p=await Od(n,d.beforePath,d.afterPath,"new");if(a(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,AC));let f=await Promise.all(m.map(({beforePath:g,afterPath:y})=>Od(n,g,y,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},Xs=async e=>{if(!Fo(e.sha))return c("Invalid commit sha");let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=Ha()[0];if(r&&Bd(r)){let o=await wC(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return CC(n,e.sha)};import{Box as rn,Text as Kn}from"ink";import _e,{useEffect as Hd,useMemo as Xh,useRef as LC,useState as kC}from"react";var Ga=(e,t,n)=>{let r=[],o=va(()=>{for(let s=0;s<t;s++){let i=Pt(BigInt(s+1));if(!be(i))continue;let l=N.createNode(Ne.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));be(l)&&r.push(l.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},jo=e=>{N.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as MC}from"react";var za=null,Va=null,$d=new Set,Kh=()=>{for(let e of $d)e()},Ud=e=>{za=e,Kh()},Ka=()=>za,qh={mark:null},Gr=e=>{Va=e,qh={mark:e},Kh()};var jd=e=>Va&&Va.sha===e?Va.row:null,Yh=()=>MC(e=>($d.add(e),()=>{$d.delete(e)}),()=>qh),hr=()=>{let{contextNode:e}=v();return za&&za.sha===e.id?e.id:null};import DC from"string-width";var Wd=(e,t)=>`${e}::patch::${t}`,BC=e=>{switch(e){case"added":return h.green;case"removed":return h.red;case"hunk":return h.accent;case"file":return h.primary;default:return h.secondary2}},Jh=(e,t)=>{let n=DC(e);return n>=t?e:e+"\xA0".repeat(t-n)},OC=e=>e==="added"?"+":e==="removed"?"-":" ",Qh=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function Zh({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=kC({state:"loading"});Hd(()=>{let A=!0;return i({state:"loading"}),Nd({sha:t}).then(P=>{A&&i(a(P)?{state:"failed",message:P.message}:{state:"loaded",rows:Pd(Md(P.value))})}),()=>{A=!1}},[t]);let l=s.state==="loaded"?s.rows:null,d=l!==null&&l.length>4e3,m=LC([]);Hd(()=>(jo(m.current),m.current=l&&!d?Ga(t,l.length,A=>Wd(t,A)):[],()=>{jo(m.current),m.current=[]}),[t,l,d]),Hd(()=>(Ud(l?{sha:t,rows:l}:null),Gr(null),()=>{Ud(null),Gr(null)}),[t,l]);let{selectedIndex:p}=oe(),{mark:f}=Yh(),g=Xh(()=>l?Ld(l,N.getCommentsByIssue(e.id),t):new Set,[l,t,e]),y=f&&f.sha===t?f.row:null,x=A=>y!==null&&A>=Math.min(y,p)&&A<=Math.max(y,p),b=Xh(()=>l?Math.max(5,l.reduce((A,P)=>Math.max(A,Qh(P).length),0)+2):5,[l]),R=Math.max(1,o-4),S=Math.max(8,r-b-6);if(s.state!=="loaded")return _e.createElement(rn,{flexDirection:"column",width:r,height:o,padding:1},_e.createElement(Kn,{color:h.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let T=A=>_e.createElement(rn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},_e.createElement(Kn,{color:h.secondary2,wrap:"truncate-end"},_n(`${t.slice(0,7)} ${n} \u2014 ${A}`,Math.max(8,r-6))));return s.rows.length===0?_e.createElement(rn,{flexDirection:"column",width:r,height:o},T("no changes"),_e.createElement(rn,{paddingX:1},_e.createElement(Kn,{color:h.primary},"This commit changed no files."))):d?_e.createElement(rn,{flexDirection:"column",width:r,height:o},T("too large to draw here"),_e.createElement(rn,{paddingX:1,flexDirection:"column"},_e.createElement(Kn,{color:h.primary},`${s.rows.length.toLocaleString()} lines of diff.`),_e.createElement(Kn,{color:h.secondary2},"Press o to open it in your editor."))):_e.createElement(rn,{flexDirection:"column",width:r,height:o},T(y===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),_e.createElement(mt,{scrollByOne:!0,height:R,selectedIndex:p,itemHeight:1},s.rows.map((A,P)=>{let M=P===p,O=BC(A.kind);if(A.kind==="file")return _e.createElement(rn,{key:Wd(t,P),paddingX:1},_e.createElement(Kn,{backgroundColor:h.secondary,color:M?h.accent:O,bold:!0,wrap:"truncate-end"},Jh(` ${_n(qs(A.text),S)}`,S+b+1)));let W=x(P),X=`${OC(A.kind)}${_n(qs(A.text),S)}`;return _e.createElement(rn,{key:Wd(t,P),paddingX:1},_e.createElement(rn,{flexShrink:0},_e.createElement(Kn,{color:M||W?h.accent:h.secondary2,dimColor:!M&&!W,wrap:"truncate-end"},`${M?"\u276F":"\xA0"}${W?"\u258C":"\xA0"}${Qh(A).padStart(b-2,"\xA0")}`)),_e.createElement(rn,{flexShrink:0},_e.createElement(Kn,{color:h.yellow,wrap:"truncate-end"},g.has(P)?"\u2502":"\xA0")),_e.createElement(Kn,{color:M?h.accent:O,backgroundColor:M||W?h.secondary:void 0,wrap:"truncate-end"},M||W?Jh(X,S+1):X))})))}var $C=e=>Pe(e,"diff"),ty=e=>{for(let t of e)N.deleteNode(t.id)},UC=(e,t,n)=>Ne.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),jC=(e,t)=>{let n=N.getNode($C(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>UC(o,s,n.id)).map(o=>N.createNode(o)).filter(be).map(({value:o})=>o).filter(lt);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&U.navigate({contextNode:n,selectedIndex:0}),r},HC=e=>`+${e.insertions} -${e.deletions}`;function ny({ticket:e,width:t,height:n}){let[r,o]=_C({state:"loading"}),s=H(e.id);ey(()=>{let x=!0;return o({state:"loading"}),zn({ref:s}).then(b=>{x&&o(a(b)?{state:"failed",message:b.message}:{state:"loaded",commits:b.value})}),()=>{x=!1}},[s]);let i=FC([]),l=r.state==="loaded"?r.commits:null;ey(()=>(ty(i.current),i.current=l?jC(e,l):[],()=>{ty(i.current),i.current=[]}),[e,l]);let{selectedIndex:d,contextNode:m}=oe(),p=l?.find(x=>x.sha===m.id)??null,g=Math.max(1,n-4),y=Math.max(12,t-34);return r.state!=="loaded"?Qe.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},Qe.createElement(Tn,{color:h.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):p?Qe.createElement(Zh,{ticket:e,sha:p.sha,subject:p.subject,width:t,height:n}):r.commits.length===0?Qe.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},Qe.createElement(Tn,{color:h.primary},"No commits reference this ticket."),Qe.createElement(Vr,{paddingTop:1},Qe.createElement(Tn,{color:h.primary},"Commits are matched by the"),Qe.createElement(Tn,{color:h.accent},` ${s} `),Qe.createElement(Tn,{color:h.primary},"prefix on their subject line."))):Qe.createElement(Vr,{flexDirection:"column",width:t,height:n},Qe.createElement(Vr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},Qe.createElement(Tn,{color:h.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Qe.createElement(mt,{height:g,itemHeight:2,selectedIndex:d},r.commits.map((x,b)=>{let R=b===d,S=x.subject.length>y?x.subject.slice(0,y-1)+"\u2026":x.subject;return Qe.createElement(Vr,{key:x.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Qe.createElement(Tn,{color:h.accent},R?"\u276F ":" "),Qe.createElement(Vr,{paddingLeft:1},Qe.createElement(Tn,{color:h.secondary2},`${x.sha.slice(0,7)} `),Qe.createElement(Tn,{color:R?h.accent:h.primary},S),Qe.createElement(Tn,{color:h.secondary2},` ${HC(x)} ${pr(x.time)}`)))})))}import{Box as qa,Text as WC}from"ink";import qn from"react";var ry=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=oe(),{title:o}=t,s=t.parentNodeId?N.getNode(t.parentNodeId):void 0,i=s&&_(s)?o===Te.ASSIGNEES?s.props.assignees??[]:o===Te.TAGS?(s.props.tags??[]).filter(l=>N.getTag(l)):[]:[];return qn.createElement(qa,{alignItems:"center",paddingTop:1},qn.createElement(qa,{minWidth:12},qn.createElement(St,{isSelected:n}),qn.createElement(WC,{color:n?h.accent:h.secondary2},o,":")),qn.createElement(qa,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,d)=>{let m=r.id===t.id&&d===e;return qn.createElement(qa,{key:`${o}-${l}`,paddingRight:2,minHeight:1},qn.createElement(St,{isSelected:m}),o===Te.ASSIGNEES?qn.createElement(ur,{isSelected:m,id:l}):o===Te.TAGS?qn.createElement(Lo,{isSelected:m,id:l}):null)})))};import{Box as Ho,Text as zd}from"ink";import Ut,{useEffect as GC,useMemo as Kd,useRef as VC}from"react";var Gd=e=>Math.max(5,String(Math.max(e,1)).length+3),oy=(e,t)=>Math.max(0,e-6-Gd(t));var Vd=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var zC="\u2029",sy=(e,t)=>`${e}::inline-line::${t}`,qd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=oe(),d=Kd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Kd(()=>d.join("\0"),[d]),p=VC([]);GC(()=>(jo(p.current),p.current=Ga(e,d.length,b=>sy(e,b)),()=>{jo(p.current),p.current=[]}),[e,m]);let f=Gd(d.length),g=oy(s,d.length),x=Kd(()=>Rd(d).map(b=>{if(b.kind==="code"||b.kind==="caption")return{...b,text:_n(b.text,g)};if(b.kind==="text"||b.kind==="heading"){let R=b.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...b,spans:Ks(_n(R,g))}}return b}),[d,g]).map((b,R)=>{let S=l.id===e&&i===R;return Ut.createElement(Ho,{key:sy(e,R)},Ut.createElement(Ho,{flexShrink:0},Ut.createElement(zd,{color:S?h.primary:h.secondary2,dimColor:!S},`${R+1} `.padStart(f,"\xA0"))),b.kind==="blank"?Ut.createElement(zd,{backgroundColor:S?"gray":void 0},zC):Ut.createElement(Ho,null,Ut.createElement(Cd,{line:b,width:b.kind==="code"?g:0,wrap:"truncate-end"})))});return Ut.createElement(Ho,{flexDirection:"column",paddingTop:1},Ut.createElement(Ho,null,Ut.createElement(St,{isSelected:o}),Ut.createElement(zd,{color:o?h.accent:h.secondary2},t)),Ut.createElement(Ho,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Ut.createElement(mt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))};var qC=e=>Pe(e,"description"),YC=e=>Pe(e,"comments"),XC=e=>Pe(e,"history"),JC=e=>Pe(e,"diff"),QC=e=>Pe(e,"attachments"),iy=({ticket:e,height:t})=>{let n=Go(()=>sh(e),[e]),{selectedIndex:r,contextNode:o}=oe(),s=process.stdout.columns||120,i=Go(()=>qC(e.id),[e.id]),l=Go(()=>YC(e.id),[e.id]),d=Go(()=>XC(e.id),[e.id]),m=Go(()=>JC(e.id),[e.id]),p=Go(()=>QC(e.id),[e.id]),f=N.getAttachmentsByIssue(e.id).length,g=o.id===e.id,y=o.id===l||o.parentNodeId===l,x=o.id===d||o.parentNodeId===d,b=o.id===p||o.parentNodeId===p,R=o.id===m||o.parentNodeId===m,S=de(e.id);if(y){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(Ah,{ticket:e,width:s,height:J}))}if(b){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(dh,{ticket:e,width:s,height:J}))}if(R){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(ny,{ticket:e,width:s,height:J}))}if(x){let F=N.getNode(d),J=F&<(F)?F.props.value??"":"",Ke=Vd(t);return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},F?Ct.createElement(qd,{id:F.id,label:"Event log",text:J,selected:!1,maxWidth:s,rows:Ke}):null)}let T=[d,m,l,p],A=F=>T.includes(F),P=S.reduce((F,J)=>vs(J)?F+1:F,0),M=S.reduce((F,J)=>A(J.id)?F+1:F,0),O=S.findIndex(F=>A(F.id)),W=Vd(t,P,M),X=(F,J,Ke,Jn)=>Ct.createElement(Wo,{key:F.id,paddingTop:J===O?1:0},Ct.createElement(St,{isSelected:Ke}),Ct.createElement(KC,{backgroundColor:h.secondary,color:Ke?h.accent:h.primary},Jn)),Ee=(F,J,Ke)=>F.id===i?Ct.createElement(qd,{key:F.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:J,maxWidth:s,rows:W}):vs(F)?Ct.createElement(ry,{key:F.id,parent:F,selected:J,selectedIndex:r}):F.id===l?X(F,Ke,J,` Comments (${n}) \u203A\u203A `):F.id===p?X(F,Ke,J,` Attachments (${f}) \u203A\u203A `):F.id===d?X(F,Ke,J," History \u203A\u203A "):F.id===m?X(F,Ke,J," Diff \u203A\u203A "):null;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((F,J)=>Ee(F,g&&r===J,J)))};var eN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let d=t.context,m=d===ie.TICKET||d===ie.FIELD_LIST||d===ie.FIELD,p=d===ie.BOARD||d===ie.SWIMLANE,f=d===ie.TICKET?t:r.find(R=>R.context===ie.TICKET),g=Math.floor(l/3),y=Math.floor(l/Math.max(e.length,1)),x=Math.min(y,g),b=s==="dense";return Ya.createElement(ZC,{flexDirection:"row",height:i},p&&e.map((R,S)=>{let T=t.id===R.id,A=T?n:-1,P=t.context===ie.BOARD&&n===S;return Ya.createElement(oh,{key:R.id,height:i,width:x,swimlane:R,isSelected:P,isDense:b,isFocused:T,listSelectedIndex:A,mode:o})}),m&&f&&Ya.createElement(iy,{height:i,ticket:f}))},Xa=Ya.memo(eN);import{render as rN}from"ink";import{Writable as oN}from"node:stream";var Js=e=>String(e).padStart(2,"0"),sN=e=>{let t=e.getUTCFullYear(),n=Js(e.getUTCMonth()+1),r=Js(e.getUTCDate()),o=Js(e.getUTCHours()),s=Js(e.getUTCMinutes()),i=Js(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},iN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",aN=async(e,{width:t,height:n})=>{let r="",o=new oN({write(i,l,d){let m=lN(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),d()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=rN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},lN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ly=async()=>{let{viewMode:e}=V(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(S=>S.context==="BOARD");if(!i)return c("No board found to export");let l=120,d=40,m=await aN(nN.createElement(Xa,{height:d,width:l,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&gn(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:d});if(!m)return c("Failed to render board export");let p=Oi(process.cwd());if(a(p))return c("Unable to export, epiq root not found");let f=new Date,g=sN(f),y=`board_${iN(i.title)}_${g}.md`,x=Gm(p.value);ay.mkdirSync(x,{recursive:!0});let b=tN.join(x,y),R=`# Board - ${i.title}
|
|
70
|
+
`):e},wh=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],rC({...t,note:n}),`\`${t.filePath}\` ${Th(t)}`,"```",sC(e),"```"].join(`
|
|
71
|
+
`)};var iC=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let c=i;for(;c.length>n;)s&&(o.push(s),s=""),o.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(o.push(s),s=c):s=c}return s&&o.push(s),o},Js=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},aC=/!\[([^\]]*)\]\([^)]*\)/g,lC=e=>e.replace(aC,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),cC=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),dC=4,Qs=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(dC)),kd=e=>{let t=!1;return e.map(Qs).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Xs(n);if(r)return{kind:"caption",text:Ld(r)};let o=lC(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Js(s[1]??"")}:{kind:"text",spans:Js(o)}})},Ph=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Mh=(e,t)=>{let n=[];for(let r of kd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of Ph(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of iC(cC(r.spans),t))n.push({kind:r.kind,spans:Js(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Lh=(e,t)=>{let n=Xs(e),r=n?Nh(e):null;if(!n||r===null)return Mh(Pd(e).split(`
|
|
72
|
+
`),t);let o=Ah(e),s=r.split(`
|
|
73
|
+
`).map(Qs),i=n.side===n.endSide?n.start:void 0,c=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Mh(o.split(`
|
|
74
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Ld(n)},...s.flatMap((u,p)=>Ph(u,Math.max(1,t-c)).map((m,f)=>({kind:"code",text:m,number:i===void 0||f>0?void 0:i+p})))]};import{Box as kh,Text as Gr}from"ink";import Ht from"react";var Dh=({spans:e,bold:t,wrap:n})=>Ht.createElement(Gr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?Ht.createElement(Gr,{key:o,color:y.yellow},r.text):Ht.createElement(Gr,{key:o},r.text))),Dd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return Ht.createElement(Gr,null," ");case"fence":return Ht.createElement(Gr,{color:y.secondary2},"```");case"caption":return Ht.createElement(Gr,{color:y.accent,wrap:r},e.text);case"heading":return Ht.createElement(Dh,{spans:e.spans,bold:!0,wrap:r});case"text":return Ht.createElement(Dh,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Ht.createElement(Gr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Bh=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return Ht.createElement(kh,{flexDirection:"column"},e.map((o,s)=>Ht.createElement(kh,{key:s},Ht.createElement(Dd,{line:o,width:t,gutter:r}))))};var pC=4,fC=e=>Me(e,"comments"),gC=e=>N.getCommentsByIssue(e.id).sort((t,n)=>Fh(t.id)-Fh(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),_h=e=>{for(let t of e)N.deleteNode(t.id)},hC=(e,t)=>{let n=N.getNode(fC(e.id));if(!n||!at(n))return[];let r=t.map((o,s)=>vh(o,s,n.id)).map(N.createNode).filter(ve).map(({value:o})=>o).filter(Es);return t.length>0&&v().selectedIndex<0&&$.navigate({contextNode:n,selectedIndex:0}),r};function jh({ticket:e,width:t,height:n}){let r=Oh(()=>gC(e),[e]),o=mC([]);uC(()=>(_h(o.current),o.current=hC(e,r),()=>{_h(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=ne(),c=Math.max(1,n-4),u=Math.max(20,t-8),p=Oh(()=>r.map(f=>{let g=Lh(f.md,u);return g.length>0?g:[{kind:"blank"}]}),[r,u]),m=p.map(f=>f.length+pC);return r.length===0?Ye.createElement(gr,{flexDirection:"column",width:t,height:n,padding:1},Ye.createElement(hr,{color:y.primary},"No comments yet."),Ye.createElement(gr,{paddingTop:1},Ye.createElement(hr,{color:y.primary},"Use"),Ye.createElement(hr,{color:y.accent}," :comment "),Ye.createElement(hr,{color:y.primary},"to add the first one."))):Ye.createElement(gr,{flexDirection:"column",width:t,height:n},Ye.createElement(gr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Ye.createElement(hr,{color:y.secondary2},"Comments (",r.length,") ")),Ye.createElement(ut,{height:c,itemHeights:m,selectedIndex:s},r.map((f,g)=>{let h=g===s;return Ye.createElement(gr,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ye.createElement(gr,{flexDirection:"row",paddingBottom:1},Ye.createElement(hr,{color:y.accent},h?"\u276F ":" "),Ye.createElement(gr,{paddingLeft:1},Ye.createElement(hr,{color:y.secondary2},`#${g+1} `),Ye.createElement(mr,{id:f.authorId}),Ye.createElement(hr,{color:y.secondary2}," "+fr(De(f.id))))),Ye.createElement(gr,{paddingLeft:3,paddingBottom:1},Ye.createElement(Bh,{lines:p[g]??[],width:u})))})))}import{Box as zr,Text as Tn}from"ink";import Xe,{useEffect as my,useRef as tN,useState as nN}from"react";var sn=e=>{let t=re(e??process.cwd());return a(t)?l(t.message):d("Resolved Epiq repo root",t.value)},jo=e=>/^[0-9a-f]{7,40}$/i.test(e);var yC="EPIQ_CACHE_MS",za=e=>{let t=process.env[yC];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e};var $o="",$h="",Uh=5e3,Uo=null;var vC=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),Ho=async(e={})=>{let t=sn(e.repoRoot);if(a(t))return l(t.message);let n=Mt(t.value);if(a(n))return l(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&Uo&&Uo.repoRoot===t.value&&Uo.stateBranch===n.value.stateBranch&&Date.now()-Uo.fetchedAt<za(Uh))return d("Computed commit timeline",Uo.result);let o=await U({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${$h}%H${$o}%at${$o}%an${$o}%ae${$o}%s`]});if(a(o))return l(o.message);let s=o.value.stdout.split($h).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
75
|
+
`),[p,m,f,g,...h]=(c??"").split($o);if(!p||!m)return null;let x=u.join(" "),b=Number(/(\d+) insertion/.exec(x)?.[1]??0),R=Number(/(\d+) deletion/.exec(x)?.[1]??0);return{sha:p,time:Number(m)*1e3,author:f??"unknown",authorEmail:g??"",subject:h.join($o),linesChanged:b+R,insertions:b,deletions:R}}).filter(i=>i!==null).filter(i=>vC(i.time,e.start,e.end));return r&&(Uo={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),d("Computed commit timeline",s)},Kn=async e=>{let t=e.ref.trim();if(!t)return l("ref must not be empty");if(t.length!==7)return l(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await Ho({repoRoot:e.repoRoot});if(a(n))return l(n.message);let r=`${t.toUpperCase()} `,o=c=>c.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[c,u]of s.entries()){if(!o(u))continue;let p=s[c+1];i.push({...u,precedingSha:p&&o(p)?p.sha:null})}return d("Matched commits by ref",i)};var Bd=async e=>{if(!jo(e.sha))return l("Invalid commit sha");let t=sn(e.repoRoot);if(a(t))return l(t.message);let n=await U({cwd:t.value,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return a(n)?l(n.message):d("Read commit patch",n.value.stdout)},bC=200,Hh=e=>/^0+$/.test(e),Ka=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Wh=/^(\d+|-)\t(\d+|-)\t(.+)$/,Vh=async(e,t,n,r)=>{let o=await U({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",t,n,...r&&r.length>0?["--",...r]:[]]});if(a(o))return l(o.message);let s=o.value.stdout.split(`
|
|
76
|
+
`).filter(p=>p!==""),i=s.filter(p=>!Ka.test(p)&&!Wh.test(p));if(i.length>0)return l(`Could not parse ${i.length} line(s) of "git diff --raw --numstat" output, e.g. "${i[0]}"`);let c=new Map;for(let p of s){let m=Wh.exec(p);m&&c.set(m[3]??"",{insertions:m[1]==="-"?0:Number(m[1]),deletions:m[2]==="-"?0:Number(m[2]),isBinary:m[1]==="-"&&m[2]==="-"})}let u=s.filter(p=>Ka.test(p)).map(p=>{let m=Ka.exec(p),f=m?.[1]??"",g=m?.[2]??"",h=m?.[3]??"";return{path:h,beforeBlob:Hh(f)?null:f,afterBlob:Hh(g)?null:g,...c.get(h)??{insertions:0,deletions:0,isBinary:!1}}});return d("Listed changed files with blob hashes",u)},zh=async(e,t)=>{if(t.length>bC)return l(`${t.length} files changed \u2014 too many to show as a diff`);let n=t.flatMap(s=>s.isBinary?[]:[s.beforeBlob,s.afterBlob].filter(i=>i!==null)),r=await Ui(n,e);if(a(r))return l(r.message);let o=r.value;return d("Read changed file contents",t.map(s=>({path:s.path,before:s.isBinary||!s.beforeBlob?"":o.get(s.beforeBlob)??"",after:s.isBinary||!s.afterBlob?"":o.get(s.afterBlob)??"",insertions:s.insertions,deletions:s.deletions,isBinary:s.isBinary})))},Od=async e=>{if(!jo(e.sha))return l("Invalid commit sha");let t=sn(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=await Vh(n,`${e.sha}~1`,e.sha);if(a(r))return l(r.message);if(r.value.length===0)return l("No changed files found for this commit");let o=await zh(n,r.value);if(a(o))return l(o.message);let s=o.value;return d("Loaded commit diff",{sha:e.sha,files:s})},xC=/^[0-9a-f]{40}$/,IC=async(e,t,n)=>{let r=await U({cwd:e,args:["log","--raw","--no-renames","--abbrev=40","--format=%H",`${t}..${n}`]});if(a(r))return l(r.message);let o=new Map,s=null;for(let i of r.value.stdout.split(`
|
|
77
|
+
`)){if(xC.test(i)){s=new Set,o.set(i,s);continue}let c=Ka.exec(i);c&&s&&s.add(c[3]??"")}return d("Listed changed paths per commit",o)},Gh=e=>{let t=new Set;for(let n of e)for(let r of n)t.add(r);return t},EC=async(e,t,n)=>{if(t===n)return!0;let r=await U({cwd:e,args:["merge-base","--is-ancestor",t,n]});return!a(r)},SC="4b825dc642cb6eb9a060e54bf8d69288fbee4904",RC=async(e,t)=>{let n=await U({cwd:e,args:["rev-parse","--verify","--quiet",`${t}^1`]});return a(n)?SC:`${t}~1`},Fd=async e=>{let t=sn(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=await Kn({repoRoot:n,ref:e.ref});if(a(r))return l(r.message);let o=r.value;if(o.length===0)return l("No commits reference this ticket");let s=o[0].sha,i=s;for(let T=o.length-1;T>0;T--){let P=o[T].sha;if(await EC(n,P,s)){i=P;break}}let c=await RC(n,i),u=await IC(n,c,s);if(a(u))return l(u.message);let p=u.value,m=new Set(o.map(T=>T.sha)),f=[...p.keys()].filter(T=>m.has(T)),g=f.length===p.size,h=new Map;for(let T of f)for(let P of p.get(T)??[])h.has(P)||h.set(P,T);let x=(T,P)=>d("Loaded squashed diff",{ref:e.ref.trim().toUpperCase(),from:c,to:s,commits:f.length,files:T.map(M=>({...M,sha:h.get(M.path)??s})),contiguous:g,overlappingPaths:P}),b,R=[];if(!g){let T=Gh(f.map(M=>p.get(M)??new Set)),P=Gh([...p.entries()].filter(([M])=>!m.has(M)).map(([,M])=>M));if(T.size===0)return x([],[]);b=[...T],R=[...T].filter(M=>P.has(M)).sort()}let S=await Vh(n,c,s,b);if(a(S))return l(S.message);let A=await zh(n,S.value);return a(A)?l(A.message):x(A.value,R)};var CC=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,qa=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let r=0;r<t.length;r++){if(t[r]!=="\\"){n+=t[r];continue}let o=t[++r];if(o==="n")n+=`
|
|
78
|
+
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},Kh=e=>{let t=qa(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},jd=e=>{let t=[],n=null,r=0,o=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
|
|
79
|
+
`)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=qa(m.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let c=n,u=c.lines.length===0;if(u&&i.startsWith("--- ")){let m=Kh(i.slice(4));m&&(c.oldPath=m);continue}if(u&&i.startsWith("+++ ")){let m=Kh(i.slice(4));m&&(c.path=m);continue}if(u&&i.startsWith("rename from ")){c.oldPath=qa(i.slice(12));continue}if(u&&i.startsWith("rename to ")){c.path=qa(i.slice(10));continue}if(u&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){c.binary=!0,c.lines.push({kind:"note",text:"Binary file"});continue}let p=CC.exec(i);if(p){r=Number(p[1]),o=Number(p[3]),c.lines.push({kind:"hunk",text:i});continue}if(!u){if(i.startsWith("\\")){c.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){c.added++,c.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){c.removed++,c.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){c.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&c.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},_d=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null;var $d=e=>e.flatMap(t=>[{kind:"file",text:`${_d(t)?`${_d(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),Ya=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},Ud=(e,t,n)=>{let r=t.map(i=>Xs(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=Ya(e),s=new Set;return e.forEach((i,c)=>{let u=i.newLine;if(u===void 0)return;let p=o[c]?.file;r.some(m=>m.filePath===p&&m.start<=u&&u<=m.end)&&s.add(c)}),s},qh=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,NC=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,Yh=e=>{let t=NC.exec(e);if(!t)return null;let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,r),end:Math.max(n,r),note:e.slice(t[0].length)}},Xh=(e,t)=>Ya(e)[t]?.file??null,Jh=(e,t,n,r)=>{let o=Ya(e),s=u=>e.findIndex((p,m)=>o[m]?.file===t&&(p.kind==="added"||p.kind==="context")&&p.newLine===u),i=s(n),c=s(r);return i===-1||c===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:Hd(e,i,c)},Hd=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let c=g=>(g.kind==="added"||g.kind==="context")&&g.newLine!==void 0;if(!c(s)||!c(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let u=Ya(e),p=u[r],m=u[o];if(p.file!==m.file)return{ok:!1,reason:"A comment covers one file at a time"};if(p.hunk!==m.hunk)return{ok:!1,reason:"A comment covers one hunk at a time"};let f=e.slice(r,o+1).filter(c);return{ok:!0,value:{filePath:p.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(g=>g.text).join(`
|
|
80
|
+
`)}}};import{existsSync as zd}from"node:fs";import{chmod as Kd}from"node:fs/promises";import Ja from"node:path";import{spawn as AC,spawnSync as TC}from"node:child_process";import wC from"node:os";import Qh from"node:path";import{ulid as MC}from"ulid";function Wd(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function PC(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Xa(){let{preferredEditor:e}=V(),t=[e?PC(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Gd(e){let[t=""]=Wd(e);return/(^|\/)code(-insiders)?$/.test(t)}function Zh(e,t){let[n="",...r]=Wd(e);return{command:n,args:[...r,...t]}}function ey(e,t){return Zh(e,Gd(e)?["--wait",t]:[t])}function LC(e,t,n,r="new"){return Zh(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function ty(e){let t=Qh.join(wC.tmpdir(),"epiq");ot.mkDir(t);let n=Qh.join(t,MC());ot.writeToFile(n,e??"");let r=Xa();for(let o of r){let{command:s,args:i}=ey(o,n);if(!s)continue;let c=TC(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let u=ot.readFile(n);if(u==null)return l("Unable to read edited file");let p=u.replace(/\r?\n$/,"");return d("Successfully edited",p)}}return l("Unable to open editor")}var kC=new Set(["vim","vi","nvim","nano","pico","ed"]);function DC(e){let[t=""]=Wd(e),n=t.split("/").pop()??t;return kC.has(n)}var BC=600;function ny({command:e,args:t},n){return new Promise(r=>{if(!e){r(l(`"${n}" is not a usable editor command`));return}let o=AC(e,t,{stdio:"ignore",detached:!0}),s=!1,i=u=>{s||(s=!0,clearTimeout(c),r(u))};o.on("error",u=>i(l(u.message))),o.on("exit",u=>{i(u===0?d("Opened editor",!0):l(`"${n}" exited with code ${u}`))});let c=setTimeout(()=>{o.unref(),i(d("Opened editor",!0))},BC)})}function OC(e,t){return DC(e)?Promise.resolve(l(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):ny(ey(e,t),e)}function Vd(e,t,n,r="new"){return ny(LC(e,t,n,r),e)}async function ry(e){let t=Xa();if(t.length===0)return l("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=l("Unable to open editor");for(let r of t){let o=await OC(r,e);if(!a(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}import{chmodSync as FC,existsSync as _C,lstatSync as jC,mkdirSync as $C}from"node:fs";import UC from"node:os";import HC from"node:path";var Zs=(...e)=>{let t=HC.join(UC.tmpdir(),"epiq",...e);try{return _C(t)&&jC(t).isSymbolicLink()?l(`Refusing to write through a symlink at ${t}`):($C(t,{recursive:!0,mode:448}),FC(t,448),d("Prepared private temp dir",t))}catch(n){return l(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var WC=async(e,t)=>{let n=await U({cwd:e,args:["show",t]});if(a(n))return l(n.message);let r=Zs("commit-diffs");if(a(r))return l(r.message);let o=Ja.join(r.value,`${t}.diff`);return zd(o)||(ot.writeToFile(o,n.value.stdout),await Kd(o,292)),ry(o)},GC=12,VC=800,oy=async(e,t,n)=>{let r=await U({cwd:e,args:["show",`${t}:${n}`]});return a(r)?"":r.value.stdout},zC=async(e,t)=>{let n=await U({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(a(n))return l(n.message);let r=n.value.stdout.split(`
|
|
81
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?l("No changed files found for this commit"):d("Listed changed files",r)},KC=async(e,t,n)=>{let r=await zC(e,t);if(a(r))return l(r.message);let o=r.value;if(o.length>GC)return l(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Zs("commit-diffs",t);if(a(s))return l(s.message);let i=s.value,c=await Promise.all(o.map(async(g,h)=>{let[x,b]=await Promise.all([oy(e,`${t}~1`,g),oy(e,t,g)]),R=Ja.basename(g),S=Ja.join(i,String(h),"before",R),A=Ja.join(i,String(h),"after",R);return zd(S)||(ot.writeToFile(S,x),await Kd(S,292)),zd(A)||(ot.writeToFile(A,b),await Kd(A,292)),{beforePath:S,afterPath:A}})),[u,...p]=c;if(!u)return l("No changed files found for this commit");let m=await Vd(n,u.beforePath,u.afterPath,"new");if(a(m)||p.length===0)return m;await new Promise(g=>setTimeout(g,VC));let f=await Promise.all(p.map(({beforePath:g,afterPath:h})=>Vd(n,g,h,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return m},ei=async e=>{if(!jo(e.sha))return l("Invalid commit sha");let t=sn(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=Xa()[0];if(r&&Gd(r)){let o=await KC(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return WC(n,e.sha)};import{Box as an,Text as qn}from"ink";import Fe,{useEffect as Jd,useMemo as ly,useRef as XC,useState as JC}from"react";var Qa=(e,t,n)=>{let r=[],o=Ea(()=>{for(let s=0;s<t;s++){let i=Dt(BigInt(s+1));if(!ve(i))continue;let c=N.createNode(Re.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));ve(c)&&r.push(c.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},Wo=e=>{N.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as qC}from"react";var el=null,Za=null,qd=new Set,sy=()=>{for(let e of qd)e()},Yd=e=>{el=e,sy()},tl=()=>el,iy={mark:null},Vr=e=>{Za=e,iy={mark:e},sy()};var Xd=e=>Za&&Za.sha===e?Za.row:null,ay=()=>qC(e=>(qd.add(e),()=>{qd.delete(e)}),()=>iy),yr=()=>{let{contextNode:e}=v();return el&&el.sha===e.id?e.id:null};import QC from"string-width";var Qd=(e,t)=>`${e}::patch::${t}`,ZC=e=>{switch(e){case"added":return y.green;case"removed":return y.red;case"hunk":return y.accent;case"file":return y.primary;default:return y.secondary2}},cy=(e,t)=>{let n=QC(e);return n>=t?e:e+"\xA0".repeat(t-n)},eN=e=>e==="added"?"+":e==="removed"?"-":" ",dy=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function uy({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=JC({state:"loading"});Jd(()=>{let T=!0;return i({state:"loading"}),Bd({sha:t}).then(P=>{T&&i(a(P)?{state:"failed",message:P.message}:{state:"loaded",rows:$d(jd(P.value))})}),()=>{T=!1}},[t]);let c=s.state==="loaded"?s.rows:null,u=c!==null&&c.length>4e3,p=XC([]);Jd(()=>(Wo(p.current),p.current=c&&!u?Qa(t,c.length,T=>Qd(t,T)):[],()=>{Wo(p.current),p.current=[]}),[t,c,u]),Jd(()=>(Yd(c?{sha:t,rows:c}:null),Vr(null),()=>{Yd(null),Vr(null)}),[t,c]);let{selectedIndex:m}=ne(),{mark:f}=ay(),g=ly(()=>c?Ud(c,N.getCommentsByIssue(e.id),t):new Set,[c,t,e]),h=f&&f.sha===t?f.row:null,x=T=>h!==null&&T>=Math.min(h,m)&&T<=Math.max(h,m),b=ly(()=>c?Math.max(5,c.reduce((T,P)=>Math.max(T,dy(P).length),0)+2):5,[c]),R=Math.max(1,o-4),S=Math.max(8,r-b-6);if(s.state!=="loaded")return Fe.createElement(an,{flexDirection:"column",width:r,height:o,padding:1},Fe.createElement(qn,{color:y.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let A=T=>Fe.createElement(an,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Fe.createElement(qn,{color:y.secondary2,wrap:"truncate-end"},jn(`${t.slice(0,7)} ${n} \u2014 ${T}`,Math.max(8,r-6))));return s.rows.length===0?Fe.createElement(an,{flexDirection:"column",width:r,height:o},A("no changes"),Fe.createElement(an,{paddingX:1},Fe.createElement(qn,{color:y.primary},"This commit changed no files."))):u?Fe.createElement(an,{flexDirection:"column",width:r,height:o},A("too large to draw here"),Fe.createElement(an,{paddingX:1,flexDirection:"column"},Fe.createElement(qn,{color:y.primary},`${s.rows.length.toLocaleString()} lines of diff.`),Fe.createElement(qn,{color:y.secondary2},"Press o to open it in your editor."))):Fe.createElement(an,{flexDirection:"column",width:r,height:o},A(h===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),Fe.createElement(ut,{scrollByOne:!0,height:R,selectedIndex:m,itemHeight:1},s.rows.map((T,P)=>{let M=P===m,O=ZC(T.kind);if(T.kind==="file")return Fe.createElement(an,{key:Qd(t,P),paddingX:1},Fe.createElement(qn,{backgroundColor:y.secondary,color:M?y.accent:O,bold:!0,wrap:"truncate-end"},cy(` ${jn(Qs(T.text),S)}`,S+b+1)));let W=x(P),Y=`${eN(T.kind)}${jn(Qs(T.text),S)}`;return Fe.createElement(an,{key:Qd(t,P),paddingX:1},Fe.createElement(an,{flexShrink:0},Fe.createElement(qn,{color:M||W?y.accent:y.secondary2,dimColor:!M&&!W,wrap:"truncate-end"},`${M?"\u276F":"\xA0"}${W?"\u258C":"\xA0"}${dy(T).padStart(b-2,"\xA0")}`)),Fe.createElement(an,{flexShrink:0},Fe.createElement(qn,{color:y.yellow,wrap:"truncate-end"},g.has(P)?"\u2502":"\xA0")),Fe.createElement(qn,{color:M?y.accent:O,backgroundColor:M||W?y.secondary:void 0,wrap:"truncate-end"},M||W?cy(Y,S+1):Y))})))}var rN=e=>Me(e,"diff"),py=e=>{for(let t of e)N.deleteNode(t.id)},oN=(e,t,n)=>Re.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),sN=(e,t)=>{let n=N.getNode(rN(e.id));if(!n||!at(n))return[];let r=t.map((o,s)=>oN(o,s,n.id)).map(o=>N.createNode(o)).filter(ve).map(({value:o})=>o).filter(at);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&$.navigate({contextNode:n,selectedIndex:0}),r},iN=e=>`+${e.insertions} -${e.deletions}`;function fy({ticket:e,width:t,height:n}){let[r,o]=nN({state:"loading"}),s=H(e.id);my(()=>{let x=!0;return o({state:"loading"}),Kn({ref:s}).then(b=>{x&&o(a(b)?{state:"failed",message:b.message}:{state:"loaded",commits:b.value})}),()=>{x=!1}},[s]);let i=tN([]),c=r.state==="loaded"?r.commits:null;my(()=>(py(i.current),i.current=c?sN(e,c):[],()=>{py(i.current),i.current=[]}),[e,c]);let{selectedIndex:u,contextNode:p}=ne(),m=c?.find(x=>x.sha===p.id)??null,g=Math.max(1,n-4),h=Math.max(12,t-34);return r.state!=="loaded"?Xe.createElement(zr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(Tn,{color:y.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):m?Xe.createElement(uy,{ticket:e,sha:m.sha,subject:m.subject,width:t,height:n}):r.commits.length===0?Xe.createElement(zr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(Tn,{color:y.primary},"No commits reference this ticket."),Xe.createElement(zr,{paddingTop:1},Xe.createElement(Tn,{color:y.primary},"Commits are matched by the"),Xe.createElement(Tn,{color:y.accent},` ${s} `),Xe.createElement(Tn,{color:y.primary},"prefix on their subject line."))):Xe.createElement(zr,{flexDirection:"column",width:t,height:n},Xe.createElement(zr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Xe.createElement(Tn,{color:y.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Xe.createElement(ut,{height:g,itemHeight:2,selectedIndex:u},r.commits.map((x,b)=>{let R=b===u,S=x.subject.length>h?x.subject.slice(0,h-1)+"\u2026":x.subject;return Xe.createElement(zr,{key:x.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Xe.createElement(Tn,{color:y.accent},R?"\u276F ":" "),Xe.createElement(zr,{paddingLeft:1},Xe.createElement(Tn,{color:y.secondary2},`${x.sha.slice(0,7)} `),Xe.createElement(Tn,{color:R?y.accent:y.primary},S),Xe.createElement(Tn,{color:y.secondary2},` ${iN(x)} ${fr(x.time)}`)))})))}import{Box as nl,Text as aN}from"ink";import Yn from"react";var gy=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=ne(),{title:o}=t,s=t.parentNodeId?N.getNode(t.parentNodeId):void 0,i=s&&_(s)?o===Ne.ASSIGNEES?s.props.assignees??[]:o===Ne.TAGS?(s.props.tags??[]).filter(c=>N.getTag(c)):[]:[];return Yn.createElement(nl,{alignItems:"center",paddingTop:1},Yn.createElement(nl,{minWidth:12},Yn.createElement(Ct,{isSelected:n}),Yn.createElement(aN,{color:n?y.accent:y.secondary2},o,":")),Yn.createElement(nl,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let p=r.id===t.id&&u===e;return Yn.createElement(nl,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Yn.createElement(Ct,{isSelected:p}),o===Ne.ASSIGNEES?Yn.createElement(mr,{isSelected:p,id:c}):o===Ne.TAGS?Yn.createElement(Do,{isSelected:p,id:c}):null)})))};import{Box as Go,Text as tu}from"ink";import Wt,{useEffect as lN,useMemo as nu,useRef as cN}from"react";var Zd=e=>Math.max(5,String(Math.max(e,1)).length+3),hy=(e,t)=>Math.max(0,e-6-Zd(t));var eu=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var dN="\u2029",yy=(e,t)=>`${e}::inline-line::${t}`,ru=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=ne(),u=nu(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=nu(()=>u.join("\0"),[u]),m=cN([]);lN(()=>(Wo(m.current),m.current=Qa(e,u.length,b=>yy(e,b)),()=>{Wo(m.current),m.current=[]}),[e,p]);let f=Zd(u.length),g=hy(s,u.length),x=nu(()=>kd(u).map(b=>{if(b.kind==="code"||b.kind==="caption")return{...b,text:jn(b.text,g)};if(b.kind==="text"||b.kind==="heading"){let R=b.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...b,spans:Js(jn(R,g))}}return b}),[u,g]).map((b,R)=>{let S=c.id===e&&i===R;return Wt.createElement(Go,{key:yy(e,R)},Wt.createElement(Go,{flexShrink:0},Wt.createElement(tu,{color:S?y.primary:y.secondary2,dimColor:!S},`${R+1} `.padStart(f,"\xA0"))),b.kind==="blank"?Wt.createElement(tu,{backgroundColor:S?"gray":void 0},dN):Wt.createElement(Go,null,Wt.createElement(Dd,{line:b,width:b.kind==="code"?g:0,wrap:"truncate-end"})))});return Wt.createElement(Go,{flexDirection:"column",paddingTop:1},Wt.createElement(Go,null,Wt.createElement(Ct,{isSelected:o}),Wt.createElement(tu,{color:o?y.accent:y.secondary2},t)),Wt.createElement(Go,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Wt.createElement(ut,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))};var mN=e=>Me(e,"description"),pN=e=>Me(e,"comments"),fN=e=>Me(e,"history"),gN=e=>Me(e,"diff"),hN=e=>Me(e,"attachments"),vy=({ticket:e,height:t})=>{let n=zo(()=>yh(e),[e]),{selectedIndex:r,contextNode:o}=ne(),s=process.stdout.columns||120,i=zo(()=>mN(e.id),[e.id]),c=zo(()=>pN(e.id),[e.id]),u=zo(()=>fN(e.id),[e.id]),p=zo(()=>gN(e.id),[e.id]),m=zo(()=>hN(e.id),[e.id]),f=N.getAttachmentsByIssue(e.id).length,g=o.id===e.id,h=o.id===c||o.parentNodeId===c,x=o.id===u||o.parentNodeId===u,b=o.id===m||o.parentNodeId===m,R=o.id===p||o.parentNodeId===p,S=le(e.id);if(h){let X=t-3;return At.createElement(Vo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},At.createElement(jh,{ticket:e,width:s,height:X}))}if(b){let X=t-3;return At.createElement(Vo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},At.createElement(Eh,{ticket:e,width:s,height:X}))}if(R){let X=t-3;return At.createElement(Vo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},At.createElement(fy,{ticket:e,width:s,height:X}))}if(x){let F=N.getNode(u),X=F&&at(F)?F.props.value??"":"",Ve=eu(t);return At.createElement(Vo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},F?At.createElement(ru,{id:F.id,label:"Event log",text:X,selected:!1,maxWidth:s,rows:Ve}):null)}let A=[u,p,c,m],T=F=>A.includes(F),P=S.reduce((F,X)=>Is(X)?F+1:F,0),M=S.reduce((F,X)=>T(X.id)?F+1:F,0),O=S.findIndex(F=>T(F.id)),W=eu(t,P,M),Y=(F,X,Ve,Qn)=>At.createElement(Vo,{key:F.id,paddingTop:X===O?1:0},At.createElement(Ct,{isSelected:Ve}),At.createElement(uN,{backgroundColor:y.secondary,color:Ve?y.accent:y.primary},Qn)),xe=(F,X,Ve)=>F.id===i?At.createElement(ru,{key:F.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:X,maxWidth:s,rows:W}):Is(F)?At.createElement(gy,{key:F.id,parent:F,selected:X,selectedIndex:r}):F.id===c?Y(F,Ve,X,` Comments (${n}) \u203A\u203A `):F.id===m?Y(F,Ve,X,` Attachments (${f}) \u203A\u203A `):F.id===u?Y(F,Ve,X," History \u203A\u203A "):F.id===p?Y(F,Ve,X," Diff \u203A\u203A "):null;return At.createElement(Vo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((F,X)=>xe(F,g&&r===X,X)))};var vN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,p=u===oe.TICKET||u===oe.FIELD_LIST||u===oe.FIELD,m=u===oe.BOARD||u===oe.SWIMLANE,f=u===oe.TICKET?t:r.find(R=>R.context===oe.TICKET),g=Math.floor(c/3),h=Math.floor(c/Math.max(e.length,1)),x=Math.min(h,g),b=s==="dense";return rl.createElement(yN,{flexDirection:"row",height:i},m&&e.map((R,S)=>{let A=t.id===R.id,T=A?n:-1,P=t.context===oe.BOARD&&n===S;return rl.createElement(hh,{key:R.id,height:i,width:x,swimlane:R,isSelected:P,isDense:b,isFocused:A,listSelectedIndex:T,mode:o})}),p&&f&&rl.createElement(vy,{height:i,ticket:f}))},ol=rl.memo(vN);import{render as IN}from"ink";import{Writable as EN}from"node:stream";var ti=e=>String(e).padStart(2,"0"),SN=e=>{let t=e.getUTCFullYear(),n=ti(e.getUTCMonth()+1),r=ti(e.getUTCDate()),o=ti(e.getUTCHours()),s=ti(e.getUTCMinutes()),i=ti(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},RN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",CN=async(e,{width:t,height:n})=>{let r="",o=new EN({write(i,c,u){let p=NN(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(r=p),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=IN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},NN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xy=async()=>{let{viewMode:e}=V(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(S=>S.context==="BOARD");if(!i)return l("No board found to export");let c=120,u=40,p=await CN(xN.createElement(ol,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&yn(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!p)return l("Failed to render board export");let m=$i(process.cwd());if(a(m))return l("Unable to export, epiq root not found");let f=new Date,g=SN(f),h=`board_${RN(i.title)}_${g}.md`,x=tp(m.value);by.mkdirSync(x,{recursive:!0});let b=bN.join(x,h),R=`# Board - ${i.title}
|
|
82
82
|
Date: ${f.toISOString()}
|
|
83
83
|
|
|
84
84
|
\`\`\`text
|
|
85
|
-
${
|
|
85
|
+
${p}
|
|
86
86
|
\`\`\`
|
|
87
|
-
`;return
|
|
88
|
-
`).map(
|
|
87
|
+
`;return by.writeFileSync(b,R,"utf8"),d("Exported board layout",b)};import{useSyncExternalStore as ZW}from"react";var sl,AN=new Set,Iy=()=>{for(let e of AN)e()};var vr=()=>{if(!sl)throw new Error("Ui state not initialized. Call initUiState() first.");return sl};var Ey=(e={})=>(sl=e,Iy(),d("UX state initialized",null)),TN=e=>{let t=vr();return sl=e(t),Iy(),d("UX state updated",null)},br=e=>TN(t=>({...t,...e}));import{ulid as ou}from"ulid";var Sy=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=le(t.id)[n];if(e.modifier===kt.DESCRIPTION)return MN();if(r&&Es(r))return wN(e);if(e.modifier===kt.TITLE){let o=pe();if(a(o))return l("Unable to resolve user ID");let s=r;if(!s)return l("Missing node");if(s.readonly)return l("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return l("Provide a title");let c=await Ie();return a(c)?c:B([{id:ou(),action:"edit.title",payload:{id:s.id,name:i},...D(o.value)}],c.value)}return l("Unknown edit command")},wN=async e=>{let t=pe();if(a(t))return l("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=le(n.id)[r];if(!o||!Es(o))return l("Select a comment first");if(o.readonly)return l("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return l("Unable to resolve comment issue");let i=v().nodes[s];if(!i||!_(i))return l("Unable to resolve comment issue");if(i.readonly)return l("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=N.getComment(c);if(!u||u.deleted)return l("Unable to resolve comment");if(u.issue!==i.id)return l("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return l("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let p=e.inputString.trim();if(!p)return l("Provide a comment");let m=await Ie();if(a(m))return m;let f=m.value;return B([{id:ou(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:p},...D(t.value)}],f)},MN=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let t=await Ie();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=yt([...r,o],"TICKET");if(a(s))return l("Edit target must be an issue");let i=s.value;if(!_(i))return l("Edit target must be an issue");if(i.readonly)return l("Cannot edit readonly issue");let c=le(i.id).find(f=>f.title===Ne.DESCRIPTION);if(!c)return l("No target found");if(c.readonly)return l("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return l("Selected field is not editable text");let p=ty(u);if(a(p))return l("Failed to edit field");let m=p.value;return m===u?d("No changes made",null):B([{id:ou(),action:"edit.description",payload:{id:i.id,md:m},...D(e.value)}],n)};import LN from"node:fs";import iu from"node:path";import su from"node:fs";import PN from"node:path";var Ry=async e=>{let t=PN.join(e,".gitignore"),n=su.existsSync(t)?su.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
88
|
+
`).map(u=>u.trim()),s=r.filter(u=>!o.some(p=>p===u||p===u.replace(/\/$/,"")||p==="/"+u||p==="/"+u.replace(/\/$/,"")));if(s.length===0)return d("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
89
89
|
`);return n=n.trimEnd()+`
|
|
90
90
|
|
|
91
|
-
${
|
|
92
|
-
`,
|
|
93
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
94
|
-
`));let o;try{o=JSON.parse(r.value.stdout)}catch(x){return
|
|
95
|
-
`));let
|
|
96
|
-
`,"utf8"),ti.renameSync(p,s)}catch(f){try{ti.rmSync(p,{force:!0})}catch{}return c(`Unable to write ${ni}: ${f instanceof Error?f.message:String(f)}`)}return u("Stored command history",null)};var TN=e=>e.some(t=>t.action==="init.workspace"),Ny=async(e,t)=>{let n=Ue(e);return a(n)?c(n.message):ls({cwd:t,branch:n.value})},wN=e=>{let t=me(process.cwd());if(a(t))return!1;let n=he({repoRoot:t.value});return!a(n)&&n.value===e},el=async e=>{let t=he({repoRoot:e});if(a(t))return tn(3,t.message);let n=t.value,r=await dr({repoRoot:e,stateBranchRoot:n,stateBranchName:Bi().stateBranch});if(a(r))return tn(3,r.message);let o=Zt(n);if(a(o))return tn(3,o.message);if(!TN(o.value.events)){let p=await Hs({worktreeRoot:n,operation:"boot pull",fn:()=>Ta(n,()=>Ny(e,n))});if(a(p)?logger.info(3,p.message):p.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(p.value)&&logger.info(3,p.value.message),o=Zt(n),a(o))return tn(3,o.message)}let{events:s,unreadable:i}=o.value,l=en(s,i);if(a(l))return tn(4,l.message);w({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let d=Ji({root:e});a(d)&&logger.info(d.message);let m=Ry({root:e});return a(m)&&logger.info(m.message),mf(a(m)?[]:m.value),u("Loaded project",void 0)},MN=async e=>{let t=he({repoRoot:e});if(a(t))return c(t.message);let n=t.value,r=await Bn({repoRoot:n});if(a(r))return c(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await Hs({worktreeRoot:n,operation:"boot pull",fn:()=>Ta(n,()=>(To("Pulling"),Ny(e,n)))});if(a(o))return Ve(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return as(s.message)?(Ca("Offline"),u("Offline",void 0)):Ve(s.message);if(!s.value)return jr("Already synced"),u("Already synced",void 0);if(!wN(n))return u("Project changed during the pull",void 0);let i=gd(n);return a(i)?i:(jr("Pulled"),u("Pulled and reloaded",void 0))},tl=e=>{MN(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${wo(t)}`)})},Ay=()=>{let e=en([]);return a(e)?tn(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var LN=e=>e==="~"||e.startsWith("~/")?Ty.join(PN.homedir(),e.slice(1)):e,kN=(e,t)=>{let n=e.trim();if(!n)return c("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):c(`No recent project #${n}`)}let r=me(Ty.resolve(LN(n)));return a(r)?c(`No epiq project at ${n}`):u("Resolved project path",r.value)},wy=async()=>{let e=aa();if(Q(""),v().hasProjectDefinition)return c("Already in a project; run epiq from another directory");let t=$n({exclude:process.cwd()}),n=a(t)?[]:t.value,r=kN(e,n);if(a(r))return c(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return c(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await el(o);return a(i)?(process.chdir(s),c(i.message)):(tl(o),u(`Opened ${Io(o)}`,null))};var nl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=ba(n,t);if(a(s))return c(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,d=sn();if(a(d))return d;let m=Qt(i),{fatal:p,skipped:f}=In(m);if(p.length>0)return sn(),w(o),c(p.map(y=>y.message).join(", "));En(f);let g=v().nodes[e];return g?(U.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(sn(),w(o),c("Board did not exist at that date"))};var My=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)};var DN=20,BN=16,ON=150,rl=null,ol=null;var Kr=()=>{rl!==null&&(clearInterval(rl),rl=null),ol!==null&&(clearTimeout(ol),ol=null)},Py=()=>{Kr(),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Ly=({events:e,startTime:t,durationMs:n})=>{Kr();let r=e.length,o=ho(e.map(f=>er(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=My(o),l=Math.max(1,Math.round(n*DN/1e3)),d=Math.max(Math.round(n/l),BN),m=0,p=0;w({mode:I.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),rl=setInterval(()=>{m++;let f=m/l,g=[],y,x;for(;p<r&&i[p]<=f;){let R=e[p],S=Os(R);if(a(S)){if(Ao(S)){p++;continue}Py();return}g.push(...od(R)),y=R,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let S=Os(e[p]);if(a(S)&&!Ao(S))break}let R=v().replay;w({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),Kr(),ol=setTimeout(Py,ON);return}let b=v().replay;w({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:y?x??b?.currentTime??t:b?.currentTime??t,currentLabel:y?sl(y):b?.currentLabel??"",flashNodeIds:y?[...new Set(g)]:b?.flashNodeIds??[]}})},d)};var ky=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await qt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=he({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ae().commandMeta;if(Kr(),r==="now"){let l=cr(n.value);if(a(l))return c(l.message);let d=sn();if(a(d))return d;let m=Qt(l.value),{fatal:p,skipped:f}=In(m);return p.length>0?c(p.map(g=>g.message).join(", ")):(En(f),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=xa(n.value);if(a(l))return l;let d=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),m=d===void 0?null:er(d),p=(d===void 0?null:l.value.get(d.id)??null)??(m===null?null:gs(m));if(p===null)return c(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=Lr(r||o.trim());if(!l)return c("Invalid peek date");s=l.getTime()}let i=nl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(w({mode:I.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var Dy=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await qt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=he({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ae().commandMeta,{dateInput:s,durationInput:i}=na(r,o);if(Kr(),v().syncStatus.status==="syncing")return c("Cannot replay while syncing, try again in a moment");let l=Lr(s);if(!l)return c("Invalid replay date");let d=i?ta(i):15e3;if(d===null)return c("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=v(),f=nl({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(sn(),w(p),u("Nothing to replay from that point",!0)):(Ly({events:g,startTime:m,durationMs:d}),u("Replaying board history",!0))};import{spawn as _N}from"node:child_process";var $N=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},By=async e=>new Promise(t=>{let{command:n,args:r}=$N();try{let o=_N(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(c(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):c(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(c(`Clipboard tool not available (${n})`))}});var ri=async(e,t)=>{if(!e.trim())return c(`Nothing to copy: ${t} is empty`);let n=await By(e);return a(n)?n:u(`Copied ${t} to clipboard`,null)},Oy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=Es({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return c("Nothing selected to copy from");switch(e.modifier){case Xe.REF:return ri(H(o.id),"ref");case Xe.TITLE:return ri(o.title,"title");case Xe.DESCRIPTION:return r?ri(r.props?.description??"","description"):c("No issue in scope");case Xe.TAGS:{if(!r)return c("No issue in scope");let s=hn(r).map(({name:i})=>i);return ri(s.join(", "),"tags")}case Xe.ASSIGNEES:{if(!r)return c("No issue in scope");let s=yn(r).map(({name:i})=>i);return ri(s.join(", "),"assignees")}default:return c("Yank one of: ref, title, description, tags, assignees")}};var Fy=async()=>{Q(""),w({mode:I.DEFAULT});let e=xe();if(a(e))return c(e.message);if(e.value.syncStatus.status==="syncing")return c("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Ma();return a(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:I.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as _y}from"ulid";var $y=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to resolve child to delete");let o=await Se();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=_(t)?t.id:t.parentNodeId;if(!i)return c("Unable to resolve comment issue");let l=v().nodes[i];if(!l||!_(l))return c("Unable to resolve comment issue");let d=l.log?.filter(ah).find(m=>m.payload.id===s);return d?d.payload.author!==e.value.userId?c("You can only delete your own comments"):B([{id:_y(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],o.value):c("Unable to resolve comment")}return B([{id:_y(),action:"delete.node",payload:{id:r.id},...D(e.value)}],o.value)};import{ulid as UN}from"ulid";var Uy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to close issue, no target found");if(!_(r))return c("Cannot close in this context");let o=v().nodes[ye];if(!o)return c("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return c("Issue is already closed");let s=await Se();if(a(s))return s;let i=s.value,l=Sn(o.id,r.id,{at:"end"},e.value,i);if(a(l))return l;let d=B([{id:UN(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...D(e.value)}],i);return a(d)?d:u("Issue closed",null)};import{ulid as jN}from"ulid";var il=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};var jy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):Nt(r.id,"TICKET");if(a(o))return c("Cannot reopen in this context");let s=o.value,i=v().nodes[ye];if(!i)return c("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return c("Issue is not closed");if(!_(s))return c("Target node is not issue");let l=il(s);if(!l)return c("Unable to resolve previous parent from issue history");if(l===i.id)return c("Previous parent resolves to closed swimlane");let d=v().nodes[l];if(!d)return c("Previous parent no longer exists");let m=await Se();if(a(m))return m;let p=m.value,f=Sn(d.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let g=B([{id:jN(),action:"reopen.issue",payload:{id:s.id,parent:d.id,rank:f.value},...D(e.value)}],p);return a(g)?g:u("Issue reopened",null)};import{ulid as HN}from"ulid";var Hy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Missing node");if(r.readonly)return c("Cannot rename readonly node");let o=aa();if(!o)return c("Provide a title");let s=await Se();return a(s)?s:B([{id:HN(),action:"edit.title",payload:{id:r.id,name:o},...D(e.value)}],s.value)};import{ulid as WN}from"ulid";var Wy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let o=N.findTagByName(r);if(!o)return c(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return c("Invalid untag target");let i=Nt(s.id,"TICKET");if(a(i))return c("Unable to untag issue in this context");let l=i.value;if(!_(l))return c("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return c("Issue is not tagged with that tag");let m=await Se();return a(m)?m:B([{id:WN(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...D(e.value)}],m.value)};import{ulid as eu}from"ulid";var Gy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let{selectedNode:o}=v();if(!o)return c("Invalid tag target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to tag issue in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=await Se();if(a(l))return l;let d=N.findTagByName(r),m=d?.id??eu();return(i.props.tags??[]).includes(m)?c("Already tagged with that tag"):B([...d?[]:[{id:eu(),action:"create.tag",payload:{id:m,name:r},...D(e.value)}],{id:eu(),action:"add.issue.tag",payload:{id:i.id,tag:m},...D(e.value)}],l.value)};import{ulid as tu}from"ulid";var oi=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},Vy=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=et(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ye(s,i?.name),resolved:!0}:{...Ye(o||e,e),resolved:!1}};var al=e=>{let{eventLog:t=[],contributors:n}=v();return oi({events:t,registry:n,logFileNames:lr(e)})};var zy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return c("Provide an assignee");let{selectedIndex:i,contextNode:l}=v(),d=de(l.id)[i];if(!d)return c("Invalid assign target");let m=Nt(d.id,"TICKET");if(a(m))return c("Unable to assign issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Se();if(a(f))return f;let g=al(f.value),y=!o&&s.toLowerCase()==="me",x,b;if(y)x=e.value.userId,b=g.find(T=>T.id===x)?.name??e.value.userName;else{let T=g.filter(P=>P.name===s);if(T.length>1)return c(`"${s}" matches ${T.length} contributors (${T.map(P=>P.id).join(", ")}). Assign from the GUI to choose by id.`);let A=T[0];if(!A&&!o)return c(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=A?.id??tu(),b=A?.name??s}if((p.props.assignees??[]).includes(x))return c("Assignee already assigned");let S=!!v().contributors[x];return B([...S?[]:[{id:tu(),action:"create.contributor",payload:{id:x,name:b},...D(e.value)}],{id:tu(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...D(e.value)}],f.value)};import{ulid as GN}from"ulid";var Ky=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return c("Invalid unassign target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to unassign in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=i.props.assignees??[],d=r.toLowerCase()==="me",m=await Se();if(a(m))return m;let p=d?l.filter(g=>g===e.value.userId):al(m.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(p.length>1)return c(`"${r}" matches ${p.length} assignees (${p.join(", ")}). Unassign from the GUI to choose by id.`);let f=p[0];return f?B([{id:GN(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],m.value):c(d?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as qy}from"ulid";var VN=e=>{let t=e.trim(),n=hr(),r=n?Fh(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Ka();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=_h(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=$h(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:yh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},Yy=async e=>{let t=VN(e.inputString);if(!t.ok)return c(t.reason);let{md:n,anchored:r}=t;if(!n)return c("Provide a comment");if(n.length>4e3)return c(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=pe();if(a(o))return c("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),l=yt([...s,i],"TICKET");if(a(l))return c("Edit target must be an issue");let d=l.value;if(!d)return c("Invalid comment target");let m=d.context==="TICKET"?u("Resolved ticket",d):Nt(d.id,"TICKET");if(a(m))return c("Unable to comment on issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Se();if(a(f))return f;let g=await B([{id:qy(),action:"add.issue.comment",payload:{id:qy(),issue:p.id,author:o.value.userId,md:n},...D(o.value)}],f.value);return r&&!a(g)&&Gr(null),g};import{ulid as JN}from"ulid";var ll=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",zN=e=>{let t=ht();return a(t)?ll({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:ll(t.value)},si=()=>{let e=pn();return a(e)?c(e.message):u("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:uo(e.value.autoSyncDebounceMs),blockedReason:zN(e.value)})},zo=e=>{let t=e.intervalMs===void 0?void 0:co(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return c(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=si();if(a(n))return n;let r=Bt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return c(r.message);je({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=si();return a(o)?u("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var Xy=()=>{let e=ae().commandMeta.inputString,t=co(e);if(t===null)return c(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=zo({intervalMs:t});return a(n)?n:u(`Auto sync interval set to ${t}ms`,null)};var Jy=()=>{let e=ae().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return c("Invalid response");let t=Lp(e),n=zo({enabled:t===!0});return a(n)?n:u(`Auto sync set to "${e}"`,null)};import{ulid as YN}from"ulid";var nu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),Qy="",Zy=new Map,KN=15e3;var qN=async(e,t)=>{let n=`${e} ${t??""}`,r=Zy.get(n);if(r&&Date.now()-r.at<_a(KN))return u("Cached author scan",r.authors);let o=await De({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${Qy}%ae`]});if(o.exitCode!==0)return c(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
97
|
-
`)){let l=i.lastIndexOf(Qy);if(l===-1)continue;let d=i.slice(0,l),m=et(i.slice(l+1));if(!tr(m))continue;let p=s.get(m)??{names:new Set,commits:0};d&&p.names.add(d),p.commits+=1,s.set(m,p)}return Zy.set(n,{at:Date.now(),authors:s}),u("Scanned repository authors",s)},wn=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await qN(e,t);if(a(o))return c(o.message);let s=o.value,i=new Map;for(let d of Object.values(r)){if(d.tombstoned)continue;let m=i.get(d.email)??new Set;m.add(d.contributor),i.set(d.email,m)}let l=new Set(n.flatMap(d=>nu(d??"")));return u("Found candidates",[...s.entries()].map(([d,m])=>({email:d,names:[...m.names],commits:m.commits,looksLikeYours:[...m.names].some(p=>nu(p).some(f=>l.has(f)))||nu(d.split("@")[0]??"").some(p=>l.has(p)),claimedBy:[...i.get(d)??[]]})).sort((d,m)=>d.looksLikeYours===m.looksLikeYours?m.commits-d.commits:Number(m.looksLikeYours)-Number(d.looksLikeYours)))},br=e=>e.filter(t=>t.claimedBy.length===0);var ev=()=>{let e=Tc();if(!e)return u("Nothing here to decline",null);let t=pn(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=Bt({declinedEmailBoards:r});return a(o)?c(o.message):(je({declinedEmailBoards:[...new Set([...V().declinedEmailBoards??[],e])]}),u("Declined",null))},tv=async()=>{let e=ae().commandMeta.inputString.trim();if(e==="none"){let R=ev();return a(R)?R:u("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=V();if(!t)return c("Set a username first with :config username");let o=xe();if(a(o))return c("Board is not loaded");let s=me(process.cwd());if(a(s))return c(s.message);let i=Ue(s.value),l=await wn({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(l))return l;let m=br(l.value);if(Eo(m.map(R=>R.email)),m.length===0){if(!Mp()){let R=ev();if(a(R))return R}return u("No unclaimed addresses in this history.",null)}if(!e)return w({mode:I.IDENTITY}),u("Opened identity",null);let p=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let R of p){let S=m.find(T=>T.email===et(R));if(!S){g.push(R);continue}f.includes(S)||f.push(S)}if(g.length>0)return c(`Not on the list: ${g.join(", ")}. Pick one of ${m.map(R=>R.email).join(", ")}.`);let y=he({repoRoot:s.value});if(a(y))return y;let x=f.map(R=>({id:YN(),action:"link.contributor.email",payload:{contributor:t,email:R.email},userId:t})),b=B(x,y.value);return a(b)?c(b.message):u(`Claimed ${f.map(R=>R.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as XN}from"ulid";var nv=()=>{let e=ae().commandMeta.inputString.trim(),{userId:t}=V();if(!t)return c("Set a username first with :config username");let n=xe();if(a(n))return c("Board is not loaded");let r=fn(n.value.emailLinks,t);if(r.length===0)return c("You have not claimed any addresses.");if(!e)return c(`Which one? ${r.join(", ")}.`);let o=r.find(d=>d===et(e));if(!o)return c(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=me(process.cwd());if(a(s))return s;let i=he({repoRoot:s.value});if(a(i))return i;let l=B([{id:XN(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(l)?c(l.message):u(`Unclaimed ${o}`,null)};var rv=()=>{let e=ae().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return c("Invalid response");let n=Bt({logLevel:e});return a(n)?n:(je({logLevel:e}),u(`Auto sync set to "${e}"`,null))};var ov=e=>{let t=e.inputString.trim();switch(e.modifier){case ve.USERNAME:{if(process.env[kn])return c(`Cannot change the configured user while ${kn} names this process`);let n=pn();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||JN();if(!i||!l)return c("Unable to resolve user name or id");let d=Bt({userName:i,userId:l,preferredEditor:o??""});return a(d)?d:(je({userName:i,userId:l}),u(`Username set to "${i}"`,null))}case ve.EDITOR:{if(!t)return c("No editor provided");let n=Bt({preferredEditor:t});return a(n)?n:(je({preferredEditor:t}),u(`Editor configuration set to "${t}"`,null))}case ve.VIEW:{if(t!=="wide"&&t!=="dense")return c("Invalid view mode");let n=Bt({viewMode:t});return a(n)?n:(je({viewMode:t}),u(`View set to "${t}"`,null))}case ve.EMAILS:return tv();case ve.EMAILS_UNCLAIM:return nv();case ve.AUTOSYNC:return Jy();case ve.LOG_LEVEL:return rv();case ve.SYNC_DEBOUNCE_MS:return Xy();case ve.ATTACHMENT_MAX_KB:return Kp();default:return c("Unknown config command")}};var ru=()=>{let e=kp(),t=v().mode;if(!(t!==I.COMMAND_LINE&&t!==I.DEFAULT)){if(!e){w({mode:I.DEFAULT});return}w({mode:I.COMMAND_LINE}),Q(e)}};var cl=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:I.COMMAND_LINE,action:xy},{intent:G.Delete,description:"Delete the currently selected node",mode:I.COMMAND_LINE,action:$y,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:I.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ae().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Oe(C.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return c("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:I.DEFAULT})),u("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:I.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return vr({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:I.HELP}),u("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:I.COMMAND_LINE,action:Uy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:I.COMMAND_LINE,action:jy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:I.COMMAND_LINE,action:fy,onSuccess:ru},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:I.COMMAND_LINE,action:wy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:I.COMMAND_LINE,action:Iy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:I.COMMAND_LINE,action:Hy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:I.COMMAND_LINE,action:Wy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:I.COMMAND_LINE,action:Gy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:I.COMMAND_LINE,action:zy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:I.COMMAND_LINE,action:Ky,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:I.COMMAND_LINE,action:async(e,t)=>Yy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:I.COMMAND_LINE,action:Fy},{intent:G.Peek,description:"View board state at another point in time",mode:I.COMMAND_LINE,action:ky},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:I.COMMAND_LINE,action:Dy},{intent:G.Export,description:"Export the current board layout to markdown",mode:I.COMMAND_LINE,action:async()=>{let e=await ly();return a(e)?e:(w({mode:I.DEFAULT}),u("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:I.COMMAND_LINE,action:async()=>(U.exit(),u("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:I.COMMAND_LINE,action:async(e,t)=>uy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:I.COMMAND_LINE,action:async(e,t)=>Oy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:I.COMMAND_LINE,action:(e,t)=>ov(t),onSuccess:ru}];var QN=new Set(["peek","replay","filter","view-help","yank"]),jt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=ae();if(!n)return c("No command to confirm");if(!e&&r===bn.Invalid)return c("Invalid command");let i=La(n);df();let{readOnly:l}=v();if(l&&!QN.has(i))return Ts({status:Qn.Fail,message:"Command not available in readonly state",value:null});let d=cl.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!d)return Ts({status:Qn.Fail,message:"Command not found",value:null});let m;try{m=await d.action(d,{command:n,inputString:s,modifier:o})}catch(f){return Ts({status:Qn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(m))return Ts(m);let p=!e;if(uf({addToHistory:p,line:t}),p){let f=Cy({commands:ae().commandHistory});a(f)&&logger.info(f.message)}return d.onSuccess?.(),V().autoSync&&Pa(),m};var dl=[{intent:E.Exit,mode:I.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:I.COMMAND_LINE}),Q("move cancel"),jt({isForceExecutedBySystem:!0}))},{intent:E.InitMove,mode:I.DEFAULT,description:"[m] move",action:()=>(w({mode:I.COMMAND_LINE}),Q("move start"),jt({isForceExecutedBySystem:!0}))},{intent:E.ConfirmMove,mode:I.MOVE,description:"[m] confirm move",action:()=>(w({mode:I.COMMAND_LINE}),Q("move confirm"),jt({isForceExecutedBySystem:!0}))}],ul=[{intent:E.MovePreviousItem,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItem,mode:I.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move next"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MovePreviousItemJump,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move jump-previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItemJump,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move jump-next"),jt({isForceExecutedBySystem:!0})):c("No pending move")}],sv=[{intent:E.MoveToNextContainer,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move to-next"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveToPreviousContainer,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move to-previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")}];var iv={[ie.WORKSPACE]:[...dl,...ul],[ie.BOARD]:[...dl,...ul],[ie.SWIMLANE]:[...dl,...ul,...sv],[ie.TICKET]:[],[ie.FIELD]:[],[ie.FIELD_LIST]:[],[ie.TEXT]:[],[ie.COMMENT]:[]};import eA from"node:fs";import tA from"node:path";import{spawn as ZN}from"node:child_process";function av(e){let t=process.platform,o=ZN(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var lv=e=>{let t=me(process.cwd());if(a(t))return c("Unable to resolve project root");let n=he({repoRoot:t.value});if(a(n))return c(n.message);let r=Br(e.hash,e.ext),o=tA.join(ms(n.value),r);return eA.existsSync(o)?(av(o),u(`Opened ${e.name}`,null)):c("Attachment file not found \u2014 run :sync to fetch it")};var cv=()=>{Q("");let{pendingNavTarget:e}=yr();w({mode:I.DEFAULT}),e&&U.navigate(e),vr({pendingNavTarget:void 0})},dv=[{intent:E.ExitCommandLine,mode:I.HELP,action:()=>(cv(),u("Exiting help",null))},{intent:E.Exit,mode:I.HELP,action:()=>(cv(),u("Closed help",null))},{intent:E.NavPreviousItem,mode:I.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:E.NavNextItem,mode:I.HELP,action:()=>(U.navigateToNextItem(),u("Navigating to next help item",null))},{intent:E.NavPreviousItemJump,mode:I.HELP,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous help item",null))},{intent:E.NavNextItemJump,mode:I.HELP,action:()=>(U.jumpToNextItem(),u("Jumping to next help item",null))},{intent:E.NavToPreviousContainer,mode:I.HELP,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:E.NavToNextContainer,mode:I.HELP,action:()=>(U.navigateToNextContainer(),u("Navigating to next help container",null))}];var uv=()=>{Q(""),w({mode:I.DEFAULT})},mv=[{intent:E.Confirm,mode:I.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=So();return e?(w({mode:I.COMMAND_LINE}),Q(`config emails ${e}`),u("Proposed claim",null)):u("Nothing left to claim",null)}},{intent:E.ExitCommandLine,mode:I.IDENTITY,action:()=>(uv(),u("Closed identity",null))},{intent:E.Exit,mode:I.IDENTITY,description:"[esc] close",action:()=>(uv(),u("Closed identity",null))}];var nA=e=>{w({mode:I.COMMAND_LINE});let{pendingNavTarget:t}=yr();t&&U.navigate(t),vr({pendingNavTarget:void 0}),Q(`${e} `)},pv=()=>{Q("");let{pendingNavTarget:e}=yr();e&&U.navigate(e),vr({pendingNavTarget:void 0}),w({mode:I.DEFAULT})},fv=[{intent:E.InitCommandPalette,mode:I.DEFAULT,description:"[?] command palette",action:()=>{Q("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return vr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:I.PALETTE}),u("Opening command palette",null)}},{intent:E.Confirm,mode:I.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!nr(e))return c("Command only applicable on text nodes");if(e.props.disabled)return c("Command is not available in this context");let t=e.title;return t?(nA(t),u("Selected command",t)):u("No command selected",null)}},{intent:E.ExitCommandLine,mode:I.PALETTE,action:()=>(pv(),u("Exiting palette",null))},{intent:E.Exit,mode:I.PALETTE,action:()=>(pv(),u("Closed command palette",null))},{intent:E.NavPreviousItem,mode:I.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.PALETTE,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavToPreviousContainer,mode:I.PALETTE,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.PALETTE,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var gv=()=>{let e=hr();if(!e)return u("Nothing to comment on here",null);let t=Ka();if(!t||t.sha!==e)return c("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=kd(t.rows,jd(e)??r,r);return o.ok?(w({mode:I.COMMAND_LINE}),Q(`${C.COMMENT} ${Oh(o.value.start,o.value.end)} `),u("Commenting on a diff line",null)):c(o.reason)},hv=[{intent:E.InitCommandLine,mode:I.DEFAULT,description:"[:] write command",action:()=>(w({mode:I.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...dv,...mv,...fv,{intent:E.AddItem,mode:I.DEFAULT,description:"[n] new...",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.NEW} `),u("Adding new item",null))},{intent:E.Delete,mode:I.DEFAULT,description:"[d] delete",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.DELETE} `),u("Deleting item",null))},{intent:E.Confirm,mode:I.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Ie(e?.id??"")?.length){let r=e?N.getAttachment(e.id):void 0;if(r)return lv(r);if(hr())return gv();if(e?.title===Te.DESCRIPTION)return w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Propose command",!0);if(e?.title===Te.ASSIGNEES)return w({mode:I.COMMAND_LINE}),Q(`${C.ASSIGN} `),u("Propose command",!0);if(e?.title===Te.TAGS)return w({mode:I.COMMAND_LINE}),Q(`${C.TAG} `),u("Propose command",!0);if(t.title===Te.DESCRIPTION&&e?.context==="TEXT")return w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Propose command",!0)}return U.enterChildNode(),u("Entering context",null)}},{intent:E.OpenInEditor,mode:I.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===Pe(n,"diff")?e?.id:hr()??void 0;return o?Xs({sha:o}):u("Nothing here opens in an editor",null)}},{intent:E.MarkDiffLine,mode:I.DEFAULT,action:()=>{let e=hr();if(!e)return u("Nothing to mark here",null);let{selectedIndex:t}=v(),n=jd(e);return Gr(n===t?null:{sha:e,row:Math.max(0,t)}),u("Marked diff line",null)}},{intent:E.CommentOnDiffLine,mode:I.DEFAULT,action:()=>hr()?gv():u("Nothing to comment on here",null)},{intent:E.Yank,mode:I.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Te.DESCRIPTION?Xe.DESCRIPTION:e?.title===Te.TAGS?Xe.TAGS:e?.title===Te.ASSIGNEES?Xe.ASSIGNEES:Xe.REF,r=Oe(C.YANK).includes(t)?t:Xe.REF;return w({mode:I.COMMAND_LINE}),Q(`${C.YANK} ${r}`),u("Propose command",!0)}},{intent:E.EditTitle,mode:I.DEFAULT,description:"[r] rename title",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:E.EditDescription,mode:I.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Exiting context",null))},{intent:E.Exit,mode:I.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),u("Exiting context",null))},{intent:E.NavPreviousItem,mode:I.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.DEFAULT,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavPreviousItemJump,mode:I.DEFAULT,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous item",null))},{intent:E.NavNextItemJump,mode:I.DEFAULT,action:()=>(U.jumpToNextItem(),u("Jumping to next item",null))},{intent:E.NavToPreviousContainer,mode:I.DEFAULT,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.DEFAULT,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var rA=500,oA=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),yv=e=>{let t=oA(e);t&&ia(n=>(n+t).slice(0,rA))};var sA=[I.COMMAND_LINE,I.PALETTE],iA=e=>e==="edit title "?v().selectedNode?.title??"":"",aA=e=>[{intent:E.MoveCursorLeft,mode:e,action:()=>(Uc(-1),u("Moving cursor left",null))},{intent:E.MoveCursorRight,mode:e,action:()=>(Uc(1),u("Moving cursor right",null))},{intent:E.MoveCursorLeftOfWord,mode:e,action:()=>(jc("left"),u("Moving cursor left of word",null))},{intent:E.MoveCursorRightOfWord,mode:e,action:()=>(jc("right"),u("Moving cursor right of word",null))},{intent:E.AutoCompleteCommand,mode:e,action:()=>(ia((t,{remainder:n})=>{let r=n?t+n:t;return r+iA(r)}),u("Auto-completing command",null))},{intent:E.CaptureInput,mode:e,action:(t,{sequence:n})=>(yv(n??""),u("Capturing input",null))},{intent:E.EraseInput,mode:e,action:()=>(lf(),u("Erasing input",null))},{intent:E.EraseInputWord,mode:e,action:()=>(cf(),u("Erasing input word",null))}],vv=[{intent:E.Confirm,mode:I.COMMAND_LINE,action:()=>(jt(),u("Executing command",null))},{intent:E.ViewHelp,mode:I.DEFAULT,action:()=>(w({mode:I.HELP}),u("Viewing help",null))},...sA.flatMap(aA),{intent:E.ExitCommandLine,mode:I.COMMAND_LINE,action:()=>(pf(),w({mode:I.DEFAULT}),u("Exiting command line",null))},{intent:E.GetLastCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(ff(),u("Getting last command from history",null))},{intent:E.GetNextCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(gf(),u("Getting next command from history",null))}];var ou=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},bv=({keys:e})=>e.length===1?0:1,xv=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(ou).filter(r=>r!==null).sort((r,o)=>bv(r)-bv(o))};function Iv(e,t,n){let r=t[e];if(!r)return c("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?c("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Ev=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var At,su,iu=new Set,au=()=>{for(let e of iu)e()},cA=e=>(iu.add(e),()=>iu.delete(e));function lu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return c("derive(): contextNodeId is missing");if(!r)return c("derive(): rootNode is missing");if(!o[r])return c("derive(): unable to find root node");let l=o[t];if(!l)return c("Unable to derive state, contextNode not found");let d=Iv(t,o,r);if(a(d))return logger.error(d.message),d;let m=d.value,{context:p}=l,f=[...hv,...iv[p]??[],...vv],g=xv(f,n),y=Ev(f),x=dA(o,s),b=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:y,selectedNode:b,renderedChildrenIndex:x})}var v=()=>{if(!At)throw new Error("State not initialized. Call initWorkspaceState() first.");return At},xe=()=>At?u("Retrieved state",At):c("State not initialized. Call initWorkspaceState() first.");Np(e=>At?fn(At.emailLinks,e):[]);function Bs(e){su=e;let t=me(process.cwd()),n=!1;if(!a(t)){let s=Tt(t.value);if(a(s))return c(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:I.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=lu(r);return a(o)?o:(At=o.value,au(),u("State initialized",null))}var qr=!1,ii=null;function Fe(e){let t=v(),n=e(t);if(qr)return n.nodes!==t.nodes&&(xr=null),ii=n,At={...t,...n},u("State updated",null);let r=lu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,au(),u("State updated",null))}function va(e){if(qr)return u("Joined batch",e());qr=!0,ii=null,xr=new Set;let t=()=>{let n=ii;if(qr=!1,ii=null,n===null)return null;let r=lu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,au(),u("State updated",null))};try{let n=e(),r=t();return r&&a(r)?c(r.message):u("State updated",n)}finally{qr&&t()}}var hg=()=>qr,w=e=>Fe(t=>({...t,...e}));function Yr(e,t,n){if(!qr)return Fe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&xr?.add(i.parentNodeId),l.parentNodeId&&xr?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return ii=s,At={...r,...s},u("State updated",null)}var oe=()=>lA(cA,v,v),xr=null,Sv=null,dA=(e,t)=>{let n=At?.renderedChildrenIndex,r=n!==void 0&&xr!==null&&e===Sv&&t.length===0&&At?.filters.length===0,o;if(r){o={...n};let s=mg(e,xr);for(let i of xr){let l=s[i];l?o[i]=l:delete o[i]}}else o=ug(e,t);return Sv=e,xr=new Set,o},de=e=>v()?.renderedChildrenIndex[e]??[],sn=()=>su?Bs(su):c("Cannot reset state: no initial workspace found"),_t=()=>At!==void 0;var Nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return c("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return c(`No ancestor found for context: ${t}`)},cu=(e,t)=>{let{nodes:n}=v(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},Ir=(e,t)=>e?e.readonly?c({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:c("Node not found"),N={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.userId&&n.userId!==t)return c("Contributor is already linked to another user");let r={...n,userId:t},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){N.deleteNodes([e])},deleteNodes(e){e.length!==0&&Fe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create comment, missing issue");if(!_(t))return c("Can only comment on issues");let n=Yr("comments",e.id,{...e,deleted:!1});return a(n)?c("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return c("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return c("Unable to edit comment, missing issue");if(!_(r))return c("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Yr("comments",e,o);return a(s)?c("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return c("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Yr("comments",e,n);return a(r)?c("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create attachment, missing issue");if(!_(t))return c("Can only attach to issues");let n=Fe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?c("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return c("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Fe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?c("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return c("Edit target node not found");let o=Ir(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return c("Rename target node not found");let r=Ir(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("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["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Ie(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return c("Node not found");if(!s)return c("Target parent not found");if(r===e)return c("Cannot move root node");if(e===t)return c("Cannot move node into itself");let i=Ir(o,"move");if(i)return i;if(cu(t,e))return c("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),u("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return c("Node not found");if(r===e)return c("Cannot delete root node");let s=Ir(o,"delete");if(s)return s;let i=new Set,l=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of Ie(p.id))l(f.id)}};l(e);let d={...structuredClone(t)};for(let m of i){if(!d[m])return c("Unable to locate node to delete");d[m]={...d[m],isDeleted:!0}}return n?(w({nodes:d}),u("Successfully tomb stoned",o)):c("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return c("Contributor not found");let n={...t,name:bo,tombstoned:!0},r=Fe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?c("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.tombstoned)return c("Cannot rename a removed contributor");let r={...n,name:t},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to restore contributor"):u("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return c("Unable to link email, missing contributor");let r={email:et(e),contributor:t,authorId:n},o=hs(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return u("Email already linked",s);let i=Fe(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return a(i)?c("Unable to link email"):u("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=hs(e,t),o=v().emailLinks[r];if(!o)return c("Unable to unlink, no such link");if(o.tombstoned)return u("Email already unlinked",o);if(!qi(n,o))return c("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Fe(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return a(i)?c("Unable to unlink email"):u("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Fe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?c("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to assign contributor, missing contributor");if(!r)return c("Unable to assign contributor, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return c("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to unassign, missing contributor");if(!r)return c("Unable to unassign, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return u("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(i),u("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return c("Unable to add tag, missing tag");if(!r)return c("Unable to add tag, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return c("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return c("Unable to remove tag, missing tag");if(!r)return c("Unable to remove tag, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return u("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return c("Tag not found");let n={...t,tombstoned:!0},r=Fe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?c("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return c("Tag not found");let r={...n,name:t,tombstoned:!1},o=Fe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?c("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=Fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?c("Could not create tag"):u("Tag created",e)},createNode(e){let t=Yr("nodes",e.id,e);return a(t)?c("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return c("Failed to locate node");let n={...t,readonly:!0},r=Yr("nodes",e,n);return a(r)?c(r.message):u("Locked node",n)},updateNode(e){let t=Yr("nodes",e.id,e);return a(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return Ie(e)}};var uA=(e,t)=>e+" ".repeat(Math.max(0,t-Rv(e))),mA=(e,t)=>" ".repeat(Math.max(0,t-Rv(e)))+e,ml=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),pA=(e,t)=>t?e<t?"up":e>t?"down":null:null,fA=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?Er.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=pA(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Cv=e=>`${Math.max(1,Math.round(e/1024))} KB`,Nv=e=>N.getAttachment(e)?.name??"",gA=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Er.bgHex(qe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Er.bgHex(qe(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Er.hex(qe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Er.hex(qe(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${Er.dim(`(${Cv(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Nv(e.payload.id);return t?`"${t}"`:""}default:return""}},hA=e=>{let t=pr(Be(e));return Er.gray(mA(t,8))},yA=12,vA=e=>uA(`${e}`,yA),bA=e=>{let t=xe();return a(t)?e:Ki(e,t.value.contributors[e]?.name)},xA=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=N.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Cv(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Nv(e.payload.id);return t?`"${t}"`:""}default:return""}},sl=e=>[ml(e.action),xA(e)].filter(Boolean).join(" "),Av=(e,t)=>{let n=hA(e.id),r=vA(bA(e.userId)),o=Er.dim("\u203A"),s=e.action==="move.node"?fA(e,t):[ml(e.action),gA(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var IA=e=>Pe(e,"comments"),EA=e=>Pe(e,"description"),SA=e=>Pe(e,"assignees"),RA=e=>Pe(e,"tags"),CA=e=>Pe(e,"history"),NA=e=>Pe(e,"diff"),AA=e=>Pe(e,"attachments"),ai=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=N.getNode(e);if(!l){let p=N.createNode({...Ne.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:u("Virtual field created",void 0)}if(!lt(l))return c(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=N.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:u("Virtual field updated",void 0)},Tv=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=N.getNode(e);if(!i){let m=N.createNode({...Ne.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:u("Virtual field list created",void 0)}if(!vs(i))return c(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let d=N.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(d)?d:u("Virtual field list updated",void 0)},pl=null,TA=()=>{if(pl)return u("Virtual field ranks",pl);let e=Pt(Xt/4n),t=Pt(Xt/2n),n=Pt(Xt*3n/4n),r=Pt(Xt*7n/8n),o=Pt(Xt*15n/16n),s=Pt(Xt*13n/16n),i=Pt(Xt*27n/32n);return a(e)?e:a(t)?t:a(n)?n:a(r)?r:a(o)?o:a(s)?s:a(i)?i:(pl={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},u("Virtual field ranks",pl))},og=e=>{let t=TA();if(a(t))return t;let n=t.value,r=ai({id:EA(e.id),name:Te.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=Tv({id:SA(e.id),name:Te.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=Tv({id:RA(e.id),name:Te.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=ai({id:IA(e.id),name:Te.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let l=ai({id:AA(e.id),name:Te.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(l))return l;let d=ai({id:CA(e.id),name:Te.HISTORY,parentNodeId:e.id,rank:n.log,value:wA(e),readonly:!0,childRenderAxis:"vertical"});if(a(d))return d;let m=ai({id:NA(e.id),name:Te.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(m)?m:u("Ticket virtual nodes materialized",void 0)},wA=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Av(r,n.get(r.action)??[])).join(`
|
|
98
|
-
`)},
|
|
99
|
-
`)[0]?.trim()??"";return t.length>
|
|
100
|
-
`)){let i=s.indexOf(" ");if(i===-1)continue;let l=s.slice(0,i),d=s.slice(i+1);l==="user.name"&&(r=d.trim()||null),l==="user.email"&&(o=et(d)||null)}return Vv.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},yl=async e=>(await zv(e)).email,Rr=async e=>(await zv(e)).name;var Xr=e=>{let t=me(e??process.cwd());return a(t)?c(t.message):u("Resolved Epiq repo root",t.value)},vl=null,ee=async(e,t)=>{let n=Xr(e);if(a(n))return n;let r=he({repoRoot:n.value});if(a(r))return c(r.message);let o=Ue(n.value);if(a(o))return c(o.message);if(!(vl!==null&&vl.repoRoot===n.value&&vl.stateBranchRoot===r.value&&XA.existsSync(Mr(r.value)))){let f=await Us({repoRoot:n.value,stateBranchName:o.value});if(a(f))return c(f.message);let g=await dr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return c(g.message);vl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await j({cwd:r.value,args:["pull","--ff-only"]});a(f)&&se.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=ht();a(l)||je(l.value),je({gitEmail:await yl(n.value),gitName:await Rr(n.value)});let d=xn(r.value);if(Nf(r.value)===d&&_t()&&st().mode==="live")return u("Booted Epiq state, unchanged",i);let m=Zt(r.value);if(a(m))return c(m.message);let p=en(m.value.events,m.value.unreadable);return a(p)?c(p.message):(Af(r.value,d),u("Booted Epiq state",i))},te=()=>{let e=ht();return a(e)?c(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):c("Unable to retrieve user name"):c("Unable to retrieve user id")},q=()=>{let e=xe();return a(e)?c(e.message):e};var Ko=e=>hn(e).map(t=>Ye(t.id,t.name));var qo=e=>yn(e).map(({id:t,name:n})=>Ye(t,n));import JA from"node:fs";import QA from"node:path";import{ulid as gu}from"ulid";var tt=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Issue not found"):_(n)?n.readonly?c("Issue is readonly"):u("Found issue",n):c("Target must be an issue")},Cr=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Swimlane not found"):gn(n)?n.readonly?c("Swimlane is readonly"):u("Found swimlane",n):c("Target must be a swimlane")},fu=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Board not found"):rr(n)?n.readonly?c("Board is readonly"):u("Found board",n):c("Target must be a board")};var ZA=e=>{if(e.filePath)try{return u("Read attachment file",{data:JA.readFileSync(e.filePath),name:e.name??QA.basename(e.filePath)})}catch(t){return c(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):c("Provide either filePath or dataBase64")},bl=()=>{let e=ht();return a(e)?vn:e.value.attachmentMaxKb??vn},hu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=ZA(e);if(a(s))return s;let i=Vp(t.value.stateBranchRoot,s.value.data,bl());if(a(i))return i;let l=Re(s.value.name).trim()||"image",d=gu(),m={id:gu(),...D(n.value),action:"add.issue.attachment",payload:{id:d,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:l,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);if(a(p))return c(p.message);let f=Br(i.value.hash,i.value.ext);return u("Added issue attachment",{id:d,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Bc(l,f)})},yu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return c("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return c("You can only delete your own attachments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let l={id:gu(),...D(n.value),action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},vu=async e=>{let t=await ee(e.repoRoot,{pull:!1});return a(t)?t:zp(t.value.stateBranchRoot,e.fileName,bl())};var eT=365*24*60*60*1e3,bu=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return u("Issue description",n&&_(n)&&!n.isDeleted?n.props.description??"":"")},Jr=()=>{let e=q();if(a(e))return e;let t=st(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(b=>rr(b)&&!b.isDeleted),s=Date.now()-eT,i=new Map,l=new Map;for(let b of r)if(!b.isDeleted){if(gn(b)&&b.parentNodeId){let R=i.get(b.parentNodeId)??[];R.push(b),i.set(b.parentNodeId,R)}if(_(b)&&b.parentNodeId){if(b.parentNodeId===ye&&Be(b.id)<s)continue;let R=l.get(b.parentNodeId)??[];R.push(b),l.set(b.parentNodeId,R)}}let d=new Set;for(let b of l.values())for(let R of b)d.add(R.id);let m=ht();if(a(m))return m;let p={},f=N.getCommentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(p[b.id]=(f.get(b.id)??[]).map(R=>{let S=N.getContributor(R.authorId);return{id:R.id,issueId:R.issue,body:R.md,author:Ye(R.authorId,S?.name),createdAt:Be(R.id)}}));let g=new Map;for(let b of e.value.eventLog)b.action==="add.issue.attachment"&&g.set(b.payload.id,b.payload.author);let y={},x=N.getAttachmentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(y[b.id]=(x.get(b.id)??[]).map(R=>({id:R.id,issueId:R.issue,name:R.name,fileName:Br(R.hash,R.ext),bytes:R.bytes,createdAt:Be(R.id),canDelete:g.get(R.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((b,R)=>b.rank.localeCompare(R.rank)).map(b=>({id:b.id,ref:H(b.id),title:b.title,readonly:!!b.readonly||n,swimlanes:(i.get(b.id)??[]).sort((R,S)=>R.rank.localeCompare(S.rank)).map(R=>({id:R.id,title:R.title,readonly:!!R.readonly||n,issues:(l.get(R.id)??[]).sort((S,T)=>S.rank.localeCompare(T.rank)).map(S=>({id:S.id,ref:H(S.id),title:Re(S.title),description:S.props.description??"",createdAt:Be(S.id),enteredLaneAt:fl(S.log??[],Be(S.id)),readonly:!!S.readonly||n,tags:Ko(S),assignees:qo(S),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===ye})),parentNodeId:R.parentNodeId}))})),tags:N.getTags().map(b=>({...b,...Ye(b.id,b.name)})),contributors:Object.values(e.value.contributors).map(b=>({...b,...Ye(b.id,b.name)})),user:{id:m.value.userId??"",name:m.value.userName??"",color:qe(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:y,attachmentMaxKb:bl(),timeTravel:t})},Kv=null,tT=e=>{if(e===Kv)return;let t=Ji({root:e});if(a(t)){se.info(t.message);return}Kv=e},Ht=async(e={})=>{if(st().mode!=="live")return Jr();let t=await ee(e.repoRoot,{pull:!1});return a(t)?t:(tT(t.value.repoRoot),Jr())},ci=async(e={})=>{To();let t=Xr(e.repoRoot);if(a(t))return c("Sync failed");let n=te();if(a(n))return n;let r=await wa({cwd:t.value,ownEventFileName:ir(n.value)});return a(r)?(ld(r.message),r):(jr(),u("Synced",r.value))};import{ulid as Wt}from"ulid";var di=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):c("Provide issueId or issueIds")},Yo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):c(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},ui=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:H(r),reason:o.message}):n.done.push({id:r,ref:H(r)})}return n};var Xv=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Eu(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=q();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(_).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==ye).filter(l=>e.boardId?(l.parentNodeId?r[l.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(l=>!e.swimlaneId||l.parentNodeId===e.swimlaneId).filter(l=>!e.tag||Ko(l).some(d=>Xv(d.name,e.tag))).filter(l=>!e.assignee||qo(l).some(d=>Xv(d.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Re((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Re(l.title),swimlane:i(l),tags:Ko(l).map(d=>d.name),assignees:qo(l).map(d=>d.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Re(l.title),description:l.props.description??"",createdAt:Be(l.id),enteredLaneAt:fl(l.log??[],Be(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===ye,readonly:!!l.readonly,tags:Ko(l),assignees:qo(l)})))}var Su=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Re(e.title);if(!o)return c("Issue title cannot be empty");let s=e.description??"",i=ct("Issue title",o,300)??ct("Issue description",s,2e4);if(i)return c(i);if((e.tagNames?.length??0)>20)return c(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return c(`Cannot set more than ${20} assignees at once`);let l=Cr(e.parentId);if(a(l))return l;let d=Hn(e.parentId,n.value,t.value.stateBranchRoot);if(a(d))return d;let m=Qa({name:o,parent:e.parentId,user:n.value,rank:d.value});if(a(m))return m;let p=[...m.value],f=p.find(b=>b.action==="add.issue")?.payload.id;if(!f)return c("Unable to determine created issue id");s&&p.push({id:Wt(),...D(n.value),action:"edit.description",payload:{id:f,md:s}});let g=[];for(let b of e.tagNames??[]){let R=Re(b).trim();if(!R||g.some(P=>P.name===R))continue;let S=ct("Tag name",R,60);if(S)return c(S);let T=N.findTagByName(R),A=T?.id??Wt();T||p.push({id:Wt(),...D(n.value),action:"create.tag",payload:{id:A,name:R}}),p.push({id:Wt(),...D(n.value),action:"add.issue.tag",payload:{id:f,tag:A}}),g.push({id:A,name:R})}let y=[];for(let b of e.assigneeNames??[]){let R=Re(b).trim();if(!R||y.some(P=>P.name===R))continue;let S=ct("Assignee name",R,80);if(S)return c(S);let T=Object.values(r.value.contributors).find(P=>P.name===R),A=T?.id??Wt();T||p.push({id:Wt(),...D(n.value),action:"create.contributor",payload:{id:A,name:R}}),p.push({id:Wt(),...D(n.value),action:"add.issue.assignee",payload:{id:f,assignee:A}}),y.push({id:A,name:R})}let x=B(p,t.value.stateBranchRoot);return a(x)?c(x.message):u("Created issue",{id:f,ref:H(f),title:o,parentId:e.parentId,description:s,tags:g,assignees:y})},nT=(e,t,n)=>{let r=tt(e);if(a(r))return r;let o=Sn(ye,e,{at:"end"},t,n);if(a(o))return o;let s={id:Wt(),...D(t),action:"close.issue",payload:{id:e,parent:ye,rank:o.value}},i=B([s],n);return a(i)?c(i.message):u("Closed issue",{id:e,ref:H(e)})};async function Ru(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=di(e);if(a(r))return r;let o=s=>nT(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yo("Closed",ui(r.value,o)):o(r.value[0])}var Cu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return c("Issue not found");if(!_(o))return c("Target must be an issue");if(o.parentNodeId!==ye)return c("Issue is not closed");let s=il(o);if(!s)return c("Unable to resolve previous parent from issue history");if(s===ye)return c("Previous parent resolves to closed swimlane");let i=Cr(s);if(a(i))return i;let l=i.value,d=Sn(l.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(d))return d;let m={id:Wt(),...D(n.value),action:"reopen.issue",payload:{id:o.id,parent:l.id,rank:d.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Reopened issue",{id:o.id,ref:H(o.id),parentId:l.id})},rT=(e,t,n,r)=>{let o=tt(e);if(a(o))return o;let s=Cr(t.parentId);if(a(s))return s;let i=Sn(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let l={id:Wt(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},d=B([l],r);return a(d)?c(d.message):u("Moved issue",{id:e,ref:H(e),parentId:t.parentId})};async function Nu(e){let t=Xr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=he({repoRoot:t.value});if(a(r))return r;let o=Zt(r.value);if(a(o))return o;let s=en(o.value.events,o.value.unreadable);if(a(s))return s;let i=di(e);if(a(i))return i;let l=d=>rT(d,e,n.value,r.value);return e.issueIds?Yo("Moved",ui(i.value,l)):l(i.value[0])}var Au=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Be(r.id),action:r.action,label:sl(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:Ye(r.userId,t.value.contributors[r.userId]?.name)}))):c("Issue not found")},Tu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=o.value,i=ct("Issue description",e.description,2e4);if(i)return c(i);let l=s.props.description??"";if(l===e.description)return u("No changes made",{id:e.issueId,ref:H(e.issueId),description:l});let d={id:Wt(),...D(n.value),action:"edit.description",payload:{id:e.issueId,md:e.description}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue description",{id:e.issueId,ref:H(e.issueId),description:e.description})},wu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=o.value,i=Re(e.title);if(!i.trim())return c("Issue title cannot be empty");let l=ct("Issue title",i,300);if(l)return c(l);if(s.title===i)return u("No changes made",{id:e.issueId,ref:H(e.issueId),title:i});let d={id:Wt(),...D(n.value),action:"edit.title",payload:{id:e.issueId,name:i}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue title",{id:e.issueId,ref:H(e.issueId),title:i})};import{ulid as Nr}from"ulid";var Mu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return c("Workspace not found");if(st().mode!=="live")return c("Cannot add a board while time travelling");let s=Re(e.title);if(!s.trim())return c("Board title cannot be empty");let i=ct("Board title",s,300);if(i)return c(i);let l=Hn(o.id,n.value,t.value.stateBranchRoot);if(a(l))return l;let d=Nr(),m={id:Nr(),...D(n.value),action:"add.board",payload:{id:d,name:s,parent:o.id,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Created board",{id:d,ref:H(d),title:s})},Pu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return c("Board not found");if(!rr(o))return c("Edit target must be a board");if(o.readonly)return c("Cannot edit readonly board");if(st().mode!=="live")return c("Cannot rename a board while time travelling");let s=Re(e.title);if(!s.trim())return c("Board title cannot be empty");let i=ct("Board title",s,300);if(i)return c(i);if(o.title===s)return u("No changes made",{id:e.boardId,ref:H(e.boardId),title:s});let l={id:Nr(),...D(n.value),action:"edit.title",payload:{id:e.boardId,name:s}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Edited board title",{id:e.boardId,ref:H(e.boardId),title:s})};var Lu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=fu(e.boardId);if(a(o))return o;if(st().mode!=="live")return c("Cannot add a swimlane while time travelling");let s=Re(e.title);if(!s.trim())return c("Swimlane title cannot be empty");let i=ct("Swimlane title",s,300);if(i)return c(i);let l=Hn(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let d=Nr(),m={id:Nr(),...D(n.value),action:"add.swimlane",payload:{id:d,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Created swimlane",{id:d,ref:H(d),title:s,boardId:e.boardId})},ku=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Cr(e.swimlaneId);if(a(o))return o;let s=o.value,i=Re(e.title);if(!i.trim())return c("Swimlane title cannot be empty");let l=ct("Swimlane title",i,300);if(l)return c(l);if(s.title===i)return u("No changes made",{id:e.swimlaneId,ref:H(e.swimlaneId),title:i});let d={id:Nr(),...D(n.value),action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited swimlane title",{id:e.swimlaneId,ref:H(e.swimlaneId),title:i})},Du=async e=>{let t=Xr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=he({repoRoot:t.value});if(a(r))return r;let o=Zt(r.value);if(a(o))return o;let s=en(o.value.events,o.value.unreadable);if(a(s))return s;let i=Cr(e.swimlaneId);if(a(i))return i;let l=fu(e.boardId);if(a(l))return l;let d=Sn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let m={id:Nr(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},p=B([m],r.value);return a(p)?c(p.message):u("Moved swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId),boardId:e.boardId})},Bu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Cr(e.swimlaneId);if(a(o))return o;let s={id:Nr(),...D(n.value),action:"delete.node",payload:{id:e.swimlaneId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId)})};import{ulid as mi}from"ulid";async function Ou(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=di(e);if(a(r))return r;let o=Re(e.tagName).trim();if(!o)return c("Tag name cannot be empty");let s=ct("Tag name",o,60);if(s)return c(s);let i=ui(r.value,tt);if(!e.issueIds&&i.failed[0])return c(i.failed[0].reason);if(i.done.length===0)return c(Yo("Tagged",i).message);let l=N.findTagByName(o),d=l?.id??mi(),m=[...l?[]:[{id:mi(),...D(n.value),action:"create.tag",payload:{id:d,name:o}}],...i.done.map(({id:y})=>({id:mi(),...D(n.value),action:"add.issue.tag",payload:{id:y,tag:d}}))],p=B(m,t.value.stateBranchRoot);if(a(p))return c(p.message);let f={id:d,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Yo("Tagged",i);return a(g)?g:u(g.message,{...g.value,tag:f})}var Fu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return c("Tag not found");if(o.tombstoned)return c("Tag is already deleted");let s=[{id:mi(),...D(n.value),action:"tombstone.tag",payload:{id:e.tagId}}],i=B(s,t.value.stateBranchRoot);return a(i)?c(i.message):u("Deleted tag",{id:o.id,name:o.name})};var _u=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return c("Tag not found");let s={id:mi(),...D(n.value),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Removed issue tag",{id:e.issueId,ref:H(e.issueId),tagId:e.tagId})};import{ulid as Zr}from"ulid";var Qv=async(e,t)=>{let n=lr(e).get(t);return n===void 0?void 0:{id:t,name:n}},$u=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let b=r.value.contributors[s],R=b?void 0:await Qv(t.value.stateBranchRoot,s);if(!b&&!R)return c("Unknown assignee id");let S=b??R,T=[...b?[]:[{id:Zr(),...D(n.value),action:"create.contributor",payload:{id:S.id,name:S.name}}],{id:Zr(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:S.id}}],A=B(T,t.value.stateBranchRoot);return a(A)?c(A.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:S.id,name:S.name}})}let i=Re(e.assigneeName??"").trim();if(!i)return c("Provide assigneeId, self or assigneeName");let l=ct("Assignee name",i,80);if(l)return c(l);let d=oi({events:r.value.eventLog??[],registry:r.value.contributors,logFileNames:lr(t.value.stateBranchRoot)}).filter(b=>b.name===i);if(d.length>1)return c(`"${i}" matches ${d.length} contributors (${d.map(({id:b})=>b).join(", ")}). Assign by assigneeId to choose.`);let m=d[0];if(!m&&!e.createUnlinked)return c(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let p=m?.id??Zr(),f=m?.name??i,y=[...!!r.value.contributors[p]?[]:[{id:Zr(),...D(n.value),action:"create.contributor",payload:{id:p,name:f}}],{id:Zr(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],x=B(y,t.value.stateBranchRoot);return a(x)?c(x.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:p,name:f}})},Uu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;if(!r.value.contributors[e.contributorId])return c("Contributor not found");if(await Qv(t.value.stateBranchRoot,e.contributorId))return c("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Zr(),...D(n.value),action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(i,t.value.stateBranchRoot);return a(l)?c(l.message):u("Tombstoned contributor",{id:e.contributorId,name:bo})};var ju=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=cr(t.value.stateBranchRoot);if(a(o))return c(o.message);let s=e.boardId?Bv(o.value,e.boardId):o.value,i=new Set,l=sg(t.value.stateBranchRoot);if(a(l))return c(l.message);for(let p of l.value)p.userId&&i.add(p.userId);let d=r.value.contributors,m=oi({events:s,registry:d,logFileNames:lr(t.value.stateBranchRoot)}).map(({id:p,name:f,isExternal:g})=>({...Ye(p,f),isSelf:p===n.value.userId,isExternal:g,isRemoved:d[p]?.tombstoned===!0,hasAuthoredAnywhere:i.has(p)}));return u("Listed board contributors",m)},Hu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return c("Assignee not found");let s={id:Zr(),...D(n.value),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Removed issue assignee",{id:e.issueId,ref:H(e.issueId),assigneeId:e.assigneeId})};import{ulid as xl}from"ulid";var pi=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return c("Comment cannot be empty");if(s.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=xl(),l={id:xl(),...D(n.value),action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},fi=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return c("Unable to resolve comment");if(o.payload.author!==n.value.userId)return c("You can only delete your own comments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:xl(),...D(n.value),action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Wu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return c("Unable to resolve comment");if(o.payload.author!==n.value.userId)return c("You can only edit your own comments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return c("Comment was deleted");let l=e.body.trim();if(!l)return c("Comment cannot be empty");if(l.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let d={id:xl(),...D(n.value),action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})};import{ulid as Zv}from"ulid";var Gu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;if(!tr(e.email))return c(`Not an email address: ${e.email}`);let o=et(e.email),s=e.contributorId??n.value.userId;if(!r.value.contributors[s])return c(`Unknown contributor: ${s}`);let i=ys(r.value.emailLinks,o);if(i.includes(s))return u(`${o} is already yours`,{contributor:s,email:o,contested:i.filter(d=>d!==s)});let l=B([{id:Zv(),action:"link.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(l)?c(l.message):u(i.length>0?`Claimed ${o}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${o}`,{contributor:s,email:o,contested:i})},Vu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=et(e.email),s=e.contributorId??n.value.userId,i=r.value.emailLinks[hs(o,s)];if(!i||i.tombstoned)return c(`No such link: ${o} to ${s}`);if(!qi(n.value.userId,i))return c("Only whoever made a claim, or the contributor it names, may undo it");let l=B([{id:Zv(),action:"unlink.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(l)?c(l.message):u(`Unclaimed ${o}`,{contributor:s,email:o})},Il=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=q();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let g=s.get(f.email)??new Set;g.add(f.contributor),s.set(f.email,g)}let i=[...s.entries()].map(([f,g])=>({email:f,contested:g.size>1,claimants:[...g].map(y=>Ye(y,o[y]?.name))})).sort((f,g)=>f.email.localeCompare(g.email)),l=te(),d=a(l)?[]:fn(r,l.value.userId),m=V().gitEmail,p=m?ys(r,m).filter(f=>a(l)||f!==l.value.userId):[];return u("Listed contributor emails",{emails:i,mine:d,git:m?{email:m,linkedToMe:d.includes(m),heldByOthers:p.map(f=>Ye(f,o[f]?.name))}:null})},El=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let{userId:o,userName:s}=n.value,i=Ue(t.value.repoRoot),l=await wn({repoRoot:t.value.repoRoot,stateBranch:a(i)?void 0:i.value,names:[s,await Rr(t.value.repoRoot)],links:r.value.emailLinks});if(a(l))return l;let d=br(l.value),m=d.filter(p=>p.looksLikeYours);return u(d.length===0?"No unclaimed addresses in this history":`${d.length} unclaimed address(es) in this history, ${m.length>0?`${m.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:o,candidates:d,likely:m.length})};var eb=(e,t)=>{let n=0,r=0,o=null;for(let s of e){if(s.userId!==t)continue;s.action==="add.issue"&&n++,s.action==="add.issue.comment"&&r++;let i=yo(s.id);if(a(i))continue;let l=i.value.getTime();(o===null||l<o)&&(o=l)}return{tickets:n,comments:r,joinedAt:o}};var zu=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let{userId:o,userName:s}=n.value,i=eb(r.value.eventLog,o),l=Ue(t.value.repoRoot),d=await wn({repoRoot:t.value.repoRoot,stateBranch:a(l)?void 0:l.value,names:[s,await Rr(t.value.repoRoot)],links:r.value.emailLinks}),m=a(d)?[]:d.value.filter(p=>p.claimedBy.length===1&&p.claimedBy[0]===o);return u("Derived personal stats",{...i,scanned:!a(d),commits:m.reduce((p,f)=>p+f.commits,0),claimedEmails:m.length})};var Mn="1.10.0";import oT from"node:fs";import tb from"node:path";var gi=Number(process.env.EPIQ_GUI_PORT)||3710,Ku="/api/instance",qu="epiq",Sl=e=>{try{return oT.realpathSync(tb.resolve(e))}catch{return tb.resolve(e)}},sT=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===qu&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},nb=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${Ku}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return sT(s)?s:null}catch{return null}finally{clearTimeout(r)}};var iT=/^(```|~~~)[^\n]*\n[\s\S]*?\n\1[ \t]*$/gm,aT=/^(?:```|~~~)[\s\S]*$/m,lT=/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,cT=/^[ \t]*\|.*$/gm,dT=/!\[[^\]]*\]\([^)]*\)/g,uT=/\[([^\]]*)\]\([^)]*\)/g,mT=/^[ \t]*(?:[#>]+[ \t]*|[-*+][ \t]+|\d+[.)][ \t]+)/gm,pT=/^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/gm,fT=/[*`~]/g,gT=/(?<![0-9A-Za-z])_|_(?![0-9A-Za-z])/g,hT=e=>Re(e.replace(iT," ").replace(aT," ").replace(dT," ").replace(uT,"$1").replace(pT," ").replace(lT," ").replace(cT,t=>t.replaceAll("|"," ")).replace(mT,"").replace(fT,"").replace(gT,"")),yT=.5,rb=(e,t)=>{if(t<=0)return"";let n=hT(e);if(n.length<=t)return n;let r="\u2026",o=t-r.length;if(o<=0)return r.slice(0,t);let s=n.slice(0,o),i=s.lastIndexOf(" ");return`${(i>=o*yT?s.slice(0,i):s).trimEnd()}${r}`};var vT=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),eo=e=>a(e)?e:u(e.message,vT(e.value)),bT=(e,t)=>(e.boards??[]).flatMap(n=>n.swimlanes??[]).flatMap(n=>n.issues??[]).find(n=>n.id===t),ob=(e,t)=>{let n=bT(e,t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}},xT=280,sb=(e,t)=>({issueId:e,excerpt:rb(t,xT)});var ib=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=me(e.project.repoRoot);if(a(g))return null;let y=he({repoRoot:g.value});return a(y)?null:xn(y.value)}let l=()=>{let g=pn();return a(g)?(se.error(g.message),null):g.value},d=()=>{let g=l();if(!g)return!1;let y=ht();return a(y)?!1:!!g.autoSync&&ll(y.value)===null},m=()=>{let g=uo(l()?.autoSyncDebounceMs);return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)&&d()){r=!0,o=Date.now();try{await Sr(async()=>{if(st().mode!=="live")return;await ci({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let y=eo(await Ht({repoRoot:e.project.repoRoot}));a(y)||Ur({type:"state",payload:y})})}finally{r=!1,f()}}};function f(){n||!d()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,reschedule:()=>{t&&(clearTimeout(t),t=void 0),f()},dispose:()=>{n=!0,t&&clearTimeout(t)}}};var IT=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),Yu=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!IT.has(n.hostname)},ab=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:Yu(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as aw}from"ws";var Pn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var ET=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},lb=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...Pn(i),changed:i.addedCount+i.removed})).reduce((i,l)=>i===null||l.changed>i.changed?l:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>ET(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var nt={line:["//"],block:[["/*","*/"]]},Gt={line:["#"],block:[]},Xu={line:["--"],block:[]},Xo={line:[],block:[["<!--","-->"]]},ST={line:[],block:[]},Y=(e,t)=>({name:e,comment:t}),Rl=Y("TypeScript",nt),Cl=Y("JavaScript",nt),cb={ts:Rl,tsx:Rl,mts:Rl,cts:Rl,js:Cl,jsx:Cl,mjs:Cl,cjs:Cl,py:Y("Python",{line:["#"],block:[['"""','"""']]}),rb:Y("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:Y("Go",nt),rs:Y("Rust",nt),java:Y("Java",nt),kt:Y("Kotlin",nt),swift:Y("Swift",nt),c:Y("C",nt),h:Y("C",nt),cc:Y("C++",nt),cpp:Y("C++",nt),hpp:Y("C++",nt),cs:Y("C#",nt),php:Y("PHP",nt),scala:Y("Scala",nt),dart:Y("Dart",nt),lua:Y("Lua",Xu),hs:Y("Haskell",Xu),sql:Y("SQL",Xu),ex:Y("Elixir",Gt),exs:Y("Elixir",Gt),pl:Y("Perl",Gt),r:Y("R",Gt),jl:Y("Julia",Gt),sh:Y("Shell",Gt),bash:Y("Shell",Gt),zsh:Y("Shell",Gt),vue:Y("Vue",Xo),svelte:Y("Svelte",Xo),html:Y("HTML",Xo),xml:Y("XML",Xo),md:Y("Markdown",Xo),mdx:Y("Markdown",Xo),css:Y("CSS",{line:[],block:[["/*","*/"]]}),scss:Y("CSS",nt),less:Y("CSS",nt),yml:Y("YAML",Gt),yaml:Y("YAML",Gt),toml:Y("TOML",Gt),ini:Y("INI",Gt),json:Y("JSON",ST)},RT="Other",db=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},to=e=>cb[db(e)]?.name??RT,hi=e=>cb[db(e)]?.comment??null,CT=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],NT=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jo=e=>NT.test(e)||CT.some(t=>t.test(e)),AT=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,TT=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,wT=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,an=e=>AT.test(e)||TT.test(e)||wT.test(e),ub=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),mb=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),pb=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),MT=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,PT=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,fb=e=>MT.test(e),gb=e=>PT.test(e);var hb=/\b(TODO|FIXME|HACK|XXX)\b/,LT=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,Ju=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},kT=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},yb=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,d=0;for(let p of e.files){if(p.binary||an(p.path))continue;let f=hi(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=to(p.path),y=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let b=Ju(x,f);if(hb.test(x)&&i++,b==="blank"){s++;continue}if(b==="comment"){r++,y.comment++,f&<.test(kT(x,f))&&d++;continue}o++,y.code++}for(let{text:x}of p.removedLines)hb.test(x)&&l++;n.set(g,y)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:l,commentedOutCodeLines:d}};var DT=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Nl=6,Qu=10,BT=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},OT=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},FT=e=>{if(e.length<Nl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Nl<=e.length;r++){let o=e.slice(r,r+Nl);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
101
|
-
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let
|
|
102
|
-
`)){if(f.startsWith(
|
|
103
|
-
`)){let f=
|
|
104
|
-
`)){let S=Ju(R,y);S==="comment"&&b.comment++,S==="code"&&b.code++}d.set(x,b)}let m=new Map;for(let[p,f]of d){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Cb=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||an(l.path))&&Jo(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(Pn(l)),l.status==="deleted"&&o.push(Pn(l));for(let{text:d}of l.added)fb(d)&&s++,gb(d)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var qT=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Nb=async({repoRoot:e,ref:t,commits:n})=>{let r=await Sb({repoRoot:e,shas:n.map(l=>l.sha)});if(a(r))return c(r.message);let o=r.value,s=qT(n),i=s?await Rb({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:lb({commits:n,patch:o}),languages:bb({patch:o,languagesBefore:i?.languages??null}),tests:Cb({patch:o}),comments:yb({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:vb({patch:o})})};var yi=e=>{if(a(e))return e;let t=xe(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=ap(n),s=e.value.map(i=>({...i,authorIdentity:Vy({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return u(e.message,s)};var YT=32,vi=new Map;var XT=(e,t)=>{if(vi.set(e,t),vi.size>YT){let n=vi.keys().next();n.done||vi.delete(n.value)}return t},Al=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return c("idOrRef must not be empty");let n=t.length>7?H(t):t.toUpperCase(),r=me(e.repoRoot??process.cwd());if(a(r))return c(r.message);let o=r.value,s=yi(await zn({repoRoot:o,ref:n}));if(a(s))return c(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.authorIdentity?.resolved?p.authorIdentity.name:p.author,subject:p.subject})),l=[o,n,i.map(p=>`${p.sha}:${p.author}`).join(",")].join(" "),d=vi.get(l);if(d)return u("Derived issue stats",d);let m=await Nb({repoRoot:o,ref:n,commits:i});return a(m)?c(m.message):u("Derived issue stats",XT(l,m.value))};var JT=new RegExp(`^[0-9A-Z]{${7}}$`),QT=e=>{let t=e.indexOf(" ");if(t===-1)return null;let n=e.slice(0,t).toUpperCase();return JT.test(n)?n:null},ZT=e=>{let t={};for(let n of e){let r=QT(n.subject);if(!r)continue;let o=t[r]??={commits:0,insertions:0,deletions:0};o.commits++,o.insertions+=n.insertions,o.deletions+=n.deletions}return t},Ab=async(e={})=>{let t=await Uo({repoRoot:e.repoRoot});return a(t)?t:u("Collected diff stats by ref",ZT(t.value))};var ew="Filed here",Tb=(e,t)=>e.set(t,(e.get(t)??0)+1),wb=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?ew:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Mb=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[d,m]of l.entries()){if(m!==e)continue;s++,Tb(r,l[d-1]??null);let p=l[d+1];p!==void 0&&(i++,Tb(o,p))}return{arrived:s,departed:i,arrivesFrom:wb(r,s,n),movesOnTo:wb(o,i,n)}};var Pb=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var bi=1440*60*1e3,tw=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*bi,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,d]of i.entries()){let m=s.get(d.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((d.enteredAt-o)/bi)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/bi)-1);for(let y=f;y<=g;y++)m[y].push(o+y*bi-d.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((d,m)=>({t:o+m*bi,median:Pb(d.sort((p,f)=>p-f)),count:d.length}))]))},Lb=({laneId:e,journeys:t,now:n,days:r})=>tw({laneIds:[e],journeys:t,now:n,days:r})[e];var nw=40,rw=30,ow=()=>({tickets:0,commits:0,insertions:0,deletions:0}),sw=async(e,t)=>{let n=ow();for(let r of t.slice(0,nw)){let o=await Al({repoRoot:e,idOrRef:H(r)});a(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},kb=async e=>{let t=q();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return c("Swimlane not found");let o=Object.values(n).filter(_),s=o.map(d=>du(d.log??[],Be(d.id))),i=Mb(e.swimlaneId,s.map(d=>d.map(m=>m.laneId)),d=>n[d]?.title??"Elsewhere"),l=o.filter(d=>d.parentNodeId===e.swimlaneId).map(d=>d.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Be(e.swimlaneId),...i,stayTrend:Lb({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:rw}),code:await sw(e.repoRoot,l)})};var Db=new Set(["sync","email:link","email:unlink","issues:create","board:create","board:edit:title","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Bb=e=>{let t=$n({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Io(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Ob=e=>{let t=$n();if(a(t))return c(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):c(`Not a recent project: ${e}`)};import{z as k}from"zod";var re=k.string().min(1),Fb=k.discriminatedUnion("at",[k.object({at:k.literal("start")}),k.object({at:k.literal("end")}),k.object({at:k.literal("before"),sibling:re}),k.object({at:k.literal("after"),sibling:re})]),xi=k.number().finite(),ce=(e,t)=>k.object({type:k.literal(e),payload:t}),no=e=>k.object({type:k.literal(e)}),iw=k.discriminatedUnion("type",[no("state:get"),no("issues:list"),no("sync"),no("time-travel:live"),no("diff-stats:get"),ce("project:open",k.object({root:k.string().min(1)})),ce("issues:create",k.object({title:k.string(),parentId:re,description:k.string().optional(),tagNames:k.array(k.string()).optional()})),ce("board:create",k.object({title:k.string()})),ce("board:edit:title",k.object({boardId:re,title:k.string()})),ce("swimlane:create",k.object({title:k.string(),boardId:re})),ce("swimlane:edit:title",k.object({swimlaneId:re,title:k.string()})),ce("swimlane:delete",k.object({swimlaneId:re})),ce("swimlane:move",k.object({swimlaneId:re,boardId:re,position:Fb.optional()})),ce("issues:move",k.object({issueId:re,parentId:re,position:Fb.optional()})),ce("issue:edit:title",k.object({issueId:re,title:k.string()})),ce("issue:edit:description",k.object({issueId:re,description:k.string()})),ce("issue:tag:add",k.object({issueId:re,tagName:k.string()})),ce("issue:tag:remove",k.object({issueId:re,tagId:re})),ce("contributor:remove",k.object({contributorId:re})),ce("tag:remove",k.object({tagId:re})),k.object({type:k.literal("contributors:get"),payload:k.object({boardId:re.optional()}).optional()}),ce("issue:assignee:add",k.object({issueId:re,assigneeId:re.optional(),assigneeName:k.string().optional(),createUnlinked:k.boolean().optional()})),ce("issue:assignee:remove",k.object({issueId:re,assigneeId:re})),ce("issue:close",k.object({issueId:re})),ce("issue:reopen",k.object({issueId:re})),ce("issue:comment:add",k.object({issueId:re,body:k.string()})),ce("issue:comment:delete",k.object({issueId:re,commentId:re})),ce("issue:comment:edit",k.object({issueId:re,commentId:re,body:k.string()})),ce("issue:get",k.object({issueId:re})),ce("issue:preview:get",k.object({issueId:re})),k.object({type:k.literal("timeline:get"),payload:k.object({start:xi.optional(),end:xi.optional(),boardId:re.optional(),requestId:k.number().finite().optional()}).optional()}),k.object({type:k.literal("commits:get"),payload:k.object({start:xi.optional(),end:xi.optional(),requestId:k.number().finite().optional()}).optional()}),ce("time-travel:scrub",k.object({targetTime:xi})),ce("time-travel:checkout-event",k.object({eventId:k.string().min(1)})),ce("commit:inspect",k.object({sha:k.string()})),k.object({type:k.literal("emails:get")}),ce("email:link",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ce("email:unlink",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ce("commit:diff:get",k.object({sha:k.string()})),ce("issue:commits:get",k.object({issueId:re})),ce("issue:squashed-diff:get",k.object({issueId:re})),ce("issue:stats:get",k.object({issueId:re})),ce("swimlane:stats:get",k.object({swimlaneId:re})),no("me:stats:get"),no("settings:get"),ce("settings:set",k.object({autoSync:k.boolean().optional(),autoSyncIntervalMs:k.number().finite().optional()}))]);var _b=e=>{let t=iw.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var lw=1024*1024,tm=()=>{Ur({type:"state",payload:eo(Jr())})},ne=(e,t)=>{e.send(JSON.stringify(t))},Ii=async(e,t)=>{let n=eo(await Ht({repoRoot:t}));return a(n)&&n.message===pc?ne(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Bb(t)}}):ne(e,{type:"state",payload:n})},cw=async(e,t)=>{let n=()=>ne(e,{type:"state",payload:eo(Jr())});if(st().mode!=="live")return n();let r=await Ht({repoRoot:t});return st().mode!=="live"?n():ne(e,{type:"state",payload:eo(r)})},ze=async(e,t,n,r,o)=>{if(ne(e,{type:r,payload:o}),a(o))return ne(e,{type:"failed",payload:o.message});n(),cw(e,t)},$b=(e,t,{onStateChanged:n,onSyncSettingsChanged:r,getPort:o})=>{new aw({server:e,path:"/ws",maxPayload:lw,verifyClient:i=>!Yu(i.origin,o())}).on("connection",i=>{Ng(i),i.on("message",async l=>{let d=async m=>{let{type:p}=m,f=t.repoRoot;if(p==="project:open"){let g=Ob(m.payload.root);return ne(i,{type:"project:open:result",payload:g}),a(g)?void 0:(t.repoRoot=g.value,Ii(i,g.value))}if(p==="timeline:get"){let{requestId:g,...y}=m.payload??{};return ne(i,{type:"timeline",requestId:g,payload:await jv({repoRoot:f,...y})})}if(p==="issue:get"){let g=m.payload?.issueId,y=Jr(),x=Au(g);return ne(i,{type:"issue",payload:a(y)?y:u("Issue detail",{...ob(y.value,g),history:a(x)?[]:x.value})})}if(p==="issue:preview:get"){let{issueId:g}=m.payload,y=bu(g);return ne(i,{type:"issue:preview:result",payload:{issueId:g,result:a(y)?y:u("Issue preview",sb(g,y.value))}})}if(p==="commits:get"){let{requestId:g,...y}=m.payload??{};return ne(i,{type:"commits",requestId:g,payload:yi(await Uo({repoRoot:f,...y}))})}if(p==="emails:get")return ne(i,{type:"emails",payload:await Il({repoRoot:f}),suggestions:await El({repoRoot:f})});if(p==="email:link"||p==="email:unlink"){let y=await(p==="email:link"?Gu:Vu)({repoRoot:f,...m.payload});return ne(i,{type:"emails",payload:await Il({repoRoot:f}),suggestions:await El({repoRoot:f}),lastAction:a(y)?{ok:!1,message:y.message}:{ok:!0,message:y.message}}),ze(i,f,n,`${p}:result`,y)}if(p==="me:stats:get")return ne(i,{type:"me:stats",payload:await zu({repoRoot:f})});if(p==="settings:get")return ne(i,{type:"settings",payload:si()});if(p==="settings:set"){let g=zo({enabled:m.payload.autoSync,intervalMs:m.payload.autoSyncIntervalMs});return a(g)||r(),ne(i,{type:"settings",payload:a(g)?si():g,lastAction:a(g)?{ok:!1,message:g.message}:{ok:!0,message:g.message}})}if(p==="commit:inspect")return ne(i,{type:"commit:inspect:result",payload:await Xs({repoRoot:f,sha:m.payload.sha})});if(p==="commit:diff:get"){let{sha:g}=m.payload;return ne(i,{type:"commit:diff:result",payload:{sha:g,result:await Ad({repoRoot:f,sha:g})}})}if(p==="issue:commits:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:commits:result",payload:{issueId:g,result:yi(await zn({repoRoot:f,ref:H(g)}))}})}if(p==="issue:squashed-diff:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:squashed-diff:result",payload:{issueId:g,result:await Td({repoRoot:f,ref:H(g)})}})}if(p==="issue:stats:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:stats:result",payload:{issueId:g,result:await Al({repoRoot:f,idOrRef:H(g)})}})}if(p==="diff-stats:get")return ne(i,{type:"diff-stats",payload:await Ab({repoRoot:f})});if(p==="swimlane:stats:get"){let{swimlaneId:g}=m.payload;return ne(i,{type:"swimlane:stats:result",payload:{swimlaneId:g,result:await kb({repoRoot:f,swimlaneId:g})}})}if(p==="time-travel:scrub"){let g=await pu({repoRoot:f,targetTime:m.payload.targetTime});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="time-travel:checkout-event"){let g=await Wv({repoRoot:f,eventId:m.payload.eventId});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="time-travel:live"){let g=await Gv({repoRoot:f});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="state:get")return Ii(i,f);if(p==="sync"){let g=await ci({repoRoot:f});return ne(i,{type:"sync:result",payload:g}),n(),Ii(i,f)}if(p==="issue:comment:add"){let g=await pi({repoRoot:f,...m.payload});return ze(i,f,n,"issue:comment:add:result",g)}if(p==="issue:comment:edit"){let g=await Wu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:comment:edit:result",g)}if(p==="issue:comment:delete"){let g=await fi({repoRoot:f,...m.payload});return ne(i,{type:"issue:comment:delete:result",payload:g}),a(g)?ne(i,{type:"failed",payload:g.message}):(n(),Ii(i,f))}if(p==="issue:edit:description"){let g=await Tu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:edit:description:result",g)}if(p==="issue:edit:title"){let g=await wu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:edit:title:result",g)}if(p==="issue:tag:add"){let g=await Ou({repoRoot:f,...m.payload});return ze(i,f,n,"issue:tag:add:result",g)}if(p==="issue:tag:remove"){let g=await _u({repoRoot:f,...m.payload});return ze(i,f,n,"issue:tag:remove:result",g)}if(p==="contributor:remove"){let g=await Uu({repoRoot:f,...m.payload});return ze(i,f,n,"contributor:remove:result",g)}if(p==="tag:remove"){let g=await Fu({repoRoot:f,...m.payload});return ze(i,f,n,"tag:remove:result",g)}if(p==="contributors:get")return ne(i,{type:"contributors",payload:await ju({repoRoot:f,...m.payload})});if(p==="issue:assignee:add"){let g=await $u({repoRoot:f,...m.payload});return ze(i,f,n,"issue:assignee:add:result",g)}if(p==="issue:assignee:remove"){let g=await Hu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:assignee:remove:result",g)}if(p==="issues:list")return ne(i,{type:"issues",payload:await Eu({repoRoot:f})});if(p==="issues:create"){let g=await Su({...m.payload,repoRoot:f});return ne(i,{type:"issues:create:result",payload:g}),a(g)?Ur({type:"failed",payload:g.message}):(n(),Ii(i,f))}if(p==="board:create"){let g=await Mu({...m.payload,repoRoot:f});return ze(i,f,n,"board:create:result",g)}if(p==="board:edit:title"){let g=await Pu({...m.payload,repoRoot:f});return ze(i,f,n,"board:edit:title:result",g)}if(p==="swimlane:create"){let g=await Lu({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:create:result",g)}if(p==="swimlane:edit:title"){let g=await ku({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:edit:title:result",g)}if(p==="swimlane:delete"){let g=await Bu({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:delete:result",g)}if(p==="swimlane:move"){if(!m.payload.position)return ne(i,{type:"error",message:"Missing move position"});let g=await Du({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:move:result",g)}if(p==="issues:move"){if(!m.payload.position)return ne(i,{type:"error",message:"Missing move position"});let g=await Nu({...m.payload,repoRoot:f});return ze(i,f,n,"issues:move:result",g)}if(p==="issue:close"){let g=await Ru({repoRoot:f,issueId:m.payload.issueId});return ze(i,f,n,"issue:close:result",g)}if(p==="issue:reopen"){let g=await Cu({repoRoot:f,issueId:m.payload.issueId});return ze(i,f,n,"issue:reopen:result",g)}return ne(i,{type:"error",message:"Unknown message type"})};try{let m=_b(JSON.parse(l.toString()));if(!m.ok)return ne(i,{type:"error",message:m.error});let p=m.message;return Db.has(p.type)?await Sr(async()=>st().mode!=="live"?ne(i,{type:"failed",payload:"Read-only while viewing history"}):d(p)):await d(p)}catch(m){return ne(i,{type:"error",message:m instanceof Error?m.message:String(m)})}})})};var fw=ro.dirname(pw(import.meta.url)),gw=process.env.IS_LOCAL==="true"?ro.resolve(process.cwd(),"dist/gui"):ro.join(fw,"gui"),Tl,hw=async()=>(Tl===void 0&&(Tl=await import("node:sea").catch(()=>null)),Tl?.isSea()?Tl:null),Le=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},yw=e=>Le(e,409,{isError:!0,message:"Read-only while viewing history"}),wl=(e,t)=>Sr(async()=>st().mode!=="live"?yw(e):t()),Ub=async(e,t=1024*1024)=>new Promise((n,r)=>{let o=[],s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),vw=2*1024*1024,bw={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},xw=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",jb=new Map,Iw=e=>`"${uw("sha1").update(e).digest("base64url")}"`,Ew=async e=>{try{let{size:t,mtimeMs:n}=await dw(e);return`${t}:${n}`}catch{return null}},Sw=e=>{try{return decodeURIComponent(e)}catch{return null}},Hb=async(e,t,n)=>{let r=e==="/"?"/index.html":Sw(e);if(r===null)return Le(n,404,{isError:!0,message:"Not found"});let o=r.replace(/^\/+/,""),s=ro.resolve(gw),i=ro.resolve(s,o),l=ro.relative(s,i);if(l.startsWith("..")||ro.isAbsolute(l))return Le(n,403,{isError:!0,message:"Forbidden"});let d=await hw(),m=d?"sea":await Ew(i),p=m===null?void 0:jb.get(l),f=p&&p.stamp===m?p.etag:null;if(f&&t.headers["if-none-match"]===f)return n.writeHead(304,{etag:f,"cache-control":"no-cache"}),n.end();try{let g=d?Buffer.from(d.getAsset(`gui/${l}`)):await Wb(i),y=f??Iw(g);return m!==null&&jb.set(l,{stamp:m,etag:y}),n.writeHead(200,{"content-type":xw(i),etag:y,"cache-control":"no-cache"}),n.end(g)}catch{return Le(n,404,{isError:!0,message:`Not found: ${o}`})}},Rw=async(e,t=gi)=>new Promise((n,r)=>{let o=s=>{let i=d=>{if(e.off("listening",l),d.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(d)},l=()=>{e.off("error",i);let d=e.address();if(!d||typeof d=="string"){r(new Error("Unable to resolve address"));return}n(d.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),Gb=async e=>{Mv(!1);let t=0,n={repoRoot:e.repoRoot},r=mw.createServer((l,d)=>{o(l,d).catch(m=>(logger.error(`[gui] ${l.method} ${l.url}: ${m instanceof Error?m.message:String(m)}`),d.headersSent?d.end():Le(d,500,{isError:!0,message:"Internal error"})))});async function o(l,d){let m=new URL(l.url??"/","http://127.0.0.1"),p=ab({method:l.method,origin:l.headers.origin,contentType:l.headers["content-type"]},t);if(p)return Le(d,p.status,{isError:!0,message:p.message});if(l.method==="GET"&&m.pathname===Ku)return Le(d,200,{app:qu,repoRoot:Sl(n.repoRoot),version:Mn,pid:process.pid});if(m.pathname==="/api/state")return Le(d,200,await Ht({repoRoot:n.repoRoot}));if(l.method==="POST"&&m.pathname==="/api/comments")try{let f=await Ub(l);if(!f.issueId||!f.body?.trim())return Le(d,400,{isError:!0,message:"Missing issueId or body"});let g=f.issueId,y=f.body;return await wl(d,async()=>{let x=await pi({repoRoot:n.repoRoot,issueId:g,body:y});return a(x)?Le(d,400,{isError:!0,message:x.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))})}catch(f){return Le(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add comment"})}if(l.method==="POST"&&m.pathname==="/api/attachments")try{let f=await Ub(l,vw);if(!f.issueId||!f.dataBase64)return Le(d,400,{isError:!0,message:"Missing issueId or dataBase64"});let g=f.issueId,y=f.dataBase64,x=f.name??"";return await wl(d,async()=>{let b=await hu({repoRoot:n.repoRoot,issueId:g,name:x,dataBase64:y});return a(b)?Le(d,400,{isError:!0,message:b.message}):Le(d,200,{...await Ht({repoRoot:n.repoRoot}),attachment:b.value})})}catch(f){return Le(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add attachment"})}if(l.method==="DELETE"&&m.pathname.startsWith("/api/attachments/")){let f=decodeURIComponent(m.pathname.replace("/api/attachments/",""));return f?wl(d,async()=>{let g=await yu({repoRoot:n.repoRoot,attachmentId:f});return a(g)?Le(d,400,{isError:!0,message:g.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))}):Le(d,400,{isError:!0,message:"Missing attachment id"})}if(l.method==="GET"&&m.pathname.startsWith("/media/")){let f=decodeURIComponent(m.pathname.replace("/media/","")),g=await vu({repoRoot:n.repoRoot,fileName:f});if(a(g))return Le(d,404,{isError:!0,message:g.message});try{let y=await Wb(g.value.filePath);return d.writeHead(200,{"content-type":bw[g.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),d.end(y)}catch{return Le(d,404,{isError:!0,message:"Attachment blob not found"})}}if(l.method==="DELETE"&&m.pathname.startsWith("/api/comments/")){let f=decodeURIComponent(m.pathname.replace("/api/comments/",""));return f?wl(d,async()=>{let g=await fi({repoRoot:n.repoRoot,commentId:f});return a(g)?Le(d,400,{isError:!0,message:g.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))}):Le(d,400,{isError:!0,message:"Missing comment id"})}return m.pathname.startsWith("/board/")||m.pathname==="/log"?Hb("/",l,d):Hb(m.pathname,l,d)}try{t=await Rw(r)}catch(l){return c(l instanceof Error?`Unable to start GUI server: ${l.message}`:`Unable to start GUI server: ${String(l)}`)}let s=ib({project:n});$b(r,n,{onStateChanged:()=>s.queueSync(),onSyncSettingsChanged:()=>s.reschedule(),getPort:()=>t}),r.on("close",s.dispose);let i=r.address();return!i||typeof i=="string"?(r.close(),c("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${i.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var zb=async e=>{let t=lo({});if(a(t))return c(t.message);let n=ht();be(n)&&je(n.value);let r=await nb(gi);if(r&&r.repoRoot===Sl(e.repoRoot)){let i=`http://127.0.0.1:${gi}`;return console.log(`Epiq GUI already running for this project at ${Vb.cyan(i)}`),bc(i),u("Reused running GUI",{url:i})}let o=await Gb({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Vb.cyan(s)}`),bc(s),u("Started GUI",{url:s})};import{Box as Xn}from"ink";import ke from"react";import{Box as nm,Text as Ei}from"ink";import ln,{useEffect as Cw,useMemo as Nw}from"react";import{ulid as Aw}from"ulid";var Kb=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return ln.createElement(Ei,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?ln.createElement(Ei,{color:n,dimColor:o},e):ln.createElement(Ei,{color:n,dimColor:o},e.slice(0,l),ln.createElement(Ei,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},qb=Aw(),Tw=e=>`${e}`,ww=e=>{let{pendingNavTarget:t}=yr();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Oe(C.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(C))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==C.PALETTE).map(i=>{let l=La(i),d=cl.find(m=>m.intent===l);return{command:i,description:d?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,l)=>i.isAvailable!==l.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(l.command))},Mw=e=>Ne.text({id:qb,parentNodeId:e,rank:"000000",name:"Command Palette",readonly:!0,isVirtual:!0}),Pw=(e,t,n)=>Ne.text({id:Tw(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,disabled:!e.isAvailable,readonly:!0,isVirtual:!0}),rm=[],Lw=e=>{Yb();let t=N.createNode(Mw(v().rootNodeId));a(t)||!nr(t.value)||(rm=[t.value,...e.map((n,r)=>Pw(n,r,qb)).map(N.createNode).filter(be).map(({value:n})=>n).filter(nr)],U.navigate({contextNode:t.value,selectedIndex:0}))},Yb=()=>{let e=rm.map(t=>t.id);rm=[];for(let t of e)N.deleteNode(t)};function Xb({width:e,height:t}){let r=hf().value.trim().toLowerCase(),o=Nw(()=>ww(r),[r]);Cw(()=>(Lw(o),()=>{Yb()}),[o]);let s=v().selectedIndex;return ln.createElement(nm,{flexDirection:"column",width:e,height:t-2},ln.createElement(mt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let d=l===s,m=i.isAvailable?h.accent:h.secondary2,p=i.isAvailable?"":"[unavailable] ";return ln.createElement(nm,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},ln.createElement(Ei,{color:m,dimColor:!i.isAvailable},d?"\u276F ":" ",ln.createElement(Kb,{text:fp(i.command),match:r,color:m,dimColor:!i.isAvailable})),ln.createElement(nm,{paddingLeft:2},ln.createElement(Kb,{text:p+i.description,match:r.length>=2?r:"",color:d&&i.isAvailable?h.primary:h.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Kw}from"ink";import Ll from"react";import Ri from"chalk";import{Box as Si,Text as ex}from"ink";import oo,{useEffect as tx,useMemo as kw,useState as nx}from"react";var Qo=["\u2803","\u2806","\u2830","\u2818"],Jb=120,Qb=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qo.length+Qo.length)%Qo.length;return Qo[r]}return e?"?":":"},Zb=({infoMessage:e,isPending:t})=>t&&e.includes(fe)?"":e;var rx=Ri.hex(h.secondary),Dw=Ri.inverse,Bw=Ri.inverse.hex(h.secondary2),Ow={hint:"",hints:[],overlap:0,remainder:""},sx=({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}},Fw=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=qe(t);return{bg:r=>Ri.bgHex(n).black(r),bgCursor:r=>Ri.bgHex(n).inverse.black(r)}}return Sc(t)},_w=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=sx({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},ox=()=>({value:dt.value,cursorPosition:dt.cursorPosition,commandIsPending:dt.commandIsPending,autoCompletion:dt.commandMeta.autoCompletion??Ow,infoMessage:dt.commandMeta.infoMessage,validationStatus:dt.commandMeta.validity,command:dt.commandMeta.command,inputString:dt.commandMeta.inputString,modifier:dt.commandMeta.modifier}),$w=(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,ix=({width:e,mode:t})=>{let[n,r]=nx(ox());tx(()=>{let T=()=>{let P=ox();r(M=>$w(M,P)?M:P)},A=$c(T);return T(),()=>{A()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:d,command:m,modifier:p,validationStatus:f}=n,g=l&&f===bn.Invalid,y=Zb({infoMessage:i,isPending:l}),[x,b]=nx(0);tx(()=>{if(!l){b(0);return}let T=setInterval(()=>{b(A=>(A+1)%Qo.length)},Jb);return()=>{clearInterval(T)}},[l]);let R=Qb({isPalette:t===I.PALETTE,isPending:l,frame:x}),S=kw(()=>{let T=Math.max(0,Math.min(s,o.length)),A=sx({value:o,command:m}),P=_w({value:o,command:m,modifier:p}),M=m?Sc(m):null,O=Fw({command:m,modifier:p}),W=(it,ft)=>{let io=A&&ft>=A.start&&ft<A.end,ql=P&&ft>=P.start&&ft<P.end;return io&&M?M.fg(it):ql&&O?O.bg(it):it},X=(it,ft)=>{let io=A&&ft>=A.start&&ft<A.end,ql=P&&ft>=P.start&&ft<P.end;return io&&M?M.fgCursor(it):ql&&O?O.bgCursor(it):Dw(it)},Ee=o.slice(0,T),F=o[T]??" ",J=T<o.length?o.slice(T+1):"",Ke=Array.from(Ee).map((it,ft)=>W(it,ft)).join(""),Jn=X(F,T),os=Array.from(J).map((it,ft)=>W(it,T+1+ft)).join("");if(d.hint){let it=d.hint[d.overlap]??F;Jn=Bw(it),os=rx(d.remainder.slice(1)+J)}return Ke+Jn+os},[o,s,d,m,p]);return oo.createElement(Si,{flexDirection:"column",justifyContent:"flex-start"},oo.createElement(Si,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},oo.createElement(Si,{height:1,flexWrap:"nowrap"},oo.createElement(Si,{flexShrink:0},oo.createElement(ex,{wrap:"truncate-start"},rx(R),S)),y&&oo.createElement(Si,{flexShrink:1,minWidth:0},oo.createElement(ex,{wrap:"truncate",color:g?h.red:h.secondary2},` ${y} `)))))};import{Box as Uw,Text as Ci}from"ink";import Zo from"react";var ax=" ",jw=({keys:e,label:t})=>e.length+1+t.length,Hw=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?ax.length:0)+jw(o);if(r+i>t-4)break;n.push(o),r+=i}return n},lx=({width:e,availableHints:t})=>{let n=Hw(t,e);return Zo.createElement(Uw,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},n.length?Zo.createElement(Ci,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>Zo.createElement(Ci,{key:`${o}-${s}`},i>0?ax:"",Zo.createElement(Ci,{color:h.accent},o),Zo.createElement(Ci,{color:h.secondary2}," ",s)))):Zo.createElement(Ci,{color:h.secondary2},"\xA0"))};import{Box as Ww,Text as Ml}from"ink";import Ni,{useEffect as Gw,useRef as es,useState as Vw}from"react";var zw=40,Pl=.3,om="\u2500",cx=1,dx=16,ux=({width:e})=>{let{replay:t}=oe(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*cx,[l,d]=Vw(0),m=es(r);m.current=r;let p=es(0),f=es(0),g=es(0),y=es(0),x=es(0);if(Gw(()=>{if(!n){p.current=0,g.current=0,y.current=0,x.current=0,d(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let A=setInterval(()=>{let P=Date.now(),M=m.current;if(M!==g.current){let F=M-g.current,J=P-f.current;if(F<0)y.current=0,x.current=0;else if(F>0&&J>0){let Ke=F/J;y.current=y.current===0?Ke:y.current*(1-Pl)+Ke*Pl,x.current=x.current===0?F:x.current*(1-Pl)+F*Pl}p.current=M,f.current=P,g.current=M}let O=P-f.current,W=Math.min(x.current,y.current*O),X=Math.min(1,p.current+W),Ee=Math.round(X*i);d(F=>F===Ee?F:Ee)},zw);return()=>clearInterval(A)},[n,i]),!t)return null;let b=A=>{let P=s>1?A/(s-1):0,M=Math.round(P*(dx-1))/(dx-1);return Gi(M)},R=Math.min(s,Math.floor(l/cx)),S=[];for(let A=0;A<R;A++){let P=b(A),M=S[S.length-1];M&&M.color===P?M.text+=om:S.push({text:om,color:P})}let T=om.repeat(Math.max(0,s-R));return Ni.createElement(Ww,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1,columnGap:1},Ni.createElement(Ml,{color:h.secondary2},"\u25B6"),Ni.createElement(Ml,null,S.map((A,P)=>Ni.createElement(Ml,{key:P,color:A.color},A.text)),Ni.createElement(Ml,{color:h.secondary,dimColor:!0},T)))};var Ai=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=oe(),o=t===I.COMMAND_LINE||t===I.PALETTE;return Ll.createElement(Kw,null,o?Ll.createElement(ix,{width:e,mode:t}):r==="replay"?Ll.createElement(ux,{width:e}):Ll.createElement(lx,{width:e,mode:t,availableHints:n}))};import{Box as Ar,Text as ts}from"ink";import bt,{useEffect as qw,useMemo as Yw}from"react";import{ulid as mx}from"ulid";var Dl=mx(),Xw=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(ou).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),Jw=e=>Ne.text({id:Dl,parentNodeId:e,rank:"000000",name:"Help",isVirtual:!0,readonly:!0}),Qw=(e,t,n)=>Ne.text({id:mx(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,readonly:!0,isVirtual:!0}),kl=[],px=()=>{let e=kl.filter(n=>n.id!==Dl).map(n=>n.id),t=kl.filter(n=>n.id===Dl).map(n=>n.id);kl=[];for(let n of[...e,...t])N.deleteNode(n)},Zw=e=>{px();let t=N.createNode(Jw(v().rootNodeId));if(a(t)||!nr(t.value))return logger.error("Could not attach help nodes");kl=[t.value,...e.map((n,r)=>Qw(n,r,Dl)).map(N.createNode).filter(be).map(({value:n})=>n).filter(nr)],U.navigate({contextNode:t.value,selectedIndex:0})},fx=({width:e,height:t})=>{let n=Yw(()=>Xw(),[]);qw(()=>(Zw(n),()=>{px()}),[n]);let r=v().selectedIndex;return bt.createElement(Ar,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},bt.createElement(Ar,{paddingX:1,justifyContent:"center"},bt.createElement(ts,{color:h.accent},"Help"),bt.createElement(ts,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),bt.createElement(Ar,{paddingX:1,marginTop:1},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(ts,{color:h.secondary},"Key(s)")),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(ts,{color:h.secondary},"Action"))),bt.createElement(mt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return bt.createElement(Ar,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(ts,{color:h.accent},o)),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(ts,{color:l?h.primary:h.secondary2},s)))})))};import{Box as ns,Text as xt}from"ink";import we,{useEffect as eM,useState as sm}from"react";var Bl=({index:e,email:t,note:n,noteColor:r})=>we.createElement(ns,null,we.createElement(xt,{color:h.accent},e===void 0?" ":` ${e}.`),we.createElement(xt,null," ",t),n&&we.createElement(xt,{color:r??h.secondary2},` ${n}`)),gx=({height:e})=>{let[t,n]=sm([]),[r,o]=sm([]),[s,i]=sm(null),{userName:l,gitEmail:d,gitName:m,userId:p}=V();return eM(()=>{let f=!0;return(async()=>{let y=xe(),x=me(process.cwd());if(a(y)||a(x)||!p)return;let b=y.value.emailLinks,R=fn(b,p);n(R.map(P=>({email:P,others:ys(b,P).filter(M=>M!==p).map(M=>y.value.contributors[M]?.name??M)})));let S=Ue(x.value),T=await wn({repoRoot:x.value,stateBranch:a(S)?void 0:S.value,names:[l,m],links:b});if(!f)return;if(a(T)){i(T.message);return}let A=br(T.value);Eo(A.map(P=>P.email)),o(A)})(),()=>{f=!1}},[p,l,m,d]),we.createElement(ns,{height:e-4,flexDirection:"column",paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},we.createElement(ns,null,we.createElement(xt,{color:h.accent,bold:!0},l??"Not configured"),we.createElement(xt,{color:h.secondary2}," on this board")),s&&we.createElement(xt,{color:h.red},s),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},"CLAIMED"),t.length===0?we.createElement(Bl,{email:"Nothing claimed \u2014 your commits show the name git signed them with.",note:""}):t.map(f=>we.createElement(Bl,{key:f.email,email:f.email,note:f.others.length>0?`CONTESTED: also ${f.others.join(", ")}, resolves to nobody`:f.email===d?"your git identity here":void 0,noteColor:f.others.length>0?h.yellow:void 0}))),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},"UNCLAIMED IN THIS HISTORY"),r.length===0?we.createElement(Bl,{email:"Nothing left to claim here."}):r.map(f=>we.createElement(Bl,{key:f.email,email:f.email,note:`${f.commits} commit${f.commits===1?"":"s"} as ${f.names.join(", ")||"unknown"}`}))),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},"[enter]")," writes a claim for the first into the command line, to confirm or change."),we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},":config emails")," claims by address,",we.createElement(xt,{color:h.accent}," :config emails-unclaim "),"gives one back."),we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},"[esc]")," to close")))};import tM from"chalk";import{Box as so,Text as rt}from"ink";import Me from"react";var nM=8,rM=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,nM)},hx=({width:e,height:t})=>{let n=rM();return Me.createElement(so,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Me.createElement(rt,{color:h.accent,bold:!0},"Initialize project"),Me.createElement(rt,null,`This folder is not an ${tM.hex(h.accent)("epiq")} project yet.`),Me.createElement(rt,{color:h.primary},"To start tracking issues here, we need to initialize a new",Me.createElement(rt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),Me.createElement(so,{marginTop:1,flexDirection:"column"},Me.createElement(so,null,Me.createElement(rt,{color:h.accent}," "),Me.createElement(rt,{color:h.primary},"Type "),Me.createElement(rt,{backgroundColor:h.secondary}," :init "))),Me.createElement(so,{marginTop:1},Me.createElement(rt,{color:h.secondary2},"This will create, commit and push "),Me.createElement(rt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")),n.length>0&&Me.createElement(so,{marginTop:1,flexDirection:"column"},Me.createElement(rt,{color:h.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>Me.createElement(so,{key:r.projectId},Me.createElement(rt,{color:h.accent},` ${o+1} `),Me.createElement(rt,{color:h.primary},Io(r.root)),Me.createElement(rt,{color:h.secondary2},` ${r.root}`))),Me.createElement(so,{marginTop:1},Me.createElement(rt,{color:h.accent}," "),Me.createElement(rt,{color:h.primary},"Type "),Me.createElement(rt,{backgroundColor:h.secondary}," :open 1 "),Me.createElement(rt,{color:h.secondary2}," or "),Me.createElement(rt,{backgroundColor:h.secondary}," :open <path> "))))};import{Box as Fl,Text as Dt}from"ink";import $e from"react";import{Box as Ol,Text as Yn}from"ink";import kt,{useEffect as oM,useState as yx}from"react";var vx=()=>{let[e,t]=yx(null),[n,r]=yx(null);return oM(()=>{let o=!0;return(async()=>{let i=xe(),l=me(process.cwd());if(a(i)||a(l))return;let d=Ue(l.value),{userName:m,gitName:p}=V(),f=await wn({repoRoot:l.value,stateBranch:a(d)?void 0:d.value,names:[m,p],links:i.value.emailLinks});if(!o)return;if(a(f)){r(f.message);return}let g=br(f.value);Eo(g.map(y=>y.email)),t(g)})(),()=>{o=!1}},[]),n?kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.red},n)):e===null?null:e.length===0?kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.secondary2},"No unclaimed addresses in this history \u2014 type",kt.createElement(Yn,{color:h.accent}," :config emails none "),"to move on.")):kt.createElement(Ol,{flexDirection:"column",marginTop:1},e.map(o=>kt.createElement(Yn,{key:o.email},kt.createElement(Yn,{color:h.accent}," \xB7 "),kt.createElement(Yn,null,o.email),kt.createElement(Yn,{color:h.secondary2},` ${o.commits} commit${o.commits===1?"":"s"} as ${o.names.join(", ")||"unknown"}`))),kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.secondary2},"Claim yours by address, or",kt.createElement(Yn,{color:h.accent}," none "),"to skip.")))};var sM=({isDone:e,command:t,value:n,verb:r="Type",hint:o})=>$e.createElement(Fl,null,$e.createElement(Dt,{color:h.accent,dimColor:e},e?" \u2714 ":" "),$e.createElement(Dt,{dimColor:e},r," "),$e.createElement(Dt,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&$e.createElement($e.Fragment,null,$e.createElement(Dt,{dimColor:e}," "),$e.createElement(Dt,{color:h.secondary,dimColor:e},"<"+n+">")),o),iM=(e,t)=>e.length===0?void 0:_n(e.join(", "),Math.max(12,t-34)),aM=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function im({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l,isSetEmails:d,claimedEmails:m,emailSetupDeclined:p}=Un(),f=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:i,message:"Almost there. Configure auto sync."},{key:"emails",done:d,command:":config emails",value:p?"declined":iM(m,e),message:"Last one. Claim the git addresses whose commits are yours, so the board calls them by your name."}],g=f.findIndex(x=>!x.done),y=g===-1?void 0:f[g];return $e.createElement(Fl,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},$e.createElement(Dt,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),$e.createElement(Dt,null,"Let's get you started - it's a breeze."),$e.createElement(Dt,{color:h.secondary2},"Remember - you can always search available commands by typing:",$e.createElement(Dt,{color:h.accent}," ? ")),y&&$e.createElement(Dt,{color:h.secondary2},y.message),$e.createElement(Fl,{flexDirection:"column"},f.map((x,b)=>{if(!(g===-1||b<=g))return null;let S=b===g,T=S&&g===0;return $e.createElement(Fl,{key:x.key,flexDirection:"column",marginBottom:1},$e.createElement(sM,{isDone:x.done,command:T?":config us":x.command,value:x.done?aM(x.value):void 0,verb:S&&!T?"Waiting:":"Type",hint:T?$e.createElement(Dt,{color:h.secondary2}," then ",$e.createElement(Dt,{color:h.accent},"tab")," to auto-complete ",$e.createElement(Dt,{backgroundColor:h.secondary},` ${x.command.split(" ").pop()} `)):void 0}),x.key==="emails"&&!x.done&&$e.createElement(vx,null))})))}import Hl from"chalk";import{Box as wi,Text as rs}from"ink";import Ze from"react";import{Box as _l,Text as bx}from"ink";import Tr from"react";import lM from"chalk";var cM=e=>(N.getTag(e)?.name??"").length+3,dM=e=>{let t=N.getContributor(e);return(t?t.name:"").length+3},xx=({width:e})=>{let{viewMode:t}=V(),n=oe(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],d=Nt(l?.id??o.id,"TICKET"),m=be(d)?d.value:void 0,p=(m?.props.tags??[]).filter(M=>N.getTag(M)),f=m?.props.assignees??[],g=m?.parentNodeId?!cu(o.id,m.parentNodeId)&&t==="dense":!1,y=r.map((M,O)=>{let W=O===r.length-1,X=Ie(M.id),Ee=W?X?.[s]?.title:void 0;return`${O?" / ":""}${M.title??""}${Ee?` \u25B8 ${Ee}`:""}`}).join(""),x=m?N.getCommentsByIssue(m.id):[],b=x.length?String(x.length).length+11:0,R=g?p.reduce((M,O)=>M+cM(O),0)+f.reduce((M,O)=>M+dM(O),0)+b:0,S=l?.id!=null&&!(t==="wide"&&_(l)),T=Math.max(0,e-R),A=y.substring(0,T)+(S?lM.hex(h.secondary2).dim(` ${H(l.id)}`):""),P=g?[...p.map(M=>Tr.createElement(_l,{key:`tag-${M}`,paddingLeft:1},Tr.createElement(Lo,{id:M}))),...f.map(M=>Tr.createElement(_l,{key:`assignee-${M}`,paddingLeft:1},Tr.createElement(ur,{id:M}))),x.length?Tr.createElement(_l,{key:"comments",paddingLeft:1},Tr.createElement(bx,{color:h.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Tr.createElement(_l,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Tr.createElement(bx,{color:h.secondary2},A),P)};import{Box as uM,Text as Ix}from"ink";import $l from"react";var mM=({filters:e})=>$l.createElement(uM,{columnGap:1},$l.createElement(Ix,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>$l.createElement(Ix,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ex=$l.memo(mM);import{Box as pM,Text as Ul}from"ink";import Ti from"react";function Sx(){let{eventLog:e,unappliedEvents:t}=oe(),n=e.at(-1)?.id,r=yo(n??""),o=be(r)?Fa(r.value):"INVALID DATE";return Ti.createElement(pM,{paddingLeft:1},Ti.createElement(Ul,{backgroundColor:h.accent,color:h.secondary}," Readonly "),Ti.createElement(Ul,{color:h.accent}," "+t.length+" edits ago at "+o+"."),Ti.createElement(Ul,{color:h.accent}," Resume with "),Ti.createElement(Ul,{backgroundColor:h.accent,color:h.secondary}," ",":peek now"," "))}import{Box as fM,Text as am}from"ink";import jl from"react";function Rx(){let{replay:e}=oe();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return jl.createElement(fM,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},jl.createElement(am,{backgroundColor:h.accent,color:h.secondary}," \u25B6 REPLAY "),jl.createElement(am,{color:h.secondary2},Fa(new Date(r))),jl.createElement(am,{color:h.accent},`${t}/${n} edits`))}import lm from"chalk";import{Box as gM,Text as Cx}from"ink";import cm,{useEffect as hM,useState as yM}from"react";var vM=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],bM=150,Nx=12,xM=.36,Ax=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)}},IM=({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)}`},EM=(e,t,n)=>{let r=Ax(e),o=Ax(t);return IM({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},SM=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return EM(s,i,o)};function Tx({syncStatus:e,autoSync:t}){let[n,r]=yM(0);hM(()=>{if(e.status!=="syncing"){r(0);return}let l=0,d=setInterval(()=>{l+=1;let m=(Math.sin(l*xM)+1)/2,p=Math.round(m*(Nx-1));r(f=>f===p?f:p)},bM);return()=>clearInterval(d)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:h.secondary2,failed:h.yellow,offline:h.secondary2,pending:h.secondary2,syncing:SM(vM,n/(Nx-1))??""}[e.status];return cm.createElement(gM,null,cm.createElement(Cx,null,lm.hex(h.secondary2).dim(t?"Sync (auto): ":"Sync: ")),cm.createElement(Cx,null,lm.hex(i)("\u25CF")+lm.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import kx from"chalk";import{Text as Dx}from"ink";import Bx,{useEffect as AM,useState as TM}from"react";import dm from"chalk";var RM="https://registry.npmjs.org/epiq/latest",um=null,wx=0,CM=1e3*60*60*24,Mx=e=>e.replace(/^v/,""),NM=(e,t)=>{let n=Mx(e).split(".").map(Number),r=Mx(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Px=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(um&&Date.now()-wx<CM)return um;try{let t=await fetch(RM);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?NM(r,e)>0:!1};return um=o,wx=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Lx=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?dm.hex(h.accent).dim(s):dm.hex(h.secondary).dim(s)).join(dm.hex(h.secondary2).dim("."))};function Ox(){let[e,t]=TM({current:Mn,latest:null,updateAvailable:!1});return AM(()=>{let n=!0;return Px(Mn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Bx.createElement(Dx,{dimColor:!0,color:h.secondary2},Mn+" "):Bx.createElement(Dx,null,kx.hex(h.secondary2).dim(Mn),kx.hex(h.accent).dim(" \u2197 "),Lx(Mn,e.latest))}function Mi({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=oe(),{userName:i,preferredEditor:l,autoSync:d}=V(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?Fn(s.currentLabel,Math.max(0,p)):"";return Ze.createElement(wi,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Ze.createElement(wi,{paddingLeft:1},Ze.createElement(rs,{color:h.secondary2},g)):f?Ze.createElement(rs,null," "):o===I.PALETTE?Ze.createElement(wi,null,Ze.createElement(rs,{color:h.accent},"Command Palette"),Ze.createElement(rs,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):Ze.createElement(wi,{paddingLeft:1},e.length>0?Ze.createElement(Ex,{filters:e}):Ze.createElement(xx,{width:p})),n==="live"?Ze.createElement(wi,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Ze.createElement(Tx,{autoSync:!!d,syncStatus:r}),Ze.createElement(rs,null,Hl.hex(h.secondary2).dim("Mode: ")+Hl.hex(h.secondary2).dim(o.padEnd(8," "))," "),Ze.createElement(Fx,{icon:"@",value:i}),Ze.createElement(Fx,{icon:"\u276F",value:l}),Ze.createElement(Ox,null)):"",n==="peek"?Ze.createElement(Sx,null):"",n==="replay"?Ze.createElement(Rx,null):"")}function Fx({icon:e,value:t}){return Ze.createElement(rs,null,Hl.dim(e)+Hl.hex(h.accent)(` ${t??"-"} `))}import{Box as wM,Text as MM}from"ink";import Pi from"react";import{Box as Wl,Text as mm}from"ink";import wr from"react";function pm(){let e=oe(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?de(t?.id):[];return wr.createElement(Wl,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:s},wr.createElement(Wl,{padding:1,paddingTop:0,paddingBottom:0},wr.createElement(mm,null,"Select a board:")),wr.createElement(Wl,{padding:1,flexDirection:"column"},i.map((l,d)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===d,f=de(l.id).flatMap(({id:g})=>Ie(g)).length;return wr.createElement(Wl,{key:l.id??d},wr.createElement(mm,{color:m?h.accent:h.secondary2},wr.createElement(St,{isSelected:m})),wr.createElement(mm,{color:m?h.accent:h.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var PM=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=oe(),d=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Pi.createElement(wM,{flexDirection:"row"},e.context==="WORKSPACE"?Pi.createElement(pm,null):d?Pi.createElement(Xa,{height:f,width:i,swimlanes:(l[d.id]??[]).filter(g=>g!==void 0&&gn(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Pi.createElement(MM,null))},_x=Pi.memo(PM);import{useEffect as LM}from"react";var kM=e=>{LM(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=V();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:d}=v();d==="default"&&!l&&Pa(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},$x=({autoSync:e})=>(kM(e),null);function fm({width:e,height:t}){let n=oe(),{autoSync:r,viewMode:o}=Zm(),s=n.filters;if(n.mode===I.HELP)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(fx,{width:e,height:t}));if(n.mode===I.IDENTITY)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(gx,{width:e,height:t}));if(n.mode===I.PALETTE)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{filters:s}),ke.createElement(Xb,{width:e,height:t-2}),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Un(),l=!i,d=i&&!n.hasProjectDefinition;if(l)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{hideBreadCrumb:!0,filters:s}),ke.createElement(im,{height:t,width:e})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:[]}));if(d)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{hideBreadCrumb:!0,filters:s}),ke.createElement(hx,{height:t,width:e})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:[]}));let m=yt(n.breadCrumb??[],"BOARD");if(be(m)){let p=m.value.id,f=de(p).length,g=3,y=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,y)*Math.max(f,g)}return ke.createElement(Xn,{flexDirection:"column"},ke.createElement($x,{autoSync:r}),ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{filters:s}),ke.createElement(_x,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:n.availableHints}))}import DM from"readline";var Gl,Vl,Ln,BM=new Set([E.MoveCursorLeft,E.EraseInputWord,E.MoveCursorLeftOfWord,E.MoveCursorRight,E.MoveCursorRightOfWord,E.NavToPreviousContainer,E.NavToNextContainer,E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.SetViewDense,E.SetViewWide,E.Confirm,E.Exit,E.Yank,E.InitCommandLine,E.InitCommandPalette,E.ExitCommandLine,E.CaptureInput,E.EraseInput,E.EraseInputWord,E.HideHelp,E.ViewHelp,E.SetViewDense,E.SetViewWide,E.GetLastCommandFromHistory,E.GetNextCommandFromHistory,E.AutoCompleteCommand]),OM=new Set([E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.NavToPreviousContainer,E.NavToNextContainer,E.Confirm,E.Exit,E.InitCommandPalette,E.InitMove,E.MoveNextItem,E.MovePreviousItem,E.MoveNextItemJump,E.MovePreviousItemJump,E.MoveToNextContainer,E.MoveToPreviousContainer,E.Delete,E.AddItem,E.EditTitle,E.EditDescription,E.ConfirmMove,E.Edit,E.ViewHelp,E.Yank]),Ux=async e=>{if(e.ctrl&&e.name==="c")return U.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=yf(e,n);if(!s||r&&!BM.has(s)||o==="replay"&&n===I.DEFAULT&&OM.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},FM=()=>async function(t,n){n.name!=="escape"&&(Ln&&(clearTimeout(Ln),Ln=void 0),await Ux(n))},_M=()=>async function(t){if(t.length===1&&t[0]===27){Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{Ux({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ln=void 0},25);return}Ln&&(clearTimeout(Ln),Ln=void 0)};function jx(){Gl&&process.stdin.removeListener("keypress",Gl),Vl&&process.stdin.removeListener("data",Vl),Gl=FM(),Vl=_M(),DM.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Vl),process.stdin.on("keypress",Gl)}async function Hx(){try{let e=lo({});if(a(e))return tn(0,e.message);let t=ht();be(t)&&je(t.value);let n=me(process.cwd());je({gitEmail:await yl(process.cwd()),gitName:await Rr(process.cwd())});let r=be(n)?await el(n.value):Ay();if(a(r))return r;let o=gm();return a(o)?tn(6,o.message):(jx(),be(n)&&tl(n.value),u("Booted Epiq",void 0))}catch(e){return tn(0,wo(e))}}dy();var HM=`${cn.bold("Epiq CLI")}
|
|
91
|
+
${c}
|
|
92
|
+
`,su.writeFileSync(t,n,"utf8"),ee.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)};var kN=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return a(t)?t:d("Checked git diff",t.value.stdout.split(`
|
|
93
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},ce=(e,t)=>l(`[${e}] ${t}`),Cy=async({cwd:e,user:t})=>{let n=ji(),r=await Jt(e);if(a(r))return ce(1,r.message);let o=r.value,s=await Bm(o);if(a(s))return ce(2,s.message);if(s.value)return ce(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await kN(o);if(a(i))return ce(2.5,i.message);if(i.value.length>0)return ce(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(hs(o))return ce(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return ce(5,"Missing Epiq user id");let p=await zg(o);if(a(p))return ce(6,p.message);let m=n.stateBranch,f=await Hi({repoRoot:o,branch:m});if(a(f))return ce(6,f.message);if(f.value)return ce(6,`State branch already exists: ${m}`);let g=await DN({repoRoot:o,stateBranch:m});if(a(g))return ce(6,g.message);if(g.value)return BN({repoRoot:o,stateBranch:m});let h=await Ed({repoRoot:o,stateBranchName:m});if(a(h))return ce(6,h.message);let x=ps();if(a(x))return ce(7,x.message);let b=iu.join(Pr(),n.projectId),R=await ur({repoRoot:o,stateBranchRoot:b,stateBranchName:m});if(a(R))return ce(8,R.message);let S=iu.join(b,".epiq");LN.mkdirSync(S,{recursive:!0});let A=Bg({userId:c,userName:u});if(a(A))return ce(9,A.message);for(let ft of A.value){let ao=hg({event:ft,rootDir:b});if(a(ao))return ce(9,ao.message)}let T=ar({userId:c}),P=ga(b,T);if(a(P))return ce(9,P.message);let M=Id(b,n);if(a(M))return ce(9,M.message);let O=await Pa({stateBranchRoot:b,eventFileName:T});if(a(O))return ce(10,O.message);let W=await Ce.stage({cwd:b,pathspec:[dt]});if(a(W))return ce(10,W.message);let Y=await go({cwd:b,message:"[epiq:init]"});if(a(Y))return ce(10,Y.message);let xe=await Ry(o);if(a(xe))return ce(11,xe.message);let F=lc({repoRoot:o,fileContents:n});if(a(F))return ce(12,F.message);let X=await Ce.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(a(X))return ce(13,X.message);let Ve=await Ce.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Ve))return ce(13,Ve.message);let Qn=[],is=await U({cwd:o,args:["push","-u","origin","HEAD"]});a(is)&&Qn.push(`[init:14] ${is.message}`);let st=await Gs({repoRoot:o,stateBranchRoot:b});return a(st)&&Qn.push(`[init:15] ${st.message}`),d("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:m,stateBranchRoot:b,defaultEvents:A.value,warnings:Qn})},DN=async({repoRoot:e,stateBranch:t})=>{let n=await On({repoRoot:e});if(a(n))return l(n.message);if(!n.value)return d("No remote",!1);let r=await cs({repoRoot:e,branch:t});return a(r)?l(`Could not ask origin whether ${t} exists: ${r.message}`):r},BN=async({repoRoot:e,stateBranch:t})=>{let n=await U({cwd:e,args:["fetch","origin",t]});if(a(n))return ce(6,n.message);let r=await U({cwd:e,args:["show",`origin/${t}:${dt}`]});if(a(r))return ce(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${dt} from a checkout that has it, for example:`,"",` git show origin/main:${dt} > ${dt}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
94
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(x){return ce(6,`The identity on origin/${t} is not readable: ${x instanceof Error?x.message:String(x)}`)}let s=lc({repoRoot:e,fileContents:o});if(a(s))return ce(12,s.message);let i=await Ce.stage({cwd:e,pathspec:[dt]});if(a(i))return ce(13,i.message);let c=await Ce.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[dt]});if(a(c))return ce(13,c.message);let u=ps();if(a(u))return ce(7,u.message);let p=iu.join(Pr(),o.projectId),m=await Ws({repoRoot:e,stateBranchName:t});if(a(m))return ce(8,m.message);let f=await ur({repoRoot:e,stateBranchRoot:p,stateBranchName:t});if(a(f))return ce(8,f.message);let g=[],h=await U({cwd:e,args:["push","-u","origin","HEAD"]});return a(h)&&g.push(`[init:14] ${h.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:p,defaultEvents:[],warnings:g})};var ni=(e,t)=>l(`[${e}] ${t}`),Ny=async()=>{J("");let e=Un();if(!e.isSetupDone||!e.userName)return ni(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=V(),n=t.userName,r=t.userId;if(!r||!n)return ni(5,"Missing Epiq user id");let o=await Cy({cwd:process.cwd(),user:{userId:r,userName:n}});if(a(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let c=tn(o.value.defaultEvents).filter(a);if(c.length>0)return ni(16,c.map(g=>g.message).join(`
|
|
95
|
+
`));let u=de();if(a(u))return ni(16,u.message);let{rootNodeId:p,nodes:m}=u.value,f=m[p];return f?($.navigate({contextNode:f,selectedIndex:0}),w({hasProjectDefinition:!0}),d(s,null)):ni(16,"Unable to resolve initialized root node")};import{ulid as FN}from"ulid";import{ulid as ON}from"ulid";var Ay=null,ln=()=>structuredClone(Ay),ri=e=>{Ay=e},Ty=()=>{let{contextNode:e,selectedIndex:t}=v(),r=be(e.id)[t];return r?d("Resolved selected child",r):l("Target node not found")},au=({id:e,parentId:t,position:n={at:"end"}})=>{let r=be(t).filter(o=>o.id!==e);return Ca(r,n)},wy=({id:e,parentId:t,position:n={at:"end"}})=>{let r=pe();if(a(r))return l("Unable to resolve user ID");let o=au({parentId:t,id:e,position:n});return a(o)?o:d("Created pending move state",{id:ON(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},My=e=>{ri(e);let t=js(e,!0);return a(t)?t:d("Node moved successfully",t.value)};function lu(e){let t=Ty();if(a(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return l("Missing parent node id");let o=r[n.parentNodeId];if(!o)return l("Missing parent node");let s=be(o.id),i=s.findIndex(({id:p})=>p===n.id);if(i<0)return l("Current node not found among siblings");let c=s[i+e];if(!c)return l("Missing sibling node");let u=wy({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:My(u.value)}function oi(e,t=1){let n=Ty();if(a(n))return n;let{contextNode:r,selectedIndex:o}=v(),s=be(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),c=i===o?void 0:s[i];if(!c)return l("Missing sibling node");let u=wy({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:c.id}});return a(u)?u:My(u.value)}var Py=()=>{let e=ln();if(!e)return l("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return l("Move parent not found");let o=be(n).findIndex(s=>s.id===t);return o===-1?l("Moved node not found among rendered children"):($.navigate({contextNode:r,selectedIndex:o}),d("Synchronized navigation to moved node",null))},Ko=(e,t="Moved preview")=>{if(a(e))return ln()&&w({mode:I.MOVE}),e;let n=Py();return a(n)?n:(w({mode:I.MOVE}),d(t,null))},Ly=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{modifier:t}=se().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=be(n.id)[r];if(!o)return w({mode:I.DEFAULT}),l("No move target");if(t==="start"){if(o.readonly)return l("Target node is read-only");if(r===-1)return l("No item selected");if(!o.parentNodeId)return l("Target has no parent");let s=be(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return l("Target not found among siblings");let c=s[i-1],u=s[i+1],p=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},m=au({parentId:o.parentNodeId,id:o.id,position:p});return a(m)?m:(ri({id:FN(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:m.value.rank},...D(e.value)}),w({mode:I.MOVE}),d("Move initialized",null))}if(t==="next")return Ko(oi(1));if(t==="previous")return Ko(oi(-1));if(t==="jump-next")return Ko(oi(1,$s));if(t==="jump-previous")return Ko(oi(-1,$s));if(t==="to-next")return Ko(lu(1));if(t==="to-previous")return Ko(lu(-1));if(t==="confirm"){let s=ln();if(!s)return l("No pending move to confirm");let i=await Ie();if(a(i))return i;let c=B([s],i.value);if(a(c))return c;let u=Py();return a(u)?u:(ri(null),w({mode:I.DEFAULT}),d("Moved item",null))}return t==="cancel"?(ri(null),w({mode:I.DEFAULT}),d("Cancelling move",null)):l("Invalid move modifier")};import{ulid as al}from"ulid";import{monotonicFactory as _N,ulid as jN}from"ulid";var $N=_N(),il=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=$N();return d("Created issue events",[{id:jN(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])};var ky=async(e,t)=>{let n=pe();if(a(n))return l("Unable to resolve user ID");let r=await Ie();if(a(r))return r;let o=r.value;if(!t.inputString)return l(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=v(),u=p=>{let m=B([p],o);if(a(m))return m;let f=N.getNode(m.value[0].result.id);if(!f)return l("Created node not found");if(!f.parentNodeId)return m;let g=N.getNode(f.parentNodeId);return g?($.navigate({contextNode:g,selectedIndex:N.getSiblings(f.parentNodeId).findIndex(({id:h})=>h===f.id)}),m):l("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:p}=v(),m=N.getNode(p);if(!m)return l("Workspace not found");let f=Wn(m.id,n.value,o);return a(f)?f:u({id:al(),action:"add.board",payload:{id:al(),name:t.inputString,parent:m.id,rank:f.value},...D(n.value)})}if(t.modifier==="swimlane"){let p=yt(s,"BOARD");if(a(p))return l("Unable to add swimlane in this context");let m=Wn(p.value.id,n.value,o);return a(m)?m:u({id:al(),action:"add.swimlane",payload:{id:al(),name:t.inputString,parent:p.value.id,rank:m.value},...D(n.value)})}if(t.modifier==="issue"){let p=le(i.id)[c],m=i.context==="SWIMLANE"?i:i.context==="BOARD"&&p?.context==="SWIMLANE"?p:(()=>{let A=yt(s,"SWIMLANE");return a(A)?null:A.value})();if(!m)return l("Unable to add issue in this context");let f=Wn(m.id,n.value,o);if(a(f))return f;let g=il({name:t.inputString,parent:m.id,rank:f.value,user:n.value});if(a(g))return g;let h=g.value,x=B([...h],o);if(a(x))return x;if(!x.value[0])return l("Issue creation failed");let S=h.find(A=>A.action==="add.issue")?.payload.id;return S?($.navigate({contextNode:m,selectedIndex:N.getSiblings(m.id).findIndex(({id:A})=>A===S)}),d("Issue created",null)):l("Unable to determine ticket id")}return d("Success",null)};import XN from"node:os";import Uy from"node:path";import si from"node:fs";import UN from"node:path";import{z as Kr}from"zod";var ii="command-history.json",HN=20,WN=Kr.object({projectId:Kr.string().min(1),commands:Kr.array(Kr.string()),lastUsedAt:Kr.number().finite()}),GN=Kr.object({projects:Kr.array(WN)}),Dy=()=>{let e=Zs();return a(e)?e:d("Resolved command history path",UN.join(e.value,ii))},VN=()=>{try{let e=re(process.cwd());return a(e)?null:e.value}catch{return null}},By=e=>{if(!si.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=si.readFileSync(e,"utf8")}catch(o){return l(`Unable to read ${ii}: ${o instanceof Error?o.message:String(o)}`)}let n;try{n=JSON.parse(t)}catch(o){return d("Unparsable command history",{state:"corrupt",reason:`Invalid ${ii}: ${o instanceof Error?o.message:String(o)}`})}let r=GN.safeParse(n);return r.success?d("Read command history",{state:"read",projects:r.data.projects}):d("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${ii} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},Oy=({root:e})=>{let t=pn(e);if(a(t))return l(t.message);let n=Dy();if(a(n))return n;let r=By(n.value);if(a(r))return r;let o=r.value;if(o.state==="corrupt")return l(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return d("Read command history",s?.commands.slice(0,Ms)??[])},Fy=({commands:e,root:t=VN(),now:n=Date.now()})=>{if(t===null)return d("No project; command history not stored",null);let r=pn(t);if(a(r))return l(r.message);let o=Dy();if(a(o))return o;let s=o.value,i=By(s);if(a(i))return i;let c=i.value,u=c.state==="read"?c.projects:[],p=[{projectId:r.value,commands:e.slice(0,Ms),lastUsedAt:n},...u.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,HN),m=`${s}.${process.pid}.tmp`;try{si.writeFileSync(m,JSON.stringify({projects:p},null,2)+`
|
|
96
|
+
`,"utf8"),si.renameSync(m,s)}catch(f){try{si.rmSync(m,{force:!0})}catch{}return l(`Unable to write ${ii}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)};var zN=e=>e.some(t=>t.action==="init.workspace"),_y=async(e,t)=>{let n=ke(e);return a(n)?l(n.message):us({cwd:t,branch:n.value})},KN=e=>{let t=re(process.cwd());if(a(t))return!1;let n=me({repoRoot:t.value});return!a(n)&&n.value===e},cu=!1,jy=()=>cu,ll=async e=>{cu=!0;try{return await qN(e)}finally{cu=!1}},qN=async e=>{let t=me({repoRoot:e});if(a(t))return on(3,t.message);let n=t.value,r=await ur({repoRoot:e,stateBranchRoot:n,stateBranchName:ji().stateBranch});if(a(r))return on(3,r.message);let o=et(n),s=nn(n);if(a(s))return on(3,s.message);if(!zN(s.value.events)){let f=await Vs({worktreeRoot:n,operation:"boot pull",fn:()=>Oa(n,()=>_y(e,n))});if(a(f)?logger.info(3,f.message):f.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(f.value)&&logger.info(3,f.value.message),o=et(n),s=nn(n),a(s))return on(3,s.message)}let{events:i,unreadable:c}=s.value,u=rn(i,c);if(a(u))return on(4,u.message);To(n,o),w({hasProjectDefinition:!0,hasInitializingEvents:!!i.length});let p=ea({root:e});a(p)&&logger.info(p.message);let m=Oy({root:e});return a(m)&&logger.info(m.message),Rf(a(m)?[]:m.value),d("Loaded project",void 0)},YN=async e=>{let t=me({repoRoot:e});if(a(t))return l(t.message);let n=t.value,r=await On({repoRoot:n});if(a(r))return l(r.message);if(!r.value)return d("No remote to pull",void 0);let o=await Vs({worktreeRoot:n,operation:"boot pull",fn:()=>Oa(n,()=>(Mo("Pulling"),_y(e,n)))});if(a(o))return We(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return ds(s.message)?(wa("Offline"),d("Offline",void 0)):We(s.message);if(!s.value)return Ur("Already synced"),d("Already synced",void 0);if(!KN(n))return d("Project changed during the pull",void 0);let i=zs(n);return a(i)?i:(Ur("Pulled"),d("Pulled and reloaded",void 0))},cl=e=>{YN(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Po(t)}`)})},$y=()=>{let e=rn([]);return a(e)?on(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),d("Booted without a project",void 0))};var JN=e=>e==="~"||e.startsWith("~/")?Uy.join(XN.homedir(),e.slice(1)):e,QN=(e,t)=>{let n=e.trim();if(!n)return l("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?d("Resolved recent project",o.root):l(`No recent project #${n}`)}let r=re(Uy.resolve(JN(n)));return a(r)?l(`No epiq project at ${n}`):d("Resolved project path",r.value)},Hy=async()=>{let e=da();if(J(""),v().hasProjectDefinition)return l("Already in a project; run epiq from another directory");let t=$n({exclude:process.cwd()}),n=a(t)?[]:t.value,r=QN(e,n);if(a(r))return l(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(c){return l(`Unable to enter ${o}: ${c instanceof Error?c.message:String(c)}`)}let i=await ll(o);return a(i)?(process.chdir(s),l(i.message)):(cl(o),d(`Opened ${Eo(o)}`,null))};var dl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=Sa(n,t);if(a(s))return l(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=cn();if(a(u))return u;let p=tn(i),{fatal:m,skipped:f}=En(p);if(m.length>0)return cn(),w(o),l(m.map(h=>h.message).join(", "));Sn(f);let g=v().nodes[e];return g?($.navigate({contextNode:g,selectedIndex:r}),d("",{unappliedEvents:c})):(cn(),w(o),l("Board did not exist at that date"))};var Wy=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)};var ZN=20,eA=16,tA=150,ul=null,ml=null;var qr=()=>{ul!==null&&(clearInterval(ul),ul=null),ml!==null&&(clearTimeout(ml),ml=null)},Gy=()=>{qr(),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Vy=({events:e,startTime:t,durationMs:n})=>{qr();let r=e.length,o=yo(e.map(f=>tr(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Wy(o),c=Math.max(1,Math.round(n*ZN/1e3)),u=Math.max(Math.round(n/c),eA),p=0,m=0;w({mode:I.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),ul=setInterval(()=>{p++;let f=p/c,g=[],h,x;for(;m<r&&i[m]<=f;){let R=e[m],S=js(R);if(a(S)){if(wo(S)){m++;continue}Gy();return}g.push(...hd(R)),h=R,x=o[m],m++}if(m>=r||p>=c){for(;m<r;m++){let S=js(e[m]);if(a(S)&&!wo(S))break}let R=v().replay;w({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),qr(),ml=setTimeout(Gy,tA);return}let b=v().replay;w({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:r,startTime:t,endTime:s,currentTime:h?x??b?.currentTime??t:b?.currentTime??t,currentLabel:h?pl(h):b?.currentLabel??"",flashNodeIds:h?[...new Set(g)]:b?.flashNodeIds??[]}})},u)};var zy=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await Jt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=me({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=se().commandMeta;if(qr(),r==="now"){let c=dr(n.value);if(a(c))return l(c.message);let u=cn();if(a(u))return u;let p=tn(c.value),{fatal:m,skipped:f}=En(p);return m.length>0?l(m.map(g=>g.message).join(", ")):(Sn(f),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let c=Ra(n.value);if(a(c))return c;let u=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),p=u===void 0?null:tr(u),m=(u===void 0?null:c.value.get(u.id)??null)??(p===null?null:vs(p));if(m===null)return l(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?m:m+1}else{let c=Lr(r||o.trim());if(!c)return l("Invalid peek date");s=c.getTime()}let i=dl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(w({mode:I.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))};var Ky=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await Jt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=me({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=se().commandMeta,{dateInput:s,durationInput:i}=sa(r,o);if(qr(),v().syncStatus.status==="syncing")return l("Cannot replay while syncing, try again in a moment");let c=Lr(s);if(!c)return l("Invalid replay date");let u=i?oa(i):15e3;if(u===null)return l("Invalid replay duration (try e.g. 30s or 2m)");let p=c.getTime(),m=v(),f=dl({boardId:e.value.id,targetTime:p,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(cn(),w(m),d("Nothing to replay from that point",!0)):(Vy({events:g,startTime:p,durationMs:u}),d("Replaying board history",!0))};import{spawn as rA}from"node:child_process";var oA=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},qy=async e=>new Promise(t=>{let{command:n,args:r}=oA();try{let o=rA(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(l(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?d("Copied to clipboard",null):l(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(l(`Clipboard tool not available (${n})`))}});var ai=async(e,t)=>{if(!e.trim())return l(`Nothing to copy: ${t} is empty`);let n=await qy(e);return a(n)?n:d(`Copied ${t} to clipboard`,null)},Yy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=Cs({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return l("Nothing selected to copy from");switch(e.modifier){case qe.REF:return ai(H(o.id),"ref");case qe.TITLE:return ai(o.title,"title");case qe.DESCRIPTION:return r?ai(r.props?.description??"","description"):l("No issue in scope");case qe.TAGS:{if(!r)return l("No issue in scope");let s=vn(r).map(({name:i})=>i);return ai(s.join(", "),"tags")}case qe.ASSIGNEES:{if(!r)return l("No issue in scope");let s=bn(r).map(({name:i})=>i);return ai(s.join(", "),"assignees")}default:return l("Yank one of: ref, title, description, tags, assignees")}};var Xy=async()=>{J(""),w({mode:I.DEFAULT});let e=de();if(a(e))return l(e.message);if(e.value.syncStatus.status==="syncing")return l("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await _a();return a(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:I.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as Jy}from"ulid";var Qy=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=le(t.id)[n];if(!r)return l("Unable to resolve child to delete");let o=await Ie();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=_(t)?t.id:t.parentNodeId;if(!i)return l("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!_(c))return l("Unable to resolve comment issue");let u=c.log?.filter(bh).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?l("You can only delete your own comments"):B([{id:Jy(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],o.value):l("Unable to resolve comment")}return B([{id:Jy(),action:"delete.node",payload:{id:r.id},...D(e.value)}],o.value)};import{ulid as sA}from"ulid";var Zy=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=le(t.id)[n];if(!r)return l("Unable to close issue, no target found");if(!_(r))return l("Cannot close in this context");let o=v().nodes[he];if(!o)return l("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return l("Issue is already closed");let s=await Ie();if(a(s))return s;let i=s.value,c=Rn(o.id,r.id,{at:"end"},e.value,i);if(a(c))return c;let u=B([{id:sA(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...D(e.value)}],i);return a(u)?u:d("Issue closed",null)};import{ulid as iA}from"ulid";var fl=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};var ev=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=le(t.id)[n];if(!r)return l("Unable to reopen issue, no target found");let o=r.context==="TICKET"?d("Resolved ticket",r):Tt(r.id,"TICKET");if(a(o))return l("Cannot reopen in this context");let s=o.value,i=v().nodes[he];if(!i)return l("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return l("Issue is not closed");if(!_(s))return l("Target node is not issue");let c=fl(s);if(!c)return l("Unable to resolve previous parent from issue history");if(c===i.id)return l("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return l("Previous parent no longer exists");let p=await Ie();if(a(p))return p;let m=p.value,f=Rn(u.id,s.id,{at:"end"},e.value,m);if(a(f))return f;let g=B([{id:iA(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...D(e.value)}],m);return a(g)?g:d("Issue reopened",null)};import{ulid as aA}from"ulid";var tv=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=le(t.id)[n];if(!r)return l("Missing node");if(r.readonly)return l("Cannot rename readonly node");let o=da();if(!o)return l("Provide a title");let s=await Ie();return a(s)?s:B([{id:aA(),action:"edit.title",payload:{id:r.id,name:o},...D(e.value)}],s.value)};import{ulid as lA}from"ulid";var nv=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let o=N.findTagByName(r);if(!o)return l(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return l("Invalid untag target");let i=Tt(s.id,"TICKET");if(a(i))return l("Unable to untag issue in this context");let c=i.value;if(!_(c))return l("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return l("Issue is not tagged with that tag");let p=await Ie();return a(p)?p:B([{id:lA(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...D(e.value)}],p.value)};import{ulid as du}from"ulid";var rv=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let{selectedNode:o}=v();if(!o)return l("Invalid tag target");let s=Tt(o.id,"TICKET");if(a(s))return l("Unable to tag issue in this context");let i=s.value;if(!_(i))return l("Target node is not issue");let c=await Ie();if(a(c))return c;let u=N.findTagByName(r),p=u?.id??du();return(i.props.tags??[]).includes(p)?l("Already tagged with that tag"):B([...u?[]:[{id:du(),action:"create.tag",payload:{id:p,name:r},...D(e.value)}],{id:du(),action:"add.issue.tag",payload:{id:i.id,tag:p},...D(e.value)}],c.value)};import{ulid as uu}from"ulid";var li=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},ov=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=Ze(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ke(s,i?.name),resolved:!0}:{...Ke(o||e,e),resolved:!1}};var gl=e=>{let{eventLog:t=[],contributors:n}=v();return li({events:t,registry:n,logFileNames:cr(e)})};var sv=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return l("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),u=le(c.id)[i];if(!u)return l("Invalid assign target");let p=Tt(u.id,"TICKET");if(a(p))return l("Unable to assign issue in this context");let m=p.value;if(!_(m))return l("Target node is not issue");let f=await Ie();if(a(f))return f;let g=gl(f.value),h=!o&&s.toLowerCase()==="me",x,b;if(h)x=e.value.userId,b=g.find(A=>A.id===x)?.name??e.value.userName;else{let A=g.filter(P=>P.name===s);if(A.length>1)return l(`"${s}" matches ${A.length} contributors (${A.map(P=>P.id).join(", ")}). Assign from the GUI to choose by id.`);let T=A[0];if(!T&&!o)return l(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=T?.id??uu(),b=T?.name??s}if((m.props.assignees??[]).includes(x))return l("Assignee already assigned");let S=!!v().contributors[x];return B([...S?[]:[{id:uu(),action:"create.contributor",payload:{id:x,name:b},...D(e.value)}],{id:uu(),action:"add.issue.assignee",payload:{id:m.id,assignee:x},...D(e.value)}],f.value)};import{ulid as cA}from"ulid";var iv=async()=>{let e=pe();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return l("Invalid unassign target");let s=Tt(o.id,"TICKET");if(a(s))return l("Unable to unassign in this context");let i=s.value;if(!_(i))return l("Target node is not issue");let c=i.props.assignees??[],u=r.toLowerCase()==="me",p=await Ie();if(a(p))return p;let m=u?c.filter(g=>g===e.value.userId):gl(p.value).filter(g=>g.name===r&&c.includes(g.id)).map(g=>g.id);if(m.length>1)return l(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let f=m[0];return f?B([{id:cA(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],p.value):l(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as av}from"ulid";var dA=e=>{let t=e.trim(),n=yr(),r=n?Yh(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=tl();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=Xh(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=Jh(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:wh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},lv=async e=>{let t=dA(e.inputString);if(!t.ok)return l(t.reason);let{md:n,anchored:r}=t;if(!n)return l("Provide a comment");if(n.length>4e3)return l(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=pe();if(a(o))return l("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),c=yt([...s,i],"TICKET");if(a(c))return l("Edit target must be an issue");let u=c.value;if(!u)return l("Invalid comment target");let p=u.context==="TICKET"?d("Resolved ticket",u):Tt(u.id,"TICKET");if(a(p))return l("Unable to comment on issue in this context");let m=p.value;if(!_(m))return l("Target node is not issue");let f=await Ie();if(a(f))return f;let g=await B([{id:av(),action:"add.issue.comment",payload:{id:av(),issue:m.id,author:o.value.userId,md:n},...D(o.value)}],f.value);return r&&!a(g)&&Vr(null),g};import{ulid as hA}from"ulid";var hl=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",uA=e=>{let t=ht();return a(t)?hl({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:hl(t.value)},ci=()=>{let e=gn();return a(e)?l(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:mo(e.value.autoSyncDebounceMs),blockedReason:uA(e.value)})},qo=e=>{let t=e.intervalMs===void 0?void 0:uo(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return l(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=ci();if(a(n))return n;let r=jt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return l(r.message);je({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=ci();return a(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var cv=()=>{let e=se().commandMeta.inputString,t=uo(e);if(t===null)return l(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=qo({intervalMs:t});return a(n)?n:d(`Auto sync interval set to ${t}ms`,null)};var dv=()=>{let e=se().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return l("Invalid response");let t=Gp(e),n=qo({enabled:t===!0});return a(n)?n:d(`Auto sync set to "${e}"`,null)};import{ulid as fA}from"ulid";var mu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),uv="",mv=new Map,mA=15e3;var pA=async(e,t)=>{let n=`${e} ${t??""}`,r=mv.get(n);if(r&&Date.now()-r.at<za(mA))return d("Cached author scan",r.authors);let o=await Le({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${uv}%ae`]});if(o.exitCode!==0)return l(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
97
|
+
`)){let c=i.lastIndexOf(uv);if(c===-1)continue;let u=i.slice(0,c),p=Ze(i.slice(c+1));if(!nr(p))continue;let m=s.get(p)??{names:new Set,commits:0};u&&m.names.add(u),m.commits+=1,s.set(p,m)}return mv.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},wn=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await pA(e,t);if(a(o))return l(o.message);let s=o.value,i=new Map;for(let u of Object.values(r)){if(u.tombstoned)continue;let p=i.get(u.email)??new Set;p.add(u.contributor),i.set(u.email,p)}let c=new Set(n.flatMap(u=>mu(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>mu(m).some(f=>c.has(f)))||mu(u.split("@")[0]??"").some(m=>c.has(m)),claimedBy:[...i.get(u)??[]]})).sort((u,p)=>u.looksLikeYours===p.looksLikeYours?p.commits-u.commits:Number(p.looksLikeYours)-Number(u.looksLikeYours)))},xr=e=>e.filter(t=>t.claimedBy.length===0);var pv=()=>{let e=$c();if(!e)return d("Nothing here to decline",null);let t=gn(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=jt({declinedEmailBoards:r});return a(o)?l(o.message):(je({declinedEmailBoards:[...new Set([...V().declinedEmailBoards??[],e])]}),d("Declined",null))},fv=async()=>{let e=se().commandMeta.inputString.trim();if(e==="none"){let R=pv();return a(R)?R:d("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=V();if(!t)return l("Set a username first with :config username");let o=de();if(a(o))return l("Board is not loaded");let s=re(process.cwd());if(a(s))return l(s.message);let i=ke(s.value),c=await wn({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(c))return c;let p=xr(c.value);if(So(p.map(R=>R.email)),p.length===0){if(!Hp()){let R=pv();if(a(R))return R}return d("No unclaimed addresses in this history.",null)}if(!e)return w({mode:I.IDENTITY}),d("Opened identity",null);let m=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let R of m){let S=p.find(A=>A.email===Ze(R));if(!S){g.push(R);continue}f.includes(S)||f.push(S)}if(g.length>0)return l(`Not on the list: ${g.join(", ")}. Pick one of ${p.map(R=>R.email).join(", ")}.`);let h=me({repoRoot:s.value});if(a(h))return h;let x=f.map(R=>({id:fA(),action:"link.contributor.email",payload:{contributor:t,email:R.email},userId:t})),b=B(x,h.value);return a(b)?l(b.message):d(`Claimed ${f.map(R=>R.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as gA}from"ulid";var gv=()=>{let e=se().commandMeta.inputString.trim(),{userId:t}=V();if(!t)return l("Set a username first with :config username");let n=de();if(a(n))return l("Board is not loaded");let r=hn(n.value.emailLinks,t);if(r.length===0)return l("You have not claimed any addresses.");if(!e)return l(`Which one? ${r.join(", ")}.`);let o=r.find(u=>u===Ze(e));if(!o)return l(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=re(process.cwd());if(a(s))return s;let i=me({repoRoot:s.value});if(a(i))return i;let c=B([{id:gA(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(c)?l(c.message):d(`Unclaimed ${o}`,null)};var hv=()=>{let e=se().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return l("Invalid response");let n=jt({logLevel:e});return a(n)?n:(je({logLevel:e}),d(`Auto sync set to "${e}"`,null))};var yv=e=>{let t=e.inputString.trim();switch(e.modifier){case ye.USERNAME:{if(process.env[Dn])return l(`Cannot change the configured user while ${Dn} names this process`);let n=gn();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,c=r||hA();if(!i||!c)return l("Unable to resolve user name or id");let u=jt({userName:i,userId:c,preferredEditor:o??""});return a(u)?u:(je({userName:i,userId:c}),d(`Username set to "${i}"`,null))}case ye.EDITOR:{if(!t)return l("No editor provided");let n=jt({preferredEditor:t});return a(n)?n:(je({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case ye.VIEW:{if(t!=="wide"&&t!=="dense")return l("Invalid view mode");let n=jt({viewMode:t});return a(n)?n:(je({viewMode:t}),d(`View set to "${t}"`,null))}case ye.EMAILS:return fv();case ye.EMAILS_UNCLAIM:return gv();case ye.AUTOSYNC:return dv();case ye.LOG_LEVEL:return hv();case ye.SYNC_DEBOUNCE_MS:return cv();case ye.ATTACHMENT_MAX_KB:return sf();default:return l("Unknown config command")}};var pu=()=>{let e=Vp(),t=v().mode;if(!(t!==I.COMMAND_LINE&&t!==I.DEFAULT)){if(!e){w({mode:I.DEFAULT});return}w({mode:I.COMMAND_LINE}),J(e)}};var yl=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:I.COMMAND_LINE,action:Ly},{intent:G.Delete,description:"Delete the currently selected node",mode:I.COMMAND_LINE,action:Qy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:I.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=se().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Be(C.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return l("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Oe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:I.DEFAULT})),d("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:I.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return br({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:I.HELP}),d("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:I.COMMAND_LINE,action:Zy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:I.COMMAND_LINE,action:ev,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:I.COMMAND_LINE,action:Ny,onSuccess:pu},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:I.COMMAND_LINE,action:Hy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:I.COMMAND_LINE,action:ky,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:I.COMMAND_LINE,action:tv,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:I.COMMAND_LINE,action:nv,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:I.COMMAND_LINE,action:rv,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:I.COMMAND_LINE,action:sv,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:I.COMMAND_LINE,action:iv,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:I.COMMAND_LINE,action:async(e,t)=>lv(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:I.COMMAND_LINE,action:Xy},{intent:G.Peek,description:"View board state at another point in time",mode:I.COMMAND_LINE,action:zy},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:I.COMMAND_LINE,action:Ky},{intent:G.Export,description:"Export the current board layout to markdown",mode:I.COMMAND_LINE,action:async()=>{let e=await xy();return a(e)?e:(w({mode:I.DEFAULT}),d("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:I.COMMAND_LINE,action:async()=>($.exit(),d("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:I.COMMAND_LINE,action:async(e,t)=>Sy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:I.COMMAND_LINE,action:async(e,t)=>Yy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:I.COMMAND_LINE,action:(e,t)=>yv(t),onSuccess:pu}];var yA=new Set(["peek","replay","filter","view-help","yank"]),Gt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=se();if(!n)return l("No command to confirm");if(!e&&r===In.Invalid)return l("Invalid command");let i=$a(n);Ef();let{readOnly:c}=v();if(c&&!yA.has(i))return Ps({status:Zn.Fail,message:"Command not available in readonly state",value:null});let u=yl.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!u)return Ps({status:Zn.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:o})}catch(f){return Ps({status:Zn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(p))return Ps(p);let m=!e;if(Sf({addToHistory:m,line:t}),m){let f=Fy({commands:se().commandHistory});a(f)&&logger.info(f.message)}return u.onSuccess?.(),V().autoSync&&ja(),p};var vl=[{intent:E.Exit,mode:I.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:I.COMMAND_LINE}),J("move cancel"),Gt({isForceExecutedBySystem:!0}))},{intent:E.InitMove,mode:I.DEFAULT,description:"[m] move",action:()=>(w({mode:I.COMMAND_LINE}),J("move start"),Gt({isForceExecutedBySystem:!0}))},{intent:E.ConfirmMove,mode:I.MOVE,description:"[m] confirm move",action:()=>(w({mode:I.COMMAND_LINE}),J("move confirm"),Gt({isForceExecutedBySystem:!0}))}],bl=[{intent:E.MovePreviousItem,mode:I.MOVE,action:()=>ln()?(w({mode:I.COMMAND_LINE}),J("move previous"),Gt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:E.MoveNextItem,mode:I.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>ln()?(w({mode:I.COMMAND_LINE}),J("move next"),Gt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:E.MovePreviousItemJump,mode:I.MOVE,action:()=>ln()?(w({mode:I.COMMAND_LINE}),J("move jump-previous"),Gt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:E.MoveNextItemJump,mode:I.MOVE,action:()=>ln()?(w({mode:I.COMMAND_LINE}),J("move jump-next"),Gt({isForceExecutedBySystem:!0})):l("No pending move")}],vv=[{intent:E.MoveToNextContainer,mode:I.MOVE,action:()=>ln()?(w({mode:I.COMMAND_LINE}),J("move to-next"),Gt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:E.MoveToPreviousContainer,mode:I.MOVE,action:()=>ln()?(w({mode:I.COMMAND_LINE}),J("move to-previous"),Gt({isForceExecutedBySystem:!0})):l("No pending move")}];var bv={[oe.WORKSPACE]:[...vl,...bl],[oe.BOARD]:[...vl,...bl],[oe.SWIMLANE]:[...vl,...bl,...vv],[oe.TICKET]:[],[oe.FIELD]:[],[oe.FIELD_LIST]:[],[oe.TEXT]:[],[oe.COMMENT]:[]};import bA from"node:fs";import xA from"node:path";import{spawn as vA}from"node:child_process";function xv(e){let t=process.platform,o=vA(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var Iv=e=>{let t=re(process.cwd());if(a(t))return l("Unable to resolve project root");let n=me({repoRoot:t.value});if(a(n))return l(n.message);let r=Br(e.hash,e.ext),o=xA.join(gs(n.value),r);return bA.existsSync(o)?(xv(o),d(`Opened ${e.name}`,null)):l("Attachment file not found \u2014 run :sync to fetch it")};var Ev=()=>{J("");let{pendingNavTarget:e}=vr();w({mode:I.DEFAULT}),e&&$.navigate(e),br({pendingNavTarget:void 0})},Sv=[{intent:E.ExitCommandLine,mode:I.HELP,action:()=>(Ev(),d("Exiting help",null))},{intent:E.Exit,mode:I.HELP,action:()=>(Ev(),d("Closed help",null))},{intent:E.NavPreviousItem,mode:I.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>($.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:E.NavNextItem,mode:I.HELP,action:()=>($.navigateToNextItem(),d("Navigating to next help item",null))},{intent:E.NavPreviousItemJump,mode:I.HELP,action:()=>($.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:E.NavNextItemJump,mode:I.HELP,action:()=>($.jumpToNextItem(),d("Jumping to next help item",null))},{intent:E.NavToPreviousContainer,mode:I.HELP,action:()=>($.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:E.NavToNextContainer,mode:I.HELP,action:()=>($.navigateToNextContainer(),d("Navigating to next help container",null))}];var Rv=()=>{J(""),w({mode:I.DEFAULT})},Cv=[{intent:E.Confirm,mode:I.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=Ro();return e?(w({mode:I.COMMAND_LINE}),J(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:E.ExitCommandLine,mode:I.IDENTITY,action:()=>(Rv(),d("Closed identity",null))},{intent:E.Exit,mode:I.IDENTITY,description:"[esc] close",action:()=>(Rv(),d("Closed identity",null))}];var IA=e=>{w({mode:I.COMMAND_LINE});let{pendingNavTarget:t}=vr();t&&$.navigate(t),br({pendingNavTarget:void 0}),J(`${e} `)},Nv=()=>{J("");let{pendingNavTarget:e}=vr();e&&$.navigate(e),br({pendingNavTarget:void 0}),w({mode:I.DEFAULT})},Av=[{intent:E.InitCommandPalette,mode:I.DEFAULT,description:"[?] command palette",action:()=>{J("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return br({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:I.PALETTE}),d("Opening command palette",null)}},{intent:E.Confirm,mode:I.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!rr(e))return l("Command only applicable on text nodes");if(e.props.disabled)return l("Command is not available in this context");let t=e.title;return t?(IA(t),d("Selected command",t)):d("No command selected",null)}},{intent:E.ExitCommandLine,mode:I.PALETTE,action:()=>(Nv(),d("Exiting palette",null))},{intent:E.Exit,mode:I.PALETTE,action:()=>(Nv(),d("Closed command palette",null))},{intent:E.NavPreviousItem,mode:I.PALETTE,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.PALETTE,action:()=>($.navigateToNextItem(),d("Navigating to next item",null))},{intent:E.NavToPreviousContainer,mode:I.PALETTE,action:()=>($.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.PALETTE,action:()=>($.navigateToNextContainer(),d("Navigating to next container",null))}];var Tv=()=>{let e=yr();if(!e)return d("Nothing to comment on here",null);let t=tl();if(!t||t.sha!==e)return l("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=Hd(t.rows,Xd(e)??r,r);return o.ok?(w({mode:I.COMMAND_LINE}),J(`${C.COMMENT} ${qh(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):l(o.reason)},wv=[{intent:E.InitCommandLine,mode:I.DEFAULT,description:"[:] write command",action:()=>(w({mode:I.COMMAND_LINE}),J(""),d("Entering command line mode",null))},...Sv,...Cv,...Av,{intent:E.AddItem,mode:I.DEFAULT,description:"[n] new...",action:()=>(w({mode:I.COMMAND_LINE}),J(`${C.NEW} `),d("Adding new item",null))},{intent:E.Delete,mode:I.DEFAULT,description:"[d] delete",action:()=>(w({mode:I.COMMAND_LINE}),J(`${C.DELETE} `),d("Deleting item",null))},{intent:E.Confirm,mode:I.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!be(e?.id??"")?.length){let r=e?N.getAttachment(e.id):void 0;if(r)return Iv(r);if(yr())return Tv();if(e?.title===Ne.DESCRIPTION)return w({mode:I.COMMAND_LINE}),J(`${C.EDIT} description `),d("Propose command",!0);if(e?.title===Ne.ASSIGNEES)return w({mode:I.COMMAND_LINE}),J(`${C.ASSIGN} `),d("Propose command",!0);if(e?.title===Ne.TAGS)return w({mode:I.COMMAND_LINE}),J(`${C.TAG} `),d("Propose command",!0);if(t.title===Ne.DESCRIPTION&&e?.context==="TEXT")return w({mode:I.COMMAND_LINE}),J(`${C.EDIT} description `),d("Propose command",!0)}return $.enterChildNode(),d("Entering context",null)}},{intent:E.OpenInEditor,mode:I.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===Me(n,"diff")?e?.id:yr()??void 0;return o?ei({sha:o}):d("Nothing here opens in an editor",null)}},{intent:E.MarkDiffLine,mode:I.DEFAULT,action:()=>{let e=yr();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=v(),n=Xd(e);return Vr(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:E.CommentOnDiffLine,mode:I.DEFAULT,action:()=>yr()?Tv():d("Nothing to comment on here",null)},{intent:E.Yank,mode:I.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Ne.DESCRIPTION?qe.DESCRIPTION:e?.title===Ne.TAGS?qe.TAGS:e?.title===Ne.ASSIGNEES?qe.ASSIGNEES:qe.REF,r=Be(C.YANK).includes(t)?t:qe.REF;return w({mode:I.COMMAND_LINE}),J(`${C.YANK} ${r}`),d("Propose command",!0)}},{intent:E.EditTitle,mode:I.DEFAULT,description:"[r] rename title",action:()=>(w({mode:I.COMMAND_LINE}),J(`${C.EDIT} title ${v().selectedNode?.title}`),d("Exiting context",null))},{intent:E.EditDescription,mode:I.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:I.COMMAND_LINE}),J(`${C.EDIT} description `),d("Exiting context",null))},{intent:E.Exit,mode:I.DEFAULT,description:"[q] exit context",action:()=>($.enterParentNode(),d("Exiting context",null))},{intent:E.NavPreviousItem,mode:I.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>($.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.DEFAULT,action:()=>($.navigateToNextItem(),d("Navigating to next item",null))},{intent:E.NavPreviousItemJump,mode:I.DEFAULT,action:()=>($.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:E.NavNextItemJump,mode:I.DEFAULT,action:()=>($.jumpToNextItem(),d("Jumping to next item",null))},{intent:E.NavToPreviousContainer,mode:I.DEFAULT,action:()=>($.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.DEFAULT,action:()=>($.navigateToNextContainer(),d("Navigating to next container",null))}];var EA=500,SA=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Mv=e=>{let t=SA(e);t&&ca(n=>(n+t).slice(0,EA))};var RA=[I.COMMAND_LINE,I.PALETTE],CA=e=>e==="edit title "?v().selectedNode?.title??"":"",NA=e=>[{intent:E.MoveCursorLeft,mode:e,action:()=>(Qc(-1),d("Moving cursor left",null))},{intent:E.MoveCursorRight,mode:e,action:()=>(Qc(1),d("Moving cursor right",null))},{intent:E.MoveCursorLeftOfWord,mode:e,action:()=>(Zc("left"),d("Moving cursor left of word",null))},{intent:E.MoveCursorRightOfWord,mode:e,action:()=>(Zc("right"),d("Moving cursor right of word",null))},{intent:E.AutoCompleteCommand,mode:e,action:()=>(ca((t,{remainder:n})=>{let r=n?t+n:t;return r+CA(r)}),d("Auto-completing command",null))},{intent:E.CaptureInput,mode:e,action:(t,{sequence:n})=>(Mv(n??""),d("Capturing input",null))},{intent:E.EraseInput,mode:e,action:()=>(xf(),d("Erasing input",null))},{intent:E.EraseInputWord,mode:e,action:()=>(If(),d("Erasing input word",null))}],Pv=[{intent:E.Confirm,mode:I.COMMAND_LINE,action:()=>(Gt(),d("Executing command",null))},{intent:E.ViewHelp,mode:I.DEFAULT,action:()=>(w({mode:I.HELP}),d("Viewing help",null))},...RA.flatMap(NA),{intent:E.ExitCommandLine,mode:I.COMMAND_LINE,action:()=>(Cf(),w({mode:I.DEFAULT}),d("Exiting command line",null))},{intent:E.GetLastCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(Nf(),d("Getting last command from history",null))},{intent:E.GetNextCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(Af(),d("Getting next command from history",null))}];var fu=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Lv=({keys:e})=>e.length===1?0:1,kv=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(fu).filter(r=>r!==null).sort((r,o)=>Lv(r)-Lv(o))};function Dv(e,t,n){let r=t[e];if(!r)return l("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=o[o.length-1];return!c||c.id!==n?l("buildBreadCrumb(): node is not connected to root"):(o.reverse(),d("Breadcrumb built",o))}var Bv=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 wt,gu,hu=new Set,yu=()=>{for(let e of hu)e()},TA=e=>(hu.add(e),()=>hu.delete(e));function vu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return l("derive(): contextNodeId is missing");if(!r)return l("derive(): rootNode is missing");if(!o[r])return l("derive(): unable to find root node");let c=o[t];if(!c)return l("Unable to derive state, contextNode not found");let u=Dv(t,o,r);if(a(u))return logger.error(u.message),u;let p=u.value,{context:m}=c,f=[...wv,...bv[m]??[],...Pv],g=kv(f,n),h=Bv(f),x=wA(o,s),b=x[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:c,breadCrumb:p,availableHints:g,availableActions:f,actionIndex:h,selectedNode:b,renderedChildrenIndex:x})}var v=()=>{if(!wt)throw new Error("State not initialized. Call initWorkspaceState() first.");return wt},de=()=>wt?d("Retrieved state",wt):l("State not initialized. Call initWorkspaceState() first.");_p(e=>wt?hn(wt.emailLinks,e):[]);function _s(e){gu=e;let t=re(process.cwd()),n=!1;if(!a(t)){let s=Mt(t.value);if(a(s))return l(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:I.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=vu(r);return a(o)?o:(wt=o.value,yu(),d("State initialized",null))}var Yr=!1,di=null;function Oe(e){let t=v(),n=e(t);if(Yr)return n.nodes!==t.nodes&&(Ir=null),di=n,wt={...t,...n},d("State updated",null);let r=vu(n);return a(r)?l(r.message??"Unable to update state"):(wt=r.value,yu(),d("State updated",null))}function Ea(e){if(Yr)return d("Joined batch",e());Yr=!0,di=null,Ir=new Set;let t=()=>{let n=di;if(Yr=!1,di=null,n===null)return null;let r=vu(n);return a(r)?l(r.message??"Unable to update state"):(wt=r.value,yu(),d("State updated",null))};try{let n=e(),r=t();return r&&a(r)?l(r.message):d("State updated",n)}finally{Yr&&t()}}var Ng=()=>Yr,w=e=>Oe(t=>({...t,...e}));function Xr(e,t,n){if(!Yr)return Oe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],c=n;i?.parentNodeId&&Ir?.add(i.parentNodeId),c.parentNodeId&&Ir?.add(c.parentNodeId)}o[t]=n;let s={...r,[e]:o};return di=s,wt={...r,...s},d("State updated",null)}var ne=()=>AA(TA,v,v),Ir=null,Ov=null,wA=(e,t)=>{let n=wt?.renderedChildrenIndex,r=n!==void 0&&Ir!==null&&e===Ov&&t.length===0&&wt?.filters.length===0,o;if(r){o={...n};let s=Eg(e,Ir);for(let i of Ir){let c=s[i];c?o[i]=c:delete o[i]}}else o=Ig(e,t);return Ov=e,Ir=new Set,o},le=e=>v()?.renderedChildrenIndex[e]??[],cn=()=>gu?_s(gu):l("Cannot reset state: no initial workspace found"),Rt=()=>wt!==void 0;var Tt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return l("Node not found");if(r.context===t)return d("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return d("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return l(`No ancestor found for context: ${t}`)},bu=(e,t)=>{let{nodes:n}=v(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},Er=(e,t)=>e?e.readonly?l({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:l("Node not found"),N={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.userId&&n.userId!==t)return l("Contributor is already linked to another user");let r={...n,userId:t},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to link contributor to user"):d("Linked contributor to user",r)},deleteNode(e){N.deleteNodes([e])},deleteNodes(e){e.length!==0&&Oe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create comment, missing issue");if(!_(t))return l("Can only comment on issues");let n=Xr("comments",e.id,{...e,deleted:!1});return a(n)?l("Unable to create comment"):d("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return l("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return l("Unable to edit comment, missing issue");if(!_(r))return l("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Xr("comments",e,o);return a(s)?l("Unable to edit comment"):d("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return l("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Xr("comments",e,n);return a(r)?l("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create attachment, missing issue");if(!_(t))return l("Can only attach to issues");let n=Oe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?l("Unable to create attachment"):d("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return l("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Oe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?l("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return l("Edit target node not found");let o=Er(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),d("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return l("Rename target node not found");let r=Er(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),d("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["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return be(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return l("Node not found");if(!s)return l("Target parent not found");if(r===e)return l("Cannot move root node");if(e===t)return l("Cannot move node into itself");let i=Er(o,"move");if(i)return i;if(bu(t,e))return l("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),d("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return l("Node not found");if(r===e)return l("Cannot delete root node");let s=Er(o,"delete");if(s)return s;let i=new Set,c=p=>{let m=t[p];if(!(!m||i.has(p))){i.add(p);for(let f of be(m.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let p of i){if(!u[p])return l("Unable to locate node to delete");u[p]={...u[p],isDeleted:!0}}return n?(w({nodes:u}),d("Successfully tomb stoned",o)):l("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return l("Contributor not found");let n={...t,name:xo,tombstoned:!0},r=Oe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?l("Unable to remove contributor"):d("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.tombstoned)return l("Cannot rename a removed contributor");let r={...n,name:t},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to rename contributor"):d("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to restore contributor"):d("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return l("Unable to link email, missing contributor");let r={email:Ze(e),contributor:t,authorId:n},o=bs(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=Oe(c=>({...c,emailLinks:{...c.emailLinks,[o]:r}}));return a(i)?l("Unable to link email"):d("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=bs(e,t),o=v().emailLinks[r];if(!o)return l("Unable to unlink, no such link");if(o.tombstoned)return d("Email already unlinked",o);if(!Ji(n,o))return l("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Oe(c=>({...c,emailLinks:{...c.emailLinks,[r]:s}}));return a(i)?l("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Oe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?l("Unable to create contributor"):d("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to assign contributor, missing contributor");if(!r)return l("Unable to assign contributor, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return l("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return l("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),d("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to unassign, missing contributor");if(!r)return l("Unable to unassign, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return l("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return d("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),d("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return l("Unable to add tag, missing tag");if(!r)return l("Unable to add tag, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return l("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return l("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return l("Unable to remove tag, missing tag");if(!r)return l("Unable to remove tag, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return l("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return d("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return l("Tag not found");let n={...t,tombstoned:!0},r=Oe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?l("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return l("Tag not found");let r={...n,name:t,tombstoned:!1},o=Oe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?l("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=Oe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?l("Could not create tag"):d("Tag created",e)},createNode(e){let t=Xr("nodes",e.id,e);return a(t)?l("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return l("Failed to locate node");let n={...t,readonly:!0},r=Xr("nodes",e,n);return a(r)?l(r.message):d("Locked node",n)},updateNode(e){let t=Xr("nodes",e.id,e);return a(t)?t:d("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return be(e)}};var MA=(e,t)=>e+" ".repeat(Math.max(0,t-Fv(e))),PA=(e,t)=>" ".repeat(Math.max(0,t-Fv(e)))+e,xl=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),LA=(e,t)=>t?e<t?"up":e>t?"down":null:null,kA=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?Sr.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=LA(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},_v=e=>`${Math.max(1,Math.round(e/1024))} KB`,jv=e=>N.getAttachment(e)?.name??"",DA=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Sr.bgHex(ze(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Sr.bgHex(ze(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Sr.hex(ze(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Sr.hex(ze(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${Sr.dim(`(${_v(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=jv(e.payload.id);return t?`"${t}"`:""}default:return""}},BA=e=>{let t=fr(De(e));return Sr.gray(PA(t,8))},OA=12,FA=e=>MA(`${e}`,OA),_A=e=>{let t=de();return a(t)?e:Xi(e,t.value.contributors[e]?.name)},jA=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=N.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${_v(e.payload.bytes)})`;case"delete.issue.attachment":{let t=jv(e.payload.id);return t?`"${t}"`:""}default:return""}},pl=e=>[xl(e.action),jA(e)].filter(Boolean).join(" "),$v=(e,t)=>{let n=BA(e.id),r=FA(_A(e.userId)),o=Sr.dim("\u203A"),s=e.action==="move.node"?kA(e,t):[xl(e.action),DA(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var $A=e=>Me(e,"comments"),UA=e=>Me(e,"description"),HA=e=>Me(e,"assignees"),WA=e=>Me(e,"tags"),GA=e=>Me(e,"history"),VA=e=>Me(e,"diff"),zA=e=>Me(e,"attachments"),ui=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=N.getNode(e);if(!c){let m=N.createNode({...Re.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(m)?m:d("Virtual field created",void 0)}if(!at(c))return l(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let p=N.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return a(p)?p:d("Virtual field updated",void 0)},Uv=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=N.getNode(e);if(!i){let p=N.createNode({...Re.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(p)?p:d("Virtual field list created",void 0)}if(!Is(i))return l(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return d("Virtual field list unchanged",void 0);let u=N.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:d("Virtual field list updated",void 0)},Il=null,KA=()=>{if(Il)return d("Virtual field ranks",Il);let e=Dt(Zt/4n),t=Dt(Zt/2n),n=Dt(Zt*3n/4n),r=Dt(Zt*7n/8n),o=Dt(Zt*15n/16n),s=Dt(Zt*13n/16n),i=Dt(Zt*27n/32n);return a(e)?e:a(t)?t:a(n)?n:a(r)?r:a(o)?o:a(s)?s:a(i)?i:(Il={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},d("Virtual field ranks",Il))},fg=e=>{let t=KA();if(a(t))return t;let n=t.value,r=ui({id:UA(e.id),name:Ne.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=Uv({id:HA(e.id),name:Ne.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=Uv({id:WA(e.id),name:Ne.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=ui({id:$A(e.id),name:Ne.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let c=ui({id:zA(e.id),name:Ne.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(c))return c;let u=ui({id:GA(e.id),name:Ne.HISTORY,parentNodeId:e.id,rank:n.log,value:qA(e),readonly:!0,childRenderAxis:"vertical"});if(a(u))return u;let p=ui({id:VA(e.id),name:Ne.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(p)?p:d("Ticket virtual nodes materialized",void 0)},qA=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>$v(r,n.get(r.action)??[])).join(`
|
|
98
|
+
`)},Hv=!0,Wv=e=>{Hv=e},yd=()=>Hv;import Dw from"node:http";import oo from"node:path";import{fileURLToPath as Bw}from"node:url";var YA=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},xu=(e,t)=>{let n=[];for(let r of e){let o=YA(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=tr(r);n.push({laneId:o,enteredAt:s===null?t:vs(s)})}return n},El=(e,t)=>xu(e,t).at(-1)?.enteredAt??t;var XA=e=>e.payload??{},Iu=e=>{let t=new Map,n={},r=new Set,o=new Set,s=new Set;for(let i of e){let{id:c,name:u}=XA(i);if(c)switch(i.action){case"create.contributor":case"create.tag":t.set(c,u??""),r.add(c),o.delete(c);break;case"rename.contributor":u!==void 0&&r.has(c)&&!o.has(c)&&t.set(c,u);break;case"tombstone.contributor":r.has(c)&&(t.set(c,xo),o.add(c));break;case"restore.contributor":case"restore.tag":u!==void 0&&r.has(c)&&(t.set(c,u),o.delete(c));break;case"add.board":u!==void 0&&(t.set(c,u),s.add(c));break;case"add.swimlane":u!==void 0&&(t.set(c,u),s.add(c),n[c]=u);break;case"edit.title":u!==void 0&&s.has(c)&&(t.set(c,u),c in n&&(n[c]=u));break;default:break}}return{byId:t,lanes:n}};var JA=e=>{let t=new Map,n=new Map;for(let r of e){let o=r.payload;!o?.id||!o.parent||(r.action==="move.node"&&t.set(r.id,n.get(o.id)),n.set(o.id,o.parent))}return t},Vv=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},QA=e=>{let t=new Set,n=new Map;for(let r of e){let o=r.payload,s=o?.id;s&&(r.action==="add.issue"&&t.add(s),o.parent&&n.set(s,o.parent))}return{issueIds:t,parentById:n}},ZA=(e,{issueIds:t,parentById:n})=>{let r=e.payload;if(r?.issue)return r.issue;let o=new Set,s=r?.id;for(;s!==void 0&&!o.has(s);){if(t.has(s))return s;o.add(s),s=n.get(s)}return null},eT=new Set(["add.issue.comment","edit.issue.comment","delete.issue.comment"]),tT=e=>eT.has(e.action)?e.payload?.id??null:null,nT=new Set(["add.issue","move.node","close.issue","reopen.issue"]),rT=(e,t)=>{let n=new Map;return e.map((r,o)=>{let s=t[o]??null;if(s===null)return{lane:null,laneBefore:null};let i=r.payload,c=null;if(nT.has(r.action)&&i?.id===s&&i.parent){let u=n.get(s);u!==void 0&&u!==i.parent&&(c=u),n.set(s,i.parent)}return{lane:n.get(s)??null,laneBefore:c}})},Gv=90,oT=e=>{let t=e.trim().split(`
|
|
99
|
+
`)[0]?.trim()??"";return t.length>Gv?`${t.slice(0,Gv).trimEnd()}\u2026`:t},sT=(e,t,n)=>{let r=e.payload,o=Vv(e),s=e.action?xl(e.action):"";if(r?.md!==void 0){let c=oT(r.md);return c?`${s}: ${c}`:s}if(e.action==="move.node"&&r?.parent){let c=t.get(r.parent);return c?n.get(e.id)===r.parent?`Moved within ${c}`:`Moved to ${c}`:s}let i=o!==void 0?t.get(o)??"":r?.assignee!==void 0?t.get(r.assignee)??"":r?.email!==void 0?r.email:r?.name!==void 0?`"${r.name}"`:"";return[s,i].filter(Boolean).join(" ")},Eu=(e,t)=>e?Ke(e,t.get(e)):null,iT=(e,t)=>{let n=e.payload;return{actor:Eu(e.userId,t),tag:Eu(Vv(e),t),assignee:Eu(n?.assignee,t)}},zv=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let c=o.action==="close.issue"?r(i):null,u=s.parent??s.issue;return u&&t.set(i,u),c!==null?c:n.has(i)?i:r(i)})},Kv=e=>aT.has(e),aT=new Set(["create.contributor","rename.contributor","tombstone.contributor","restore.contributor","link.contributor.user","link.contributor.email","unlink.contributor.email"]),qv=(e,t)=>{let n=zv(e);return e.filter((r,o)=>n[o]===t)},lT=(e,t=new Map)=>{let n=new Map([...t,...Iu(e).byId]),r=JA(e),o=QA(e),s=e.map(m=>ZA(m,o)),i=rT(e,s),c=zv(e),u=yo(e.map(m=>tr(m)));return e.flatMap((m,f)=>{let g=u[f]??null;return g===null?[]:[{id:m.id,t:g,action:m.action,label:sT(m,n,r),issue:s[f]??null,target:tT(m),...i[f],board:c[f]??null,...iT(m,n)}]}).sort((m,f)=>m.t-f.t)},cT=e=>{let t=new Map;for(let r of e){if(r.issue===null||r.lane===null)continue;let o=t.get(r.issue)??[],s=o[o.length-1];(s===void 0||s.lane!==r.lane)&&(o.push({t:r.t,lane:r.lane,board:r.board}),t.set(r.issue,o))}let n=new Map;for(let[r,o]of t){let s=o[o.length-1];n.set(r,{changes:o,from:o[0].t,closedFrom:s.lane===he?s.t:null})}return n},dT=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return e[n-1]},Yv=(e,t,n)=>{let r={};for(let[o,s]of e){if(s.from>=t||s.closedFrom!==null&&s.closedFrom<t)continue;let i=dT(s.changes,t);i===void 0||i.lane===he||n&&i.board!==n||(r[o]=i.lane)}return r},uT=e=>Iu(e).lanes,mi=null,Xv=e=>{let t=et(e);if(mi&&mi.root===e&&mi.signature===t)return d("Timeline entries, cached",mi.index);let n=dr(e);if(a(n))return l(n.message);let r=lT(n.value,cr(e)),o={entries:r,lanes:cT(r),laneNames:uT(n.value)};return mi={root:e,signature:t,index:o},d("Timeline entries, built",o)};var Jv=1e5,mT=2e4,Sl=null,Qv=Promise.resolve(),Mn=e=>{let t=Qv.then(e,e);return Qv=t.then(()=>{},()=>{}),t},Rl=e=>{let t=sn(e);return a(t)?t:me({repoRoot:t.value})},Je=()=>{if(!Rt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:Sl}},Zv=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return n},eb=async(e={})=>{let t=Rl(e.repoRoot);if(a(t))return l(t.message);let n=Xv(t.value);if(a(n))return l(n.message);let r=n.value.entries,o=Date.now(),s=e.end??o,i=e.start??r[0]?.t??s;if(s<=i)return d("Empty time window",{bucketMs:0,buckets:[],capped:!1,events:[],lanesAtStart:{},laneNames:n.value.laneNames,closedLane:he,earliest:i,latest:s});let c=Zv(r,i),u=Zv(r,s),p=r.slice(c,u).filter(b=>!e.boardId||b.board===e.boardId||Kv(b.action)),m=p.map(b=>b.t),f=Math.max(1,Math.ceil((s-i)/Jv)),g=new Map;for(let b of m){let R=Math.min(Jv-1,Math.floor((b-i)/f)),S=i+R*f;g.set(S,(g.get(S)??0)+1)}let h=[...g.entries()].sort(([b],[R])=>b-R).map(([b,R])=>({t:b,count:R})),x=p.length>mT;return d("Computed event timeline",{bucketMs:f,buckets:h,capped:x,events:x?[]:p,lanesAtStart:Yv(n.value.lanes,i,e.boardId),laneNames:n.value.laneNames,closedLane:he,earliest:i,latest:s})},tb=e=>{let t=dr(e);if(a(t))return l(t.message);let n=cn();if(a(n))return l(n.message);Sl=null;let r=tn(t.value),{fatal:o,skipped:s}=En(r);return o.length>0?l(o.map(i=>i.message).join(", ")):(Sn(s),w({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Restored live state",!0))},pT=(e,t)=>{Sl=null;let n=tb(e);return a(n)?l(`${t} (recovery to live also failed: ${n.message})`):l(t)},Su=e=>Mn(async()=>{let t=Rl(e.repoRoot);if(a(t))return l(t.message);let n=Sa(t.value,e.targetTime);if(a(n))return l(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=cn();if(a(s))return s;let i=tn(r),{fatal:c,skipped:u}=En(i);return c.length>0?pT(t.value,c.map(p=>p.message).join(", ")):(Sn(u),w({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),Sl=e.targetTime,d("Checked out historical state",{asOfTime:e.targetTime}))}),nb=async e=>{let t=Rl(e.repoRoot);if(a(t))return l(t.message);let n=Ra(t.value);if(a(n))return l(n.message);let r=n.value.get(e.eventId)??null;return r===null?l("Event not found in the log"):Su({repoRoot:e.repoRoot,targetTime:r+1})},rb=(e={})=>Mn(async()=>{let t=Rl(e.repoRoot);if(a(t))return l(t.message);let n=tb(t.value);return a(n)?l(n.message):d("Returned to live state",!0)});import gT from"node:fs";var ob=new Map,fT=3e4,sb=async e=>{let t=ob.get(e);if(t&&Date.now()-t.readAt<fT)return{name:t.name,email:t.email};let n=await Le({args:["config","--get-regexp","^user\\.(name|email)$"],cwd:e}),r=null,o=null;if(n.exitCode===0)for(let s of(n.stdout??"").split(`
|
|
100
|
+
`)){let i=s.indexOf(" ");if(i===-1)continue;let c=s.slice(0,i),u=s.slice(i+1);c==="user.name"&&(r=u.trim()||null),c==="user.email"&&(o=Ze(u)||null)}return ob.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},Cl=async e=>(await sb(e)).email,Rr=async e=>(await sb(e)).name;var Jr=e=>{let t=re(e??process.cwd());return a(t)?l(t.message):d("Resolved Epiq repo root",t.value)},Nl=null,hT=async(e,t)=>{let n=Jr(e);if(a(n))return n;let r=me({repoRoot:n.value});if(a(r))return l(r.message);let o=ke(n.value);if(a(o))return l(o.message);if(!(Nl!==null&&Nl.repoRoot===n.value&&Nl.stateBranchRoot===r.value&&gT.existsSync(Mr(r.value)))){let f=await Ws({repoRoot:n.value,stateBranchName:o.value});if(a(f))return l(f.message);let g=await ur({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return l(g.message);Nl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await U({cwd:r.value,args:["pull","--ff-only"]});a(f)&&ee.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},c=ht();a(c)||je(c.value),je({gitEmail:await Cl(n.value),gitName:await Rr(n.value)});let u=et(r.value);if(ua(r.value)===u&&Rt()&&Je().mode==="live")return d("Booted Epiq state, unchanged",i);let p=nn(r.value);if(a(p))return l(p.message);let m=rn(p.value.events,p.value.unreadable);return a(m)?l(m.message):(To(r.value,u),d("Booted Epiq state",i))},Vt=()=>{let e=ht();return a(e)?l(e.message):e.value.userId?e.value.userName?d("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):l("Unable to retrieve user name"):l("Unable to retrieve user id")},pt=()=>{let e=de();return a(e)?l(e.message):e},Ot=e=>hT(e,{pull:!1}),ue=async e=>{let t=await Ot(e);if(a(t))return t;let n=Vt();if(a(n))return n;let r=pt();return a(r)?r:d("Booted",{boot:t.value,actor:n.value,state:r.value})};var yT=e=>{let t=N.getNode(e);if(!t)return[];let n=new Set;t.parentNodeId&&n.add(t.parentNodeId);for(let r of t.log??[]){let o=r.payload;o.id===e&&o.parent&&n.add(o.parent)}return[...n]},Al=e=>{let t=new Set;e.parentNodeId&&t.add(e.parentNodeId);for(let r of e.log??[]){let o=r.payload;o.id===e.id&&o.parent&&t.add(o.parent)}let n=new Set;for(let r of t)for(let o of yT(r))n.add(o);return[...n]},Yo=e=>vn(e).map(t=>Ke(t.id,t.name));var Xo=e=>bn(e).map(({id:t,name:n})=>Ke(t,n));import vT from"node:fs";import bT from"node:path";import{ulid as Cu}from"ulid";var tt=e=>{let t=pt();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Issue not found"):_(n)?n.readonly?l("Issue is readonly"):d("Found issue",n):l("Target must be an issue")},Cr=e=>{let t=pt();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Swimlane not found"):yn(n)?n.readonly?l("Swimlane is readonly"):d("Found swimlane",n):l("Target must be a swimlane")},Ru=e=>{let t=pt();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Board not found"):or(n)?n.readonly?l("Board is readonly"):d("Found board",n):l("Target must be a board")};var xT=e=>{if(e.filePath)try{return d("Read attachment file",{data:vT.readFileSync(e.filePath),name:e.name??bT.basename(e.filePath)})}catch(t){return l(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?d("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):l("Provide either filePath or dataBase64")},Tl=()=>{let e=ht();return a(e)?xn:e.value.attachmentMaxKb??xn},Nu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;let r=xT(e);if(a(r))return r;let o=rf(t.value.boot.stateBranchRoot,r.value.data,Tl());if(a(o))return o;let s=Ee(r.value.name).trim()||"image",i=Cu(),c={id:Cu(),...D(t.value.actor),action:"add.issue.attachment",payload:{id:i,issue:e.issueId,author:t.value.actor.userId,hash:o.value.hash,ext:o.value.ext,name:s,bytes:o.value.bytes}},u=B([c],t.value.boot.stateBranchRoot);if(a(u))return l(u.message);let p=Br(o.value.hash,o.value.ext);return d("Added issue attachment",{id:i,issueId:e.issueId,fileName:p,bytes:o.value.bytes,markdown:Kc(s,p)})},Au=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(c=>c.action==="add.issue.attachment"&&c.payload.id===e.attachmentId);if(!n)return l("Unable to resolve attachment");if(n.payload.author!==t.value.actor.userId)return l("You can only delete your own attachments");let r=tt(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(c=>c.action==="delete.issue.attachment"&&c.payload.id===e.attachmentId))return d("Attachment already deleted",{id:e.attachmentId,issueId:n.payload.issue});let s={id:Cu(),...D(t.value.actor),action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:n.payload.issue}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?l(i.message):d("Deleted issue attachment",{id:e.attachmentId,issueId:n.payload.issue})},Tu=async e=>{let t=await Ot(e.repoRoot);return a(t)?t:of(t.value.stateBranchRoot,e.fileName,Tl())};var IT=365*24*60*60*1e3,wu=e=>{let t=pt();if(a(t))return t;let n=t.value.nodes[e];return d("Issue description",n&&_(n)&&!n.isDeleted?n.props.description??"":"")},Qr=()=>{let e=pt();if(a(e))return e;let t=Je(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(b=>or(b)&&!b.isDeleted),s=Date.now()-IT,i=new Map,c=new Map;for(let b of r)if(!b.isDeleted){if(yn(b)&&b.parentNodeId){let R=i.get(b.parentNodeId)??[];R.push(b),i.set(b.parentNodeId,R)}if(_(b)&&b.parentNodeId){if(b.parentNodeId===he&&De(b.id)<s)continue;let R=c.get(b.parentNodeId)??[];R.push(b),c.set(b.parentNodeId,R)}}let u=new Set;for(let b of c.values())for(let R of b)u.add(R.id);let p=ht();if(a(p))return p;let m={},f=N.getCommentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!u.has(b.id)||(m[b.id]=(f.get(b.id)??[]).map(R=>{let S=N.getContributor(R.authorId);return{id:R.id,issueId:R.issue,body:R.md,author:Ke(R.authorId,S?.name),createdAt:De(R.id)}}));let g=new Map;for(let b of e.value.eventLog)b.action==="add.issue.attachment"&&g.set(b.payload.id,b.payload.author);let h={},x=N.getAttachmentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!u.has(b.id)||(h[b.id]=(x.get(b.id)??[]).map(R=>({id:R.id,issueId:R.issue,name:R.name,fileName:Br(R.hash,R.ext),bytes:R.bytes,createdAt:De(R.id),canDelete:g.get(R.id)===p.value.userId})));return d("Retrieved Epiq GUI state",{boards:o.sort((b,R)=>b.rank.localeCompare(R.rank)).map(b=>({id:b.id,ref:H(b.id),title:b.title,readonly:!!b.readonly||n,swimlanes:(i.get(b.id)??[]).sort((R,S)=>R.rank.localeCompare(S.rank)).map(R=>({id:R.id,title:R.title,readonly:!!R.readonly||n,issues:(c.get(R.id)??[]).sort((S,A)=>S.rank.localeCompare(A.rank)).map(S=>({id:S.id,ref:H(S.id),title:Ee(S.title),description:S.props.description??"",createdAt:De(S.id),enteredLaneAt:El(S.log??[],De(S.id)),readonly:!!S.readonly||n,tags:Yo(S),assignees:Xo(S),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===he,boardIds:Al(S)})),parentNodeId:R.parentNodeId}))})),tags:N.getTags().map(b=>({...b,...Ke(b.id,b.name)})),contributors:Object.values(e.value.contributors).map(b=>({...b,...Ke(b.id,b.name)})),user:{id:p.value.userId??"",name:p.value.userName??"",color:ze(p.value.userName??"")},commentsByIssueId:m,attachmentsByIssueId:h,attachmentMaxKb:Tl(),timeTravel:t})},ib=null,ET=e=>{if(e===ib)return;let t=ea({root:e});if(a(t)){ee.info(t.message);return}ib=e},zt=async(e={})=>{if(Je().mode!=="live")return Qr();let t=await Ot(e.repoRoot);return a(t)?t:(ET(t.value.repoRoot),Qr())},pi=async(e={})=>{Mo();let t=Jr(e.repoRoot);if(a(t))return l("Sync failed");let n=Vt();if(a(n))return n;let r=await Fa({cwd:t.value,ownEventFileName:ar(n.value)});return a(r)?(xd(r.message),r):(Ur(),d("Synced",r.value))};import{ulid as Kt}from"ulid";var fi=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?d("Resolved targets",t):l("Provide issueId or issueIds")},Jo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?d(r,t):l(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},gi=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:H(r),reason:o.message}):n.done.push({id:r,ref:H(r)})}return n};var cb=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Lu(e){let t=await Ot(e.repoRoot);if(a(t))return t;let n=pt();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(_).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==he).filter(c=>e.boardId?(c.parentNodeId?r[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Yo(c).some(u=>cb(u.name,e.tag))).filter(c=>!e.assignee||Xo(c).some(u=>cb(u.name,e.assignee))).filter(c=>!o||c.title.toLowerCase().includes(o)||(c.props.description??"").toLowerCase().includes(o)),i=c=>Ee((c.parentNodeId?r[c.parentNodeId]?.title:void 0)??"");return e.brief?d("Listed issues",s.map(c=>({id:c.id,ref:H(c.id),title:Ee(c.title),swimlane:i(c),tags:Yo(c).map(u=>u.name),assignees:Xo(c).map(u=>u.name)}))):d("Listed issues",s.map(c=>({id:c.id,ref:H(c.id),title:Ee(c.title),description:c.props.description??"",createdAt:De(c.id),enteredLaneAt:El(c.log??[],De(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===he,boardIds:Al(c),readonly:!!c.readonly,tags:Yo(c),assignees:Xo(c)})))}var ku=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Ee(e.title);if(!n)return l("Issue title cannot be empty");let r=e.description??"",o=lt("Issue title",n,300)??lt("Issue description",r,2e4);if(o)return l(o);if((e.tagNames?.length??0)>20)return l(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return l(`Cannot set more than ${20} assignees at once`);let s=Cr(e.parentId);if(a(s))return s;let i=Wn(e.parentId,t.value.actor,t.value.boot.stateBranchRoot);if(a(i))return i;let c=il({name:n,parent:e.parentId,user:t.value.actor,rank:i.value});if(a(c))return c;let u=[...c.value],p=u.find(h=>h.action==="add.issue")?.payload.id;if(!p)return l("Unable to determine created issue id");r&&u.push({id:Kt(),...D(t.value.actor),action:"edit.description",payload:{id:p,md:r}});let m=[];for(let h of e.tagNames??[]){let x=Ee(h).trim();if(!x||m.some(A=>A.name===x))continue;let b=lt("Tag name",x,60);if(b)return l(b);let R=N.findTagByName(x),S=R?.id??Kt();R||u.push({id:Kt(),...D(t.value.actor),action:"create.tag",payload:{id:S,name:x}}),u.push({id:Kt(),...D(t.value.actor),action:"add.issue.tag",payload:{id:p,tag:S}}),m.push({id:S,name:x})}let f=[];for(let h of e.assigneeNames??[]){let x=Ee(h).trim();if(!x||f.some(A=>A.name===x))continue;let b=lt("Assignee name",x,80);if(b)return l(b);let R=Object.values(t.value.state.contributors).find(A=>A.name===x),S=R?.id??Kt();R||u.push({id:Kt(),...D(t.value.actor),action:"create.contributor",payload:{id:S,name:x}}),u.push({id:Kt(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:p,assignee:S}}),f.push({id:S,name:x})}let g=B(u,t.value.boot.stateBranchRoot);return a(g)?l(g.message):d("Created issue",{id:p,ref:H(p),title:n,parentId:e.parentId,description:r,tags:m,assignees:f})},ST=(e,t,n)=>{let r=tt(e);if(a(r))return r;let o=Rn(he,e,{at:"end"},t,n);if(a(o))return o;let s={id:Kt(),...D(t),action:"close.issue",payload:{id:e,parent:he,rank:o.value}},i=B([s],n);return a(i)?l(i.message):d("Closed issue",{id:e,ref:H(e)})};async function Du(e){let t=await Ot(e.repoRoot);if(a(t))return t;let n=Vt();if(a(n))return n;let r=fi(e);if(a(r))return r;let o=s=>ST(s,n.value,t.value.stateBranchRoot);return e.issueIds?Jo("Closed",gi(r.value,o)):o(r.value[0])}var Bu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[e.issueId];if(!n||n.isDeleted)return l("Issue not found");if(!_(n))return l("Target must be an issue");if(n.parentNodeId!==he)return l("Issue is not closed");let r=fl(n);if(!r)return l("Unable to resolve previous parent from issue history");if(r===he)return l("Previous parent resolves to closed swimlane");let o=Cr(r);if(a(o))return o;let s=o.value,i=Rn(s.id,n.id,{at:"end"},t.value.actor,t.value.boot.stateBranchRoot);if(a(i))return i;let c={id:Kt(),...D(t.value.actor),action:"reopen.issue",payload:{id:n.id,parent:s.id,rank:i.value}},u=B([c],t.value.boot.stateBranchRoot);return a(u)?l(u.message):d("Reopened issue",{id:n.id,ref:H(n.id),parentId:s.id})},RT=(e,t,n,r)=>{let o=tt(e);if(a(o))return o;let s=Cr(t.parentId);if(a(s))return s;let i=Rn(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let c={id:Kt(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=B([c],r);return a(u)?l(u.message):d("Moved issue",{id:e,ref:H(e),parentId:t.parentId})};async function Ou(e){let t=Jr(e.repoRoot);if(a(t))return t;let n=Vt();if(a(n))return n;let r=me({repoRoot:t.value});if(a(r))return r;let o=nn(r.value);if(a(o))return o;let s=rn(o.value.events,o.value.unreadable);if(a(s))return s;let i=fi(e);if(a(i))return i;let c=u=>RT(u,e,n.value,r.value);return e.issueIds?Jo("Moved",gi(i.value,c)):c(i.value[0])}var Fu=e=>{let t=pt();if(a(t))return t;let n=t.value.nodes[e];return n?d("Read issue history",(n.log??[]).map(r=>({id:r.id,t:De(r.id),action:r.action,label:pl(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:Ke(r.userId,t.value.contributors[r.userId]?.name)}))):l("Issue not found")},_u=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;let r=n.value,o=lt("Issue description",e.description,2e4);if(o)return l(o);let s=r.props.description??"";if(s===e.description)return d("No changes made",{id:e.issueId,ref:H(e.issueId),description:s});let i={id:Kt(),...D(t.value.actor),action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.boot.stateBranchRoot);return a(c)?l(c.message):d("Edited issue description",{id:e.issueId,ref:H(e.issueId),description:e.description})},ju=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;let r=n.value,o=Ee(e.title);if(!o.trim())return l("Issue title cannot be empty");let s=lt("Issue title",o,300);if(s)return l(s);if(r.title===o)return d("No changes made",{id:e.issueId,ref:H(e.issueId),title:o});let i={id:Kt(),...D(t.value.actor),action:"edit.title",payload:{id:e.issueId,name:o}},c=B([i],t.value.boot.stateBranchRoot);return a(c)?l(c.message):d("Edited issue title",{id:e.issueId,ref:H(e.issueId),title:o})};import{ulid as Nr}from"ulid";var $u=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[t.value.state.rootNodeId];if(!n)return l("Workspace not found");if(Je().mode!=="live")return l("Cannot add a board while time travelling");let r=Ee(e.title);if(!r.trim())return l("Board title cannot be empty");let o=lt("Board title",r,300);if(o)return l(o);let s=Wn(n.id,t.value.actor,t.value.boot.stateBranchRoot);if(a(s))return s;let i=Nr(),c={id:Nr(),...D(t.value.actor),action:"add.board",payload:{id:i,name:r,parent:n.id,rank:s.value}},u=B([c],t.value.boot.stateBranchRoot);return a(u)?l(u.message):d("Created board",{id:i,ref:H(i),title:r})},Uu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[e.boardId];if(!n||n.isDeleted)return l("Board not found");if(!or(n))return l("Edit target must be a board");if(n.readonly)return l("Cannot edit readonly board");if(Je().mode!=="live")return l("Cannot rename a board while time travelling");let r=Ee(e.title);if(!r.trim())return l("Board title cannot be empty");let o=lt("Board title",r,300);if(o)return l(o);if(n.title===r)return d("No changes made",{id:e.boardId,ref:H(e.boardId),title:r});let s={id:Nr(),...D(t.value.actor),action:"edit.title",payload:{id:e.boardId,name:r}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?l(i.message):d("Edited board title",{id:e.boardId,ref:H(e.boardId),title:r})};var Hu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Ru(e.boardId);if(a(n))return n;if(Je().mode!=="live")return l("Cannot add a swimlane while time travelling");let r=Ee(e.title);if(!r.trim())return l("Swimlane title cannot be empty");let o=lt("Swimlane title",r,300);if(o)return l(o);let s=Wn(e.boardId,t.value.actor,t.value.boot.stateBranchRoot);if(a(s))return s;let i=Nr(),c={id:Nr(),...D(t.value.actor),action:"add.swimlane",payload:{id:i,name:r,parent:e.boardId,rank:s.value}},u=B([c],t.value.boot.stateBranchRoot);return a(u)?l(u.message):d("Created swimlane",{id:i,ref:H(i),title:r,boardId:e.boardId})},Wu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Cr(e.swimlaneId);if(a(n))return n;let r=n.value,o=Ee(e.title);if(!o.trim())return l("Swimlane title cannot be empty");let s=lt("Swimlane title",o,300);if(s)return l(s);if(r.title===o)return d("No changes made",{id:e.swimlaneId,ref:H(e.swimlaneId),title:o});let i={id:Nr(),...D(t.value.actor),action:"edit.title",payload:{id:e.swimlaneId,name:o}},c=B([i],t.value.boot.stateBranchRoot);return a(c)?l(c.message):d("Edited swimlane title",{id:e.swimlaneId,ref:H(e.swimlaneId),title:o})},Gu=async e=>{let t=Jr(e.repoRoot);if(a(t))return t;let n=Vt();if(a(n))return n;let r=me({repoRoot:t.value});if(a(r))return r;let o=nn(r.value);if(a(o))return o;let s=rn(o.value.events,o.value.unreadable);if(a(s))return s;let i=Cr(e.swimlaneId);if(a(i))return i;let c=Ru(e.boardId);if(a(c))return c;let u=Rn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(u))return u;let p={id:Nr(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},m=B([p],r.value);return a(m)?l(m.message):d("Moved swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId),boardId:e.boardId})},Vu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Cr(e.swimlaneId);if(a(n))return n;let r={id:Nr(),...D(t.value.actor),action:"delete.node",payload:{id:e.swimlaneId}},o=B([r],t.value.boot.stateBranchRoot);return a(o)?l(o.message):d("Deleted swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId)})};import{ulid as hi}from"ulid";async function zu(e){let t=await Ot(e.repoRoot);if(a(t))return t;let n=Vt();if(a(n))return n;let r=fi(e);if(a(r))return r;let o=Ee(e.tagName).trim();if(!o)return l("Tag name cannot be empty");let s=lt("Tag name",o,60);if(s)return l(s);let i=gi(r.value,tt);if(!e.issueIds&&i.failed[0])return l(i.failed[0].reason);if(i.done.length===0)return l(Jo("Tagged",i).message);let c=N.findTagByName(o),u=c?.id??hi(),p=[...c?[]:[{id:hi(),...D(n.value),action:"create.tag",payload:{id:u,name:o}}],...i.done.map(({id:h})=>({id:hi(),...D(n.value),action:"add.issue.tag",payload:{id:h,tag:u}}))],m=B(p,t.value.stateBranchRoot);if(a(m))return l(m.message);let f={id:u,name:o};if(!e.issueIds)return d("Added issue tag",{...i.done[0],tag:f});let g=Jo("Tagged",i);return a(g)?g:d(g.message,{...g.value,tag:f})}var Ku=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.tags[e.tagId];if(!n)return l("Tag not found");if(n.tombstoned)return l("Tag is already deleted");let r=[{id:hi(),...D(t.value.actor),action:"tombstone.tag",payload:{id:e.tagId}}],o=B(r,t.value.boot.stateBranchRoot);return a(o)?l(o.message):d("Deleted tag",{id:n.id,name:n.name})};var qu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;if(!t.value.state.tags[e.tagId])return l("Tag not found");let r={id:hi(),...D(t.value.actor),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},o=B([r],t.value.boot.stateBranchRoot);return a(o)?l(o.message):d("Removed issue tag",{id:e.issueId,ref:H(e.issueId),tagId:e.tagId})};import{ulid as eo}from"ulid";var ub=async(e,t)=>{let n=cr(e).get(t);return n===void 0?void 0:{id:t,name:n}},Yu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;let r=e.self?t.value.actor.userId:e.assigneeId;if(r){let h=t.value.state.contributors[r],x=h?void 0:await ub(t.value.boot.stateBranchRoot,r);if(!h&&!x)return l("Unknown assignee id");let b=h??x,R=[...h?[]:[{id:eo(),...D(t.value.actor),action:"create.contributor",payload:{id:b.id,name:b.name}}],{id:eo(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:b.id}}],S=B(R,t.value.boot.stateBranchRoot);return a(S)?l(S.message):d("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:b.id,name:b.name}})}let o=Ee(e.assigneeName??"").trim();if(!o)return l("Provide assigneeId, self or assigneeName");let s=lt("Assignee name",o,80);if(s)return l(s);let i=li({events:t.value.state.eventLog??[],registry:t.value.state.contributors,logFileNames:cr(t.value.boot.stateBranchRoot)}).filter(h=>h.name===o);if(i.length>1)return l(`"${o}" matches ${i.length} contributors (${i.map(({id:h})=>h).join(", ")}). Assign by assigneeId to choose.`);let c=i[0];if(!c&&!e.createUnlinked)return l(`No contributor named "${o}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let u=c?.id??eo(),p=c?.name??o,f=[...!!t.value.state.contributors[u]?[]:[{id:eo(),...D(t.value.actor),action:"create.contributor",payload:{id:u,name:p}}],{id:eo(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:u}}],g=B(f,t.value.boot.stateBranchRoot);return a(g)?l(g.message):d("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:u,name:p}})},Xu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;if(!t.value.state.contributors[e.contributorId])return l("Contributor not found");if(await ub(t.value.boot.stateBranchRoot,e.contributorId))return l("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let o=[{id:eo(),...D(t.value.actor),action:"tombstone.contributor",payload:{id:e.contributorId}}],s=B(o,t.value.boot.stateBranchRoot);return a(s)?l(s.message):d("Tombstoned contributor",{id:e.contributorId,name:xo})};var Ju=async(e={})=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=dr(t.value.boot.stateBranchRoot);if(a(n))return l(n.message);let r=e.boardId?qv(n.value,e.boardId):n.value,o=new Set,s=gg(t.value.boot.stateBranchRoot);if(a(s))return l(s.message);for(let u of s.value)u.userId&&o.add(u.userId);let i=t.value.state.contributors,c=li({events:r,registry:i,logFileNames:cr(t.value.boot.stateBranchRoot)}).map(({id:u,name:p,isExternal:m})=>({...Ke(u,p),isSelf:u===t.value.actor.userId,isExternal:m,isRemoved:i[u]?.tombstoned===!0,hasAuthoredAnywhere:o.has(u)}));return d("Listed board contributors",c)},Qu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;if(!t.value.state.contributors[e.assigneeId])return l("Assignee not found");let r={id:eo(),...D(t.value.actor),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},o=B([r],t.value.boot.stateBranchRoot);return a(o)?l(o.message):d("Removed issue assignee",{id:e.issueId,ref:H(e.issueId),assigneeId:e.assigneeId})};import{ulid as wl}from"ulid";var yi=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=tt(e.issueId);if(a(n))return n;let r=e.body.trim();if(!r)return l("Comment cannot be empty");if(r.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${r.length})`);let o=wl(),s={id:wl(),...D(t.value.actor),action:"add.issue.comment",payload:{id:o,issue:e.issueId,md:r,author:t.value.actor.userId}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?l(i.message):d("Added issue comment",{id:o,issueId:e.issueId,body:r})},vi=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(c=>c.action==="add.issue.comment"&&c.payload.id===e.commentId);if(!n)return l("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return l("You can only delete your own comments");let r=tt(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(c=>c.action==="delete.issue.comment"&&c.payload.id===e.commentId))return d("Comment already deleted",{id:e.commentId,issueId:n.payload.issue});let s={id:wl(),...D(t.value.actor),action:"delete.issue.comment",payload:{id:e.commentId,issue:n.payload.issue}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?l(i.message):d("Deleted issue comment",{id:e.commentId,issueId:n.payload.issue})},Zu=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(u=>u.action==="add.issue.comment"&&u.payload.id===e.commentId);if(!n)return l("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return l("You can only edit your own comments");let r=tt(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(u=>u.action==="delete.issue.comment"&&u.payload.id===e.commentId))return l("Comment was deleted");let s=e.body.trim();if(!s)return l("Comment cannot be empty");if(s.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i={id:wl(),...D(t.value.actor),action:"edit.issue.comment",payload:{id:e.commentId,issue:n.payload.issue,md:s}},c=B([i],t.value.boot.stateBranchRoot);return a(c)?l(c.message):d("Edited issue comment",{id:e.commentId,issueId:n.payload.issue,body:s})};import{ulid as mb}from"ulid";var em=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;if(!nr(e.email))return l(`Not an email address: ${e.email}`);let n=Ze(e.email),r=e.contributorId??t.value.actor.userId;if(!t.value.state.contributors[r])return l(`Unknown contributor: ${r}`);let o=xs(t.value.state.emailLinks,n);if(o.includes(r))return d(`${n} is already yours`,{contributor:r,email:n,contested:o.filter(i=>i!==r)});let s=B([{id:mb(),action:"link.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return a(s)?l(s.message):d(o.length>0?`Claimed ${n}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${n}`,{contributor:r,email:n,contested:o})},tm=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Ze(e.email),r=e.contributorId??t.value.actor.userId,o=t.value.state.emailLinks[bs(n,r)];if(!o||o.tombstoned)return l(`No such link: ${n} to ${r}`);if(!Ji(t.value.actor.userId,o))return l("Only whoever made a claim, or the contributor it names, may undo it");let s=B([{id:mb(),action:"unlink.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return a(s)?l(s.message):d(`Unclaimed ${n}`,{contributor:r,email:n})},Ml=async(e={})=>{let t=await Ot(e.repoRoot);if(a(t))return t;let n=pt();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let g=s.get(f.email)??new Set;g.add(f.contributor),s.set(f.email,g)}let i=[...s.entries()].map(([f,g])=>({email:f,contested:g.size>1,claimants:[...g].map(h=>Ke(h,o[h]?.name))})).sort((f,g)=>f.email.localeCompare(g.email)),c=Vt(),u=a(c)?[]:hn(r,c.value.userId),p=V().gitEmail,m=p?xs(r,p).filter(f=>a(c)||f!==c.value.userId):[];return d("Listed contributor emails",{emails:i,mine:u,git:p?{email:p,linkedToMe:u.includes(p),heldByOthers:m.map(f=>Ke(f,o[f]?.name))}:null})},Pl=async(e={})=>{let t=await ue(e.repoRoot);if(a(t))return t;let{userId:n,userName:r}=t.value.actor,o=ke(t.value.boot.repoRoot),s=await wn({repoRoot:t.value.boot.repoRoot,stateBranch:a(o)?void 0:o.value,names:[r,await Rr(t.value.boot.repoRoot)],links:t.value.state.emailLinks});if(a(s))return s;let i=xr(s.value),c=i.filter(u=>u.looksLikeYours);return d(i.length===0?"No unclaimed addresses in this history":`${i.length} unclaimed address(es) in this history, ${c.length>0?`${c.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:n,candidates:i,likely:c.length})};var pb=(e,t)=>{let n=0,r=0,o=null;for(let s of e){if(s.userId!==t)continue;s.action==="add.issue"&&n++,s.action==="add.issue.comment"&&r++;let i=vo(s.id);if(a(i))continue;let c=i.value.getTime();(o===null||c<o)&&(o=c)}return{tickets:n,comments:r,joinedAt:o}};var nm=async(e={})=>{let t=await ue(e.repoRoot);if(a(t))return t;let{userId:n,userName:r}=t.value.actor,o=pb(t.value.state.eventLog,n),s=ke(t.value.boot.repoRoot),i=await wn({repoRoot:t.value.boot.repoRoot,stateBranch:a(s)?void 0:s.value,names:[r,await Rr(t.value.boot.repoRoot)],links:t.value.state.emailLinks}),c=a(i)?[]:i.value.filter(u=>u.claimedBy.length===1&&u.claimedBy[0]===n);return d("Derived personal stats",{...o,scanned:!a(i),commits:c.reduce((u,p)=>u+p.commits,0),claimedEmails:c.length})};var Pn="1.12.0";import CT from"node:fs";import fb from"node:path";var bi=Number(process.env.EPIQ_GUI_PORT)||3710,rm="/api/instance",om="epiq",Ll=e=>{try{return CT.realpathSync(fb.resolve(e))}catch{return fb.resolve(e)}},NT=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===om&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},gb=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${rm}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return NT(s)?s:null}catch{return null}finally{clearTimeout(r)}};var hb=e=>{let t,n=!1,r=!1,o=0,s=()=>{let m=gn();return a(m)?(ee.error(m.message),null):m.value},i=()=>{let m=s();if(!m)return!1;let f=ht();return a(f)?!1:!!m.autoSync&&hl(f.value)===null},c=()=>{let m=mo(s()?.autoSyncDebounceMs);return Math.max(0,m-(Date.now()-o))},u=async()=>{if(!(n||r)&&i()){r=!0,o=Date.now();try{await Mn(async()=>{Je().mode==="live"&&(await pi({repoRoot:e.project.repoRoot}),await e.publisher.publishIfLogMoved())})}finally{r=!1,p()}}};function p(){n||!i()||r||t||(t=setTimeout(()=>{t=void 0,u()},c()))}return p(),{queueSync:p,reschedule:()=>{t&&(clearTimeout(t),t=void 0),p()},dispose:()=>{n=!0,t&&clearTimeout(t)}}};var kl=(e,t)=>{let n,r=!1,o=async()=>{let s=Date.now();try{await e()}catch(i){logger.error("[watch] check threw",i)}r||(n=setTimeout(o,Math.max(t,Date.now()-s)))};return n=setTimeout(o,t),()=>{r=!0,n&&clearTimeout(n)}};var AT=/^(```|~~~)[^\n]*\n[\s\S]*?\n\1[ \t]*$/gm,TT=/^(?:```|~~~)[\s\S]*$/m,wT=/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,MT=/^[ \t]*\|.*$/gm,PT=/!\[[^\]]*\]\([^)]*\)/g,LT=/\[([^\]]*)\]\([^)]*\)/g,kT=/^[ \t]*(?:[#>]+[ \t]*|[-*+][ \t]+|\d+[.)][ \t]+)/gm,DT=/^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/gm,BT=/[*`~]/g,OT=/(?<![0-9A-Za-z])_|_(?![0-9A-Za-z])/g,FT=e=>Ee(e.replace(AT," ").replace(TT," ").replace(PT," ").replace(LT,"$1").replace(DT," ").replace(wT," ").replace(MT,t=>t.replaceAll("|"," ")).replace(kT,"").replace(BT,"").replace(OT,"")),_T=.5,yb=(e,t)=>{if(t<=0)return"";let n=FT(e);if(n.length<=t)return n;let r="\u2026",o=t-r.length;if(o<=0)return r.slice(0,t);let s=n.slice(0,o),i=s.lastIndexOf(" ");return`${(i>=o*_T?s.slice(0,i):s).trimEnd()}${r}`};var jT=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),to=e=>a(e)?e:d(e.message,jT(e.value)),$T=(e,t)=>(e.boards??[]).flatMap(n=>n.swimlanes??[]).flatMap(n=>n.issues??[]).find(n=>n.id===t),vb=(e,t)=>{let n=$T(e,t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}},UT=280,bb=(e,t)=>({issueId:e,excerpt:yb(t,UT)});var HT=1e3,xb=e=>{let t=re(e.repoRoot);if(a(t))return null;let n=me({repoRoot:t.value});return a(n)?null:n.value},Ib=e=>{let n=(()=>{let o=xb(e.project);return o===null?null:et(o)})();return{publishIfLogMoved:async()=>{let o=xb(e.project);if(o===null||await Ba(o))return;let s=et(o);if(s===n)return;n=s;let i=to(await zt({repoRoot:e.project.repoRoot}));a(i)||$r({type:"state",payload:i})}}},Eb=(e,t=HT)=>kl(()=>Mn(async()=>{Je().mode==="live"&&await e.publishIfLogMoved()}),t);var WT=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),sm=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!WT.has(n.hostname)},Sb=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:sm(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as ww}from"ws";var Ln=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var GT=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},Rb=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...Ln(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>GT(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var nt={line:["//"],block:[["/*","*/"]]},qt={line:["#"],block:[]},im={line:["--"],block:[]},Qo={line:[],block:[["<!--","-->"]]},VT={line:[],block:[]},q=(e,t)=>({name:e,comment:t}),Dl=q("TypeScript",nt),Bl=q("JavaScript",nt),Cb={ts:Dl,tsx:Dl,mts:Dl,cts:Dl,js:Bl,jsx:Bl,mjs:Bl,cjs:Bl,py:q("Python",{line:["#"],block:[['"""','"""']]}),rb:q("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:q("Go",nt),rs:q("Rust",nt),java:q("Java",nt),kt:q("Kotlin",nt),swift:q("Swift",nt),c:q("C",nt),h:q("C",nt),cc:q("C++",nt),cpp:q("C++",nt),hpp:q("C++",nt),cs:q("C#",nt),php:q("PHP",nt),scala:q("Scala",nt),dart:q("Dart",nt),lua:q("Lua",im),hs:q("Haskell",im),sql:q("SQL",im),ex:q("Elixir",qt),exs:q("Elixir",qt),pl:q("Perl",qt),r:q("R",qt),jl:q("Julia",qt),sh:q("Shell",qt),bash:q("Shell",qt),zsh:q("Shell",qt),vue:q("Vue",Qo),svelte:q("Svelte",Qo),html:q("HTML",Qo),xml:q("XML",Qo),md:q("Markdown",Qo),mdx:q("Markdown",Qo),css:q("CSS",{line:[],block:[["/*","*/"]]}),scss:q("CSS",nt),less:q("CSS",nt),yml:q("YAML",qt),yaml:q("YAML",qt),toml:q("TOML",qt),ini:q("INI",qt),json:q("JSON",VT)},zT="Other",Nb=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},no=e=>Cb[Nb(e)]?.name??zT,xi=e=>Cb[Nb(e)]?.comment??null,KT=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],qT=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Zo=e=>qT.test(e)||KT.some(t=>t.test(e)),YT=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,XT=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,JT=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,dn=e=>YT.test(e)||XT.test(e)||JT.test(e),Ab=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Tb=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),wb=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),QT=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,ZT=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,Mb=e=>QT.test(e),Pb=e=>ZT.test(e);var Lb=/\b(TODO|FIXME|HACK|XXX)\b/,ew=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,am=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},tw=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},kb=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,c=0,u=0;for(let m of e.files){if(m.binary||dn(m.path))continue;let f=xi(m.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=no(m.path),h=n.get(g)??{comment:0,code:0};for(let{text:x}of m.added){let b=am(x,f);if(Lb.test(x)&&i++,b==="blank"){s++;continue}if(b==="comment"){r++,h.comment++,f&&ew.test(tw(x,f))&&u++;continue}o++,h.code++}for(let{text:x}of m.removedLines)Lb.test(x)&&c++;n.set(g,h)}let p=r+o;return{byLanguage:[...n.entries()].map(([m,f])=>({name:m,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(m)??null})).sort((m,f)=>f.commentLines+f.codeLines-(m.commentLines+m.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:p===0?0:r/p,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}};var nw=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Ol=6,lm=10,rw=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},ow=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},sw=e=>{if(e.length<Ol*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Ol<=e.length;r++){let o=e.slice(r,r+Ol);if(o.some(c=>c.text.length<3))continue;let s=o.map(c=>c.text).join(`
|
|
101
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let c=0;c<Ol;c++)n[i.at+c]=!0,n[r+c]=!0}return n.filter(Boolean).length},Db=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,c=null,u=[];for(let[p,m]of e.files.entries()){if(dn(m.path)&&t.push(Ln(m)),Ab(m.path)&&n.push(Ln(m)),Tb(m.path)&&r.push(Ln(m)),wb(m.path)&&(o=!0),m.binary||dn(m.path))continue;let f=m.added.map(x=>x.text),g=rw(f),h=m.status!=="deleted";for(let x of f){nw.test(x)&&s++;let b=ow(x,g);b>i&&(i=b,c=Ln(m)),h&&u.push({text:x.trim(),file:p})}u.push({text:" ",file:p})}return{generatedPaths:t.slice(0,lm),dependencyManifests:n.slice(0,lm),buildOrCiPaths:r.slice(0,lm),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:sw(u)}};var Bb=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let c=i.addedCount+i.removed;if(dn(i.path)){r+=c;continue}let u=no(i.path),p=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};p.added+=i.addedCount,p.removed+=i.removed,Zo(i.path)&&(p.addedInTests+=i.addedCount),n.set(u,p)}let o=[...n.values()].reduce((i,c)=>i+c.added+c.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,c)=>c.added+c.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}};var iw=200,cm=2e5,aw=5e4,Ob=25,lw=64*1024*1024,dm="",cw=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,dw=/^diff --git a\/(.+) b\/\1$/,Fb=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,_b=(e,t)=>e===null?"added":t===null?"deleted":"modified",uw=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),mw=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,c=!1,u=0,p=(f,g)=>g==="modified"&&f==="added"?"added":g,m=(f,g)=>{let h=n.get(f);if(h)return h.entry.status=p(h.entry.status,g),h.entry.shas.includes(r)||h.entry.shas.push(r),h;let b={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,b),b};for(let f of t.split(`
|
|
102
|
+
`)){if(f.startsWith(dm)){r=f.slice(dm.length).trim(),o=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,c=!0,s=dw.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,h=""]=/^Binary files (.*) differ$/.exec(f)??[],[x="",b=""]=h.split(" and ");o=m(s,_b(x==="/dev/null"?null:x,b==="/dev/null"?null:b)),o.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=Fb(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let h=Fb(f.slice(4),"b/"),x=h??i??s;x&&(o=m(x,_b(i,h)));continue}let g=cw.exec(f);if(g){u=Number(g[1]),c=!1;continue}if(o){if(f.startsWith("+")){let h=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<cm&&(o.entry.added.push({sha:r,line:u,text:h}),e.retainedLines++),o.pendingByText.size<aw&&o.pendingByText.set(h,(o.pendingByText.get(h)??0)+1),u++;continue}if(f.startsWith("-")){let h=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<cm&&(o.entry.removedLines.push({sha:r,line:0,text:h}),e.retainedLines++);let x=o.pendingByText.get(h)??0;x>0&&h.trim().length>2&&(e.selfChurn++,o.pendingByText.set(h,x-1))}}}},pw=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines});var jb=async({repoRoot:e,shas:t})=>{if(t.length===0)return d("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,iw).reverse(),r=uw(),o=0,s=0,i=!1;for(let u=0;u<n.length;u+=Ob){let p=n.slice(u,u+Ob),m=await U({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${dm}%H`,...p]});if(a(m))return l(m.message);if(mw(r,m.value.stdout),o+=m.value.stdout.length,s+=p.length,o>lw){i=!0;break}}let c=pw(r);return d("Scanned ticket patch",{files:c.files,insertions:c.insertions,deletions:c.deletions,selfChurn:c.selfChurn,scannedCommits:s,truncated:i||s<t.length||c.retainedLines>=cm})};var fw=40,gw=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,$b=async({repoRoot:e,sha:t})=>{let n=await Le({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let m of n.stdout.split(`
|
|
103
|
+
`)){let f=gw.exec(m);if(!f)continue;let[,g="",h=""]=f;if(dn(h))continue;let x=no(h);if(r.add(x),Zo(h)||!xi(h))continue;let b=o.get(x)??[];b.length<fw&&(b.push({blob:g,path:h}),o.set(x,b))}let s=[...o.values()].flat(),i=await Ui(s.map(m=>m.blob),e);if(a(i))return{languages:r,commentShareByLanguage:new Map};let c=i.value,u=new Map;for(let{blob:m,path:f}of s){let g=c.get(m);if(g===void 0)continue;let h=xi(f),x=no(f),b=u.get(x)??{comment:0,code:0};for(let R of g.split(`
|
|
104
|
+
`)){let S=am(R,h);S==="comment"&&b.comment++,S==="code"&&b.code++}u.set(x,b)}let p=new Map;for(let[m,f]of u){let g=f.comment+f.code;g>0&&p.set(m,f.comment/g)}return{languages:r,commentShareByLanguage:p}};var Ub=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let c of e.files)if(!(c.binary||dn(c.path))&&Zo(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&r.push(Ln(c)),c.status==="deleted"&&o.push(Ln(c));for(let{text:u}of c.added)Mb(u)&&s++,Pb(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var hw=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Hb=async({repoRoot:e,ref:t,commits:n})=>{let r=await jb({repoRoot:e,shas:n.map(c=>c.sha)});if(a(r))return l(r.message);let o=r.value,s=hw(n),i=s?await $b({repoRoot:e,sha:s}):null;return d("Derived issue stats",{ref:t,shape:Rb({commits:n,patch:o}),languages:Bb({patch:o,languagesBefore:i?.languages??null}),tests:Ub({patch:o}),comments:kb({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Db({patch:o})})};var Ii=e=>{if(a(e))return e;let t=de(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=bp(n),s=e.value.map(i=>({...i,authorIdentity:ov({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return d(e.message,s)};var yw=32,Ei=new Map;var vw=(e,t)=>{if(Ei.set(e,t),Ei.size>yw){let n=Ei.keys().next();n.done||Ei.delete(n.value)}return t},Fl=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return l("idOrRef must not be empty");let n=t.length>7?H(t):t.toUpperCase(),r=re(e.repoRoot??process.cwd());if(a(r))return l(r.message);let o=r.value,s=Ii(await Kn({repoRoot:o,ref:n}));if(a(s))return l(s.message);let i=s.value.map(m=>({sha:m.sha,time:m.time,author:m.authorIdentity?.resolved?m.authorIdentity.name:m.author,subject:m.subject})),c=[o,n,i.map(m=>`${m.sha}:${m.author}`).join(",")].join(" "),u=Ei.get(c);if(u)return d("Derived issue stats",u);let p=await Hb({repoRoot:o,ref:n,commits:i});return a(p)?l(p.message):d("Derived issue stats",vw(c,p.value))};var bw=new RegExp(`^[0-9A-Z]{${7}}$`),xw=e=>{let t=e.indexOf(" ");if(t===-1)return null;let n=e.slice(0,t).toUpperCase();return bw.test(n)?n:null},Iw=e=>{let t={};for(let n of e){let r=xw(n.subject);if(!r)continue;let o=t[r]??={commits:0,insertions:0,deletions:0};o.commits++,o.insertions+=n.insertions,o.deletions+=n.deletions}return t},Wb=async(e={})=>{let t=await Ho({repoRoot:e.repoRoot});return a(t)?t:d("Collected diff stats by ref",Iw(t.value))};var Ew="Filed here",Gb=(e,t)=>e.set(t,(e.get(t)??0)+1),Vb=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?Ew:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),zb=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let c of t)for(let[u,p]of c.entries()){if(p!==e)continue;s++,Gb(r,c[u-1]??null);let m=c[u+1];m!==void 0&&(i++,Gb(o,m))}return{arrived:s,departed:i,arrivesFrom:Vb(r,s,n),movesOnTo:Vb(o,i,n)}};var Kb=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var Si=1440*60*1e3,Sw=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*Si,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[c,u]of i.entries()){let p=s.get(u.laneId);if(!p)continue;let m=i[c+1]?.enteredAt,f=Math.max(0,Math.ceil((u.enteredAt-o)/Si)),g=m===void 0?r-1:Math.min(r-1,Math.ceil((m-o)/Si)-1);for(let h=f;h<=g;h++)p[h].push(o+h*Si-u.enteredAt)}return Object.fromEntries([...s].map(([i,c])=>[i,c.map((u,p)=>({t:o+p*Si,median:Kb(u.sort((m,f)=>m-f)),count:u.length}))]))},qb=({laneId:e,journeys:t,now:n,days:r})=>Sw({laneIds:[e],journeys:t,now:n,days:r})[e];var Rw=40,Cw=30,Nw=()=>({tickets:0,commits:0,insertions:0,deletions:0}),Aw=async(e,t)=>{let n=Nw();for(let r of t.slice(0,Rw)){let o=await Fl({repoRoot:e,idOrRef:H(r)});a(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},Yb=async e=>{let t=pt();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return l("Swimlane not found");let o=Object.values(n).filter(_),s=o.map(u=>xu(u.log??[],De(u.id))),i=zb(e.swimlaneId,s.map(u=>u.map(p=>p.laneId)),u=>n[u]?.title??"Elsewhere"),c=o.filter(u=>u.parentNodeId===e.swimlaneId).map(u=>u.id);return d("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:De(e.swimlaneId),...i,stayTrend:qb({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:Cw}),code:await Aw(e.repoRoot,c)})};var Xb=new Set(["sync","email:link","email:unlink","issues:create","board:create","board:edit:title","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Jb=e=>{let t=$n({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Eo(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Qb=e=>{let t=$n();if(a(t))return l(t.message);let n=t.value.find(r=>r.root===e);return n?d("Resolved recent project",n.root):l(`Not a recent project: ${e}`)};import{z as k}from"zod";var te=k.string().min(1),Zb=k.discriminatedUnion("at",[k.object({at:k.literal("start")}),k.object({at:k.literal("end")}),k.object({at:k.literal("before"),sibling:te}),k.object({at:k.literal("after"),sibling:te})]),Ri=k.number().finite(),ae=(e,t)=>k.object({type:k.literal(e),payload:t}),ro=e=>k.object({type:k.literal(e)}),Tw=k.discriminatedUnion("type",[ro("state:get"),ro("issues:list"),ro("sync"),ro("time-travel:live"),ro("diff-stats:get"),ae("project:open",k.object({root:k.string().min(1)})),ae("issues:create",k.object({title:k.string(),parentId:te,description:k.string().optional(),tagNames:k.array(k.string()).optional()})),ae("board:create",k.object({title:k.string()})),ae("board:edit:title",k.object({boardId:te,title:k.string()})),ae("swimlane:create",k.object({title:k.string(),boardId:te})),ae("swimlane:edit:title",k.object({swimlaneId:te,title:k.string()})),ae("swimlane:delete",k.object({swimlaneId:te})),ae("swimlane:move",k.object({swimlaneId:te,boardId:te,position:Zb.optional()})),ae("issues:move",k.object({issueId:te,parentId:te,position:Zb.optional()})),ae("issue:edit:title",k.object({issueId:te,title:k.string()})),ae("issue:edit:description",k.object({issueId:te,description:k.string()})),ae("issue:tag:add",k.object({issueId:te,tagName:k.string()})),ae("issue:tag:remove",k.object({issueId:te,tagId:te})),ae("contributor:remove",k.object({contributorId:te})),ae("tag:remove",k.object({tagId:te})),k.object({type:k.literal("contributors:get"),payload:k.object({boardId:te.optional()}).optional()}),ae("issue:assignee:add",k.object({issueId:te,assigneeId:te.optional(),assigneeName:k.string().optional(),createUnlinked:k.boolean().optional()})),ae("issue:assignee:remove",k.object({issueId:te,assigneeId:te})),ae("issue:close",k.object({issueId:te})),ae("issue:reopen",k.object({issueId:te})),ae("issue:comment:add",k.object({issueId:te,body:k.string()})),ae("issue:comment:delete",k.object({issueId:te,commentId:te})),ae("issue:comment:edit",k.object({issueId:te,commentId:te,body:k.string()})),ae("issue:get",k.object({issueId:te})),ae("issue:preview:get",k.object({issueId:te})),k.object({type:k.literal("timeline:get"),payload:k.object({start:Ri.optional(),end:Ri.optional(),boardId:te.optional(),requestId:k.number().finite().optional()}).optional()}),k.object({type:k.literal("commits:get"),payload:k.object({start:Ri.optional(),end:Ri.optional(),requestId:k.number().finite().optional()}).optional()}),ae("time-travel:scrub",k.object({targetTime:Ri})),ae("time-travel:checkout-event",k.object({eventId:k.string().min(1)})),ae("commit:inspect",k.object({sha:k.string()})),k.object({type:k.literal("emails:get")}),ae("email:link",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ae("email:unlink",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ae("commit:diff:get",k.object({sha:k.string()})),ae("issue:commits:get",k.object({issueId:te})),ae("issue:squashed-diff:get",k.object({issueId:te})),ae("issue:stats:get",k.object({issueId:te})),ae("swimlane:stats:get",k.object({swimlaneId:te})),ro("me:stats:get"),ro("settings:get"),ae("settings:set",k.object({autoSync:k.boolean().optional(),autoSyncIntervalMs:k.number().finite().optional()}))]);var ex=e=>{let t=Tw.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var Mw=1024*1024,um=()=>{$r({type:"state",payload:to(Qr())})},Z=(e,t)=>{e.send(JSON.stringify(t))},Ci=async(e,t)=>{let n=to(await zt({repoRoot:t}));return a(n)&&n.message===Sc?Z(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Jb(t)}}):Z(e,{type:"state",payload:n})},Pw=async(e,t)=>{let n=()=>Z(e,{type:"state",payload:to(Qr())});if(Je().mode!=="live")return n();let r=await zt({repoRoot:t});return Je().mode!=="live"?n():Z(e,{type:"state",payload:to(r)})},Ge=async(e,t,n,r,o)=>{if(Z(e,{type:r,payload:o}),a(o))return Z(e,{type:"failed",payload:o.message});n(),Pw(e,t)},tx=(e,t,{onStateChanged:n,onSyncSettingsChanged:r,getPort:o})=>{new ww({server:e,path:"/ws",maxPayload:Mw,verifyClient:i=>!sm(i.origin,o())}).on("connection",i=>{Og(i),i.on("message",async c=>{let u=async p=>{let{type:m}=p,f=t.repoRoot;if(m==="project:open"){let g=Qb(p.payload.root);return Z(i,{type:"project:open:result",payload:g}),a(g)?void 0:(t.repoRoot=g.value,Ci(i,g.value))}if(m==="timeline:get"){let{requestId:g,...h}=p.payload??{};return Z(i,{type:"timeline",requestId:g,payload:await eb({repoRoot:f,...h})})}if(m==="issue:get"){let g=p.payload?.issueId,h=Qr(),x=Fu(g);return Z(i,{type:"issue",payload:a(h)?h:d("Issue detail",{...vb(h.value,g),history:a(x)?[]:x.value})})}if(m==="issue:preview:get"){let{issueId:g}=p.payload,h=wu(g);return Z(i,{type:"issue:preview:result",payload:{issueId:g,result:a(h)?h:d("Issue preview",bb(g,h.value))}})}if(m==="commits:get"){let{requestId:g,...h}=p.payload??{};return Z(i,{type:"commits",requestId:g,payload:Ii(await Ho({repoRoot:f,...h}))})}if(m==="emails:get")return Z(i,{type:"emails",payload:await Ml({repoRoot:f}),suggestions:await Pl({repoRoot:f})});if(m==="email:link"||m==="email:unlink"){let h=await(m==="email:link"?em:tm)({repoRoot:f,...p.payload});return Z(i,{type:"emails",payload:await Ml({repoRoot:f}),suggestions:await Pl({repoRoot:f}),lastAction:a(h)?{ok:!1,message:h.message}:{ok:!0,message:h.message}}),Ge(i,f,n,`${m}:result`,h)}if(m==="me:stats:get")return Z(i,{type:"me:stats",payload:await nm({repoRoot:f})});if(m==="settings:get")return Z(i,{type:"settings",payload:ci()});if(m==="settings:set"){let g=qo({enabled:p.payload.autoSync,intervalMs:p.payload.autoSyncIntervalMs});return a(g)||r(),Z(i,{type:"settings",payload:a(g)?ci():g,lastAction:a(g)?{ok:!1,message:g.message}:{ok:!0,message:g.message}})}if(m==="commit:inspect")return Z(i,{type:"commit:inspect:result",payload:await ei({repoRoot:f,sha:p.payload.sha})});if(m==="commit:diff:get"){let{sha:g}=p.payload;return Z(i,{type:"commit:diff:result",payload:{sha:g,result:await Od({repoRoot:f,sha:g})}})}if(m==="issue:commits:get"){let{issueId:g}=p.payload;return Z(i,{type:"issue:commits:result",payload:{issueId:g,result:Ii(await Kn({repoRoot:f,ref:H(g)}))}})}if(m==="issue:squashed-diff:get"){let{issueId:g}=p.payload;return Z(i,{type:"issue:squashed-diff:result",payload:{issueId:g,result:await Fd({repoRoot:f,ref:H(g)})}})}if(m==="issue:stats:get"){let{issueId:g}=p.payload;return Z(i,{type:"issue:stats:result",payload:{issueId:g,result:await Fl({repoRoot:f,idOrRef:H(g)})}})}if(m==="diff-stats:get")return Z(i,{type:"diff-stats",payload:await Wb({repoRoot:f})});if(m==="swimlane:stats:get"){let{swimlaneId:g}=p.payload;return Z(i,{type:"swimlane:stats:result",payload:{swimlaneId:g,result:await Yb({repoRoot:f,swimlaneId:g})}})}if(m==="time-travel:scrub"){let g=await Su({repoRoot:f,targetTime:p.payload.targetTime});return Z(i,{type:"time-travel:result",payload:g}),a(g)?void 0:um()}if(m==="time-travel:checkout-event"){let g=await nb({repoRoot:f,eventId:p.payload.eventId});return Z(i,{type:"time-travel:result",payload:g}),a(g)?void 0:um()}if(m==="time-travel:live"){let g=await rb({repoRoot:f});return Z(i,{type:"time-travel:result",payload:g}),a(g)?void 0:um()}if(m==="state:get")return Ci(i,f);if(m==="sync"){let g=await pi({repoRoot:f});return Z(i,{type:"sync:result",payload:g}),n(),Ci(i,f)}if(m==="issue:comment:add"){let g=await yi({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:comment:add:result",g)}if(m==="issue:comment:edit"){let g=await Zu({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:comment:edit:result",g)}if(m==="issue:comment:delete"){let g=await vi({repoRoot:f,...p.payload});return Z(i,{type:"issue:comment:delete:result",payload:g}),a(g)?Z(i,{type:"failed",payload:g.message}):(n(),Ci(i,f))}if(m==="issue:edit:description"){let g=await _u({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:edit:description:result",g)}if(m==="issue:edit:title"){let g=await ju({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:edit:title:result",g)}if(m==="issue:tag:add"){let g=await zu({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:tag:add:result",g)}if(m==="issue:tag:remove"){let g=await qu({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:tag:remove:result",g)}if(m==="contributor:remove"){let g=await Xu({repoRoot:f,...p.payload});return Ge(i,f,n,"contributor:remove:result",g)}if(m==="tag:remove"){let g=await Ku({repoRoot:f,...p.payload});return Ge(i,f,n,"tag:remove:result",g)}if(m==="contributors:get")return Z(i,{type:"contributors",boardId:p.payload?.boardId,payload:await Ju({repoRoot:f,...p.payload})});if(m==="issue:assignee:add"){let g=await Yu({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:assignee:add:result",g)}if(m==="issue:assignee:remove"){let g=await Qu({repoRoot:f,...p.payload});return Ge(i,f,n,"issue:assignee:remove:result",g)}if(m==="issues:list")return Z(i,{type:"issues",payload:await Lu({repoRoot:f})});if(m==="issues:create"){let g=await ku({...p.payload,repoRoot:f});return Z(i,{type:"issues:create:result",payload:g}),a(g)?$r({type:"failed",payload:g.message}):(n(),Ci(i,f))}if(m==="board:create"){let g=await $u({...p.payload,repoRoot:f});return Ge(i,f,n,"board:create:result",g)}if(m==="board:edit:title"){let g=await Uu({...p.payload,repoRoot:f});return Ge(i,f,n,"board:edit:title:result",g)}if(m==="swimlane:create"){let g=await Hu({...p.payload,repoRoot:f});return Ge(i,f,n,"swimlane:create:result",g)}if(m==="swimlane:edit:title"){let g=await Wu({...p.payload,repoRoot:f});return Ge(i,f,n,"swimlane:edit:title:result",g)}if(m==="swimlane:delete"){let g=await Vu({...p.payload,repoRoot:f});return Ge(i,f,n,"swimlane:delete:result",g)}if(m==="swimlane:move"){if(!p.payload.position)return Z(i,{type:"error",message:"Missing move position"});let g=await Gu({...p.payload,repoRoot:f});return Ge(i,f,n,"swimlane:move:result",g)}if(m==="issues:move"){if(!p.payload.position)return Z(i,{type:"error",message:"Missing move position"});let g=await Ou({...p.payload,repoRoot:f});return Ge(i,f,n,"issues:move:result",g)}if(m==="issue:close"){let g=await Du({repoRoot:f,issueId:p.payload.issueId});return Ge(i,f,n,"issue:close:result",g)}if(m==="issue:reopen"){let g=await Bu({repoRoot:f,issueId:p.payload.issueId});return Ge(i,f,n,"issue:reopen:result",g)}return Z(i,{type:"error",message:"Unknown message type"})};try{let p=ex(JSON.parse(c.toString()));if(!p.ok)return Z(i,{type:"error",message:p.error});let m=p.message;return Xb.has(m.type)?await Mn(async()=>Je().mode!=="live"?Z(i,{type:"failed",payload:"Read-only while viewing history"}):u(m)):await u(m)}catch(p){return Z(i,{type:"error",message:p instanceof Error?p.message:String(p)})}})})};var Ow=oo.dirname(Bw(import.meta.url)),Fw=process.env.IS_LOCAL==="true"?oo.resolve(process.cwd(),"dist/gui"):oo.join(Ow,"gui"),_l,_w=async()=>(_l===void 0&&(_l=await import("node:sea").catch(()=>null)),_l?.isSea()?_l:null),Pe=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},jw=e=>Pe(e,409,{isError:!0,message:"Read-only while viewing history"}),jl=(e,t)=>Mn(async()=>Je().mode!=="live"?jw(e):t()),nx=async(e,t=1024*1024)=>new Promise((n,r)=>{let o=[],s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),$w=2*1024*1024,Uw={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},Hw=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",rx=new Map,Ww=e=>`"${kw("sha1").update(e).digest("base64url")}"`,Gw=async e=>{try{let{size:t,mtimeMs:n}=await Lw(e);return`${t}:${n}`}catch{return null}},Vw=e=>{try{return decodeURIComponent(e)}catch{return null}},ox=async(e,t,n)=>{let r=e==="/"?"/index.html":Vw(e);if(r===null)return Pe(n,404,{isError:!0,message:"Not found"});let o=r.replace(/^\/+/,""),s=oo.resolve(Fw),i=oo.resolve(s,o),c=oo.relative(s,i);if(c.startsWith("..")||oo.isAbsolute(c))return Pe(n,403,{isError:!0,message:"Forbidden"});let u=await _w(),p=u?"sea":await Gw(i),m=p===null?void 0:rx.get(c),f=m&&m.stamp===p?m.etag:null;if(f&&t.headers["if-none-match"]===f)return n.writeHead(304,{etag:f,"cache-control":"no-cache"}),n.end();try{let g=u?Buffer.from(u.getAsset(`gui/${c}`)):await sx(i),h=f??Ww(g);return p!==null&&rx.set(c,{stamp:p,etag:h}),n.writeHead(200,{"content-type":Hw(i),etag:h,"cache-control":"no-cache"}),n.end(g)}catch{return Pe(n,404,{isError:!0,message:`Not found: ${o}`})}},zw=async(e,t=bi)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),ix=async e=>{Wv(!1);let t=0,n={repoRoot:e.repoRoot},r=Dw.createServer((p,m)=>{o(p,m).catch(f=>(logger.error(`[gui] ${p.method} ${p.url}: ${f instanceof Error?f.message:String(f)}`),m.headersSent?m.end():Pe(m,500,{isError:!0,message:"Internal error"})))});async function o(p,m){let f=new URL(p.url??"/","http://127.0.0.1"),g=Sb({method:p.method,origin:p.headers.origin,contentType:p.headers["content-type"]},t);if(g)return Pe(m,g.status,{isError:!0,message:g.message});if(p.method==="GET"&&f.pathname===rm)return Pe(m,200,{app:om,repoRoot:Ll(n.repoRoot),version:Pn,pid:process.pid});if(f.pathname==="/api/state")return Pe(m,200,await zt({repoRoot:n.repoRoot}));if(p.method==="POST"&&f.pathname==="/api/comments")try{let h=await nx(p);if(!h.issueId||!h.body?.trim())return Pe(m,400,{isError:!0,message:"Missing issueId or body"});let x=h.issueId,b=h.body;return await jl(m,async()=>{let R=await yi({repoRoot:n.repoRoot,issueId:x,body:b});return a(R)?Pe(m,400,{isError:!0,message:R.message}):Pe(m,200,await zt({repoRoot:n.repoRoot}))})}catch(h){return Pe(m,400,{isError:!0,message:h instanceof Error?h.message:"Unable to add comment"})}if(p.method==="POST"&&f.pathname==="/api/attachments")try{let h=await nx(p,$w);if(!h.issueId||!h.dataBase64)return Pe(m,400,{isError:!0,message:"Missing issueId or dataBase64"});let x=h.issueId,b=h.dataBase64,R=h.name??"";return await jl(m,async()=>{let S=await Nu({repoRoot:n.repoRoot,issueId:x,name:R,dataBase64:b});return a(S)?Pe(m,400,{isError:!0,message:S.message}):Pe(m,200,{...await zt({repoRoot:n.repoRoot}),attachment:S.value})})}catch(h){return Pe(m,400,{isError:!0,message:h instanceof Error?h.message:"Unable to add attachment"})}if(p.method==="DELETE"&&f.pathname.startsWith("/api/attachments/")){let h=decodeURIComponent(f.pathname.replace("/api/attachments/",""));return h?jl(m,async()=>{let x=await Au({repoRoot:n.repoRoot,attachmentId:h});return a(x)?Pe(m,400,{isError:!0,message:x.message}):Pe(m,200,await zt({repoRoot:n.repoRoot}))}):Pe(m,400,{isError:!0,message:"Missing attachment id"})}if(p.method==="GET"&&f.pathname.startsWith("/media/")){let h=decodeURIComponent(f.pathname.replace("/media/","")),x=await Tu({repoRoot:n.repoRoot,fileName:h});if(a(x))return Pe(m,404,{isError:!0,message:x.message});try{let b=await sx(x.value.filePath);return m.writeHead(200,{"content-type":Uw[x.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),m.end(b)}catch{return Pe(m,404,{isError:!0,message:"Attachment blob not found"})}}if(p.method==="DELETE"&&f.pathname.startsWith("/api/comments/")){let h=decodeURIComponent(f.pathname.replace("/api/comments/",""));return h?jl(m,async()=>{let x=await vi({repoRoot:n.repoRoot,commentId:h});return a(x)?Pe(m,400,{isError:!0,message:x.message}):Pe(m,200,await zt({repoRoot:n.repoRoot}))}):Pe(m,400,{isError:!0,message:"Missing comment id"})}return f.pathname.startsWith("/board/")||f.pathname==="/log"?ox("/",p,m):ox(f.pathname,p,m)}try{t=await zw(r)}catch(p){return l(p instanceof Error?`Unable to start GUI server: ${p.message}`:`Unable to start GUI server: ${String(p)}`)}let s=Ib({project:n}),i=hb({project:n,publisher:s}),c=Eb(s);tx(r,n,{onStateChanged:()=>i.queueSync(),onSyncSettingsChanged:()=>i.reschedule(),getPort:()=>t}),r.on("close",()=>{i.dispose(),c()});let u=r.address();return!u||typeof u=="string"?(r.close(),l("Unable to resolve GUI server address")):d("Started GUI server",{url:`http://epiq.localhost:${u.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var lx=async e=>{let t=co({});if(a(t))return l(t.message);let n=ht();ve(n)&&je(n.value);let r=await gb(bi);if(r&&r.repoRoot===Ll(e.repoRoot)){let i=`http://127.0.0.1:${bi}`;return console.log(`Epiq GUI already running for this project at ${ax.cyan(i)}`),wc(i),d("Reused running GUI",{url:i})}let o=await ix({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${ax.cyan(s)}`),wc(s),d("Started GUI",{url:s})};import{Box as Jn}from"ink";import we from"react";import{Box as mm,Text as Ni}from"ink";import un,{useEffect as Kw,useMemo as qw}from"react";import{ulid as Yw}from"ulid";var cx=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return un.createElement(Ni,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?un.createElement(Ni,{color:n,dimColor:o},e):un.createElement(Ni,{color:n,dimColor:o},e.slice(0,c),un.createElement(Ni,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},dx=Yw(),Xw=e=>`${e}`,Jw=e=>{let{pendingNavTarget:t}=vr();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Be(C.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(C))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==C.PALETTE).map(i=>{let c=$a(i),u=yl.find(p=>p.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},Qw=e=>Re.text({id:dx,parentNodeId:e,rank:"000000",name:"Command Palette",readonly:!0,isVirtual:!0}),Zw=(e,t,n)=>Re.text({id:Xw(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,disabled:!e.isAvailable,readonly:!0,isVirtual:!0}),pm=[],eM=e=>{ux();let t=N.createNode(Qw(v().rootNodeId));a(t)||!rr(t.value)||(pm=[t.value,...e.map((n,r)=>Zw(n,r,dx)).map(N.createNode).filter(ve).map(({value:n})=>n).filter(rr)],$.navigate({contextNode:t.value,selectedIndex:0}))},ux=()=>{let e=pm.map(t=>t.id);pm=[];for(let t of e)N.deleteNode(t)};function mx({width:e,height:t}){let r=Tf().value.trim().toLowerCase(),o=qw(()=>Jw(r),[r]);Kw(()=>(eM(o),()=>{ux()}),[o]);let s=v().selectedIndex;return un.createElement(mm,{flexDirection:"column",width:e,height:t-2},un.createElement(ut,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,p=i.isAvailable?y.accent:y.secondary2,m=i.isAvailable?"":"[unavailable] ";return un.createElement(mm,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},un.createElement(Ni,{color:p,dimColor:!i.isAvailable},u?"\u276F ":" ",un.createElement(cx,{text:Np(i.command),match:r,color:p,dimColor:!i.isAvailable})),un.createElement(mm,{paddingLeft:2},un.createElement(cx,{text:m+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as gM}from"ink";import Hl from"react";import Ti from"chalk";import{Box as Ai,Text as hx}from"ink";import so,{useEffect as yx,useMemo as tM,useState as vx}from"react";var es=["\u2803","\u2806","\u2830","\u2818"],px=120,fx=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%es.length+es.length)%es.length;return es[r]}return e?"?":":"},gx=({infoMessage:e,isPending:t})=>t&&e.includes(fe)?"":e;var bx=Ti.hex(y.secondary),nM=Ti.inverse,rM=Ti.inverse.hex(y.secondary2),oM={hint:"",hints:[],overlap:0,remainder:""},Ix=({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}},sM=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ze(t);return{bg:r=>Ti.bgHex(n).black(r),bgCursor:r=>Ti.bgHex(n).inverse.black(r)}}return Bc(t)},iM=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Ix({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},xx=()=>({value:ct.value,cursorPosition:ct.cursorPosition,commandIsPending:ct.commandIsPending,autoCompletion:ct.commandMeta.autoCompletion??oM,infoMessage:ct.commandMeta.infoMessage,validationStatus:ct.commandMeta.validity,command:ct.commandMeta.command,inputString:ct.commandMeta.inputString,modifier:ct.commandMeta.modifier}),aM=(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,Ex=({width:e,mode:t})=>{let[n,r]=vx(xx());yx(()=>{let A=()=>{let P=xx();r(M=>aM(M,P)?M:P)},T=Jc(A);return A(),()=>{T()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:p,modifier:m,validationStatus:f}=n,g=c&&f===In.Invalid,h=gx({infoMessage:i,isPending:c}),[x,b]=vx(0);yx(()=>{if(!c){b(0);return}let A=setInterval(()=>{b(T=>(T+1)%es.length)},px);return()=>{clearInterval(A)}},[c]);let R=fx({isPalette:t===I.PALETTE,isPending:c,frame:x}),S=tM(()=>{let A=Math.max(0,Math.min(s,o.length)),T=Ix({value:o,command:p}),P=iM({value:o,command:p,modifier:m}),M=p?Bc(p):null,O=sM({command:p,modifier:m}),W=(st,ft)=>{let ao=T&&ft>=T.start&&ft<T.end,oc=P&&ft>=P.start&&ft<P.end;return ao&&M?M.fg(st):oc&&O?O.bg(st):st},Y=(st,ft)=>{let ao=T&&ft>=T.start&&ft<T.end,oc=P&&ft>=P.start&&ft<P.end;return ao&&M?M.fgCursor(st):oc&&O?O.bgCursor(st):nM(st)},xe=o.slice(0,A),F=o[A]??" ",X=A<o.length?o.slice(A+1):"",Ve=Array.from(xe).map((st,ft)=>W(st,ft)).join(""),Qn=Y(F,A),is=Array.from(X).map((st,ft)=>W(st,A+1+ft)).join("");if(u.hint){let st=u.hint[u.overlap]??F;Qn=rM(st),is=bx(u.remainder.slice(1)+X)}return Ve+Qn+is},[o,s,u,p,m]);return so.createElement(Ai,{flexDirection:"column",justifyContent:"flex-start"},so.createElement(Ai,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},so.createElement(Ai,{height:1,flexWrap:"nowrap"},so.createElement(Ai,{flexShrink:0},so.createElement(hx,{wrap:"truncate-start"},bx(R),S)),h&&so.createElement(Ai,{flexShrink:1,minWidth:0},so.createElement(hx,{wrap:"truncate",color:g?y.red:y.secondary2},` ${h} `)))))};import{Box as lM,Text as wi}from"ink";import ts from"react";var Sx=" ",cM=({keys:e,label:t})=>e.length+1+t.length,dM=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?Sx.length:0)+cM(o);if(r+i>t-4)break;n.push(o),r+=i}return n},Rx=({width:e,availableHints:t})=>{let n=dM(t,e);return ts.createElement(lM,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?ts.createElement(wi,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>ts.createElement(wi,{key:`${o}-${s}`},i>0?Sx:"",ts.createElement(wi,{color:y.accent},o),ts.createElement(wi,{color:y.secondary2}," ",s)))):ts.createElement(wi,{color:y.secondary2},"\xA0"))};import{Box as uM,Text as $l}from"ink";import Mi,{useEffect as mM,useRef as ns,useState as pM}from"react";var fM=40,Ul=.3,fm="\u2500",Cx=1,Nx=16,Ax=({width:e})=>{let{replay:t}=ne(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Cx,[c,u]=pM(0),p=ns(r);p.current=r;let m=ns(0),f=ns(0),g=ns(0),h=ns(0),x=ns(0);if(mM(()=>{if(!n){m.current=0,g.current=0,h.current=0,x.current=0,u(0);return}m.current=p.current,f.current=Date.now(),g.current=p.current;let T=setInterval(()=>{let P=Date.now(),M=p.current;if(M!==g.current){let F=M-g.current,X=P-f.current;if(F<0)h.current=0,x.current=0;else if(F>0&&X>0){let Ve=F/X;h.current=h.current===0?Ve:h.current*(1-Ul)+Ve*Ul,x.current=x.current===0?F:x.current*(1-Ul)+F*Ul}m.current=M,f.current=P,g.current=M}let O=P-f.current,W=Math.min(x.current,h.current*O),Y=Math.min(1,m.current+W),xe=Math.round(Y*i);u(F=>F===xe?F:xe)},fM);return()=>clearInterval(T)},[n,i]),!t)return null;let b=T=>{let P=s>1?T/(s-1):0,M=Math.round(P*(Nx-1))/(Nx-1);return Ki(M)},R=Math.min(s,Math.floor(c/Cx)),S=[];for(let T=0;T<R;T++){let P=b(T),M=S[S.length-1];M&&M.color===P?M.text+=fm:S.push({text:fm,color:P})}let A=fm.repeat(Math.max(0,s-R));return Mi.createElement(uM,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},Mi.createElement($l,{color:y.secondary2},"\u25B6"),Mi.createElement($l,null,S.map((T,P)=>Mi.createElement($l,{key:P,color:T.color},T.text)),Mi.createElement($l,{color:y.secondary,dimColor:!0},A)))};var Pi=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=ne(),o=t===I.COMMAND_LINE||t===I.PALETTE;return Hl.createElement(gM,null,o?Hl.createElement(Ex,{width:e,mode:t}):r==="replay"?Hl.createElement(Ax,{width:e}):Hl.createElement(Rx,{width:e,mode:t,availableHints:n}))};import{Box as Ar,Text as rs}from"ink";import bt,{useEffect as hM,useMemo as yM}from"react";import{ulid as Tx}from"ulid";var Gl=Tx(),vM=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(fu).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),bM=e=>Re.text({id:Gl,parentNodeId:e,rank:"000000",name:"Help",isVirtual:!0,readonly:!0}),xM=(e,t,n)=>Re.text({id:Tx(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,readonly:!0,isVirtual:!0}),Wl=[],wx=()=>{let e=Wl.filter(n=>n.id!==Gl).map(n=>n.id),t=Wl.filter(n=>n.id===Gl).map(n=>n.id);Wl=[];for(let n of[...e,...t])N.deleteNode(n)},IM=e=>{wx();let t=N.createNode(bM(v().rootNodeId));if(a(t)||!rr(t.value))return logger.error("Could not attach help nodes");Wl=[t.value,...e.map((n,r)=>xM(n,r,Gl)).map(N.createNode).filter(ve).map(({value:n})=>n).filter(rr)],$.navigate({contextNode:t.value,selectedIndex:0})},Mx=({width:e,height:t})=>{let n=yM(()=>vM(),[]);hM(()=>(IM(n),()=>{wx()}),[n]);let r=v().selectedIndex;return bt.createElement(Ar,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},bt.createElement(Ar,{paddingX:1,justifyContent:"center"},bt.createElement(rs,{color:y.accent},"Help"),bt.createElement(rs,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),bt.createElement(Ar,{paddingX:1,marginTop:1},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(rs,{color:y.secondary},"Key(s)")),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(rs,{color:y.secondary},"Action"))),bt.createElement(ut,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return bt.createElement(Ar,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(rs,{color:y.accent},o)),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(rs,{color:c?y.primary:y.secondary2},s)))})))};import{Box as os,Text as xt}from"ink";import Ae,{useEffect as EM,useState as gm}from"react";var Vl=({index:e,email:t,note:n,noteColor:r})=>Ae.createElement(os,null,Ae.createElement(xt,{color:y.accent},e===void 0?" ":` ${e}.`),Ae.createElement(xt,null," ",t),n&&Ae.createElement(xt,{color:r??y.secondary2},` ${n}`)),Px=({height:e})=>{let[t,n]=gm([]),[r,o]=gm([]),[s,i]=gm(null),{userName:c,gitEmail:u,gitName:p,userId:m}=V();return EM(()=>{let f=!0;return(async()=>{let h=de(),x=re(process.cwd());if(a(h)||a(x)||!m)return;let b=h.value.emailLinks,R=hn(b,m);n(R.map(P=>({email:P,others:xs(b,P).filter(M=>M!==m).map(M=>h.value.contributors[M]?.name??M)})));let S=ke(x.value),A=await wn({repoRoot:x.value,stateBranch:a(S)?void 0:S.value,names:[c,p],links:b});if(!f)return;if(a(A)){i(A.message);return}let T=xr(A.value);So(T.map(P=>P.email)),o(T)})(),()=>{f=!1}},[m,c,p,u]),Ae.createElement(os,{height:e-4,flexDirection:"column",paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Ae.createElement(os,null,Ae.createElement(xt,{color:y.accent,bold:!0},c??"Not configured"),Ae.createElement(xt,{color:y.secondary2}," on this board")),s&&Ae.createElement(xt,{color:y.red},s),Ae.createElement(os,{flexDirection:"column"},Ae.createElement(xt,{color:y.secondary2},"CLAIMED"),t.length===0?Ae.createElement(Vl,{email:"Nothing claimed \u2014 your commits show the name git signed them with.",note:""}):t.map(f=>Ae.createElement(Vl,{key:f.email,email:f.email,note:f.others.length>0?`CONTESTED: also ${f.others.join(", ")}, resolves to nobody`:f.email===u?"your git identity here":void 0,noteColor:f.others.length>0?y.yellow:void 0}))),Ae.createElement(os,{flexDirection:"column"},Ae.createElement(xt,{color:y.secondary2},"UNCLAIMED IN THIS HISTORY"),r.length===0?Ae.createElement(Vl,{email:"Nothing left to claim here."}):r.map(f=>Ae.createElement(Vl,{key:f.email,email:f.email,note:`${f.commits} commit${f.commits===1?"":"s"} as ${f.names.join(", ")||"unknown"}`}))),Ae.createElement(os,{flexDirection:"column"},Ae.createElement(xt,{color:y.secondary2},Ae.createElement(xt,{color:y.accent},"[enter]")," writes a claim for the first into the command line, to confirm or change."),Ae.createElement(xt,{color:y.secondary2},Ae.createElement(xt,{color:y.accent},":config emails")," claims by address,",Ae.createElement(xt,{color:y.accent}," :config emails-unclaim "),"gives one back."),Ae.createElement(xt,{color:y.secondary2},Ae.createElement(xt,{color:y.accent},"[esc]")," to close")))};import SM from"chalk";import{Box as io,Text as rt}from"ink";import Te from"react";var RM=8,CM=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,RM)},Lx=({width:e,height:t})=>{let n=CM();return Te.createElement(io,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Te.createElement(rt,{color:y.accent,bold:!0},"Initialize project"),Te.createElement(rt,null,`This folder is not an ${SM.hex(y.accent)("epiq")} project yet.`),Te.createElement(rt,{color:y.primary},"To start tracking issues here, we need to initialize a new",Te.createElement(rt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Te.createElement(io,{marginTop:1,flexDirection:"column"},Te.createElement(io,null,Te.createElement(rt,{color:y.accent}," "),Te.createElement(rt,{color:y.primary},"Type "),Te.createElement(rt,{backgroundColor:y.secondary}," :init "))),Te.createElement(io,{marginTop:1},Te.createElement(rt,{color:y.secondary2},"This will create, commit and push "),Te.createElement(rt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&Te.createElement(io,{marginTop:1,flexDirection:"column"},Te.createElement(rt,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>Te.createElement(io,{key:r.projectId},Te.createElement(rt,{color:y.accent},` ${o+1} `),Te.createElement(rt,{color:y.primary},Eo(r.root)),Te.createElement(rt,{color:y.secondary2},` ${r.root}`))),Te.createElement(io,{marginTop:1},Te.createElement(rt,{color:y.accent}," "),Te.createElement(rt,{color:y.primary},"Type "),Te.createElement(rt,{backgroundColor:y.secondary}," :open 1 "),Te.createElement(rt,{color:y.secondary2}," or "),Te.createElement(rt,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as Kl,Text as _t}from"ink";import _e from"react";import{Box as zl,Text as Xn}from"ink";import Ft,{useEffect as NM,useState as kx}from"react";var Dx=()=>{let[e,t]=kx(null),[n,r]=kx(null);return NM(()=>{let o=!0;return(async()=>{let i=de(),c=re(process.cwd());if(a(i)||a(c))return;let u=ke(c.value),{userName:p,gitName:m}=V(),f=await wn({repoRoot:c.value,stateBranch:a(u)?void 0:u.value,names:[p,m],links:i.value.emailLinks});if(!o)return;if(a(f)){r(f.message);return}let g=xr(f.value);So(g.map(h=>h.email)),t(g)})(),()=>{o=!1}},[]),n?Ft.createElement(zl,{marginTop:1},Ft.createElement(Xn,{color:y.red},n)):e===null?null:e.length===0?Ft.createElement(zl,{marginTop:1},Ft.createElement(Xn,{color:y.secondary2},"No unclaimed addresses in this history \u2014 type",Ft.createElement(Xn,{color:y.accent}," :config emails none "),"to move on.")):Ft.createElement(zl,{flexDirection:"column",marginTop:1},e.map(o=>Ft.createElement(Xn,{key:o.email},Ft.createElement(Xn,{color:y.accent}," \xB7 "),Ft.createElement(Xn,null,o.email),Ft.createElement(Xn,{color:y.secondary2},` ${o.commits} commit${o.commits===1?"":"s"} as ${o.names.join(", ")||"unknown"}`))),Ft.createElement(zl,{marginTop:1},Ft.createElement(Xn,{color:y.secondary2},"Claim yours by address, or",Ft.createElement(Xn,{color:y.accent}," none "),"to skip.")))};var AM=({isDone:e,command:t,value:n,verb:r="Type",hint:o})=>_e.createElement(Kl,null,_e.createElement(_t,{color:y.accent,dimColor:e},e?" \u2714 ":" "),_e.createElement(_t,{dimColor:e},r," "),_e.createElement(_t,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&_e.createElement(_e.Fragment,null,_e.createElement(_t,{dimColor:e}," "),_e.createElement(_t,{color:y.secondary,dimColor:e},"<"+n+">")),o),TM=(e,t)=>e.length===0?void 0:jn(e.join(", "),Math.max(12,t-34)),wM=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function hm({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c,isSetEmails:u,claimedEmails:p,emailSetupDeclined:m}=Un(),f=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."},{key:"emails",done:u,command:":config emails",value:m?"declined":TM(p,e),message:"Last one. Claim the git addresses whose commits are yours, so the board calls them by your name."}],g=f.findIndex(x=>!x.done),h=g===-1?void 0:f[g];return _e.createElement(Kl,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},_e.createElement(_t,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),_e.createElement(_t,null,"Let's get you started - it's a breeze."),_e.createElement(_t,{color:y.secondary2},"Remember - you can always search available commands by typing:",_e.createElement(_t,{color:y.accent}," ? ")),h&&_e.createElement(_t,{color:y.secondary2},h.message),_e.createElement(Kl,{flexDirection:"column"},f.map((x,b)=>{if(!(g===-1||b<=g))return null;let S=b===g,A=S&&g===0;return _e.createElement(Kl,{key:x.key,flexDirection:"column",marginBottom:1},_e.createElement(AM,{isDone:x.done,command:A?":config us":x.command,value:x.done?wM(x.value):void 0,verb:S&&!A?"Waiting:":"Type",hint:A?_e.createElement(_t,{color:y.secondary2}," then ",_e.createElement(_t,{color:y.accent},"tab")," to auto-complete ",_e.createElement(_t,{backgroundColor:y.secondary},` ${x.command.split(" ").pop()} `)):void 0}),x.key==="emails"&&!x.done&&_e.createElement(Dx,null))})))}import Ql from"chalk";import{Box as ki,Text as ss}from"ink";import Qe from"react";import{Box as ql,Text as Bx}from"ink";import Tr from"react";import MM from"chalk";var PM=e=>(N.getTag(e)?.name??"").length+3,LM=e=>{let t=N.getContributor(e);return(t?t.name:"").length+3},Ox=({width:e})=>{let{viewMode:t}=V(),n=ne(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=Tt(c?.id??o.id,"TICKET"),p=ve(u)?u.value:void 0,m=(p?.props.tags??[]).filter(M=>N.getTag(M)),f=p?.props.assignees??[],g=p?.parentNodeId?!bu(o.id,p.parentNodeId)&&t==="dense":!1,h=r.map((M,O)=>{let W=O===r.length-1,Y=be(M.id),xe=W?Y?.[s]?.title:void 0;return`${O?" / ":""}${M.title??""}${xe?` \u25B8 ${xe}`:""}`}).join(""),x=p?N.getCommentsByIssue(p.id):[],b=x.length?String(x.length).length+11:0,R=g?m.reduce((M,O)=>M+PM(O),0)+f.reduce((M,O)=>M+LM(O),0)+b:0,S=c?.id!=null&&!(t==="wide"&&_(c)),A=Math.max(0,e-R),T=h.substring(0,A)+(S?MM.hex(y.secondary2).dim(` ${H(c.id)}`):""),P=g?[...m.map(M=>Tr.createElement(ql,{key:`tag-${M}`,paddingLeft:1},Tr.createElement(Do,{id:M}))),...f.map(M=>Tr.createElement(ql,{key:`assignee-${M}`,paddingLeft:1},Tr.createElement(mr,{id:M}))),x.length?Tr.createElement(ql,{key:"comments",paddingLeft:1},Tr.createElement(Bx,{color:y.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Tr.createElement(ql,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Tr.createElement(Bx,{color:y.secondary2},T),P)};import{Box as kM,Text as Fx}from"ink";import Yl from"react";var DM=({filters:e})=>Yl.createElement(kM,{columnGap:1},Yl.createElement(Fx,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Yl.createElement(Fx,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),_x=Yl.memo(DM);import{Box as BM,Text as Xl}from"ink";import Li from"react";function jx(){let{eventLog:e,unappliedEvents:t}=ne(),n=e.at(-1)?.id,r=vo(n??""),o=ve(r)?Va(r.value):"INVALID DATE";return Li.createElement(BM,{paddingLeft:1},Li.createElement(Xl,{backgroundColor:y.accent,color:y.secondary}," Readonly "),Li.createElement(Xl,{color:y.accent}," "+t.length+" edits ago at "+o+"."),Li.createElement(Xl,{color:y.accent}," Resume with "),Li.createElement(Xl,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as OM,Text as ym}from"ink";import Jl from"react";function $x(){let{replay:e}=ne();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Jl.createElement(OM,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Jl.createElement(ym,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Jl.createElement(ym,{color:y.secondary2},Va(new Date(r))),Jl.createElement(ym,{color:y.accent},`${t}/${n} edits`))}import vm from"chalk";import{Box as FM,Text as Ux}from"ink";import bm,{useEffect as _M,useState as jM}from"react";var $M=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],UM=150,Hx=12,HM=.36;function Wx({syncStatus:e,autoSync:t}){let[n,r]=jM(0);_M(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let p=(Math.sin(c*HM)+1)/2,m=Math.round(p*(Hx-1));r(f=>f===m?f:m)},UM);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,offline:y.secondary2,pending:y.secondary2,syncing:hp($M,n/(Hx-1))??""}[e.status];return bm.createElement(FM,null,bm.createElement(Ux,null,vm.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),bm.createElement(Ux,null,vm.hex(i)("\u25CF")+vm.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import qx from"chalk";import{Text as Yx}from"ink";import Xx,{useEffect as zM,useState as KM}from"react";import xm from"chalk";var WM="https://registry.npmjs.org/epiq/latest",Im=null,Gx=0,GM=1e3*60*60*24,Vx=e=>e.replace(/^v/,""),VM=(e,t)=>{let n=Vx(e).split(".").map(Number),r=Vx(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},zx=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Im&&Date.now()-Gx<GM)return Im;try{let t=await fetch(WM);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?VM(r,e)>0:!1};return Im=o,Gx=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Kx=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?xm.hex(y.accent).dim(s):xm.hex(y.secondary).dim(s)).join(xm.hex(y.secondary2).dim("."))};function Jx(){let[e,t]=KM({current:Pn,latest:null,updateAvailable:!1});return zM(()=>{let n=!0;return zx(Pn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Xx.createElement(Yx,{dimColor:!0,color:y.secondary2},Pn+" "):Xx.createElement(Yx,null,qx.hex(y.secondary2).dim(Pn),qx.hex(y.accent).dim(" \u2197 "),Kx(Pn,e.latest))}function Di({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=ne(),{userName:i,preferredEditor:c,autoSync:u}=V(),p=64,m=process.stdout.columns-p-8,f=t||n==="replay",g=s?_n(s.currentLabel,Math.max(0,m)):"";return Qe.createElement(ki,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Qe.createElement(ki,{paddingLeft:1},Qe.createElement(ss,{color:y.secondary2},g)):f?Qe.createElement(ss,null," "):o===I.PALETTE?Qe.createElement(ki,null,Qe.createElement(ss,{color:y.accent},"Command Palette"),Qe.createElement(ss,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):Qe.createElement(ki,{paddingLeft:1},e.length>0?Qe.createElement(_x,{filters:e}):Qe.createElement(Ox,{width:m})),n==="live"?Qe.createElement(ki,{columnGap:1,paddingRight:2,"max-width":p,overflow:"hidden",justifyContent:"flex-end"},Qe.createElement(Wx,{autoSync:!!u,syncStatus:r}),Qe.createElement(ss,null,Ql.hex(y.secondary2).dim("Mode: ")+Ql.hex(y.secondary2).dim(o.padEnd(8," "))," "),Qe.createElement(Qx,{icon:"@",value:i}),Qe.createElement(Qx,{icon:"\u276F",value:c}),Qe.createElement(Jx,null)):"",n==="peek"?Qe.createElement(jx,null):"",n==="replay"?Qe.createElement($x,null):"")}function Qx({icon:e,value:t}){return Qe.createElement(ss,null,Ql.dim(e)+Ql.hex(y.accent)(` ${t??"-"} `))}import{Box as qM,Text as YM}from"ink";import Bi from"react";import{Box as Zl,Text as Em}from"ink";import wr from"react";function Sm(){let e=ne(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?le(t?.id):[];return wr.createElement(Zl,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},wr.createElement(Zl,{padding:1,paddingTop:0,paddingBottom:0},wr.createElement(Em,null,"Select a board:")),wr.createElement(Zl,{padding:1,flexDirection:"column"},i.map((c,u)=>{let p=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,f=le(c.id).flatMap(({id:g})=>be(g)).length;return wr.createElement(Zl,{key:c.id??u},wr.createElement(Em,{color:p?y.accent:y.secondary2},wr.createElement(Ct,{isSelected:p})),wr.createElement(Em,{color:p?y.accent:y.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var XM=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=ne(),u=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Bi.createElement(qM,{flexDirection:"row"},e.context==="WORKSPACE"?Bi.createElement(Sm,null):u?Bi.createElement(ol,{height:f,width:i,swimlanes:(c[u.id]??[]).filter(g=>g!==void 0&&yn(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Bi.createElement(YM,null))},Zx=Bi.memo(XM);import{useEffect as JM}from"react";var QM=e=>{JM(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=V();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=v();u==="default"&&!c&&ja(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},eI=({autoSync:e})=>(QM(e),null);import{useEffect as ZM}from"react";var tI=()=>{let e=re(process.cwd());return a(e)?d("No project here",null):me({repoRoot:e.value})},nI=async()=>{let e=tI();if(a(e))return l(e.message);if(e.value===null)return d("No project here",null);let t=e.value,n=await Ba(t);if(!Rt())return d("State not initialized",null);let r=de();if(a(r))return d("State not initialized",null);let{mode:o,readOnly:s,timeMode:i,syncStatus:c,selectedNode:u,contextNode:p}=r.value;if(jy())return d("Project loading",null);let m=tI();return a(m)||m.value!==t?d("Project changed",null):o!==I.DEFAULT||s||i!=="live"?d("Skipped while not on the live board",null):u?.isVirtual||p?.isVirtual?d("Skipped on a virtual node",null):c?.status==="syncing"?d("Sync in progress",null):n?d("Worktree held by a sync",null):et(t)===ua(t)?d("Log unchanged",null):(ee.debug("[watch] event log moved, reloading state"),zs(t))};var eP=1e3,rI=()=>(ZM(()=>kl(nI,eP),[]),null);function Rm({width:e,height:t}){let n=ne(),{autoSync:r,viewMode:o}=dp(),s=n.filters;if(n.mode===I.HELP)return we.createElement(Jn,{flexDirection:"column"},we.createElement(Mx,{width:e,height:t}));if(n.mode===I.IDENTITY)return we.createElement(Jn,{flexDirection:"column"},we.createElement(Px,{width:e,height:t}));if(n.mode===I.PALETTE)return we.createElement(Jn,{flexDirection:"column"},we.createElement(Di,{filters:s}),we.createElement(mx,{width:e,height:t-2}),we.createElement(Pi,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Un(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return we.createElement(Jn,{flexDirection:"column"},we.createElement(Jn,{flexDirection:"column"},we.createElement(Di,{hideBreadCrumb:!0,filters:s}),we.createElement(hm,{height:t,width:e})),we.createElement(Pi,{width:e,mode:n.mode,availableHints:[]}));if(u)return we.createElement(Jn,{flexDirection:"column"},we.createElement(Jn,{flexDirection:"column"},we.createElement(Di,{hideBreadCrumb:!0,filters:s}),we.createElement(Lx,{height:t,width:e})),we.createElement(Pi,{width:e,mode:n.mode,availableHints:[]}));let p=yt(n.breadCrumb??[],"BOARD");if(ve(p)){let m=p.value.id,f=le(m).length,g=3,h=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,h)*Math.max(f,g)}return we.createElement(Jn,{flexDirection:"column"},we.createElement(eI,{autoSync:r}),we.createElement(rI,null),we.createElement(Jn,{flexDirection:"column"},we.createElement(Di,{filters:s}),we.createElement(Zx,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),we.createElement(Pi,{width:e,mode:n.mode,availableHints:n.availableHints}))}import tP from"readline";var ec,tc,kn,nP=new Set([E.MoveCursorLeft,E.EraseInputWord,E.MoveCursorLeftOfWord,E.MoveCursorRight,E.MoveCursorRightOfWord,E.NavToPreviousContainer,E.NavToNextContainer,E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.SetViewDense,E.SetViewWide,E.Confirm,E.Exit,E.Yank,E.InitCommandLine,E.InitCommandPalette,E.ExitCommandLine,E.CaptureInput,E.EraseInput,E.EraseInputWord,E.HideHelp,E.ViewHelp,E.SetViewDense,E.SetViewWide,E.GetLastCommandFromHistory,E.GetNextCommandFromHistory,E.AutoCompleteCommand]),rP=new Set([E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.NavToPreviousContainer,E.NavToNextContainer,E.Confirm,E.Exit,E.InitCommandPalette,E.InitMove,E.MoveNextItem,E.MovePreviousItem,E.MoveNextItemJump,E.MovePreviousItemJump,E.MoveToNextContainer,E.MoveToPreviousContainer,E.Delete,E.AddItem,E.EditTitle,E.EditDescription,E.ConfirmMove,E.Edit,E.ViewHelp,E.Yank]),oI=async e=>{if(e.ctrl&&e.name==="c")return $.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=wf(e,n);if(!s||r&&!nP.has(s)||o==="replay"&&n===I.DEFAULT&&rP.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},oP=()=>async function(t,n){n.name!=="escape"&&(kn&&(clearTimeout(kn),kn=void 0),await oI(n))},sP=()=>async function(t){if(t.length===1&&t[0]===27){kn&&clearTimeout(kn),kn=setTimeout(()=>{oI({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),kn=void 0},25);return}kn&&(clearTimeout(kn),kn=void 0)};function sI(){ec&&process.stdin.removeListener("keypress",ec),tc&&process.stdin.removeListener("data",tc),ec=oP(),tc=sP(),tP.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",tc),process.stdin.on("keypress",ec)}async function iI(){try{let e=co({});if(a(e))return on(0,e.message);let t=ht();ve(t)&&je(t.value);let n=re(process.cwd());je({gitEmail:await Cl(process.cwd()),gitName:await Rr(process.cwd())});let r=ve(n)?await ll(n.value):$y();if(a(r))return r;let o=Cm();return a(o)?on(6,o.message):(sI(),ve(n)&&cl(n.value),d("Booted Epiq",void 0))}catch(e){return on(0,Po(e))}}Ey();var cP=`${mn.bold("Epiq CLI")}
|
|
105
105
|
|
|
106
|
-
${
|
|
107
|
-
${
|
|
106
|
+
${mn.dim("Boot in directory:")}
|
|
107
|
+
${mn.cyan("$ epiq")}
|
|
108
108
|
|
|
109
|
-
${
|
|
110
|
-
${
|
|
109
|
+
${mn.dim("Launch GUI:")}
|
|
110
|
+
${mn.cyan("$ epiq gui")}
|
|
111
111
|
|
|
112
|
-
${
|
|
113
|
-
${
|
|
114
|
-
`,
|
|
115
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
116
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
112
|
+
${mn.dim("Act as somebody other than the configured user:")}
|
|
113
|
+
${mn.cyan("$ epiq --as claude")}
|
|
114
|
+
`,Nm=aP(cP,{importMeta:import.meta,version:Pn,flags:{init:{type:"boolean",default:!1},as:{type:"string"}}}),nc=Nm.input[0];nc&&nc!=="gui"&&(console.error(mn.red(`Unknown command: ${nc}`)),process.exit(1));if(Nm.flags.as!==void 0){let e=ac(Nm.flags.as,"--as");a(e)&&(console.error(mn.red(e.message)),process.exit(1))}var aI=process.stdout.columns||120,lI=process.stdout.rows||20,rc=null,dP=e=>{try{return rc?(rc.rerender(e),d("Rerendered app",void 0)):(rc=iP(e),d("Rendered app",void 0))}catch(t){return l(`Unable to render app: ${Po(t)}`)}},Cm=()=>dP(lP.createElement(Rm,{width:aI,height:lI}));process.stdout.on("resize",()=>{if(aI=process.stdout.columns||120,lI=process.stdout.rows||20,!rc)return;let e=Cm();a(e)&&logger.info(`[boot:resize] ${e.message}`)});if(nc==="gui"){let e=await lx({repoRoot:process.cwd()});a(e)&&(console.error(mn.red(`Failed to start Epiq GUI:
|
|
115
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await iI();a(e)&&(logger.info(e.message),console.error(mn.red(`Failed to boot Epiq:
|
|
116
|
+
${e.message}`)),process.exitCode=1)}export{Cm as renderApp};
|