epiq 1.4.1 → 1.4.2
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 +637 -292
- package/dist/index.js +43 -43
- package/dist/mcp.js +33 -33
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),u("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import
|
|
2
|
+
import dn from"chalk";import{render as Rh}from"ink";import Ah from"meow";import Th from"react";import fy from"chalk";import Om from"node:path";import{z as Rt}from"zod";import er from"node:fs";import vt from"node:path";var Ft={Success:"success",Fail:"fail"},a=e=>({status:Ft.Fail,message:e,value:null}),u=(e,t)=>({status:Ft.Success,message:e,value:t}),d=e=>e.status==="fail",Q=e=>e.status==="success";import Ls from"node:fs";import ft from"node:path";import zn from"node:fs";import{ulid as gm}from"ulid";import{z as Ur}from"zod";var vm="__epiq_state__",ym=Ur.object({projectId:Ur.string().min(1),stateBranch:Ur.string().min(1),createdAt:Ur.iso.datetime()}),Cn=()=>({projectId:gm(),stateBranch:vm,createdAt:new Date().toISOString()}),ut=e=>{let t=Or(e);if(!zn.existsSync(t))return a("Missing .epiq/project.json");try{let n=zn.readFileSync(t,"utf8"),r=JSON.parse(n),o=ym.safeParse(r);return o.success?u("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},oa=e=>{let t=ut(e);return d(t)?a(t.message):u("Read projectId",t.value.projectId)},sa=({repoRoot:e,fileContents:t})=>{let n=qn(e),r=Or(e);try{if(zn.mkdirSync(n,{recursive:!0}),zn.existsSync(r)){let o=ut(e);return d(o)?a(o.message):u("Project already initialized",null)}return zn.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),u("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import hm from"node:os";import xm from"node:path";var rt=".epiq-global",Yn=()=>process.env.EPIQ_GLOBAL_DIR??xm.join(hm.homedir(),rt);var Cs=(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(l=>(d(l)&&n.delete(i),l));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Xn from"fs";import Ts from"path";import bm from"util";var ia=1e3,Im=50,Ns=0,aa=()=>process.env.EPIQ_MCP==="true",da=()=>{let e=process.cwd(),t=_r(e);return d(t)?aa()?Ts.join(process.cwd(),".epiq-mcp.log"):void 0:Ts.join(t.value,mt,"log","epiq.log")};function Em(){let e=da();if(!e||!Xn.existsSync(e))return;let n=Xn.readFileSync(e,"utf8").split(`
|
|
4
4
|
`);if(n[n.length-1]===""&&n.pop(),n.length<=ia)return;let r=n.slice(-ia).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;Xn.writeFileSync(e,r,"utf8")}function Rs(e,t,n=!1){let r=da();if(!r)return;let o=
|
|
7
|
-
`;Xn.mkdirSync(Ts.dirname(r),{recursive:!0}),Xn.appendFileSync(r,c,"utf8"),Ns++,Ns>=
|
|
6
|
+
`;Xn.writeFileSync(e,r,"utf8")}function Rs(e,t,n=!1){let r=da();if(!r)return;let o=bm.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
+
`;Xn.mkdirSync(Ts.dirname(r),{recursive:!0}),Xn.appendFileSync(r,c,"utf8"),Ns++,Ns>=Im&&(Ns=0,Em())}var As=()=>aa()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ce={info(...e){let t=As();(t==="info"||t==="debug")&&Rs("[Info]",e,!1)},debug(...e){As()==="debug"&&Rs("[Debug]",e,!0)},error(...e){let t=As();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Rs("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ce;import{spawn as Sm}from"node:child_process";import $r from"node:fs";import Jn from"node:path";var le={stage:({cwd:e,pathspec:t})=>F({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>F({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>F({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>F({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>F({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return F({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>F({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>F({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>F({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>F({args:["worktree","prune"],cwd:e})};var Nn=e=>{let t=$e(e);if(d(t))return a("Unable to resolve epiq project root");let n=ut(t.value);return d(n)?a("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},Je="origin";var ca=1e4,Cm={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},la=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!$r.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=Sm("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Cm}),s=!1,i="",c="",l=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ca}ms`].join(`
|
|
8
8
|
`);l(n?{stdout:i,stderr:p,exitCode:124}:a(p))},ca);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){l({stdout:i,stderr:p.message,exitCode:1});return}l(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
9
9
|
`)))}),o.on("close",p=>{let f=p??1;if(n){l({stdout:i,stderr:c,exitCode:f});return}if(f!==0){l(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
-
`)));return}l(u("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),F=({args:e,cwd:t})=>la({args:e,cwd:t,allowFail:!1}),pt=({args:e,cwd:t})=>la({args:e,cwd:t,allowFail:!0}),
|
|
10
|
+
`)));return}l(u("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),F=({args:e,cwd:t})=>la({args:e,cwd:t,allowFail:!1}),pt=({args:e,cwd:t})=>la({args:e,cwd:t,allowFail:!0}),Rn=async({cwd:e,message:t})=>{let n=await le.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
11
|
${n.message}`);let r=await F({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
12
|
-
${r.message}`):u("Created commit and resolved SHA",r.value.stdout.trim())},
|
|
13
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Qn).includes(r);return u("Checked worktree registration",o)},Ms=async e=>{let t=await pt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},
|
|
12
|
+
${r.message}`):u("Created commit and resolved SHA",r.value.stdout.trim())},Nm=async e=>{let t=await F({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return u("Resolved git dir",Jn.isAbsolute(n)?n:Jn.resolve(e,n))},Rm=async e=>{let t=await Nm(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if($r.existsSync(Jn.join(n,s)))return u("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($r.existsSync(Jn.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},Hr=async e=>{let t=await Rm(e);return d(t)?a(t.message):u("Checked for in-progress Git operation",t.value!==null)},ws=async({repoRoot:e})=>{let n=(await pt({args:["remote","get-url",Je],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},jr=async({repoRoot:e,branch:t})=>{let n=await pt({args:["ls-remote","--heads",Je,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Je}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},Wr=async({repoRoot:e,branch:t})=>{let n=await pt({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?u("Local branch exists",!0):n.exitCode===1?u("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},Qn=e=>{try{return $r.realpathSync.native(e)}catch{return Jn.resolve(e)}},ua=async({repoRoot:e,worktreeRoot:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=Qn(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Qn).includes(r);return u("Checked worktree registration",o)},Ms=async e=>{let t=await pt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Vr=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved current branch",t.value.stdout.trim())},ma=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},pa=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Am=async e=>(await pt({cwd:e,args:["rebase","--abort"]})).exitCode===0?u("Aborted stale rebase",!0):u("No rebase to abort",!1);var Ps=async({cwd:e,branch:t})=>{let n=await jr({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return u("Remote branch missing, skipped pull",!1);let r=await Am(e);if(d(r))return a(r.message);let o=await le.fetch({cwd:e,remote:Je,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
14
14
|
${o.message}`);let s=await le.pullRebase({cwd:e,remote:Je,branch:t});return d(s)?a(`Failed during pull --rebase
|
|
15
|
-
${s.message}`):u("Pulled with rebase",!0)},fa=async e=>{let t=await pt({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?u("No staged changes",!1):t.exitCode===1?u("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var ga=async e=>{let t=await
|
|
16
|
-
`+e.message);let t=Zn(
|
|
17
|
-
`+t.message):u("Ensured epiq storage",!0)},ba=e=>{Ls.existsSync(e)&&(
|
|
15
|
+
${s.message}`):u("Pulled with rebase",!0)},fa=async e=>{let t=await pt({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?u("No staged changes",!1):t.exitCode===1?u("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var ga=async e=>{let t=await Vr(e);return d(t)?a(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var ya="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ks=e=>ft.join(mt,zr,e),ha=()=>ft.join(mt,Ds),xa=Yn,Gr=()=>ft.join(xa(),"worktrees"),Re=({repoRoot:e})=>{let t=oa(e);return d(t)?a(t.message):u("Resolved state branch root",ft.join(Gr(),t.value))},Tm=e=>ft.join(e,mt),va=e=>ft.join(Tm(e),zr);var Zn=e=>{try{return Ls.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Kr=()=>{let e=Zn(xa());if(d(e))return a(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=Zn(Gr());return d(t)?a(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):u("Ensured epiq storage",!0)},ba=e=>{Ls.existsSync(e)&&(ce.debug("[sync] remove path",e),Ls.rmSync(e,{recursive:!0,force:!0}))};var Ia=(e,t)=>{for(let n of[va(e),va(t)]){let r=Zn(n);if(d(r))return a(r.message)}return u("Ensured state branch",void 0)},Ea=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
18
18
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
19
19
|
`).filter(Boolean).filter(i=>i!==mt);if(r.length===0)return u("State branch is storage-only",!1);let o=await F({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
20
|
-
${o.message}`);let s=await
|
|
21
|
-
`),u("Config written",null)}catch{return a(`Unable to write ~/${rt}/config.json`)}},Qe=e=>{let t=
|
|
20
|
+
${o.message}`);let s=await Rn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):u("Cleaned storage branch",!0)},gt=Cs(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):u("Resolved repo root",t.value.stdout.trim())},e=>ft.resolve(e)),Sx=Cs(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=ft.isAbsolute(n)?n:ft.join(e,n);return u("Resolved git dir",r)},e=>ft.resolve(e));var Mx=process.env.IS_LOCAL==="true",mt=".epiq",zr="events",Ds="media",wm="project.json",qn=e=>vt.join(e,mt),Or=e=>vt.join(qn(e),wm),tr=e=>vt.join(qn(e),zr),nr=e=>vt.join(qn(e),Ds),Sa=e=>vt.join(e,mt),Mm=e=>{let t=vt.join(e,mt);return er.existsSync(t)&&er.statSync(t).isDirectory()},Bs=e=>{let t=Or(e);return er.existsSync(t)&&er.statSync(t).isFile()},_r=e=>{let t=vt.resolve(e);for(;;){if(Mm(t))return u("Resolved closest .epiq root",t);let n=vt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},$e=e=>{let t=vt.resolve(e);for(;;){if(Bs(t))return u("Resolved closest epiq project root",t);let n=vt.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Ca=e=>{let t=tr(e);try{return er.mkdirSync(t,{recursive:!0}),u("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},yt=async()=>{let e=await gt(process.cwd());if(d(e))return e;let t=Re({repoRoot:e.value});return d(t)?t:u("Resolved persist root",t.value)};import{accessSync as Pm,copyFileSync as Lm,existsSync as qr,mkdirSync as Na,readdirSync as Ra,readFileSync as km,renameSync as Dm,rmSync as Bm,statSync as Aa,unlinkSync as Fm,writeFileSync as Um}from"node:fs";import An from"node:path";var Fs=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",be={writeToFile:(e,t)=>{try{let n=An.dirname(e);qr(n)||Na(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Um(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return km(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=be.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 qr(e)&&Aa(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Pm(e),!0}catch{return!1}},mkDir:e=>Na(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=An.parse(t);for(;;){let r=An.join(t,e);try{if(qr(r)&&Aa(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=An.dirname(t)}return null},readFirstJSON(e){try{if(!be.dirExists(e))return null;let t=Ra(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=An.join(e,t);return be.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return be.dirExists(e)?Ra(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Fm(e)}catch(t){(!Fs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Bm(e,{recursive:!0,force:!0})}catch(t){(!Fs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(An.dirname(t)),!n?.overwrite&&qr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Dm(e,t)}catch(r){if(Fs(r)&&r.code==="EXDEV"){Lm(e,t),this.rmFile(e);return}throw r}}};var _m={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Ta=Rt.object({logLevel:Rt.enum(["info","error","debug"]),preferredEditor:Rt.string().optional(),userName:Rt.string().optional(),userId:Rt.string().optional(),autoSync:Rt.boolean().nullable().optional(),autoSyncDebounceMs:Rt.number().optional(),attachmentMaxKb:Rt.number().optional(),viewMode:Rt.enum(["dense","wide"]).optional()}).partial(),$m="config.json",wa=Yn,Us=()=>Om.join(wa(),$m),Os=()=>{try{return be.mkDir(wa()),u(`Ensured ~/${rt} exists`,null)}catch{return a(`Unable to create ~/${rt}`)}},Hm=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${rt}/config.json JSON`)}let n=Ta.safeParse(t??{});return n.success?u("Parsed config",n.data):a(`Invalid ~/${rt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Yr=()=>{let e=Os();if(d(e))return a(e.message);let t=Us(),n=be.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Hm(n)},Ma=e=>{let t=Os();if(d(t))return a(t.message);let n=Ta.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Us();try{return be.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
21
|
+
`),u("Config written",null)}catch{return a(`Unable to write ~/${rt}/config.json`)}},Qe=e=>{let t=Yr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Ma(n)},Ut=()=>{let e=Us(),t=Os();if(d(t))return a(`Unable to create ~/${rt}`);if(!(be.readFile(e)!==null)){let g=Ma(_m);if(d(g))throw new Error(`Unable to create ~/${rt}/config.json`)}let r=Yr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:l,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value;return!s||!i?a(`User name or ID not configured in ~/${rt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:l??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as jm}from"react";var rr={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},_s=new Set,Wm=()=>{for(let e of _s)e()},K=()=>rr,Pa=()=>jm(e=>(_s.add(e),()=>{_s.delete(e)}),()=>rr),Me=e=>(rr={...rr,...e},Wm(),rr);import{spawn as Vm}from"node:child_process";import $s from"node:process";var La=e=>{let t=$s.platform==="darwin"?"open":$s.platform==="win32"?"cmd":"xdg-open",n=$s.platform==="win32"?["/c","start","",e]:[e];Vm(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Eu}from"node:fs/promises";import oy from"node:http";import Sn from"node:path";import{fileURLToPath as sy}from"node:url";import{decodeTime as Yl,ulid as q}from"ulid";import cn from"node:fs";import Xr from"node:path";var Da=async e=>{if((await pt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return u("Initial commit already exists",!1);ce.info("Creating initial commit");let n=await le.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):u("Created initial commit",!0)},ka=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Gm=async e=>{let t=await Vr(e);if(d(t))return a(t.message);let n=await ma(e);return d(n)?a(n.message):u("Built sync commit message",`[sync|branch:${ka(t.value)}:sha:${ka(n.value)}]`)},Hs=async({repoRoot:e,stateBranchName:t})=>{ce.info(`Creating ${t}`);let n=await F({args:["commit-tree",ya,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
22
22
|
${n.message}`);let r=n.value.stdout.trim(),o=await F({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
23
|
-
${o.message}`):u("Created state branch",!0)},
|
|
24
|
-
`+n.message);let r=n.value,o=r?await
|
|
23
|
+
${o.message}`):u("Created state branch",!0)},Km=async({repoRoot:e,stateBranchName:t})=>{let n=await ws({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
24
|
+
`+n.message);let r=n.value,o=r?await jr({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
25
25
|
`+o.message);let s=o.value;if(r&&s){let c=await le.fetch({cwd:e,remote:Je,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
26
|
-
${c.message}`)}let i=await
|
|
26
|
+
${c.message}`)}let i=await Wr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
|
|
27
27
|
`+i.message);if(i.value)return u("Local state branch already exists",!1);if(s){let c=await F({args:["branch","--track",t,`${Je}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
28
|
-
${c.message}`):u("Created local state branch from remote",!0)}return Hs({repoRoot:e,stateBranchName:t})},
|
|
29
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},
|
|
30
|
-
`+r.message);
|
|
31
|
-
${o.message}`):u("Created state branch worktree",!0)},
|
|
32
|
-
${l.message}`)}if(s&&!
|
|
33
|
-
${l.message}`)}let i=await ua({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=
|
|
34
|
-
${l.message}`)}return
|
|
35
|
-
${o.message}`):u("Checked out state branch",!0)},
|
|
28
|
+
${c.message}`):u("Created local state branch from remote",!0)}return Hs({repoRoot:e,stateBranchName:t})},zm=async({repoRoot:e,branch:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
29
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},qm=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Zn(Xr.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
30
|
+
`+r.message);cn.existsSync(t)&&!cn.existsSync(Xr.join(t,".git"))&&(ce.info("Removing broken state branch worktree path"),ba(t)),ce.info("Creating state branch worktree");let o=await le.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
31
|
+
${o.message}`):u("Created state branch worktree",!0)},ln=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await zm({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=Qn(t),s=r.value?Qn(r.value):null;if(s&&s===o&&cn.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o){ce.info("Moving state branch worktree to expected location");let l=await le.worktreeRemove({cwd:e,worktreeRoot:s});if(d(l))return a(`Failed to remove existing state branch worktree
|
|
32
|
+
${l.message}`)}if(s&&!cn.existsSync(s)){ce.info("Pruning stale state branch worktree");let l=await le.worktreePrune({cwd:e});if(d(l))return a(`Failed to prune stale worktrees
|
|
33
|
+
${l.message}`)}let i=await ua({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=cn.existsSync(t);if(i.value&&c)return u("State branch worktree already exists",!1);if(i.value&&!c){ce.info("Pruning missing registered state branch worktree");let l=await le.worktreePrune({cwd:e});if(d(l))return a(`Failed to prune stale worktrees
|
|
34
|
+
${l.message}`)}return qm({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Ym=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Vr(e);if(d(n))return a(n.message);if(n.value===t)return u("State branch already checked out",!1);(await pt({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ce.info("Aborted stale state branch rebase");let o=await le.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
35
|
+
${o.message}`):u("Checked out state branch",!0)},Xm=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ms(t);if(d(n))return a(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await ws({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=Nn(e);if(d(o))return o;let s=o.value,i=await jr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return u("Remote state branch missing; upstream will be configured on first push",!1);ce.info(`Configuring ${s} upstream`);let c=await le.fetch({cwd:t,remote:Je,branch:s});if(d(c))return a(`Failed to fetch ${s}
|
|
36
36
|
${c.message}`);let l=await le.setUpstream({cwd:t,branch:s,upstream:`${Je}/${s}`});return d(l)?a(`Failed to set state branch upstream
|
|
37
|
-
${l.message}`):u("Configured state branch upstream",!0)},Jr=async({stateBranchRoot:e,eventFileName:t})=>{let n=ks(t),r=Xr.join(e,n);if(!
|
|
38
|
-
${o.message}`):u("Staged state branch event file",void 0)},Ba=async({stateBranchRoot:e})=>{let t=ha(),n=Xr.join(e,t);if(!
|
|
39
|
-
${r.message}`):u("Staged state branch media files",void 0)},Fa=async({repoRoot:e,stateBranchRoot:t})=>{let n=await
|
|
40
|
-
`+n.message):
|
|
41
|
-
${s.message}`):u("Pushed state branch",!0)},Ua=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Cn(e);if(d(o))return o;let s=o.value,i=[zr(),await Gm({repoRoot:e,stateBranchName:s}),await cn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await qm({stateBranchRoot:t,stateBranchName:s}),await Ea(t),n?await Ym({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as Xm}from"ws";var Qr=new Set,Oa=e=>{Qr.add(e),e.on("close",()=>{Qr.delete(e)}),e.on("error",()=>{Qr.delete(e)})},Ut=e=>{let t=JSON.stringify(e);for(let n of Qr)n.readyState===Xm.OPEN&&n.send(t)};import{useSyncExternalStore as Wv}from"react";var B={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function js(e){return e.context===B.WORKSPACE}function T(e){return e.context===B.TICKET}function Ot(e){return e.context===B.TEXT}function Ve(e){return e.context===B.FIELD}function ir(e){return e.context===B.FIELD_LIST}var _t=e=>e.context===B.SWIMLANE,Zr=e=>e.context===B.BOARD,ar=e=>e.context===B.COMMENT;var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var _a=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",$a=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Ha=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",ja=(e,t)=>{if($a(e,e.sequence))return x.MoveCursorLeftOfWord;if(Ha(e,e.sequence))return x.MoveCursorRightOfWord;if(_a(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}},Wa=(e,t)=>{if($a(e,e.sequence))return x.MoveCursorLeftOfWord;if(Ha(e,e.sequence))return x.MoveCursorRightOfWord;if(_a(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.NavPreviousItem;case"down":return x.NavNextItem;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};function eo(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var ln=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Va=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ga=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Ka=(e,t)=>t?e.get(t)??[]:[];var za=new WeakMap,Jm=e=>{let t=za.get(e);return t||(t=Ga(e),za.set(e,t)),t};var qa=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ka(Jm(e),r).filter(s=>eo(r,s)>=n)};var Qm={hint:"",hints:[],overlap:0,remainder:""},Ya=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Qm;let o=qa({wordList:r,inputToMatch:e,overlapThreshold:1});return Zm(t,o)},Zm=(e,t)=>{let n=t[0]??"",r=eo(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as np}from"ulid";var An=24n,ep=An*4n,ot=(1n<<ep)-1n,tp=/^[0-9a-f]+$/;function Xa(e){return!e||!tp.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Ge(e,t=An){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function $e(e,t){if(!e&&!t)return Ge(ot/2n,An);let n=e?Xa(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?Xa(t):u("Resolved upper bound",ot);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return Ge(ot/2n,An);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):Ge(i,An)}function Ja(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=ot*BigInt(r+1)/(t+1n),s=Ge(o,An);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var Ws=(e,t)=>{let n=Y(e),r=Ja(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return u("Created rebalance event",{id:np(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as af}from"ulid";var to="removed",Ue=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):a("Unable to find node in breadcrumb")},Qa=["png","jpg","gif","webp"];var At=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Vs=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},$t=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){pe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!T(t))return a("Can only comment on issues");let n=pe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!T(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=pe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=pe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("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)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!T(t))return a("Can only attach to issues");let n=pe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=pe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("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)},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=$t(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 a("Rename target node not found");let r=$t(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 Y(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 a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=$t(o,"move");if(i)return i;if(Vs(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),u("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=$t(o,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of Y(p.id))c(f.id)}};c(e);let l={...structuredClone(t)};for(let m of i){if(!l[m])return a("Unable to locate node to delete");l[m]={...l[m],isDeleted:!0}}return n?(C({nodes:l}),u("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:to,tombstoned:!0},r=pe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=$t(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=$t(r,"edit");if(o)return o;if(!T(r))return a("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(c=>c!==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 a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=$t(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=$t(r,"edit");if(o)return o;if(!T(r))return a("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(c=>c!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},createTag(e){let t=pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=pe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return Y(e)}};var Z={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var He=e=>e.slice(-7).toUpperCase(),Za=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?He(e).includes(n):!0};var ee={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:B.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:He(e)},context:B.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.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:B.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:B.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:He(e)},context:B.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.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:B.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Ht from"chalk";import sd from"string-width";import{decodeTime as dp}from"ulid";import wn from"chalk";var Pe={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:Pe.cyan,accent2:Pe.magenta,primary:Pe.white,secondary:Pe.grayDark,secondary2:Pe.grayLight,gray:Pe.gray,green:Pe.green,yellow:Pe.yellow,red:Pe.red};var N={red:Pe.red,yellow:Pe.yellow,green:Pe.green,blue:Pe.blue,magenta:Pe.magenta,cyan:Pe.cyan},Tn={urgent:N.red,critical:N.red,important:N.red,blocker:N.red,asap:N.red,immediate:N.red,fail:N.red,failure:N.red,broken:N.red,bug:N.red,error:N.red,incident:N.red,outage:N.red,production:N.red,crash:N.red,security:N.red,warning:N.yellow,warn:N.yellow,risky:N.yellow,risk:N.yellow,attention:N.yellow,pending:N.yellow,review:N.yellow,"needs-review":N.yellow,qa:N.yellow,testing:N.yellow,test:N.yellow,validate:N.yellow,verification:N.yellow,staging:N.yellow,check:N.yellow,"follow-up":N.yellow,followup:N.yellow,waiting:N.yellow,blocked:N.yellow,hold:N.yellow,done:N.green,complete:N.green,completed:N.green,success:N.green,ok:N.green,stable:N.green,resolved:N.green,fixed:N.green,closed:N.green,merged:N.green,released:N.green,deployed:N.green,approved:N.green,verified:N.green,working:N.green,healthy:N.green,pass:N.green,passing:N.green,info:N.blue,information:N.blue,note:N.blue,docs:N.blue,documentation:N.blue,doc:N.blue,guide:N.blue,help:N.blue,explanation:N.blue,detail:N.blue,details:N.blue,context:N.blue,design:N.blue,discussion:N.blue,proposal:N.blue,idea:N.blue,feature:N.magenta,enhancement:N.magenta,improvement:N.magenta,refactor:N.magenta,refactoring:N.magenta,cleanup:N.magenta,optimize:N.magenta,optimization:N.magenta,perf:N.magenta,performance:N.magenta,upgrade:N.magenta,migration:N.magenta,modernize:N.magenta,debt:N.magenta,todo:N.cyan,next:N.cyan,planned:N.cyan,plan:N.cyan,future:N.cyan,backlog:N.cyan,investigate:N.cyan,explore:N.cyan,prototype:N.cyan};var Ks={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ed=(e,t,n)=>Math.max(t,Math.min(n,e)),Gs=(e,t,n)=>e+(t-e)*n,td=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},rp=e=>e.toLowerCase().trim(),op=(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)),l=0,m=0,p=0;i>=0&&i<1?(l=s,m=c):i>=1&&i<2?(l=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(l=c,p=s):(l=s,p=c);let f=o-s/2;return[Math.round((l+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},nd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var sp=(e,t,n)=>{let r=ed(n,0,1);return[Math.round(Gs(e[0],t[0],r)),Math.round(Gs(e[1],t[1],r)),Math.round(Gs(e[2],t[2],r))]};var ip=(e,t,n)=>sp(e,t,n),dr=e=>{let n=td(e)%360,r=op(n,Ks.stringColor.saturation,Ks.stringColor.lightness);return nd(r)},ue=(e,t=Tn)=>{let n=rp(e);return n&&t[n]?t[n]:dr(n)};var rd=e=>{let t=Ks.gradient.stops,n=ed(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 ip(t[s],t[s+1],i)},no=e=>nd(rd(e)),ro=e=>td(e.toLowerCase().trim())/4294967295,od=e=>{let t=ro(e);return rd(t)},ap=e=>{let[t,n,r]=od(e);return{normal:o=>wn.bgRgb(t,n,r).black(o),cursor:o=>wn.bgRgb(t,n,r).white.bold(o)}},zs=e=>{let[t,n,r]=od(e);return{fg:o=>wn.rgb(t,n,r)(o),fgCursor:o=>wn.rgb(t,n,r).inverse(o),bg:o=>wn.bgRgb(t,n,r).black(o),bgCursor:o=>wn.bgRgb(t,n,r).white.bold(o)}},oo=e=>ap(e).normal(` ${e} `);var Mn=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"},so=e=>String(e).padStart(2,"0"),io=e=>`${e.getFullYear()}-${so(e.getMonth()+1)}-${so(e.getDate())} ${so(e.getHours())}:${so(e.getMinutes())}`;var cp=(e,t)=>e+" ".repeat(Math.max(0,t-sd(e))),lp=(e,t)=>" ".repeat(Math.max(0,t-sd(e)))+e,id=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),up=(e,t)=>t?e<t?"up":e>t?"down":null:null,mp=(e,t)=>{let n=E.getNode(e.payload.parent),r=n?Ht.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=up(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},ad=e=>`${Math.max(1,Math.round(e/1024))} KB`,dd=e=>E.getAttachment(e)?.name??"",pp=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Ht.bgHex(ue(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Ht.bgHex(ue(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ht.hex(ue(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ht.hex(ue(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Ht.dim(`(${ad(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=dd(e.payload.id);return t?`"${t}"`:""}default:return""}},fp=e=>{let t=Mn(dp(e));return Ht.gray(lp(t,8))},gp=12,vp=e=>cp(`${e}`,gp),yp=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"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=E.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${ad(e.payload.bytes)})`;case"delete.issue.attachment":{let t=dd(e.payload.id);return t?`"${t}"`:""}default:return""}},cd=e=>[id(e.action),yp(e)].filter(Boolean).join(" "),ld=(e,t)=>{let n=fp(e.id),r=vp(e.userName),o=Ht.dim("\u203A"),s=e.action==="move.node"?mp(e,t):[id(e.action),pp(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as hp}from"node:crypto";var xp="0123456789ABCDEFGHJKMNPQRSTVWXYZ",bp=e=>{let t=hp("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+=xp[Number(n>>s&31n)]}return r},Ie=(e,t)=>bp(`${e}:virtual:${t}`);var Ip=e=>Ie(e,"comments"),Ep=e=>Ie(e,"description"),Sp=e=>Ie(e,"assignees"),Cp=e=>Ie(e,"tags"),Np=e=>Ie(e,"history"),Rp=e=>Ie(e,"attachments"),ao=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=E.getNode(e);if(!c){let p=E.createNode({...ee.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:u("Virtual field created",void 0)}if(!Ve(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=E.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},ud=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=E.getNode(e);if(!i){let m=E.createNode({...ee.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:u("Virtual field list created",void 0)}if(!ir(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let l=E.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(l)?l:u("Virtual field list updated",void 0)},md=e=>{let t=Ge(ot/4n),n=Ge(ot/2n),r=Ge(ot*3n/4n),o=Ge(ot*7n/8n),s=Ge(ot*15n/16n),i=Ge(ot*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;if(d(i))return i;let c=ao({id:Ep(e.id),name:Z.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let l=ud({id:Sp(e.id),name:Z.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(l))return l;let m=ud({id:Cp(e.id),name:Z.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=ao({id:Ip(e.id),name:Z.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=ao({id:Rp(e.id),name:Z.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=ao({id:Np(e.id),name:Z.HISTORY,parentNodeId:e.id,rank:i.value,value:Ap(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},Ap=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=>ld(r,n.get(r.action)??[])).join(`
|
|
42
|
-
`)};var Tp=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ve,co]=Tp;var L=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),pd=e=>{let t=E.getNode(e);if(!t||!T(t)||t.isDeleted)return null;let n=md(t);return d(n)?n:null},wp=e=>{for(let t of e){let n=pd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=pd(r);if(o)return o}return null},Mp=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Pp=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},qs=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 Pp(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Lp=e=>{pe(t=>({...t,eventLog:[...t.eventLog,e]}))},kp=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):u("Valid user",null)},Dp=(e,t)=>{let n=kp(e);if(d(n))return n;let r=[...new Set(qs(e))];t||(r.forEach(s=>Mp(s,e)),Lp(e));let o=wp(r);return o||null},Bp={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ee.workspace(t,n,r),s=cr(o);if(d(s))return L(s.message,e);let i=E.createNode(o);return d(i)?L(i.message??"Failed to initialize workspace",e):js(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=E.createNode(ee.workspace(t,n,r));return d(o)?L(o.message??"Failed to add workspace",e):js(o.value)?u("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(ee.board(t,n,r,o));return d(s)?L(s.message??"Unable to create board",e):Zr(s.value)?u("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(ee.swimlane(t,n,r,o));return d(s)?L(s.message??"Unable to create swimlane",e):_t(s.value)?u("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(ee.ticket(t,n,r,o));return d(s)?L(s.message??"Unable to create issue",e):T(s.value)?u("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=E.createNode(ee.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Z.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?L(i.message??`Unable to create field: ${n}`,e):Ve(i.value)?u("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=E.renameNode(t,n);return d(o)?L(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=E.tombstoneNode(t);return d(n)?L(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=E.createTag({id:t,name:n});return d(r)?L(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return d(r)?L(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=E.tombstoneContributor(t);return d(n)?L(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=E.restoreContributor(t,n);return d(r)?L(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=E.tag(t,n);return d(r)?L(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=E.untag(t,n);return d(r)?L(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=E.assign(t,n);return d(r)?L(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=E.unassign(t,n);return d(r)?L(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=E.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?L(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=E.editValue(t,n);return d(r)?L(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=E.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only close issues",e);let s=E.getNode(ve);if(!s)return L("Unable to locate target swimlane",e);if(n!==s.id)return L("Close target must be closed swimlane",e);let i=E.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?L(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=E.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only reopen issues",e);let s=E.getNode(ve);if(!s)return L("Unable to locate closed swimlane",e);if(n===s.id)return L("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return L("Reopen parent no longer exists",e);let c=E.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?L(c.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return d(n)?L(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=E.getNode(r);if(!s)return L(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let i=E.updateNode({...s,rank:o});if(d(i))return L(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=E.createComment({id:t,issue:n,authorId:r,authorName:E.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?L(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=E.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let s=E.editComment(t,r);return d(s)?L(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=E.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let o=E.deleteComment(t);return d(o)?L(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,c=E.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?L(c.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=E.getAttachment(t);if(!r)return L("Unable to locate attachment",e);if(r.issue!==n)return L("Attachment does not belong to issue",e);let o=E.deleteAttachment(t);return d(o)?L(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=E.linkUserId({contributorId:t,userId:e.userId});return d(n)?L(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function jt(e,t=!1){let n=Bp[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=Dp(e,t);return o||r}var st=e=>e.map(t=>jt(t));import Xp from"node:fs";import Jp from"node:path";import{decodeTime as Qp,monotonicFactory as Zp}from"ulid";import{z as ur}from"zod";var lr=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown";import lo from"node:fs";import Xs from"node:path";import{decodeTime as Op}from"ulid";import{z as Ys}from"zod";var Fp=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.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"];var Up=new Set(Fp),fd=e=>Up.has(e),gd=e=>({action:e.action,payload:e.payload});var _p=Ys.object({userId:Ys.string().min(1).default("unknown"),userName:Ys.string().min(1).default("unknown")}),$p=/^[0-9a-hjkmnp-tv-z]{26}$/i,Hp=e=>$p.test(e)?e.toUpperCase():e,jp=e=>{let t=Xs.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=_p.safeParse({userId:Hp(r),userName:o});return s.success?u("Parsed event file actor",s.data):a(`Invalid event file name ${Xs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Wp=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},Vp=(e,t)=>t in e,Gp=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Kp=e=>{let{userId:t,userName:n,...r}=e,o=Wp(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Vp(r,s)?u("Decoded persisted event",Gp({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Js=e=>{let t=[],n=new Map;for(let r of e){let o=Kp(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!fd(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");se.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return u("Decoded reconstructed events",t)},zp=e=>{if(!lo.existsSync(e))return u("Event file missing",[]);let t=jp(e);if(d(t))return a(t.message);let n=lo.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
43
|
-
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=Zs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return u("Parsed persisted events file",r)};function Qs(e){let t=tr(e);if(!lo.existsSync(t))return u("No events found",[]);let n=lo.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Xs.join(t,o)),r=[];for(let o of n){let s=
|
|
44
|
-
`,"utf8"),u("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function xd(e,t){let n=
|
|
37
|
+
${l.message}`):u("Configured state branch upstream",!0)},Jr=async({stateBranchRoot:e,eventFileName:t})=>{let n=ks(t),r=Xr.join(e,n);if(!cn.existsSync(r))return u("No event file to stage",void 0);let o=await le.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
38
|
+
${o.message}`):u("Staged state branch event file",void 0)},Ba=async({stateBranchRoot:e})=>{let t=ha(),n=Xr.join(e,t);if(!cn.existsSync(n))return u("No media directory to stage",void 0);let r=await le.stage({cwd:e,pathspec:[t]});return d(r)?a(`Failed to stage state branch media files
|
|
39
|
+
${r.message}`):u("Staged state branch media files",void 0)},Fa=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Gm(e);return d(n)?a(`Create state branch sync commit failed
|
|
40
|
+
`+n.message):Rn({cwd:t,message:n.value})},or=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ms(t);if(d(n))return a(n.message);let r=Nn(e);if(d(r))return r;let o=r.value,s=n.value?await le.push({cwd:t}):await le.push({cwd:t,remote:Je,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
|
|
41
|
+
${s.message}`):u("Pushed state branch",!0)},Ua=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Nn(e);if(d(o))return o;let s=o.value,i=[Kr(),await Km({repoRoot:e,stateBranchName:s}),await ln({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Ym({stateBranchRoot:t,stateBranchName:s}),await Ea(t),n?await Xm({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as Jm}from"ws";var Qr=new Set,Oa=e=>{Qr.add(e),e.on("close",()=>{Qr.delete(e)}),e.on("error",()=>{Qr.delete(e)})},Ot=e=>{let t=JSON.stringify(e);for(let n of Qr)n.readyState===Jm.OPEN&&n.send(t)};import{useSyncExternalStore as Vv}from"react";var B={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function js(e){return e.context===B.WORKSPACE}function T(e){return e.context===B.TICKET}function _t(e){return e.context===B.TEXT}function Ve(e){return e.context===B.FIELD}function sr(e){return e.context===B.FIELD_LIST}var $t=e=>e.context===B.SWIMLANE,Zr=e=>e.context===B.BOARD,ir=e=>e.context===B.COMMENT;var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var _a=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",$a=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Ha=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",ja=(e,t)=>{if($a(e,e.sequence))return x.MoveCursorLeftOfWord;if(Ha(e,e.sequence))return x.MoveCursorRightOfWord;if(_a(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}},Wa=(e,t)=>{if($a(e,e.sequence))return x.MoveCursorLeftOfWord;if(Ha(e,e.sequence))return x.MoveCursorRightOfWord;if(_a(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.NavPreviousItem;case"down":return x.NavNextItem;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};function eo(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var un=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Va=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ga=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Ka=(e,t)=>t?e.get(t)??[]:[];var za=new WeakMap,Qm=e=>{let t=za.get(e);return t||(t=Ga(e),za.set(e,t)),t};var qa=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ka(Qm(e),r).filter(s=>eo(r,s)>=n)};var Zm={hint:"",hints:[],overlap:0,remainder:""},Ya=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Zm;let o=qa({wordList:r,inputToMatch:e,overlapThreshold:1});return ep(t,o)},ep=(e,t)=>{let n=t[0]??"",r=eo(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as rp}from"ulid";var Tn=24n,tp=Tn*4n,ot=(1n<<tp)-1n,np=/^[0-9a-f]+$/;function Xa(e){return!e||!np.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Ge(e,t=Tn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ue(e,t){if(!e&&!t)return Ge(ot/2n,Tn);let n=e?Xa(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?Xa(t):u("Resolved upper bound",ot);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return Ge(ot/2n,Tn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):Ge(i,Tn)}function Ja(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=ot*BigInt(r+1)/(t+1n),s=Ge(o,Tn);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var Ws=(e,t)=>{let n=Y(e),r=Ja(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return u("Created rebalance event",{id:rp(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as df}from"ulid";var to="removed",Oe=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):a("Unable to find node in breadcrumb")},Qa=["png","jpg","gif","webp"];var At=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Vs=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Ht=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){pe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!T(t))return a("Can only comment on issues");let n=pe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!T(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=pe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=pe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("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)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!T(t))return a("Can only attach to issues");let n=pe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=pe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("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)},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=Ht(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 a("Rename target node not found");let r=Ht(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 Y(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 a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=Ht(o,"move");if(i)return i;if(Vs(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),u("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=Ht(o,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of Y(p.id))c(f.id)}};c(e);let l={...structuredClone(t)};for(let m of i){if(!l[m])return a("Unable to locate node to delete");l[m]={...l[m],isDeleted:!0}}return n?(C({nodes:l}),u("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:to,tombstoned:!0},r=pe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=Ht(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=Ht(r,"edit");if(o)return o;if(!T(r))return a("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(c=>c!==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 a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=Ht(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=Ht(r,"edit");if(o)return o;if(!T(r))return a("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(c=>c!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},createTag(e){let t=pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=pe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return Y(e)}};var Z={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var He=e=>e.slice(-7).toUpperCase(),Za=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?He(e).includes(n):!0};var ee={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:B.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:He(e)},context:B.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.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:B.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:B.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:He(e)},context:B.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.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:B.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import jt from"chalk";import sd from"string-width";import{decodeTime as cp}from"ulid";import Mn from"chalk";var Pe={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:Pe.cyan,accent2:Pe.magenta,primary:Pe.white,secondary:Pe.grayDark,secondary2:Pe.grayLight,gray:Pe.gray,green:Pe.green,yellow:Pe.yellow,red:Pe.red};var N={red:Pe.red,yellow:Pe.yellow,green:Pe.green,blue:Pe.blue,magenta:Pe.magenta,cyan:Pe.cyan},wn={urgent:N.red,critical:N.red,important:N.red,blocker:N.red,asap:N.red,immediate:N.red,fail:N.red,failure:N.red,broken:N.red,bug:N.red,error:N.red,incident:N.red,outage:N.red,production:N.red,crash:N.red,security:N.red,warning:N.yellow,warn:N.yellow,risky:N.yellow,risk:N.yellow,attention:N.yellow,pending:N.yellow,review:N.yellow,"needs-review":N.yellow,qa:N.yellow,testing:N.yellow,test:N.yellow,validate:N.yellow,verification:N.yellow,staging:N.yellow,check:N.yellow,"follow-up":N.yellow,followup:N.yellow,waiting:N.yellow,blocked:N.yellow,hold:N.yellow,done:N.green,complete:N.green,completed:N.green,success:N.green,ok:N.green,stable:N.green,resolved:N.green,fixed:N.green,closed:N.green,merged:N.green,released:N.green,deployed:N.green,approved:N.green,verified:N.green,working:N.green,healthy:N.green,pass:N.green,passing:N.green,info:N.blue,information:N.blue,note:N.blue,docs:N.blue,documentation:N.blue,doc:N.blue,guide:N.blue,help:N.blue,explanation:N.blue,detail:N.blue,details:N.blue,context:N.blue,design:N.blue,discussion:N.blue,proposal:N.blue,idea:N.blue,feature:N.magenta,enhancement:N.magenta,improvement:N.magenta,refactor:N.magenta,refactoring:N.magenta,cleanup:N.magenta,optimize:N.magenta,optimization:N.magenta,perf:N.magenta,performance:N.magenta,upgrade:N.magenta,migration:N.magenta,modernize:N.magenta,debt:N.magenta,todo:N.cyan,next:N.cyan,planned:N.cyan,plan:N.cyan,future:N.cyan,backlog:N.cyan,investigate:N.cyan,explore:N.cyan,prototype:N.cyan};var Ks={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ed=(e,t,n)=>Math.max(t,Math.min(n,e)),Gs=(e,t,n)=>e+(t-e)*n,td=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},op=e=>e.toLowerCase().trim(),sp=(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)),l=0,m=0,p=0;i>=0&&i<1?(l=s,m=c):i>=1&&i<2?(l=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(l=c,p=s):(l=s,p=c);let f=o-s/2;return[Math.round((l+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},nd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var ip=(e,t,n)=>{let r=ed(n,0,1);return[Math.round(Gs(e[0],t[0],r)),Math.round(Gs(e[1],t[1],r)),Math.round(Gs(e[2],t[2],r))]};var ap=(e,t,n)=>ip(e,t,n),ar=e=>{let n=td(e)%360,r=sp(n,Ks.stringColor.saturation,Ks.stringColor.lightness);return nd(r)},ue=(e,t=wn)=>{let n=op(e);return n&&t[n]?t[n]:ar(n)};var rd=e=>{let t=Ks.gradient.stops,n=ed(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 ap(t[s],t[s+1],i)},no=e=>nd(rd(e)),ro=e=>td(e.toLowerCase().trim())/4294967295,od=e=>{let t=ro(e);return rd(t)},dp=e=>{let[t,n,r]=od(e);return{normal:o=>Mn.bgRgb(t,n,r).black(o),cursor:o=>Mn.bgRgb(t,n,r).white.bold(o)}},zs=e=>{let[t,n,r]=od(e);return{fg:o=>Mn.rgb(t,n,r)(o),fgCursor:o=>Mn.rgb(t,n,r).inverse(o),bg:o=>Mn.bgRgb(t,n,r).black(o),bgCursor:o=>Mn.bgRgb(t,n,r).white.bold(o)}},oo=e=>dp(e).normal(` ${e} `);var Pn=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"},so=e=>String(e).padStart(2,"0"),io=e=>`${e.getFullYear()}-${so(e.getMonth()+1)}-${so(e.getDate())} ${so(e.getHours())}:${so(e.getMinutes())}`;var lp=(e,t)=>e+" ".repeat(Math.max(0,t-sd(e))),up=(e,t)=>" ".repeat(Math.max(0,t-sd(e)))+e,id=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),mp=(e,t)=>t?e<t?"up":e>t?"down":null:null,pp=(e,t)=>{let n=E.getNode(e.payload.parent),r=n?jt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=mp(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},ad=e=>`${Math.max(1,Math.round(e/1024))} KB`,dd=e=>E.getAttachment(e)?.name??"",fp=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?jt.bgHex(ue(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?jt.bgHex(ue(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?jt.hex(ue(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?jt.hex(ue(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${jt.dim(`(${ad(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=dd(e.payload.id);return t?`"${t}"`:""}default:return""}},gp=e=>{let t=Pn(cp(e));return jt.gray(up(t,8))},vp=12,yp=e=>lp(`${e}`,vp),hp=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"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=E.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${ad(e.payload.bytes)})`;case"delete.issue.attachment":{let t=dd(e.payload.id);return t?`"${t}"`:""}default:return""}},cd=e=>[id(e.action),hp(e)].filter(Boolean).join(" "),ld=(e,t)=>{let n=gp(e.id),r=yp(e.userName),o=jt.dim("\u203A"),s=e.action==="move.node"?pp(e,t):[id(e.action),fp(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as xp}from"node:crypto";var bp="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ip=e=>{let t=xp("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+=bp[Number(n>>s&31n)]}return r},Ie=(e,t)=>Ip(`${e}:virtual:${t}`);var Ep=e=>Ie(e,"comments"),Sp=e=>Ie(e,"description"),Cp=e=>Ie(e,"assignees"),Np=e=>Ie(e,"tags"),Rp=e=>Ie(e,"history"),Ap=e=>Ie(e,"attachments"),ao=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=E.getNode(e);if(!c){let p=E.createNode({...ee.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:u("Virtual field created",void 0)}if(!Ve(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=E.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},ud=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=E.getNode(e);if(!i){let m=E.createNode({...ee.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:u("Virtual field list created",void 0)}if(!sr(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let l=E.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(l)?l:u("Virtual field list updated",void 0)},md=e=>{let t=Ge(ot/4n),n=Ge(ot/2n),r=Ge(ot*3n/4n),o=Ge(ot*7n/8n),s=Ge(ot*15n/16n),i=Ge(ot*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;if(d(i))return i;let c=ao({id:Sp(e.id),name:Z.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let l=ud({id:Cp(e.id),name:Z.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(l))return l;let m=ud({id:Np(e.id),name:Z.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=ao({id:Ep(e.id),name:Z.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=ao({id:Ap(e.id),name:Z.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=ao({id:Rp(e.id),name:Z.HISTORY,parentNodeId:e.id,rank:i.value,value:Tp(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},Tp=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=>ld(r,n.get(r.action)??[])).join(`
|
|
42
|
+
`)};var wp=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ve,co]=wp;var L=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),pd=e=>{let t=E.getNode(e);if(!t||!T(t)||t.isDeleted)return null;let n=md(t);return d(n)?n:null},Mp=e=>{for(let t of e){let n=pd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=pd(r);if(o)return o}return null},Pp=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Lp=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},qs=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 Lp(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},kp=e=>{pe(t=>({...t,eventLog:[...t.eventLog,e]}))},Dp=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):u("Valid user",null)},Bp=(e,t)=>{let n=Dp(e);if(d(n))return n;let r=[...new Set(qs(e))];t||(r.forEach(s=>Pp(s,e)),kp(e));let o=Mp(r);return o||null},Fp={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ee.workspace(t,n,r),s=dr(o);if(d(s))return L(s.message,e);let i=E.createNode(o);return d(i)?L(i.message??"Failed to initialize workspace",e):js(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=E.createNode(ee.workspace(t,n,r));return d(o)?L(o.message??"Failed to add workspace",e):js(o.value)?u("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(ee.board(t,n,r,o));return d(s)?L(s.message??"Unable to create board",e):Zr(s.value)?u("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(ee.swimlane(t,n,r,o));return d(s)?L(s.message??"Unable to create swimlane",e):$t(s.value)?u("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(ee.ticket(t,n,r,o));return d(s)?L(s.message??"Unable to create issue",e):T(s.value)?u("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=E.createNode(ee.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Z.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?L(i.message??`Unable to create field: ${n}`,e):Ve(i.value)?u("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=E.renameNode(t,n);return d(o)?L(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=E.tombstoneNode(t);return d(n)?L(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=E.createTag({id:t,name:n});return d(r)?L(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return d(r)?L(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=E.tombstoneContributor(t);return d(n)?L(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=E.restoreContributor(t,n);return d(r)?L(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=E.tag(t,n);return d(r)?L(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=E.untag(t,n);return d(r)?L(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=E.assign(t,n);return d(r)?L(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=E.unassign(t,n);return d(r)?L(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=E.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?L(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=E.editValue(t,n);return d(r)?L(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=E.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only close issues",e);let s=E.getNode(ve);if(!s)return L("Unable to locate target swimlane",e);if(n!==s.id)return L("Close target must be closed swimlane",e);let i=E.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?L(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=E.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only reopen issues",e);let s=E.getNode(ve);if(!s)return L("Unable to locate closed swimlane",e);if(n===s.id)return L("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return L("Reopen parent no longer exists",e);let c=E.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?L(c.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return d(n)?L(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=E.getNode(r);if(!s)return L(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let i=E.updateNode({...s,rank:o});if(d(i))return L(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=E.createComment({id:t,issue:n,authorId:r,authorName:E.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?L(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=E.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let s=E.editComment(t,r);return d(s)?L(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=E.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let o=E.deleteComment(t);return d(o)?L(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,c=E.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?L(c.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=E.getAttachment(t);if(!r)return L("Unable to locate attachment",e);if(r.issue!==n)return L("Attachment does not belong to issue",e);let o=E.deleteAttachment(t);return d(o)?L(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=E.linkUserId({contributorId:t,userId:e.userId});return d(n)?L(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Wt(e,t=!1){let n=Fp[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=Bp(e,t);return o||r}var st=e=>e.map(t=>Wt(t));import Jp from"node:fs";import Qp from"node:path";import{decodeTime as Zp,monotonicFactory as ef}from"ulid";import{z as lr}from"zod";var cr=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown";import lo from"node:fs";import Xs from"node:path";import{decodeTime as _p}from"ulid";import{z as Ys}from"zod";var Up=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.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"];var Op=new Set(Up),fd=e=>Op.has(e),gd=e=>({action:e.action,payload:e.payload});var $p=Ys.object({userId:Ys.string().min(1).default("unknown"),userName:Ys.string().min(1).default("unknown")}),Hp=/^[0-9a-hjkmnp-tv-z]{26}$/i,jp=e=>Hp.test(e)?e.toUpperCase():e,Wp=e=>{let t=Xs.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=$p.safeParse({userId:jp(r),userName:o});return s.success?u("Parsed event file actor",s.data):a(`Invalid event file name ${Xs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Vp=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},Gp=(e,t)=>t in e,Kp=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),zp=e=>{let{userId:t,userName:n,...r}=e,o=Vp(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Gp(r,s)?u("Decoded persisted event",Kp({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Js=e=>{let t=[],n=new Map;for(let r of e){let o=zp(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!fd(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");ce.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return u("Decoded reconstructed events",t)},qp=e=>{if(!lo.existsSync(e))return u("Event file missing",[]);let t=Wp(e);if(d(t))return a(t.message);let n=lo.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
43
|
+
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=Zs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return u("Parsed persisted events file",r)};function Qs(e){let t=tr(e);if(!lo.existsSync(t))return u("No events found",[]);let n=lo.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Xs.join(t,o)),r=[];for(let o of n){let s=qp(o);if(d(s))return a(s.message);r.push(...s.value)}return u("All events loaded",Yp(r))}function je(e){let t=Qs(e);return d(t)?a(t.message):Js(t.value)}function uo(e,t){let n=Qs(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=Xp(n.value,t),s=Js(r);if(d(s))return a(s.message);let i=Js(o);return d(i)?a(i.message):u("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function vd(e=process.cwd()){let t=Qs(e);return d(t)?a(t.message):u("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Yp=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let g=n.get(f)??[];g.push(m),n.set(f,g)}for(let m of n.values())m.sort((p,f)=>p.id[0].localeCompare(f.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let f=n.get(p)??[];for(let g of f)s(g)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return!o.has(p)&&f!==null&&!t.has(f)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let l=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);return r},Xp=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],l=!1;try{l=_p(i)<t}catch{l=!1}!l||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var hd=1,yd=ef(),tf=lr.tuple([lr.string().min(1),lr.string().min(1).nullable()]),nf=lr.looseObject({v:lr.literal(hd),id:tf}),Zs=e=>{let t=nf.safeParse(e);return t.success?u("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},rf=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),of=e=>e.trim().length>0&&e.length<=80,se=()=>{let{userName:e,userId:t}=K();return e?t?rf(t)?of(e)?u("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},mn=({userId:e,userName:t})=>`${cr(e)}.${cr(t)}.jsonl`,sf=(e,{userId:t,userName:n})=>{let r=mn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=Qp.join(tr(e),r);return u("Successfully resolved event log path",s)},af=(e,t)=>{let n={[e.action]:e.payload,v:hd,id:t};return Zs(n)};function mo({event:e,rootDir:t}){try{let n=Ca(t);if(d(n))return n;let r=sf(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=vd(t);if(d(o))return a(o.message);let s=o.value?yd(Math.max(Date.now(),Zp(o.value)+1)):yd(),i=af(gd(e),[s,o.value]);return d(i)?a(i.message):(Jp.appendFileSync(r.value,`${JSON.stringify(i.value)}
|
|
44
|
+
`,"utf8"),u("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function xd(e,t){let n=Wt(e);if(n.status!==Ft.Success)return n;let r=mo({event:e,rootDir:t});return d(r)?r:n}function U(e,t){if(e.length===0||!e[0])return a("No events provided");let n=cf(e[0],t);if(d(n))return n;let r=e.map(s=>xd(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):u("Materialization succeeded",r.map(s=>s.value))}var cf=(e,t)=>{if(e.action==="create.contributor")return u("Contributor already being created",void 0);if(E.getContributor(e.userId))return u("Contributor exists",void 0);let n={id:df(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=xd(n,t);return d(r)?a(r.message):u("Contributor created",void 0)};var bd=e=>po(Y(e),{at:"end"}),po=(e,t={at:"end"})=>{let n=o=>d(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ue(void 0,void 0));let r=()=>n(Ue(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ue(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ue(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=Id(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(Ue(i?.rank,s.rank))}case"after":{let o=Id(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(Ue(s.rank,i?.rank))}}},Y=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Id=(e,t)=>e.findIndex(n=>n.id===t),Ed=(e,t,n={at:"end"})=>po(Y(t).filter(r=>r.id!==e),n),pn=(e,t,n,r,o)=>{let s=Ed(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=Ws(e,r);if(d(i))return i;let c=U([i.value],o);if(d(c))return c;let l=Ed(t,e,n);return d(l)?l:l.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",l.value.rank)},Ln=(e,t,n)=>{let r=bd(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=Ws(e,t);if(d(o))return o;let s=U([o.value],n);if(d(s))return s;let i=bd(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var M={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=z(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||M.navigate({contextNode:o,selectedIndex:z(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=z(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Sd(1),navigateToPreviousItem:()=>Sd(-1),navigateToNextContainer:()=>Cd(1),navigateToPreviousContainer:()=>Cd(-1),navigate:({contextNode:e,selectedIndex:t})=>{C({contextNodeId:e.id,selectedIndex:t})}},Sd=e=>{let{selectedIndex:t,contextNode:n}=v(),r=z(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:s,contextNode:n})},Cd=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=z(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 l=z(c.id),m=Math.max(0,l.length-1),p=Math.min(Math.max(0,r),m),f=l.length?p:-1;M.navigate({contextNode:c,selectedIndex:f})};var Rd=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ad=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},lf=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&Ve(t)&&t.childRenderAxis==="vertical"},fo=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Y(r.id);return M.navigate({contextNode:r,selectedIndex:Rd(t,o.length)}),!0},Td=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return fo(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Y(o.id).findIndex(c=>c.id===n.id);return i>=0?(M.navigate({contextNode:o,selectedIndex:i}),!0):Td(o.id)},Nd=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Td(n))return!0;n=t[n]?.parentNodeId}return!1},uf=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},wd=e=>{let{nodes:t,rootNodeId:n}=v();if(lf(e.contextNodeId)&&fo(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(uf(e.selectedNodeId)&&e.selectedNodeId&&Nd(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(fo(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&fo(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(Nd(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=Y(r.id);return M.navigate({contextNode:r,selectedIndex:Rd(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as mf,ulid as Tt}from"ulid";var ur=mf();function pf(){let e=We();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=z(n.id),[o]=r?z(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}):n?u("Resolved boot nav target",{contextNode:n,selectedIndex:0}):u("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function ff(){let e=pf();return d(e)?e:M.navigate(e.value)}function Md({userId:e,userName:t}){let n=ur(),r=ur(),o=ur(),s=ur(),i=ur(),c=Ue(void 0,void 0);if(d(c))return c;let l=Ue(void 0,void 0);if(d(l))return l;let m=Ue(l.value,void 0);if(d(m))return m;let p=Ue(void 0,void 0);if(d(p))return p;let f=Ue(p.value,void 0);if(d(f))return f;let g=Ue(f.value,void 0);if(d(g))return g;let I=Ue(void 0,void 0);return d(I)?I:u("Created default events",[{id:Tt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Tt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:l.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Tt(),userId:e,userName:t,action:"add.board",payload:{id:co,name:"Closed",parent:n,rank:m.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ve,name:"Closed",parent:co,rank:I.value}},{id:Tt(),userId:e,userName:t,action:"lock.node",payload:{id:co}},{id:Tt(),userId:e,userName:t,action:"lock.node",payload:{id:ve}}])}var gf=()=>{let e=We();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"};function fn(e){if(gf())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let r=ee.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=dr(r);return d(o)?o:(C({hasProjectDefinition:!1,mode:y.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=st(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
45
45
|
${n.map(r=>r.message).join(`
|
|
46
|
-
`)}`):(pf(),C({hasProjectDefinition:!0}),u("State booted successfully",null))}var fn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),go=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)}},J=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ht=null,vo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ht,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),ht)return logger.debug("[sync] syncAndReloadState joining existing promise"),ht;logger.debug("[sync] syncAndReloadState creating promise"),ht=gf();try{let e=await ht;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),d(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),ht||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),ht=null}},gf=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=Pd();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(ht)return ht;logger.debug("[sync] syncAndReloadState:start");let t=J("resolveActorId",ie());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=un(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=J("syncEpiqWithRemote",await yo({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),et(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=J("loadMergedEvents",je(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Pd();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:i.message,syncStatus:v().syncStatus}),i;let c=Ad(),l=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,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:s.value.length});let p=J("bootStateFromEventLog",pn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),a(`Unable to boot synced state. ${p.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"),C({filters:l}),logger.debug("[sync] restoreNavigationAnchor:start");let m=J("restoreNavigationAnchor",wd(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},Pd=()=>v().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Ln=3e3,Ld=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ln?null:t},kd=0,ei,ti=!1,pr=!1,ni=()=>{if(ti)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},vf=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-kd;return Math.max(0,e-t)},Dd=()=>{ei||(ei=setTimeout(async()=>{if(ei=void 0,!!Wt()){if(ni()){pr=!0;return}pr=!1,await yf()}},vf()))},yf=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Wt())return a("Cannot auto-sync before state is initialized");if(ni())return pr=!0,a("Sync already in progress");ti=!0,kd=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await vo()}finally{ti=!1,pr&&Dd()}},ho=()=>{Wt()&&(pr=!0,!ni()&&Dd())};var Vt=()=>{let e=K(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Bd=()=>{let e=_e(process.cwd());if(d(e))return!1;let t=ut(e.value);return Q(t)},Fd=e=>e===!0?"on":e===!1?"off":null,Ud=e=>e==="on"?!0:e==="off"?!1:null;var hf=e=>e.props.tags??[],xf=e=>e.props.assignees??[],Gt=e=>hf(e).map(t=>E.getTag(t)).filter(t=>!!t),Kt=e=>xf(e).map(t=>E.getContributor(t)).filter(t=>!!t),xo=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Gt(n))},bo=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",Kt(n))};var b={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var bf=/^(\d+)(h|d|w|mo|y)$/,If=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ef=({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},Sf=(e,t=new Date)=>{let n=e.match(bf);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}},Cf=e=>{let t=e.match(If);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),l=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return Ef({year:c,month:l,day:m,hour:p,minute:f})?new Date(c,l-1,m,p,f):null},gn=e=>{let t=e.trim().toLowerCase();return Sf(t)??Cf(t)};var Od=/^(\d+)(s|m)?$/,Io=e=>{let t=e.trim().toLowerCase().match(Od);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Eo=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Od.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},_d=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Nf=[{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}],ri=(e=Nf)=>{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 Rf=["BOARD","TICKET","SWIMLANE","COMMENT"],re={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Ke={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ye={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Af=[re.EDITOR,re.VIEW,re.USERNAME,re.AUTOSYNC,re.SYNC_DEBOUNCE_MS,re.ATTACHMENT_MAX_KB,re.LOG_LEVEL],Tf=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Ke.TITLE,Ke.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ke.TITLE];case"COMMENT":return[Ke.COMMENT];default:return[]}},si=[String(Ln),"5000","15000","30000","60000"],ii=["250","500","1000"],jd=["10s","20s","30s","45s"],vn=[b.COFFEE,b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],So=[b.NEW,b.EDIT,b.DELETE,b.MOVE],oi=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],$d=[b.FILTER,b.PEEK,b.REPLAY],wf={WORKSPACE:[...vn,...So],BOARD:[...$d,...vn,...So],SWIMLANE:[...$d,...vn,...So],TICKET:[...vn,...So,...oi],FIELD:[...vn,...oi],FIELD_LIST:[...vn,...oi],TEXT:[...vn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},Mf=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],fr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&T(n)),Hd=e=>e.parentNodeId===ve,Pf=({selectedNode:e,breadCrumb:t})=>{let n=Tf(e?.context);return fr({breadCrumb:t,selectedNode:e})?n.includes(Ke.DESCRIPTION)?n:[...n,Ke.DESCRIPTION]:n},Lf=({selectedNode:e,breadCrumb:t})=>{let n=fr({breadCrumb:t,selectedNode:e});return n?[ye.REF,ye.TITLE,...n.props?.description?.trim()?[ye.DESCRIPTION]:[],...Gt(n).length>0?[ye.TAGS]:[],...Kt(n).length>0?[ye.ASSIGNEES]:[]]:e?[ye.REF,ye.TITLE]:[]},kf=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Vt();if(!r)return[b.HELP,b.CONFIG];if(!Bd())return[b.HELP,b.INIT];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let o=e?.context,s=o&&Rf.includes(o),i=[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?wf[l]:[]))],c=fr({breadCrumb:n,selectedNode:e});return i.filter(l=>l===b.MOVE?!1:l===b.YANK?!!(c??e):l===b.EDIT?s||!!c:l===b.DELETE?s:l===b.UNTAG?!!(c&&Gt(c).length>0):l===b.UNASSIGN?!!(c&&Kt(c).length>0):l===b.RE_OPEN_ISSUE?!!(c&&Hd(c)):l===b.CLOSE_ISSUE?!!(c&&!Hd(c)):!0)},ae=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:kf({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.HELP]:[],[b.PEEK]:[...ri(),"now","prev","next"],[b.REPLAY]:[...ri()],[b.EDIT]:Pf({selectedNode:n,breadCrumb:o}),[b.YANK]:Lf({selectedNode:n,breadCrumb:o}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(Tn),...E.getExistingTags()])],[b.UNTAG]:[...xo()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...bo()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:E.getExistingAssignees(),[b.NEW]:Mf(s),[b.CONFIG]:[...Af],[b.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import ec from"chalk";var Wd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Vd}from"ulid";var Co=e=>{try{return u("Decoded date",new Date(Vd(e)))}catch(t){return a("Decoding failed + "+t.message)}},zt=e=>{if(!e?.id)return null;try{return Vd(e.id)}catch{return null}};import Of from"zod";import Df from"node:crypto";import gr from"node:fs";import Gd from"node:path";var xt=500,Bf=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,kn=(e,t)=>`${e}.${t}`,Ff=e=>Bf.test(e),Kd=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"):a(`Unsupported image format. Allowed: ${Qa.join(", ")}`),zd=e=>Df.createHash("sha256").update(e).digest("hex"),Uf=(e,t=xt)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Kd(e);return d(n)?n:u("Validated attachment data",{hash:zd(e),ext:n.value,bytes:e.length})},qd=(e,t,n=xt)=>{let r=Uf(t,n);if(d(r))return r;let o=nr(e),s=Gd.join(o,kn(r.value.hash,r.value.ext));try{gr.existsSync(s)||(gr.mkdirSync(o,{recursive:!0}),gr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},Yd=(e,t,n=xt)=>{if(!Ff(t))return a("Invalid attachment file name");let r=Gd.join(nr(e),t);if(!gr.existsSync(r))return a("Attachment blob not found");let o;try{o=gr.readFileSync(r)}catch(l){return a(`Unable to read attachment blob: ${l instanceof Error?l.message:String(l)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(zd(o)!==s)return a("Attachment blob does not match its content hash");let c=Kd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var vr=50,yr=5e3,Xd=()=>{let e=X().commandMeta.inputString,t=Of.coerce.number().int().min(vr).max(yr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${vr}-${yr} KB (default ${xt})`);let n=Qe({attachmentMaxKb:t.data});return d(n)?n:(Me({attachmentMaxKb:t.data}),C({mode:y.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import Jd from"chalk";var te=e=>Jd.dim(e),Ee=e=>Jd.hex(h.primary)(e),Se=({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)=>ro(f)-ro(g)).slice(0,r).map(f=>oo(f)).join(" ");return p?`${te(e)}${p}${te(n)}`:""};var bt={None:"none",Invalid:"invalid",Valid:"valid"};var Dn=140,_f=["BOARD","TICKET","SWIMLANE"],Qd=()=>{let e=v().selectedNode;if(!e?.context)return O({message:te("Missing target context")});if(_f.includes(e.context))return G();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Ie(t?.parentNodeId??"","comments"))return G()}return O({message:te("Command not available in this context")})},oe="<ENTER> to confirm",G=(e="",t=[])=>({message:te(e),validity:bt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:bt.Invalid,message:e,completionWordList:t}),Ro=e=>e.length===0,Zd=(e,t)=>{let n=Ue(v().breadCrumb,"BOARD");if(d(n))return O({message:Ee("Command is not applicable in this context")});let r=Co(n.value.id);return d(r)?O({message:Ee(`Unable to ${t}: board id is not a valid ULID`)}):_d({date:e,horizonDate:r.value})?null:O({message:Ee(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},No=e=>` ${ec.hex("#000").bgHex(ue(e))(` ${e} `)} `,ai=({modifier:e})=>{let t="confirm";return e===t?G(oe):O({message:Ro(e)?te("if you are certain, enter ")+oo(t):"",completionWordList:[t]})},$f=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:te(n)}):G():O({message:Ro(r)?t:"",completionWordList:[...e]}),yn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Ro(n)&&Ro(r)?O({message:e,completionWordList:[]}):G(t??oe),Hf=({modifier:e,inputString:t})=>{let n=ae(b.CONFIG);if(!n.includes(e))return O({message:Se({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case re.EDITOR:{let r=[...Wd];return t.trim()?r.includes(t.trim())?G(oe):O({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?G(oe):O({message:Se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.USERNAME:return t.trim()?G(oe):O({message:Ee("Enter a user name. Saved in ")+ec.bgBlack("~/.epiq-global/config.json")});case re.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?G(oe):O({message:Se({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case re.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=Fd(o);return O({message:Se({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return G(oe)}case re.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<vr||o>yr){let s=Se({prefix:" examples: ",wordList:ii,minLengthForHints:0,inputString:t});return O({message:Ee(`provide a size cap in KB (${vr}-${yr}). current: ${r??xt} KB.`)+s,completionWordList:ii})}return G(oe)}case re.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=Ld(t);if(!t.trim()||o===null||o<Ln){let s=Se({prefix:" examples: ",wordList:si,minLengthForHints:0,inputString:t});return O({message:Ee(`provide duration above ${Ln}ms. current duration: ${r}ms.`)+s,completionWordList:si})}return G(oe)}default:return O({message:Ee("Unknown config option"),completionWordList:n})}},jf=({modifier:e,inputString:t})=>{let n=ae(b.EDIT);if(!n.length)return O({message:Ee("Command not available in this context")});if(!n.includes(e)){let r=Se({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:r||Ee("Unknown edit option"),completionWordList:n})}switch(e){case Ke.COMMENT:return t.trim()?G(oe):O({message:te("write a comment...")});case Ke.TITLE:return G(oe);case Ke.DESCRIPTION:{let{preferredEditor:r}=K();return r?G(te("<ENTER> to edit in ")+r):O({message:"No editor selected"})}default:return O({message:Ee("Unknown edit option"),completionWordList:n})}},Wf=({modifier:e})=>{let t=ae(b.YANK);return t.length?t.includes(e)?G(oe+te(" and copy to clipboard")):O({message:Se({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ee("Nothing selected to copy from")})},Vf={[b.EXPORT]:()=>G(oe+te(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return G(oe);let n={message:te("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=gn(r);if(!r||!o)return O(n);let s=Zd(o,"peek");return s||G(oe)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Eo(e.modifier,e.inputString),r={message:te("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=gn(t);if(!t||!o)return O(r);let s=Zd(o,"replay");return s||(n&&Io(n)===null?O({message:Ee("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):G("<ENTER> to replay board history",n?jd:[]))},[b.EXIT]:()=>G(oe+te(" and exit the application")),[b.INIT]:()=>G(oe),[b.PALETTE]:()=>G(oe),[b.FILTER]:e=>{if(e.modifier==="clear")return G(oe);let t=s=>ae(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:Se({wordList:ae(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ae(b.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())?O({message:Se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):G():O({message:Se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=ae(b.NONE);return O({message:Se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>$f({list:ae(b.NEW),hint:Se({wordList:ae(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>G(oe),[b.EDIT]:jf,[b.COMMENT]:e=>{let t=yn({hint:te(`write a comment (max ${Dn} char)...`),onOk:te(`(${e.inputString.length}/${Dn})`)})(e);return t.validity===bt.Invalid?t:e.inputString.length>Dn?G(Ee("max input exceeded")):t},[b.CONFIG]:Hf,[b.YANK]:Wf,[b.DELETE]:e=>{let t=Qd();return t.validity==="invalid"?t:ai(e)},[b.CLOSE_ISSUE]:e=>ai(e),[b.RE_OPEN_ISSUE]:e=>ai(e),[b.MOVE]:e=>{let t=Qd();return t.validity==="invalid"?t:yn({hint:Se({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(No).join("");return yn({hint:n.length?te("create tag or reuse:")+n+te(""):te("create tag ...")})(e)},[b.UNTAG]:e=>{let t=xo();if(d(t))return O({message:Ee("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(No).slice(0,10);return n.length?yn({hint:te(" ... ")+n.join("")})(e):O({message:Ee("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=E.getExistingAssignees().map(No).slice(0,10);return yn({hint:te("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=bo();if(d(t))return O({message:Ee("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(No).slice(0,10);return n.length?yn({hint:te("remove assignee... ")+n.join("")})(e):O({message:Ee("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>G(oe),[b.COFFEE]:e=>{let{modifier:t}=e,n=ae(b.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:te("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):yn({hint:Se({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},tc=Object.fromEntries(Object.entries(Vf).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ao=["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 Gf=3,Kf=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"]),zf=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},qf=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Gf&&!Kf.has(t)&&!/^\d+$/.test(t)),Yf=e=>{let t=new Map;for(let s of zf(e))for(let i of qf(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=Ao.filter(s=>!r.has(s));return[...n,...o]},nc=Ao,rc=-1,oc=()=>{let e=We();if(d(e))return Ao;let t=e.value,n=t.eventLog.length;return n!==rc&&(nc=Yf(t),rc=n),nc};var sc=e=>Object.values(b).includes(e),ic=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:l}=tc[n].validate(n,r,s),m=n!==b.PEEK&&n!==b.REPLAY,p=o==="command"||o==="modifier"?ae(n):m?oc():[],{mode:f}=v(),g=f===y.COMMAND_LINE?i??"":"",I=[...l,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Ya(e,I):{hint:"",hints:[],remainder:"",overlap:0}}};var ac=e=>{let t=e.trimStart(),n=Jf(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=Qf(e),c=sc(r)?r:null,l=c!==null,m=r!=="",p=c?ae(c)??[]:[],f=c&&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 I=s?"":i,S=Xf(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:l,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:I,inputString:S}},Xf=(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},Jf=e=>e.trim()?e.trim().split(/\s+/):[],Qf=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Zf}from"react";var Bn=e=>e===di||e===":",di=" ",Le={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:bt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ci=new Set,dc=()=>{for(let e of ci)e()},li=e=>(ci.add(e),()=>ci.delete(e)),It=e=>{let n=e(Le),r=ac(n.value),o=n.cursorPosition===n.value.length;Le={...n,commandMeta:ic(r,o)},dc()},hr=({message:e,status:t})=>{let n=structuredClone(Le);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Le=n,dc(),u(e,null)},ui=e=>{It(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},mi=e=>{It(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Bn(n[o-1]);)o--;for(;o>0&&!Bn(n[o-1]);)o--}else{for(;o<n.length&&!Bn(n[o]);)o++;for(;o<n.length&&Bn(n[o]);)o++}return{...t,cursorPosition:o}})},cc=()=>{It(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}})},lc=()=>{It(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Bn(t[r-1]);)r--;for(;r>0&&!Bn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},To=e=>{It(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}})},uc=()=>{It(e=>({...e,commandIsPending:!0}))},V=e=>{It(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},mc=({addToHistory:e=!0})=>{It(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},pc=()=>{It(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}})},fc=()=>{It(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},X=()=>Le,gc=()=>Zf(li,X,X),vc=()=>{let[e,...t]=Le.value.split(di);return t.join(di).trim()};var x={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function eg(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function tg(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function ng(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 yc(e,t){let n=X();if(e.sequence==="?"&&t!==y.PALETTE)return x.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return x.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===y.COMMAND_LINE)return ja(e,n.value);if(t===y.PALETTE)return Wa(e,n.value);let r=eg(e)||tg(e);if(r)return rg(r,t);if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"r":return x.EditTitle;case"e":return x.EditDescription;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"y":return x.Yank;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return K().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;default:return null}}function rg(e,t){let n=t===y.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return ng(v().contextNode.childRenderAxis,e,n)}var wo=e=>{let{context:t}=v().contextNode;if(!t)return k.None;switch(e){case b.EXIT:return k.Exit;case b.EXPORT:return k.Export;case b.COFFEE:return k.Coffee;case b.INIT:return k.Init;case b.DELETE:return k.Delete;case b.EDIT:return k.Edit;case b.COMMENT:return k.Comment;case b.HELP:return k.ViewHelp;case b.RE_OPEN_ISSUE:return k.ReopenIssue;case b.CLOSE_ISSUE:return k.CloseIssue;case b.TAG:return k.TagTicket;case b.UNTAG:return k.UntagTicket;case b.ASSIGN:return k.AssignUserToTicket;case b.UNASSIGN:return k.UnassignUserFromTicket;case b.NEW:return k.NewItem;case b.FILTER:return k.Filter;case b.MOVE:return k.Move;case b.PEEK:return k.Peek;case b.REPLAY:return k.Replay;case b.CONFIG:return k.Config;case b.YANK:return k.Yank;case b.SYNC:return k.Sync;default:return k.None}},k={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as Be}from"ulid";import $c from"node:fs";import zg from"node:path";import qg from"react";import{Box as Gg}from"ink";import Fo from"react";import xg from"chalk";import{Box as fi,Text as bg}from"ink";import Et from"react";import{Text as hc}from"ink";import xc,{useEffect as bc,useState as og}from"react";var Ic={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ke=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=j(),r=Ic[n]??Ic.default,[o,s]=og(0);if(bc(()=>{s(0)},[r]),bc(()=>{if(!e)return;let c=setInterval(()=>{s(l=>(l+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return xc.createElement(hc,null,t);let i=r[o]??r[0]??t;return xc.createElement(hc,{color:h.accent,dimColor:o===1},i)};import{Box as pi,Text as sg}from"ink";import Mo from"react";var tt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),l=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,l-c+1)):Math.min(m,Math.floor(l/c)*c),f=p+c,g=e.slice(p,f),I=e.length>c,S=s,R=I?Math.max(1,Math.floor(c/e.length*S)):S,A=Math.max(0,S-R),P=Math.max(1,e.length-c),_=I?Math.floor(p/P*A):0;return Mo.createElement(pi,{flexDirection:"row",height:s,width:"100%"},Mo.createElement(pi,{flexDirection:"column",flexGrow:1,height:s},g),Mo.createElement(pi,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((w,W)=>Mo.createElement(sg,{key:W,color:I&&W>=_&&W<_+R?h.accent:h.secondary},I?"\u2502":" "))))};import{Box as _n,Text as ko}from"ink";import nt from"react";import{Text as ig}from"ink";import ag from"react";var Fn=(e,t)=>t?e&&lr(e)===t?e:t:e,Ec,Po,Sc=()=>{let{eventLog:e=[]}=v();if(Po&&Ec===e)return Po;let t=new Map,n=new Set;for(let r of e)r?.userId&&(n.add(r.userId),r.userName&&t.set(r.userId,r.userName));return Ec=e,Po={latestNames:t,authors:n},Po},qt=(e,t)=>{let{contributors:n={}}=v();return n[e]?.tombstoned?t:Fn(t,Sc().latestNames.get(e))??t},Cc=e=>Sc().authors.has(e);var dg=e=>e.toLowerCase().trim(),cg=(e,t=Tn)=>{let n=dg(e);return t[n]?t[n]:dr(n)},Yt=({id:e,isSelected:t})=>{let n=E.getContributor(e);if(!n)return;let r=qt(e,n.name);return ag.createElement(ig,{underline:t,color:cg(r)},"@"+r,Cc(e)?"":"\u2197")};import{Text as lg}from"ink";import ug from"react";var Un=({id:e,isSelected:t})=>{let n=E.getTag(e);if(n)return ug.createElement(lg,{underline:t,backgroundColor:ue(n.name),color:h.secondary}," "+n.name+" ")};import{useEffect as mg,useState as pg}from"react";var fg=80,Nc=1400,Lo=new Set,xr=null,gg=e=>(Lo.add(e),xr||(xr=setInterval(()=>{for(let t of Lo)t()},fg)),()=>{Lo.delete(e),Lo.size===0&&xr&&(clearInterval(xr),xr=null)}),vg=()=>{let e=Date.now()%Nc/Nc;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=pg(0);return mg(()=>{if(e)return gg(()=>t(n=>n+1))},[e]),no(vg())};var yg=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),ln(e.slice(r).trim(),t)]},Rc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=On(r),s=e-4,[i,c]=yg(Ze(t.title),s),l=c?null:ln(Ze(t.props.description),s)||null,m=Gt(t),p=Kt(t);return nt.createElement(_n,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?h.accent:h.secondary,justifyContent:"space-between"},nt.createElement(_n,{paddingLeft:1,flexDirection:"column"},nt.createElement(ko,{color:h.primary},i),c&&nt.createElement(ko,{color:h.primary},c),l&&nt.createElement(ko,{color:h.secondary2,dimColor:!0},l)),nt.createElement(_n,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},nt.createElement(_n,{flexDirection:"row"},m.map(f=>nt.createElement(_n,{paddingRight:1,key:f.id},nt.createElement(Un,{key:f.id,id:f.id}))),p.map(f=>nt.createElement(_n,{paddingRight:1,key:f.id},nt.createElement(Yt,{key:f.id,id:f.id})))),nt.createElement(ko,{wrap:"truncate",color:h.secondary2,dimColor:!0},He(t.id))))};import{Box as hn,Text as br}from"ink";import ze from"react";var hg=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ac=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=On(r),c=(t.props.tags??[]).map(w=>E.getTag(w)).filter(w=>!!w),l=(t.props.assignees??[]).map(w=>E.getContributor(w)).map(w=>w&&{...w,name:qt(w.id,w.name)}).filter(w=>!!w),m=1,p=c.length*(1+m),f=l.length*(2+m),g=c.map(w=>ze.createElement(hn,{key:w.id,paddingRight:m},ze.createElement(br,{color:ue(w.name)},"\u25A0"))),I=l.map(w=>ze.createElement(hn,{key:w.id,paddingRight:m},ze.createElement(br,{color:dr(w.name)},"@"+w.name.at(0)))),S=r?i:n?h.accent:s===y.MOVE?h.secondary:h.primary,R=4,A=E.getCommentsByIssue(t.id),P=A.length?String(A.length).length+2+m:0,_=A.length?ze.createElement(hn,{paddingRight:m},ze.createElement(br,{color:h.accent},"[",A.length,"]")):null;return ze.createElement(hn,{borderBottom:!0,justifyContent:"space-between"},ze.createElement(hn,null,ze.createElement(hn,{width:R},n?ze.createElement(ke,{isSelected:n}):ze.createElement(br,{color:"gray",dimColor:!0},o+1)),ze.createElement(br,{wrap:"truncate",color:S},hg(t.title,e-p-f-P-18))),ze.createElement(hn,null,g,I,_))};var Ig=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:l,replay:m}=j(),p=l[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,I=On(g),S=`${e.title} ${xg.hex(h.secondary2).dim("("+p.length+")")}`,R=3,A=o?1:5,P=s&&i===-1,_=n-(P?7:5),w=r-R-(o?2:1),W=Et.createElement(fi,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Et.createElement(ke,{isSelected:t}),Et.createElement(bg,{bold:!0,color:g?I:t?h.accent:h.primary},S," ",e.readonly?"\u{1F512}":"")),H=(D,$)=>{let Ye=s&&i===$;if(!T(D))return null;let we=f?.has(D.id)??!1;return o?Et.createElement(Ac,{key:D.id,index:$,width:n,ticket:D,isSelected:Ye,isFlashing:we,mode:c}):Et.createElement(Rc,{key:D.id,width:_,ticket:D,isSelected:Ye,isFlashing:we})};return Et.createElement(fi,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},W,Et.createElement(fi,{padding:o?1:0},p.length>0&&Et.createElement(tt,{selectedIndex:i,height:w,itemHeight:A},p.map(H)),P&&Et.createElement(ke,{isSelected:!0})))},Tc=Et.memo(Ig);import{Box as xn,Text as bi}from"ink";import Ce,{useMemo as Ir}from"react";var wc=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},Mc=(e,t,n)=>ee.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as $n,Text as wt}from"ink";import De,{useEffect as Eg,useMemo as Sg,useRef as Cg}from"react";import{decodeTime as gi}from"ulid";var Ng=e=>Ie(e,"attachments"),Rg=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>gi(t.id)-gi(n.id)),Pc=e=>{for(let t of e)E.deleteNode(t.id)},Ag=(e,t,n)=>ee.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Tg=(e,t)=>{let n=E.getNode(Ng(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Ag(o,s,n.id)).map(o=>E.createNode(o)).filter(Q).map(({value:o})=>o).filter(Ve);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},wg=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Lc({ticket:e,width:t,height:n}){let r=Sg(()=>Rg(e),[e]),o=Cg([]);Eg(()=>(Pc(o.current),o.current=Tg(e,r),()=>{Pc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(12,t-32);return r.length===0?De.createElement($n,{flexDirection:"column",width:t,height:n,padding:1},De.createElement(wt,{color:h.primary},"No attachments yet."),De.createElement($n,{paddingTop:1},De.createElement(wt,{color:h.primary},"Attach images from the browser GUI"),De.createElement(wt,{color:h.accent}," epiq gui "),De.createElement(wt,{color:h.primary},"by dropping or pasting them."))):De.createElement($n,{flexDirection:"column",width:t,height:n},De.createElement($n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},De.createElement(wt,{color:h.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),De.createElement(tt,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>l?m.name.slice(0,l-1)+"\u2026":m.name;return De.createElement($n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},De.createElement(wt,{color:h.accent},f?"\u276F ":" "),De.createElement($n,{paddingLeft:1},De.createElement(wt,{color:h.secondary2},`#${p+1} `),De.createElement(wt,{color:f?h.accent:h.primary},g),De.createElement(wt,{color:h.secondary2}," "+wg(m.bytes)+" "+Mn(gi(m.id)))))})))}import{Box as Xt,Text as Mt}from"ink";import he,{useEffect as Mg,useMemo as Pg,useRef as Lg}from"react";import{decodeTime as vi}from"ulid";var kg=e=>Ie(e,"comments"),Dg=e=>E.getCommentsByIssue(e.id).sort((t,n)=>vi(t.id)-vi(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),kc=e=>{for(let t of e)E.deleteNode(t.id)},Bg=(e,t)=>{let n=E.getNode(kg(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Mc(o,s,n.id)).map(E.createNode).filter(Q).map(({value:o})=>o).filter(ar);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Fg=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Dc({ticket:e,width:t,height:n}){let r=Pg(()=>Dg(e),[e]),o=Lg([]);Mg(()=>(kc(o.current),o.current=Bg(e,r),()=>{kc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(20,t-8);return r.length===0?he.createElement(Xt,{flexDirection:"column",width:t,height:n,padding:1},he.createElement(Mt,{color:h.primary},"No comments yet."),he.createElement(Xt,{paddingTop:1},he.createElement(Mt,{color:h.primary},"Use"),he.createElement(Mt,{color:h.accent}," :comment "),he.createElement(Mt,{color:h.primary},"to add the first one."))):he.createElement(Xt,{flexDirection:"column",width:t,height:n},he.createElement(Xt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},he.createElement(Mt,{color:h.secondary2},"Comments (",r.length,") ")),he.createElement(tt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return he.createElement(Xt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},he.createElement(Xt,{flexDirection:"row",paddingBottom:1},he.createElement(Mt,{color:h.accent},f?"\u276F ":" "),he.createElement(Xt,{paddingLeft:1},he.createElement(Mt,{color:h.secondary2},`#${p+1} `),he.createElement(Yt,{id:m.authorId}),he.createElement(Mt,{color:h.secondary2}," "+Mn(vi(m.id))))),he.createElement(Xt,{paddingLeft:3,paddingBottom:1},he.createElement(Mt,{color:h.primary},Fg(m.md,l))))})))}import{Box as Do,Text as Ug}from"ink";import Pt from"react";var Bc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=j(),{title:o}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,i=s&&T(s)?o===Z.ASSIGNEES?s.props.assignees??[]:o===Z.TAGS?s.props.tags??[]:[]:[];return Pt.createElement(Do,{alignItems:"center",paddingTop:1},Pt.createElement(Do,{minWidth:12},Pt.createElement(ke,{isSelected:n}),Pt.createElement(Ug,{color:n?h.accent:h.secondary2},o,":")),Pt.createElement(Do,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,l)=>{let m=r.id===t.id&&l===e;return Pt.createElement(Do,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Pt.createElement(ke,{isSelected:m}),o===Z.ASSIGNEES?Pt.createElement(Yt,{isSelected:m,id:c}):o===Z.TAGS?Pt.createElement(Un,{isSelected:m,id:c}):null)})))};import{Box as Bo,Text as yi}from"ink";import Lt,{useEffect as Og,useMemo as Fc}from"react";var _g="\u2029",Uc=(e,t)=>`${e}::inline-line::${t}`,hi=new Map,Oc=e=>{let t=hi.get(e)??[];hi.delete(e);for(let n of t)E.deleteNode(n)},$g=(e,t)=>{Oc(e);let n=[];t.forEach((r,o)=>{let s=Ge(BigInt(o+1));if(!Q(s))return;let i=E.createNode(ee.text({id:Uc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));Q(i)&&n.push(i.value.id)}),hi.set(e,n)},xi=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=j(),l=Fc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Fc(()=>l.join("\0"),[l]);Og(()=>($g(e,l),()=>{Oc(e)}),[e,m]);let p=g=>String(g).replace(/\r?\n/g,""),f=l.map((g,I)=>{let S=c.id===e&&i===I;return Lt.createElement(Bo,{key:Uc(e,I)},Lt.createElement(yi,{color:S?h.primary:h.secondary2,dimColor:!S},`${I+1} `.padStart(5,"\xA0")),Lt.createElement(yi,{backgroundColor:S?"gray":void 0},p(g.length?ln(g,s-10):_g)))});return Lt.createElement(Bo,{flexDirection:"column",paddingTop:1},Lt.createElement(Bo,null,Lt.createElement(ke,{isSelected:o}),Lt.createElement(yi,{color:o?h.accent:h.secondary2},t)),Lt.createElement(Bo,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},Lt.createElement(tt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var Hg=e=>Ie(e,"description"),jg=e=>Ie(e,"comments"),Wg=e=>Ie(e,"history"),Vg=e=>Ie(e,"attachments"),_c=({ticket:e,height:t})=>{let n=Ir(()=>wc(e),[e]),{selectedIndex:r,contextNode:o}=j(),s=process.stdout.columns||120,i=Ir(()=>Hg(e.id),[e.id]),c=Ir(()=>jg(e.id),[e.id]),l=Ir(()=>Wg(e.id),[e.id]),m=Ir(()=>Vg(e.id),[e.id]),p=E.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===c||o.parentNodeId===c,I=o.id===l||o.parentNodeId===l,S=o.id===m||o.parentNodeId===m,R=z(e.id);if(g){let $=t-3;return Ce.createElement(xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(Dc,{ticket:e,width:s,height:$}))}if(S){let $=t-3;return Ce.createElement(xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(Lc,{ticket:e,width:s,height:$}))}if(I){let D=E.getNode(l),$=D&&Ve(D)?D.props.value??"":"",we=t-3;return Ce.createElement(xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},D?Ce.createElement(xi,{id:D.id,label:"Event log",text:$,selected:!1,maxWidth:s,height:we}):null)}let A=R.reduce((D,$)=>ir($)||$.id===c||$.id===m||$.id===l?D+1:D,0),P=2,_=3,w=A,W=t-_-w-P,H=(D,$)=>D.id===i?Ce.createElement(xi,{key:D.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,height:W}):ir(D)?Ce.createElement(Bc,{key:D.id,parent:D,selected:$,selectedIndex:r}):D.id===c?Ce.createElement(xn,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(bi,{backgroundColor:h.secondary,color:$?h.accent:h.primary},` Comments (${n}) \u203A\u203A `)):D.id===m?Ce.createElement(xn,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(bi,{backgroundColor:h.secondary,color:$?h.accent:h.primary},` Attachments (${p}) \u203A\u203A `)):D.id===l?Ce.createElement(xn,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(bi,{backgroundColor:h.secondary,color:$?h.accent:h.primary}," History \u203A\u203A ")):null;return Ce.createElement(xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((D,$)=>H(D,f&&r===$)))};var Kg=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let l=t.context,m=l===B.TICKET||l===B.FIELD_LIST||l===B.FIELD,p=l===B.BOARD||l===B.SWIMLANE,f=l===B.TICKET?t:r.find(A=>A.context===B.TICKET),g=Math.floor(c/3),I=Math.floor(c/Math.max(e.length,1)),S=Math.min(I,g),R=s==="dense";return Fo.createElement(Gg,{flexDirection:"row",height:i},p&&e.map((A,P)=>{let _=t.id===A.id,w=_?n:-1,W=t.context===B.BOARD&&n===P;return Fo.createElement(Tc,{key:A.id,height:i,width:S,swimlane:A,isSelected:W,isDense:R,isFocused:_,listSelectedIndex:w,mode:o})}),m&&f&&Fo.createElement(_c,{height:i,ticket:f}))},Uo=Fo.memo(Kg);import{render as Yg}from"ink";import{Writable as Xg}from"node:stream";var Er=e=>String(e).padStart(2,"0"),Jg=e=>{let t=e.getUTCFullYear(),n=Er(e.getUTCMonth()+1),r=Er(e.getUTCDate()),o=Er(e.getUTCHours()),s=Er(e.getUTCMinutes()),i=Er(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},Qg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Zg=async(e,{width:t,height:n})=>{let r="",o=new Xg({write(i,c,l){let m=ev(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),l()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Yg(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},ev=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Hc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(P=>P.context==="BOARD");if(!i)return a("No board found to export");let c=120,l=40,m=await Zg(qg.createElement(Uo,{height:l,width:c,swimlanes:(s[i.id]??[]).filter(P=>P!==void 0&&_t(P)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:l});if(!m)return a("Failed to render board export");let p=$r(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=Jg(f),I=`board_${Qg(i.title)}_${g}.md`,S=Sa(p.value);$c.mkdirSync(S,{recursive:!0});let R=zg.join(S,I),A=`# Board - ${i.title}
|
|
46
|
+
`)}`):(ff(),C({hasProjectDefinition:!0}),u("State booted successfully",null))}var gn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),go=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)}},J=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ht=null,vo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ht,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),ht)return logger.debug("[sync] syncAndReloadState joining existing promise"),ht;logger.debug("[sync] syncAndReloadState creating promise"),ht=vf();try{let e=await ht;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),d(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),ht||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),ht=null}},vf=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=Pd();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(ht)return ht;logger.debug("[sync] syncAndReloadState:start");let t=J("resolveActorId",se());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=mn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=J("syncEpiqWithRemote",await yo({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),et(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=J("loadMergedEvents",je(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Pd();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:i.message,syncStatus:v().syncStatus}),i;let c=Ad(),l=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,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:s.value.length});let p=J("bootStateFromEventLog",fn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),a(`Unable to boot synced state. ${p.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"),C({filters:l}),logger.debug("[sync] restoreNavigationAnchor:start");let m=J("restoreNavigationAnchor",wd(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},Pd=()=>v().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var kn=3e3,Ld=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<kn?null:t},kd=0,ei,ti=!1,mr=!1,ni=()=>{if(ti)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},yf=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-kd;return Math.max(0,e-t)},Dd=()=>{ei||(ei=setTimeout(async()=>{if(ei=void 0,!!Vt()){if(ni()){mr=!0;return}mr=!1,await hf()}},yf()))},hf=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Vt())return a("Cannot auto-sync before state is initialized");if(ni())return mr=!0,a("Sync already in progress");ti=!0,kd=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await vo()}finally{ti=!1,mr&&Dd()}},ho=()=>{Vt()&&(mr=!0,!ni()&&Dd())};var Gt=()=>{let e=K(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Bd=()=>{let e=$e(process.cwd());if(d(e))return!1;let t=ut(e.value);return Q(t)},Fd=e=>e===!0?"on":e===!1?"off":null,Ud=e=>e==="on"?!0:e==="off"?!1:null;var xf=e=>e.props.tags??[],bf=e=>e.props.assignees??[],Kt=e=>xf(e).map(t=>E.getTag(t)).filter(t=>!!t),zt=e=>bf(e).map(t=>E.getContributor(t)).filter(t=>!!t),xo=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Kt(n))},bo=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",zt(n))};var b={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var If=/^(\d+)(h|d|w|mo|y)$/,Ef=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Sf=({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},Cf=(e,t=new Date)=>{let n=e.match(If);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}},Nf=e=>{let t=e.match(Ef);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),l=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return Sf({year:c,month:l,day:m,hour:p,minute:f})?new Date(c,l-1,m,p,f):null},vn=e=>{let t=e.trim().toLowerCase();return Cf(t)??Nf(t)};var Od=/^(\d+)(s|m)?$/,Io=e=>{let t=e.trim().toLowerCase().match(Od);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Eo=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Od.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},_d=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Rf=[{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}],ri=(e=Rf)=>{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 Af=["BOARD","TICKET","SWIMLANE","COMMENT"],re={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Ke={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ye={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Tf=[re.EDITOR,re.VIEW,re.USERNAME,re.AUTOSYNC,re.SYNC_DEBOUNCE_MS,re.ATTACHMENT_MAX_KB,re.LOG_LEVEL],wf=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Ke.TITLE,Ke.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ke.TITLE];case"COMMENT":return[Ke.COMMENT];default:return[]}},si=[String(kn),"5000","15000","30000","60000"],ii=["250","500","1000"],jd=["10s","20s","30s","45s"],yn=[b.COFFEE,b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],So=[b.NEW,b.EDIT,b.DELETE,b.MOVE],oi=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],$d=[b.FILTER,b.PEEK,b.REPLAY],Mf={WORKSPACE:[...yn,...So],BOARD:[...$d,...yn,...So],SWIMLANE:[...$d,...yn,...So],TICKET:[...yn,...So,...oi],FIELD:[...yn,...oi],FIELD_LIST:[...yn,...oi],TEXT:[...yn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},Pf=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],pr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&T(n)),Hd=e=>e.parentNodeId===ve,Lf=({selectedNode:e,breadCrumb:t})=>{let n=wf(e?.context);return pr({breadCrumb:t,selectedNode:e})?n.includes(Ke.DESCRIPTION)?n:[...n,Ke.DESCRIPTION]:n},kf=({selectedNode:e,breadCrumb:t})=>{let n=pr({breadCrumb:t,selectedNode:e});return n?[ye.REF,ye.TITLE,...n.props?.description?.trim()?[ye.DESCRIPTION]:[],...Kt(n).length>0?[ye.TAGS]:[],...zt(n).length>0?[ye.ASSIGNEES]:[]]:e?[ye.REF,ye.TITLE]:[]},Df=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Gt();if(!r)return[b.HELP,b.CONFIG];if(!Bd())return[b.HELP,b.INIT];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let o=e?.context,s=o&&Af.includes(o),i=[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Mf[l]:[]))],c=pr({breadCrumb:n,selectedNode:e});return i.filter(l=>l===b.MOVE?!1:l===b.YANK?!!(c??e):l===b.EDIT?s||!!c:l===b.DELETE?s:l===b.UNTAG?!!(c&&Kt(c).length>0):l===b.UNASSIGN?!!(c&&zt(c).length>0):l===b.RE_OPEN_ISSUE?!!(c&&Hd(c)):l===b.CLOSE_ISSUE?!!(c&&!Hd(c)):!0)},ie=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:Df({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.HELP]:[],[b.PEEK]:[...ri(),"now","prev","next"],[b.REPLAY]:[...ri()],[b.EDIT]:Lf({selectedNode:n,breadCrumb:o}),[b.YANK]:kf({selectedNode:n,breadCrumb:o}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(wn),...E.getExistingTags()])],[b.UNTAG]:[...xo()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...bo()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:E.getExistingAssignees(),[b.NEW]:Pf(s),[b.CONFIG]:[...Tf],[b.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import ec from"chalk";var Wd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Vd}from"ulid";var Co=e=>{try{return u("Decoded date",new Date(Vd(e)))}catch(t){return a("Decoding failed + "+t.message)}},qt=e=>{if(!e?.id)return null;try{return Vd(e.id)}catch{return null}};import _f from"zod";import Bf from"node:crypto";import fr from"node:fs";import Gd from"node:path";var xt=500,Ff=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Dn=(e,t)=>`${e}.${t}`,Uf=e=>Ff.test(e),Kd=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"):a(`Unsupported image format. Allowed: ${Qa.join(", ")}`),zd=e=>Bf.createHash("sha256").update(e).digest("hex"),Of=(e,t=xt)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Kd(e);return d(n)?n:u("Validated attachment data",{hash:zd(e),ext:n.value,bytes:e.length})},qd=(e,t,n=xt)=>{let r=Of(t,n);if(d(r))return r;let o=nr(e),s=Gd.join(o,Dn(r.value.hash,r.value.ext));try{fr.existsSync(s)||(fr.mkdirSync(o,{recursive:!0}),fr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},Yd=(e,t,n=xt)=>{if(!Uf(t))return a("Invalid attachment file name");let r=Gd.join(nr(e),t);if(!fr.existsSync(r))return a("Attachment blob not found");let o;try{o=fr.readFileSync(r)}catch(l){return a(`Unable to read attachment blob: ${l instanceof Error?l.message:String(l)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(zd(o)!==s)return a("Attachment blob does not match its content hash");let c=Kd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var gr=50,vr=5e3,Xd=()=>{let e=X().commandMeta.inputString,t=_f.coerce.number().int().min(gr).max(vr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${gr}-${vr} KB (default ${xt})`);let n=Qe({attachmentMaxKb:t.data});return d(n)?n:(Me({attachmentMaxKb:t.data}),C({mode:y.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import Jd from"chalk";var te=e=>Jd.dim(e),Ee=e=>Jd.hex(h.primary)(e),Se=({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)=>ro(f)-ro(g)).slice(0,r).map(f=>oo(f)).join(" ");return p?`${te(e)}${p}${te(n)}`:""};var bt={None:"none",Invalid:"invalid",Valid:"valid"};var $f=["BOARD","TICKET","SWIMLANE"],Qd=()=>{let e=v().selectedNode;if(!e?.context)return O({message:te("Missing target context")});if($f.includes(e.context))return G();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Ie(t?.parentNodeId??"","comments"))return G()}return O({message:te("Command not available in this context")})},oe="<ENTER> to confirm",G=(e="",t=[])=>({message:te(e),validity:bt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:bt.Invalid,message:e,completionWordList:t}),Ro=e=>e.length===0,Zd=(e,t)=>{let n=Oe(v().breadCrumb,"BOARD");if(d(n))return O({message:Ee("Command is not applicable in this context")});let r=Co(n.value.id);return d(r)?O({message:Ee(`Unable to ${t}: board id is not a valid ULID`)}):_d({date:e,horizonDate:r.value})?null:O({message:Ee(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},No=e=>` ${ec.hex("#000").bgHex(ue(e))(` ${e} `)} `,ai=({modifier:e})=>{let t="confirm";return e===t?G(oe):O({message:Ro(e)?te("if you are certain, enter ")+oo(t):"",completionWordList:[t]})},Hf=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:te(n)}):G():O({message:Ro(r)?t:"",completionWordList:[...e]}),hn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Ro(n)&&Ro(r)?O({message:e,completionWordList:[]}):G(t??oe),jf=({modifier:e,inputString:t})=>{let n=ie(b.CONFIG);if(!n.includes(e))return O({message:Se({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case re.EDITOR:{let r=[...Wd];return t.trim()?r.includes(t.trim())?G(oe):O({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?G(oe):O({message:Se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.USERNAME:return t.trim()?G(oe):O({message:Ee("Enter a user name. Saved in ")+ec.bgBlack("~/.epiq-global/config.json")});case re.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?G(oe):O({message:Se({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case re.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=Fd(o);return O({message:Se({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return G(oe)}case re.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<gr||o>vr){let s=Se({prefix:" examples: ",wordList:ii,minLengthForHints:0,inputString:t});return O({message:Ee(`provide a size cap in KB (${gr}-${vr}). current: ${r??xt} KB.`)+s,completionWordList:ii})}return G(oe)}case re.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=Ld(t);if(!t.trim()||o===null||o<kn){let s=Se({prefix:" examples: ",wordList:si,minLengthForHints:0,inputString:t});return O({message:Ee(`provide duration above ${kn}ms. current duration: ${r}ms.`)+s,completionWordList:si})}return G(oe)}default:return O({message:Ee("Unknown config option"),completionWordList:n})}},Wf=({modifier:e,inputString:t})=>{let n=ie(b.EDIT);if(!n.length)return O({message:Ee("Command not available in this context")});if(!n.includes(e)){let r=Se({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:r||Ee("Unknown edit option"),completionWordList:n})}switch(e){case Ke.COMMENT:return t.trim()?G(oe):O({message:te("write a comment...")});case Ke.TITLE:return G(oe);case Ke.DESCRIPTION:{let{preferredEditor:r}=K();return r?G(te("<ENTER> to edit in ")+r):O({message:"No editor selected"})}default:return O({message:Ee("Unknown edit option"),completionWordList:n})}},Vf=({modifier:e})=>{let t=ie(b.YANK);return t.length?t.includes(e)?G(oe+te(" and copy to clipboard")):O({message:Se({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ee("Nothing selected to copy from")})},Gf={[b.EXPORT]:()=>G(oe+te(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return G(oe);let n={message:te("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=vn(r);if(!r||!o)return O(n);let s=Zd(o,"peek");return s||G(oe)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Eo(e.modifier,e.inputString),r={message:te("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=vn(t);if(!t||!o)return O(r);let s=Zd(o,"replay");return s||(n&&Io(n)===null?O({message:Ee("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):G("<ENTER> to replay board history",n?jd:[]))},[b.EXIT]:()=>G(oe+te(" and exit the application")),[b.INIT]:()=>G(oe),[b.PALETTE]:()=>G(oe),[b.FILTER]:e=>{if(e.modifier==="clear")return G(oe);let t=s=>ie(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:Se({wordList:ie(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ie(b.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())?O({message:Se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):G():O({message:Se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=ie(b.NONE);return O({message:Se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>Hf({list:ie(b.NEW),hint:Se({wordList:ie(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>G(oe),[b.EDIT]:Wf,[b.COMMENT]:e=>{let t=hn({hint:te(`write a comment (max ${4e3} char)...`),onOk:te(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===bt.Invalid?t:e.inputString.length>4e3?G(Ee("max input exceeded")):t},[b.CONFIG]:jf,[b.YANK]:Vf,[b.DELETE]:e=>{let t=Qd();return t.validity==="invalid"?t:ai(e)},[b.CLOSE_ISSUE]:e=>ai(e),[b.RE_OPEN_ISSUE]:e=>ai(e),[b.MOVE]:e=>{let t=Qd();return t.validity==="invalid"?t:hn({hint:Se({prefix:"hey hacker! These commands are blocked for you... ",wordList:ie(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(No).join("");return hn({hint:n.length?te("create tag or reuse:")+n+te(""):te("create tag ...")})(e)},[b.UNTAG]:e=>{let t=xo();if(d(t))return O({message:Ee("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(No).slice(0,10);return n.length?hn({hint:te(" ... ")+n.join("")})(e):O({message:Ee("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=E.getExistingAssignees().map(No).slice(0,10);return hn({hint:te("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=bo();if(d(t))return O({message:Ee("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(No).slice(0,10);return n.length?hn({hint:te("remove assignee... ")+n.join("")})(e):O({message:Ee("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>G(oe),[b.COFFEE]:e=>{let{modifier:t}=e,n=ie(b.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:te("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):hn({hint:Se({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},tc=Object.fromEntries(Object.entries(Gf).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ao=["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 Kf=3,zf=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"]),qf=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},Yf=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Kf&&!zf.has(t)&&!/^\d+$/.test(t)),Xf=e=>{let t=new Map;for(let s of qf(e))for(let i of Yf(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=Ao.filter(s=>!r.has(s));return[...n,...o]},nc=Ao,rc=-1,oc=()=>{let e=We();if(d(e))return Ao;let t=e.value,n=t.eventLog.length;return n!==rc&&(nc=Xf(t),rc=n),nc};var sc=e=>Object.values(b).includes(e),ic=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:l}=tc[n].validate(n,r,s),m=n!==b.PEEK&&n!==b.REPLAY,p=o==="command"||o==="modifier"?ie(n):m?oc():[],{mode:f}=v(),g=f===y.COMMAND_LINE?i??"":"",I=[...l,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Ya(e,I):{hint:"",hints:[],remainder:"",overlap:0}}};var ac=e=>{let t=e.trimStart(),n=Qf(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=Zf(e),c=sc(r)?r:null,l=c!==null,m=r!=="",p=c?ie(c)??[]:[],f=c&&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 I=s?"":i,S=Jf(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:l,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:I,inputString:S}},Jf=(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},Qf=e=>e.trim()?e.trim().split(/\s+/):[],Zf=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as eg}from"react";var Bn=e=>e===di||e===":",di=" ",Le={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:bt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ci=new Set,dc=()=>{for(let e of ci)e()},li=e=>(ci.add(e),()=>ci.delete(e)),It=e=>{let n=e(Le),r=ac(n.value),o=n.cursorPosition===n.value.length;Le={...n,commandMeta:ic(r,o)},dc()},yr=({message:e,status:t})=>{let n=structuredClone(Le);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Le=n,dc(),u(e,null)},ui=e=>{It(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},mi=e=>{It(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Bn(n[o-1]);)o--;for(;o>0&&!Bn(n[o-1]);)o--}else{for(;o<n.length&&!Bn(n[o]);)o++;for(;o<n.length&&Bn(n[o]);)o++}return{...t,cursorPosition:o}})},cc=()=>{It(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}})},lc=()=>{It(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Bn(t[r-1]);)r--;for(;r>0&&!Bn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},To=e=>{It(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}})},uc=()=>{It(e=>({...e,commandIsPending:!0}))},V=e=>{It(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},mc=({addToHistory:e=!0})=>{It(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},pc=()=>{It(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}})},fc=()=>{It(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},X=()=>Le,gc=()=>eg(li,X,X),vc=()=>{let[e,...t]=Le.value.split(di);return t.join(di).trim()};var x={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function tg(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function ng(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function rg(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 yc(e,t){let n=X();if(e.sequence==="?"&&t!==y.PALETTE)return x.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return x.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===y.COMMAND_LINE)return ja(e,n.value);if(t===y.PALETTE)return Wa(e,n.value);let r=tg(e)||ng(e);if(r)return og(r,t);if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"r":return x.EditTitle;case"e":return x.EditDescription;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"y":return x.Yank;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return K().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;default:return null}}function og(e,t){let n=t===y.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return rg(v().contextNode.childRenderAxis,e,n)}var wo=e=>{let{context:t}=v().contextNode;if(!t)return k.None;switch(e){case b.EXIT:return k.Exit;case b.EXPORT:return k.Export;case b.COFFEE:return k.Coffee;case b.INIT:return k.Init;case b.DELETE:return k.Delete;case b.EDIT:return k.Edit;case b.COMMENT:return k.Comment;case b.HELP:return k.ViewHelp;case b.RE_OPEN_ISSUE:return k.ReopenIssue;case b.CLOSE_ISSUE:return k.CloseIssue;case b.TAG:return k.TagTicket;case b.UNTAG:return k.UntagTicket;case b.ASSIGN:return k.AssignUserToTicket;case b.UNASSIGN:return k.UnassignUserFromTicket;case b.NEW:return k.NewItem;case b.FILTER:return k.Filter;case b.MOVE:return k.Move;case b.PEEK:return k.Peek;case b.REPLAY:return k.Replay;case b.CONFIG:return k.Config;case b.YANK:return k.Yank;case b.SYNC:return k.Sync;default:return k.None}},k={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as Be}from"ulid";import $c from"node:fs";import qg from"node:path";import Yg from"react";import{Box as Kg}from"ink";import Fo from"react";import bg from"chalk";import{Box as fi,Text as Ig}from"ink";import Et from"react";import{Text as hc}from"ink";import xc,{useEffect as bc,useState as sg}from"react";var Ic={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ke=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=j(),r=Ic[n]??Ic.default,[o,s]=sg(0);if(bc(()=>{s(0)},[r]),bc(()=>{if(!e)return;let c=setInterval(()=>{s(l=>(l+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return xc.createElement(hc,null,t);let i=r[o]??r[0]??t;return xc.createElement(hc,{color:h.accent,dimColor:o===1},i)};import{Box as pi,Text as ig}from"ink";import Mo from"react";var tt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),l=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,l-c+1)):Math.min(m,Math.floor(l/c)*c),f=p+c,g=e.slice(p,f),I=e.length>c,S=s,R=I?Math.max(1,Math.floor(c/e.length*S)):S,A=Math.max(0,S-R),P=Math.max(1,e.length-c),_=I?Math.floor(p/P*A):0;return Mo.createElement(pi,{flexDirection:"row",height:s,width:"100%"},Mo.createElement(pi,{flexDirection:"column",flexGrow:1,height:s},g),Mo.createElement(pi,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((w,W)=>Mo.createElement(ig,{key:W,color:I&&W>=_&&W<_+R?h.accent:h.secondary},I?"\u2502":" "))))};import{Box as _n,Text as ko}from"ink";import nt from"react";import{Text as ag}from"ink";import dg from"react";var Fn=(e,t)=>t?e&&cr(e)===t?e:t:e,Ec,Po,Sc=()=>{let{eventLog:e=[]}=v();if(Po&&Ec===e)return Po;let t=new Map,n=new Set;for(let r of e)r?.userId&&(n.add(r.userId),r.userName&&t.set(r.userId,r.userName));return Ec=e,Po={latestNames:t,authors:n},Po},Yt=(e,t)=>{let{contributors:n={}}=v();return n[e]?.tombstoned?t:Fn(t,Sc().latestNames.get(e))??t},Cc=e=>Sc().authors.has(e);var cg=e=>e.toLowerCase().trim(),lg=(e,t=wn)=>{let n=cg(e);return t[n]?t[n]:ar(n)},Xt=({id:e,isSelected:t})=>{let n=E.getContributor(e);if(!n)return;let r=Yt(e,n.name);return dg.createElement(ag,{underline:t,color:lg(r)},"@"+r,Cc(e)?"":"\u2197")};import{Text as ug}from"ink";import mg from"react";var Un=({id:e,isSelected:t})=>{let n=E.getTag(e);if(n)return mg.createElement(ug,{underline:t,backgroundColor:ue(n.name),color:h.secondary}," "+n.name+" ")};import{useEffect as pg,useState as fg}from"react";var gg=80,Nc=1400,Lo=new Set,hr=null,vg=e=>(Lo.add(e),hr||(hr=setInterval(()=>{for(let t of Lo)t()},gg)),()=>{Lo.delete(e),Lo.size===0&&hr&&(clearInterval(hr),hr=null)}),yg=()=>{let e=Date.now()%Nc/Nc;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=fg(0);return pg(()=>{if(e)return vg(()=>t(n=>n+1))},[e]),no(yg())};var hg=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),un(e.slice(r).trim(),t)]},Rc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=On(r),s=e-4,[i,c]=hg(Ze(t.title),s),l=c?null:un(Ze(t.props.description),s)||null,m=Kt(t),p=zt(t);return nt.createElement(_n,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?h.accent:h.secondary,justifyContent:"space-between"},nt.createElement(_n,{paddingLeft:1,flexDirection:"column"},nt.createElement(ko,{color:h.primary},i),c&&nt.createElement(ko,{color:h.primary},c),l&&nt.createElement(ko,{color:h.secondary2,dimColor:!0},l)),nt.createElement(_n,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},nt.createElement(_n,{flexDirection:"row"},m.map(f=>nt.createElement(_n,{paddingRight:1,key:f.id},nt.createElement(Un,{key:f.id,id:f.id}))),p.map(f=>nt.createElement(_n,{paddingRight:1,key:f.id},nt.createElement(Xt,{key:f.id,id:f.id})))),nt.createElement(ko,{wrap:"truncate",color:h.secondary2,dimColor:!0},He(t.id))))};import{Box as xn,Text as xr}from"ink";import ze from"react";var xg=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ac=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=On(r),c=(t.props.tags??[]).map(w=>E.getTag(w)).filter(w=>!!w),l=(t.props.assignees??[]).map(w=>E.getContributor(w)).map(w=>w&&{...w,name:Yt(w.id,w.name)}).filter(w=>!!w),m=1,p=c.length*(1+m),f=l.length*(2+m),g=c.map(w=>ze.createElement(xn,{key:w.id,paddingRight:m},ze.createElement(xr,{color:ue(w.name)},"\u25A0"))),I=l.map(w=>ze.createElement(xn,{key:w.id,paddingRight:m},ze.createElement(xr,{color:ar(w.name)},"@"+w.name.at(0)))),S=r?i:n?h.accent:s===y.MOVE?h.secondary:h.primary,R=4,A=E.getCommentsByIssue(t.id),P=A.length?String(A.length).length+2+m:0,_=A.length?ze.createElement(xn,{paddingRight:m},ze.createElement(xr,{color:h.accent},"[",A.length,"]")):null;return ze.createElement(xn,{borderBottom:!0,justifyContent:"space-between"},ze.createElement(xn,null,ze.createElement(xn,{width:R},n?ze.createElement(ke,{isSelected:n}):ze.createElement(xr,{color:"gray",dimColor:!0},o+1)),ze.createElement(xr,{wrap:"truncate",color:S},xg(t.title,e-p-f-P-18))),ze.createElement(xn,null,g,I,_))};var Eg=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:l,replay:m}=j(),p=l[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,I=On(g),S=`${e.title} ${bg.hex(h.secondary2).dim("("+p.length+")")}`,R=3,A=o?1:5,P=s&&i===-1,_=n-(P?7:5),w=r-R-(o?2:1),W=Et.createElement(fi,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Et.createElement(ke,{isSelected:t}),Et.createElement(Ig,{bold:!0,color:g?I:t?h.accent:h.primary},S," ",e.readonly?"\u{1F512}":"")),H=(D,$)=>{let Ye=s&&i===$;if(!T(D))return null;let we=f?.has(D.id)??!1;return o?Et.createElement(Ac,{key:D.id,index:$,width:n,ticket:D,isSelected:Ye,isFlashing:we,mode:c}):Et.createElement(Rc,{key:D.id,width:_,ticket:D,isSelected:Ye,isFlashing:we})};return Et.createElement(fi,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},W,Et.createElement(fi,{padding:o?1:0},p.length>0&&Et.createElement(tt,{selectedIndex:i,height:w,itemHeight:A},p.map(H)),P&&Et.createElement(ke,{isSelected:!0})))},Tc=Et.memo(Eg);import{Box as bn,Text as bi}from"ink";import Ce,{useMemo as br}from"react";var wc=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},Mc=(e,t,n)=>ee.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as $n,Text as Mt}from"ink";import De,{useEffect as Sg,useMemo as Cg,useRef as Ng}from"react";import{decodeTime as gi}from"ulid";var Rg=e=>Ie(e,"attachments"),Ag=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>gi(t.id)-gi(n.id)),Pc=e=>{for(let t of e)E.deleteNode(t.id)},Tg=(e,t,n)=>ee.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),wg=(e,t)=>{let n=E.getNode(Rg(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Tg(o,s,n.id)).map(o=>E.createNode(o)).filter(Q).map(({value:o})=>o).filter(Ve);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Mg=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Lc({ticket:e,width:t,height:n}){let r=Cg(()=>Ag(e),[e]),o=Ng([]);Sg(()=>(Pc(o.current),o.current=wg(e,r),()=>{Pc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(12,t-32);return r.length===0?De.createElement($n,{flexDirection:"column",width:t,height:n,padding:1},De.createElement(Mt,{color:h.primary},"No attachments yet."),De.createElement($n,{paddingTop:1},De.createElement(Mt,{color:h.primary},"Attach images from the browser GUI"),De.createElement(Mt,{color:h.accent}," epiq gui "),De.createElement(Mt,{color:h.primary},"by dropping or pasting them."))):De.createElement($n,{flexDirection:"column",width:t,height:n},De.createElement($n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},De.createElement(Mt,{color:h.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),De.createElement(tt,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>l?m.name.slice(0,l-1)+"\u2026":m.name;return De.createElement($n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},De.createElement(Mt,{color:h.accent},f?"\u276F ":" "),De.createElement($n,{paddingLeft:1},De.createElement(Mt,{color:h.secondary2},`#${p+1} `),De.createElement(Mt,{color:f?h.accent:h.primary},g),De.createElement(Mt,{color:h.secondary2}," "+Mg(m.bytes)+" "+Pn(gi(m.id)))))})))}import{Box as Jt,Text as Pt}from"ink";import he,{useEffect as Pg,useMemo as Lg,useRef as kg}from"react";import{decodeTime as vi}from"ulid";var Dg=e=>Ie(e,"comments"),Bg=e=>E.getCommentsByIssue(e.id).sort((t,n)=>vi(t.id)-vi(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),kc=e=>{for(let t of e)E.deleteNode(t.id)},Fg=(e,t)=>{let n=E.getNode(Dg(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Mc(o,s,n.id)).map(E.createNode).filter(Q).map(({value:o})=>o).filter(ir);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Ug=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Dc({ticket:e,width:t,height:n}){let r=Lg(()=>Bg(e),[e]),o=kg([]);Pg(()=>(kc(o.current),o.current=Fg(e,r),()=>{kc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(20,t-8);return r.length===0?he.createElement(Jt,{flexDirection:"column",width:t,height:n,padding:1},he.createElement(Pt,{color:h.primary},"No comments yet."),he.createElement(Jt,{paddingTop:1},he.createElement(Pt,{color:h.primary},"Use"),he.createElement(Pt,{color:h.accent}," :comment "),he.createElement(Pt,{color:h.primary},"to add the first one."))):he.createElement(Jt,{flexDirection:"column",width:t,height:n},he.createElement(Jt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},he.createElement(Pt,{color:h.secondary2},"Comments (",r.length,") ")),he.createElement(tt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return he.createElement(Jt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},he.createElement(Jt,{flexDirection:"row",paddingBottom:1},he.createElement(Pt,{color:h.accent},f?"\u276F ":" "),he.createElement(Jt,{paddingLeft:1},he.createElement(Pt,{color:h.secondary2},`#${p+1} `),he.createElement(Xt,{id:m.authorId}),he.createElement(Pt,{color:h.secondary2}," "+Pn(vi(m.id))))),he.createElement(Jt,{paddingLeft:3,paddingBottom:1},he.createElement(Pt,{color:h.primary},Ug(m.md,l))))})))}import{Box as Do,Text as Og}from"ink";import Lt from"react";var Bc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=j(),{title:o}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,i=s&&T(s)?o===Z.ASSIGNEES?s.props.assignees??[]:o===Z.TAGS?s.props.tags??[]:[]:[];return Lt.createElement(Do,{alignItems:"center",paddingTop:1},Lt.createElement(Do,{minWidth:12},Lt.createElement(ke,{isSelected:n}),Lt.createElement(Og,{color:n?h.accent:h.secondary2},o,":")),Lt.createElement(Do,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,l)=>{let m=r.id===t.id&&l===e;return Lt.createElement(Do,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Lt.createElement(ke,{isSelected:m}),o===Z.ASSIGNEES?Lt.createElement(Xt,{isSelected:m,id:c}):o===Z.TAGS?Lt.createElement(Un,{isSelected:m,id:c}):null)})))};import{Box as Bo,Text as yi}from"ink";import kt,{useEffect as _g,useMemo as Fc}from"react";var $g="\u2029",Uc=(e,t)=>`${e}::inline-line::${t}`,hi=new Map,Oc=e=>{let t=hi.get(e)??[];hi.delete(e);for(let n of t)E.deleteNode(n)},Hg=(e,t)=>{Oc(e);let n=[];t.forEach((r,o)=>{let s=Ge(BigInt(o+1));if(!Q(s))return;let i=E.createNode(ee.text({id:Uc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));Q(i)&&n.push(i.value.id)}),hi.set(e,n)},xi=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=j(),l=Fc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Fc(()=>l.join("\0"),[l]);_g(()=>(Hg(e,l),()=>{Oc(e)}),[e,m]);let p=g=>String(g).replace(/\r?\n/g,""),f=l.map((g,I)=>{let S=c.id===e&&i===I;return kt.createElement(Bo,{key:Uc(e,I)},kt.createElement(yi,{color:S?h.primary:h.secondary2,dimColor:!S},`${I+1} `.padStart(5,"\xA0")),kt.createElement(yi,{backgroundColor:S?"gray":void 0},p(g.length?un(g,s-10):$g)))});return kt.createElement(Bo,{flexDirection:"column",paddingTop:1},kt.createElement(Bo,null,kt.createElement(ke,{isSelected:o}),kt.createElement(yi,{color:o?h.accent:h.secondary2},t)),kt.createElement(Bo,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},kt.createElement(tt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var jg=e=>Ie(e,"description"),Wg=e=>Ie(e,"comments"),Vg=e=>Ie(e,"history"),Gg=e=>Ie(e,"attachments"),_c=({ticket:e,height:t})=>{let n=br(()=>wc(e),[e]),{selectedIndex:r,contextNode:o}=j(),s=process.stdout.columns||120,i=br(()=>jg(e.id),[e.id]),c=br(()=>Wg(e.id),[e.id]),l=br(()=>Vg(e.id),[e.id]),m=br(()=>Gg(e.id),[e.id]),p=E.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===c||o.parentNodeId===c,I=o.id===l||o.parentNodeId===l,S=o.id===m||o.parentNodeId===m,R=z(e.id);if(g){let $=t-3;return Ce.createElement(bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(Dc,{ticket:e,width:s,height:$}))}if(S){let $=t-3;return Ce.createElement(bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(Lc,{ticket:e,width:s,height:$}))}if(I){let D=E.getNode(l),$=D&&Ve(D)?D.props.value??"":"",we=t-3;return Ce.createElement(bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},D?Ce.createElement(xi,{id:D.id,label:"Event log",text:$,selected:!1,maxWidth:s,height:we}):null)}let A=R.reduce((D,$)=>sr($)||$.id===c||$.id===m||$.id===l?D+1:D,0),P=2,_=3,w=A,W=t-_-w-P,H=(D,$)=>D.id===i?Ce.createElement(xi,{key:D.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,height:W}):sr(D)?Ce.createElement(Bc,{key:D.id,parent:D,selected:$,selectedIndex:r}):D.id===c?Ce.createElement(bn,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(bi,{backgroundColor:h.secondary,color:$?h.accent:h.primary},` Comments (${n}) \u203A\u203A `)):D.id===m?Ce.createElement(bn,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(bi,{backgroundColor:h.secondary,color:$?h.accent:h.primary},` Attachments (${p}) \u203A\u203A `)):D.id===l?Ce.createElement(bn,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(bi,{backgroundColor:h.secondary,color:$?h.accent:h.primary}," History \u203A\u203A ")):null;return Ce.createElement(bn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((D,$)=>H(D,f&&r===$)))};var zg=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let l=t.context,m=l===B.TICKET||l===B.FIELD_LIST||l===B.FIELD,p=l===B.BOARD||l===B.SWIMLANE,f=l===B.TICKET?t:r.find(A=>A.context===B.TICKET),g=Math.floor(c/3),I=Math.floor(c/Math.max(e.length,1)),S=Math.min(I,g),R=s==="dense";return Fo.createElement(Kg,{flexDirection:"row",height:i},p&&e.map((A,P)=>{let _=t.id===A.id,w=_?n:-1,W=t.context===B.BOARD&&n===P;return Fo.createElement(Tc,{key:A.id,height:i,width:S,swimlane:A,isSelected:W,isDense:R,isFocused:_,listSelectedIndex:w,mode:o})}),m&&f&&Fo.createElement(_c,{height:i,ticket:f}))},Uo=Fo.memo(zg);import{render as Xg}from"ink";import{Writable as Jg}from"node:stream";var Ir=e=>String(e).padStart(2,"0"),Qg=e=>{let t=e.getUTCFullYear(),n=Ir(e.getUTCMonth()+1),r=Ir(e.getUTCDate()),o=Ir(e.getUTCHours()),s=Ir(e.getUTCMinutes()),i=Ir(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},Zg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",ev=async(e,{width:t,height:n})=>{let r="",o=new Jg({write(i,c,l){let m=tv(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),l()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Xg(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},tv=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Hc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(P=>P.context==="BOARD");if(!i)return a("No board found to export");let c=120,l=40,m=await ev(Yg.createElement(Uo,{height:l,width:c,swimlanes:(s[i.id]??[]).filter(P=>P!==void 0&&$t(P)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:l});if(!m)return a("Failed to render board export");let p=_r(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=Qg(f),I=`board_${Zg(i.title)}_${g}.md`,S=Sa(p.value);$c.mkdirSync(S,{recursive:!0});let R=qg.join(S,I),A=`# Board - ${i.title}
|
|
47
47
|
Date: ${f.toISOString()}
|
|
48
48
|
|
|
49
49
|
\`\`\`text
|
|
50
50
|
${m}
|
|
51
51
|
\`\`\`
|
|
52
|
-
`;return $c.writeFileSync(R,A,"utf8"),u("Exported board layout",R)};var Oo=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as
|
|
52
|
+
`;return $c.writeFileSync(R,A,"utf8"),u("Exported board layout",R)};var Oo=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as wT}from"react";var _o,nv=new Set,jc=()=>{for(let e of nv)e()};var Qt=()=>{if(!_o)throw new Error("Ui state not initialized. Call initUiState() first.");return _o};var Wc=(e={})=>(_o=e,jc(),u("UX state initialized",null)),rv=e=>{let t=Qt();return _o=e(t),jc(),u("UX state updated",null)},Zt=e=>rv(t=>({...t,...e}));import{spawn as ov}from"node:child_process";function Er(e){let t=process.platform,o=ov(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as Ci}from"ulid";import{spawn as sv,spawnSync as iv}from"node:child_process";import av from"node:os";import Vc from"node:path";import{ulid as dv}from"ulid";function Ii(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 cv(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function $o(){let{preferredEditor:e}=K(),t=[e?cv(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Ei(e){let[t=""]=Ii(e);return/(^|\/)code(-insiders)?$/.test(t)}function Gc(e,t){let[n="",...r]=Ii(e);return{command:n,args:[...r,...t]}}function Kc(e,t){return Gc(e,Ei(e)?["--wait",t]:[t])}function lv(e,t,n,r="new"){return Gc(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function zc(e){let t=Vc.join(av.tmpdir(),"epiq");be.mkDir(t);let n=Vc.join(t,dv());be.writeToFile(n,e??"");let r=$o();for(let o of r){let{command:s,args:i}=Kc(o,n);if(!s)continue;let c=iv(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let l=be.readFile(n);if(l==null)return a("Unable to read edited file");let m=l.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return a("Unable to open editor")}var uv=new Set(["vim","vi","nvim","nano","pico","ed"]);function mv(e){let[t=""]=Ii(e),n=t.split("/").pop()??t;return uv.has(n)}var pv=600;function qc({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=sv(e,t,{stdio:"ignore",detached:!0}),s=!1,i=l=>{s||(s=!0,clearTimeout(c),r(l))};o.on("error",l=>i(a(l.message))),o.on("exit",l=>{i(l===0?u("Opened editor",!0):a(`"${n}" exited with code ${l}`))});let c=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},pv)})}function fv(e,t){return mv(e)?Promise.resolve(a(`"${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}`)):qc(Kc(e,t),e)}function Si(e,t,n,r="new"){return qc(lv(e,t,n,r),e)}async function Yc(e){let t=$o();if(t.length===0)return a("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=a("Unable to open editor");for(let r of t){let o=await fv(r,e);if(!d(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var Xc=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(e.modifier===Ke.DESCRIPTION)return vv();if(r&&ir(r))return gv(e);if(e.modifier===Ke.TITLE){let o=se();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await yt();return d(c)?c:U([{id:Ci(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},gv=async e=>{let t=se();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=z(n.id)[r];if(!o||!ir(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=v().nodes[s];if(!i||!T(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",l=E.getComment(c);if(!l||l.deleted)return a("Unable to resolve comment");if(l.issue!==i.id)return a("Comment does not belong to selected issue");if(l.authorId!==t.value.userId)return a("You can only edit your own comments"+l.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await yt();if(d(p))return p;let f=p.value;return U([{id:Ci(),action:"edit.issue.comment",payload:{id:l.id,issue:i.id,md:m},...t.value}],f)},vv=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let t=await yt();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=Oe([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!T(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=z(i.id).find(f=>f.title===Z.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let l=i.props.description??"";if(typeof l!="string")return a("Selected field is not editable text");let m=zc(l);if(d(m))return a("Failed to edit field");let p=m.value;return p===l?u("No changes made",null):U([{id:Ci(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import hv from"node:fs";import Qc from"node:path";import Ni from"node:fs";import yv from"node:path";var Jc=async e=>{let t=yv.join(e,".gitignore"),n=Ni.existsSync(t)?Ni.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
53
53
|
`).map(l=>l.trim()),s=r.filter(l=>!o.some(m=>m===l||m===l.replace(/\/$/,"")||m==="/"+l||m==="/"+l.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
54
54
|
`);return n=n.trimEnd()+`
|
|
55
55
|
|
|
56
56
|
${c}
|
|
57
|
-
`,Ni.writeFileSync(t,n,"utf8"),
|
|
58
|
-
`));let me=We();if(d(me))return ne(16,me.message);let{rootNodeId:Gn,nodes:Kn}=me.value,na=Kn[Gn];return na?(M.navigate({contextNode:na,selectedIndex:0}),C({hasProjectDefinition:!0,mode:y.DEFAULT}),u($,null)):ne(16,"Unable to resolve initialized root node")};import{ulid as bv}from"ulid";import{ulid as xv}from"ulid";var el=null,Zt=()=>structuredClone(el),Cr=e=>{el=e},tl=()=>{let{contextNode:e,selectedIndex:t}=v(),r=Y(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},Ri=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Y(t).filter(o=>o.id!==e);return po(r,n)},nl=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ie();if(d(r))return a("Unable to resolve user ID");let o=Ri({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:xv(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},rl=e=>{Cr(e);let t=jt(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function Ai(e){let t=tl();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=Y(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let l=nl({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(l)?l:rl(l.value)}function Ti(e){let t=tl();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),s=Y(n.id)[r+e];if(!s)return a("Missing sibling node");let i=nl({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:rl(i.value)}var ol=()=>{let e=Zt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=Y(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Ho=(e,t="Moved preview")=>{if(d(e))return e;let n=ol();return d(n)?n:(C({mode:y.MOVE}),u(t,null))},sl=async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=X().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=Y(n.id)[r];if(!o)return C({mode:y.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=Y(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],l=s[i+1],m=l!=null?{at:"before",sibling:l.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Ri({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Cr({id:bv(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:y.MOVE}),u("Move initialized",null))}if(t==="next")return Ho(Ti(1));if(t==="previous")return Ho(Ti(-1));if(t==="to-next")return Ho(Ai(1));if(t==="to-previous")return Ho(Ai(-1));if(t==="confirm"){let s=Zt();if(!s)return a("No pending move to confirm");let i=await yt();if(d(i))return i;let c=U([s],i.value);if(d(c))return c;let l=ol();return d(l)?l:(Cr(null),C({mode:y.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Cr(null),C({mode:y.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Wo}from"ulid";import{monotonicFactory as Iv,ulid as Ev}from"ulid";var Sv=Iv(),jo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Sv();return u("Created issue events",[{id:Ev(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var il=async(e,t)=>{let n=ie();if(d(n))return a("Unable to resolve user ID");let r=await yt();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=v(),l=m=>{let p=U([m],o);if(d(p))return p;let f=E.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=E.getNode(f.parentNodeId);return g?(M.navigate({contextNode:g,selectedIndex:E.getSiblings(f.parentNodeId).findIndex(({id:I})=>I===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=E.getNode(m);if(!p)return a("Workspace not found");let f=Pn(p.id,n.value,o);return d(f)?f:l({id:Wo(),action:"add.board",payload:{id:Wo(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Ue(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Pn(m.value.id,n.value,o);return d(p)?p:l({id:Wo(),action:"add.swimlane",payload:{id:Wo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=z(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let _=Ue(s,"SWIMLANE");return d(_)?null:_.value})();if(!p)return a("Unable to add issue in this context");let f=Pn(p.id,n.value,o);if(d(f))return f;let g=jo({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let I=g.value,S=U([...I],o);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let P=I.find(_=>_.action==="add.issue")?.payload.id;return P?(M.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:_})=>_===P)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};var Vo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=uo(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,l=it();if(d(l))return l;let p=st(i).filter(d);if(p.length>0)return it(),C(o),a(p.map(g=>g.message).join(", "));let f=v().nodes[e];return f?(M.navigate({contextNode:f,selectedIndex:r}),u("",{unappliedEvents:c})):(it(),C(o),a("Board did not exist at that date"))};var Cv=20,Nv=16,Rv=150,Go=null,Ko=null;var bn=()=>{Go!==null&&(clearInterval(Go),Go=null),Ko!==null&&(clearTimeout(Ko),Ko=null)},al=()=>{bn(),C({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Av=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)},dl=({events:e,startTime:t,durationMs:n})=>{bn();let r=e.length,o=e.map(f=>zt(f)??t),s=o[r-1]??Date.now(),i=Av(o),c=Math.max(1,Math.round(n*Cv/1e3)),l=Math.max(Math.round(n/c),Nv),m=0,p=0;C({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Go=setInterval(()=>{m++;let f=m/c,g=[],I;for(;p<r&&i[p]<=f;){let R=e[p],A=jt(R);if(d(A)){al();return}g.push(...qs(R)),I=R,p++}if(p>=r||m>=c){for(;p<r;p++){let A=jt(e[p]);if(d(A))break}let R=v().replay;C({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),bn(),Ko=setTimeout(al,Rv);return}let S=v().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:I?zt(I)??S?.currentTime??t:S?.currentTime??t,currentLabel:I?cd(I):S?.currentLabel??"",flashNodeIds:I?[...new Set(g)]:S?.flashNodeIds??[]}})},l)};var cl=async()=>{let e=Ue(v().breadCrumb,"BOARD");if(d(e))return e;let t=await gt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta;if(bn(),r==="now"){let c=je(n.value);if(d(c))return a(c.message);let l=it();if(d(l))return l;let p=st(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(C({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"){let c=v().eventLog.at(-1),l=zt(c);if(l===null)return a("No previous event to peek");s=l}else if(r==="next"){let c=v().unappliedEvents.at(0),l=zt(c);if(l===null)return a("No next event to peek");s=l+1}else{let c=gn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Vo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var ll=async()=>{let e=Ue(v().breadCrumb,"BOARD");if(d(e))return e;let t=await gt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta,{dateInput:s,durationInput:i}=Eo(r,o);if(bn(),v().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=gn(s);if(!c)return a("Invalid replay date");let l=i?Io(i):15e3;if(l===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=v(),f=Vo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(it(),C(p),u("Nothing to replay from that point",!0)):(dl({events:g,startTime:m,durationMs:l}),u("Replaying board history",!0))};import wv from"zod";var ul=()=>{let e=X().commandMeta.inputString,t=wv.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=Qe({autoSyncDebounceMs:t.data});return d(n)?n:(Me({autoSyncIntervalMs:t.data}),C({mode:y.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var ml=()=>{let e=X().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ud(e),n=Qe({autoSync:t});return d(n)?n:(Me({autoSync:t}),C({mode:y.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var pl=()=>{let e=X().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Qe({logLevel:e});return d(n)?n:(Me({logLevel:e}),C({mode:y.DEFAULT}),u(`Auto sync set to "${e}"`,null))};import{spawn as Mv}from"node:child_process";var Pv=()=>{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"]}}},fl=async e=>new Promise(t=>{let{command:n,args:r}=Pv();try{let o=Mv(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var Nr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await fl(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},gl=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=fr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case ye.REF:return Nr(He(o.id),"ref");case ye.TITLE:return Nr(o.title,"title");case ye.DESCRIPTION:return r?Nr(r.props?.description??"","description"):a("No issue in scope");case ye.TAGS:{if(!r)return a("No issue in scope");let s=Gt(r).map(({name:i})=>i);return Nr(s.join(", "),"tags")}case ye.ASSIGNEES:{if(!r)return a("No issue in scope");let s=Kt(r).map(({name:i})=>i);return Nr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var vl=async()=>{V(""),C({mode:y.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await vo();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Lv=e=>e.action==="add.issue.comment",yl=e=>Object.values(v().tags).find(t=>t.name===e),hl=()=>{let{eventLog:e=[],contributors:t}=v(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t)){if(o.tombstoned){n.set(o.id,o.name);continue}n.set(o.id,Fn(o.name,n.get(o.id))??o.name)}return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},kt=async()=>{let e=await yt();return d(e)?e:u("Resolved persist root",e.value)},zo=[{systemOnly:!0,intent:k.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:sl},{intent:k.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await kt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=T(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!T(c))return a("Unable to resolve comment issue");let l=c.log?.filter(Lv).find(m=>m.payload.id===s);return l?l.payload.author!==e.value.userId?a("You can only delete your own comments"):U([{id:Be(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return U([{id:Be(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=X().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>ae(b.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),u("Filter updated",null)}},{intent:k.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return Qt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:y.HELP}),u("Viewing help",null)}},{intent:k.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!T(r))return a("Cannot close in this context");let o=v().nodes[ve];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await kt();if(d(s))return s;let i=s.value,c=mn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let l=U([{id:Be(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(l)?l:u("Issue closed",null)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):At(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=v().nodes[ve];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!T(s))return a("Target node is not issue");let c=Oo(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let l=v().nodes[c];if(!l)return a("Previous parent no longer exists");let m=await kt();if(d(m))return m;let p=m.value,f=mn(l.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=U([{id:Be(),action:"reopen.issue",payload:{id:s.id,parent:l.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Zc},{intent:k.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:il,onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=vc();if(!o)return a("Provide a title");let s=await kt();return d(s)?s:U([{id:Be(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=yl(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return a("Invalid untag target");let i=At(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!T(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await kt();return d(m)?m:U([{id:Be(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let s=At(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=await kt();if(d(c))return c;let l=yl(r),m=l?.id??Be();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):U([...l?[]:[{id:Be(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Be(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),l=z(c.id)[i];if(!l)return a("Invalid assign target");let m=At(l.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!T(p))return a("Target node is not issue");let f=await kt();if(d(f))return f;let g=hl(),I=!o&&s.toLowerCase()==="me",S,R;if(I)S=e.value.userId,R=g.find(_=>_.id===S)?.name??e.value.userName;else{let _=g.filter(W=>W.name===s);if(_.length>1)return a(`"${s}" matches ${_.length} contributors (${_.map(W=>W.id).join(", ")}). Assign from the GUI to choose by id.`);let w=_[0];if(!w&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);S=w?.id??Be(),R=w?.name??s}if((p.props.assignees??[]).includes(S))return a("Assignee already assigned");let P=!!v().contributors[S];return U([...P?[]:[{id:Be(),action:"create.contributor",payload:{id:S,name:R},...e.value}],{id:Be(),action:"add.issue.assignee",payload:{id:p.id,assignee:S},...e.value}],f.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ie();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return a("Invalid unassign target");let s=At(o.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=i.props.assignees??[],l=r.toLowerCase()==="me",m=l?c.filter(g=>g===e.value.userId):hl().filter(g=>g.name===r&&c.includes(g.id)).map(g=>g.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(l?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await kt();return d(f)?f:U([{id:Be(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>Dn)return a(`Cannot exceed ${Dn} characters`);let r=ie();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=v(),i=Ue([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let l=c.context==="TICKET"?u("Resolved ticket",c):At(c.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let m=l.value;if(!T(m))return a("Target node is not issue");let p=await kt();return d(p)?p:U([{id:Be(),action:"add.issue.comment",payload:{id:Be(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:vl},{intent:k.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:cl},{intent:k.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:ll},{intent:k.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await Hc();return d(e)?e:(C({mode:y.DEFAULT}),u("Export successful",!0))}},{intent:k.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(M.exit(),u("Exit successful",!0))},{intent:k.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>Xc(t),onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>gl(t),onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case re.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??Be();if(!i||!c)return a("Unable to resolve user name or id");let l=Qe({userName:i,userId:c,preferredEditor:o??""});return d(l)?l:(Me({userName:i,userId:c}),C({mode:y.DEFAULT}),u(`Username set to "${i}"`,null))}case re.EDITOR:{if(!n)return a("No editor provided");let r=Qe({preferredEditor:n});return d(r)?r:(Me({preferredEditor:n}),C({mode:y.DEFAULT}),u(`Editor configuration set to "${n}"`,null))}case re.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Qe({viewMode:n});return d(r)?r:(Me({viewMode:n}),C({mode:y.DEFAULT}),u(`View set to "${n}"`,null))}case re.AUTOSYNC:return ml();case re.LOG_LEVEL:return pl();case re.SYNC_DEBOUNCE_MS:return ul();case re.ATTACHMENT_MAX_KB:return Xd();default:return a("Unknown config command")}}},{intent:k.Coffee,description:"Sponsor the development of Epiq!",mode:y.COMMAND_LINE,action:()=>{let e=X().commandMeta.modifier;return e==="custom"?Sr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Sr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),V(""),u("Thanks you!",null)}}];var kv=new Set(["peek","replay","filter","view-help","yank"]),St=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=X();if(!t)return a("No command to confirm");if(!e&&n===bt.Invalid)return a("Invalid command");let s=wo(t);uc();let{readOnly:i}=v();if(i&&!kv.has(s))return hr({status:Bt.Fail,message:"Command not available in readonly state",value:null});let c=zo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return hr({status:Bt.Fail,message:"Command not found",value:null});let l;try{l=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return hr({status:Bt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(l)?hr(l):(mc({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&ho(),l)};var qo=[{intent:x.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:y.COMMAND_LINE}),V("move cancel"),St({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:y.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:y.COMMAND_LINE}),V("move start"),St({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:y.MOVE,action:()=>(C({mode:y.COMMAND_LINE}),V("move confirm"),St({isForceExecutedBySystem:!0}))}],Yo=[{intent:x.MovePreviousItem,mode:y.MOVE,action:()=>Zt()?(C({mode:y.COMMAND_LINE}),V("move previous"),St({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveNextItem,mode:y.MOVE,action:()=>Zt()?(C({mode:y.COMMAND_LINE}),V("move next"),St({isForceExecutedBySystem:!0})):a("No pending move")}],xl=[{intent:x.MoveToNextContainer,mode:y.MOVE,action:()=>Zt()?(C({mode:y.COMMAND_LINE}),V("move to-next"),St({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveToPreviousContainer,mode:y.MOVE,action:()=>Zt()?(C({mode:y.COMMAND_LINE}),V("move to-previous"),St({isForceExecutedBySystem:!0})):a("No pending move")}];var bl={[B.WORKSPACE]:[...qo,...Yo],[B.BOARD]:[...qo,...Yo],[B.SWIMLANE]:[...qo,...Yo,...xl],[B.TICKET]:[],[B.FIELD]:[],[B.FIELD_LIST]:[],[B.TEXT]:[],[B.COMMENT]:[]};import Dv from"node:fs";import Bv from"node:path";var Il=e=>{let t=_e(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Re({repoRoot:t.value});if(d(n))return a(n.message);let r=kn(e.hash,e.ext),o=Bv.join(nr(n.value),r);return Dv.existsSync(o)?(Sr(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var El=()=>{V("");let{pendingNavTarget:e}=Jt();C({mode:y.DEFAULT}),e&&M.navigate(e),Qt({pendingNavTarget:void 0})},Sl=[{intent:x.ExitCommandLine,mode:y.HELP,action:()=>(El(),u("Exiting help",null))},{intent:x.Exit,mode:y.HELP,action:()=>(El(),u("Closed help",null))},{intent:x.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:x.NavNextItem,mode:y.HELP,action:()=>(M.navigateToNextItem(),u("Navigating to next help item",null))},{intent:x.NavToPreviousContainer,mode:y.HELP,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:x.NavToNextContainer,mode:y.HELP,action:()=>(M.navigateToNextContainer(),u("Navigating to next help container",null))}];var Fv=e=>{C({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=Jt();t&&M.navigate(t),Qt({pendingNavTarget:void 0}),V(`${e} `)},Cl=()=>{V("");let{pendingNavTarget:e}=Jt();e&&M.navigate(e),Qt({pendingNavTarget:void 0}),C({mode:y.DEFAULT})},Nl=[{intent:x.InitCommandPalette,mode:y.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{V("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return Qt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:y.PALETTE}),u("Opening command palette",null)}},{intent:x.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!Ot(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Fv(t),u("Selected command",t)):u("No command selected",null)}},{intent:x.ExitCommandLine,mode:y.PALETTE,action:()=>(Cl(),u("Exiting palette",null))},{intent:x.Exit,mode:y.PALETTE,action:()=>(Cl(),u("Closed command palette",null))},{intent:x.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:y.PALETTE,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:y.PALETTE,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:y.PALETTE,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var Rl=[...Sl,...Nl,{intent:x.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.NEW} `),u("Adding new item",null))},{intent:x.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.DELETE} `),u("Deleting item",null))},{intent:x.InitCommandLine,mode:y.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:y.COMMAND_LINE}),V(""),u("Entering command line mode",null))},{intent:x.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Y(e?.id??"")?.length){let r=e?E.getAttachment(e.id):void 0;if(r)return Il(r);if(e?.title===Z.DESCRIPTION)return C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Propose command",!0);if(e?.title===Z.ASSIGNEES)return C({mode:y.COMMAND_LINE}),V(`${b.ASSIGN} `),u("Propose command",!0);if(e?.title===Z.TAGS)return C({mode:y.COMMAND_LINE}),V(`${b.TAG} `),u("Propose command",!0);if(t.title===Z.DESCRIPTION&&e?.context==="TEXT")return C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Propose command",!0)}return M.enterChildNode(),u("Entering context",null)}},{intent:x.Yank,mode:y.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=v(),t=e?.title===Z.DESCRIPTION?ye.DESCRIPTION:e?.title===Z.TAGS?ye.TAGS:e?.title===Z.ASSIGNEES?ye.ASSIGNEES:ye.REF,r=ae(b.YANK).includes(t)?t:ye.REF;return C({mode:y.COMMAND_LINE}),V(`${b.YANK} ${r}`),u("Propose command",!0)}},{intent:x.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:x.EditDescription,mode:y.DEFAULT,description:"[e] edit description",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Exiting context",null))},{intent:x.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),u("Exiting context",null))},{intent:x.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:y.DEFAULT,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:y.DEFAULT,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var Uv=500,Ov=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Al=e=>{let t=Ov(e);t&&To(n=>(n+t).slice(0,Uv))};var _v=[y.COMMAND_LINE,y.PALETTE],$v=e=>[{intent:x.MoveCursorLeft,mode:e,action:()=>(ui(-1),u("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:e,action:()=>(ui(1),u("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:e,action:()=>(mi("left"),u("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:e,action:()=>(mi("right"),u("Moving cursor right of word",null))},{intent:x.AutoCompleteCommand,mode:e,action:()=>(To((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=v().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:x.CaptureInput,mode:e,action:(t,{sequence:n})=>(Al(n??""),u("Capturing input",null))},{intent:x.EraseInput,mode:e,action:()=>(cc(),u("Erasing input",null))},{intent:x.EraseInputWord,mode:e,action:()=>(lc(),u("Erasing input word",null))}],Tl=[{intent:x.Confirm,mode:y.COMMAND_LINE,action:()=>(St(),u("Executing command",null))},{intent:x.ViewHelp,mode:y.DEFAULT,action:()=>(C({mode:y.HELP}),u("Viewing help",null))},..._v.flatMap($v),{intent:x.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(C({mode:y.DEFAULT}),u("Exiting command line",null))},{intent:x.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(pc(),u("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(fc(),u("Getting next command from history",null))}];import Pl from"chalk";var Xo=Pl.dim.hex(h.secondary2)(": for command line"),wl="q to exit",Ml=`${Pl.hex(h.accent)("m")} to confirm`,wi={[B.WORKSPACE]:[Xo],[B.BOARD]:[Xo],[B.BOARD+y.COMMAND_LINE]:[Xo],[B.SWIMLANE]:[Xo],[B.TICKET+y.HELP]:[wl],[B.SWIMLANE+y.HELP]:[wl],[B.TICKET]:[],[B.FIELD]:[],[B.SWIMLANE+y.MOVE]:[Ml],[B.TICKET+y.MOVE]:[Ml]};var Rr=e=>e.trim().toLocaleLowerCase(),Hv=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},jv=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?qt(n,r.name):void 0}).filter(n=>!!n)},Ll=(e,t)=>{let n=Rr(t.value);if(!n)return!0;switch(t.target){case"title":return Rr(e.title??"").includes(n);case"description":return Rr(e.props.description??"").includes(n);case"tag":return Hv(e).map(Rr).some(o=>o.includes(n));case"assignee":return jv(e).map(Rr).some(o=>o.includes(n));case"ref":return Za(e.id,t.value);default:return!0}};function kl(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Dl=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 In,Mi,Pi=new Set,Bl=()=>{for(let e of Pi)e()},Vv=e=>(Pi.add(e),()=>Pi.delete(e));function Fl(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let l=kl(t,o,r);if(d(l))return logger.error(l.message),l;let m=l.value,{context:p}=c,f=wi[p+n]??wi[p]??[],g=[...Rl,...bl[p]??[],...Tl],I=Dl(g),S=Gv(o,s),R=S[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:g,actionIndex:I,selectedNode:R,renderedChildrenIndex:S})}var v=()=>{if(!In)throw new Error("State not initialized. Call initWorkspaceState() first.");return In},We=()=>In?u("Retrieved state",In):a("State not initialized. Call initWorkspaceState() first.");function cr(e){Mi=e;let t=_e(process.cwd()),n=!1;if(!d(t)){let s=ut(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=Fl(r);return d(o)?o:(In=o.value,Bl(),u("State initialized",null))}function pe(e){let t=v(),n=e(t),r=Fl(n);return d(r)?a(r.message??"Unable to update state"):(In=r.value,Bl(),u("State updated",null))}var C=e=>pe(t=>({...t,...e}));var j=()=>Wv(Vv,v,v),Gv=(e,t)=>{let n={};for(let r of Object.values(e))T(r)&&t.length>0&&!t.every(o=>Ll(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},z=e=>v()?.renderedChildrenIndex[e]??[],it=()=>Mi?cr(Mi):a("Cannot reset state: no initial workspace found"),Wt=()=>In!==void 0;var Li=e=>{Wt()&&(C({syncStatus:e}),Ut({type:"sync-status",payload:e}))},Jo=(e="Syncing...")=>{Li({status:"syncing",msg:e})},Qo=(e="Synced")=>{Li({status:"synced",msg:e})},ki=e=>{Li({status:"failed",msg:e})},et=e=>(ki(e),a(e));import{decodeTime as AD}from"ulid";var Kv=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=J("getRepoRootDir",await gt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=J("getStateBranchRoot",Re({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=J("ensureInitialCommit",await Da(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=J("bootstrapStateBranchStorage",await Ua({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=J("hasInProgressGitOperation(stateBranchRoot)",await jr(s));if(d(l))return a(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=J("ensureStateBranchLayout",Ia(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},zv=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=J("stageStateBranchOwnEventFile",await Jr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=J("stageStateBranchMediaFiles",await Ba({stateBranchRoot:t}));if(d(o))return a(o.message);let s=J("hasStagedChanges(after stage)",await fa(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=J("createStateBranchSyncCommit",await Fa({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),u("Committed own event file",{createdCommit:!0,commitSha:i.value}))},yo=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Jo();let n=J("ensureSyncReady",await Kv({cwd:e,ensureUpstream:!0}));if(d(n))return et(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=J("isDetachedHead(stateBranchRoot)",await ga(o));if(d(i))return et(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return et("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,l,m=!1,p=!1,f=J("getStateBranch",Cn(r));if(d(f))return et(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let I=J("commitOwnEventFileToStateBranch",await zv({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(I))return et(I.message);c=I.value.createdCommit,l=I.value.commitSha;let S=J("pullBranchRebaseIfPresent",await Ps({cwd:o,branch:g}));if(d(S))return et(S.message);if(m=S.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let R=J("pushStateBranch",await sr({stateBranchRoot:o,repoRoot:r}));if(d(R)&&pa(R.message)){let A=J("pullBranchRebaseIfPresent(retry)",await Ps({cwd:o,branch:g}));if(d(A))return et(A.message);m=m||A.value,R=J("pushStateBranch(retry)",await sr({stateBranchRoot:o,repoRoot:r}))}if(d(R))return et(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let R=J("git rev-parse HEAD",await F({args:["rev-parse","HEAD"],cwd:o}));if(d(R))return et(R.message);l=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",l)}return Qo(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:l,pulled:m,pushed:p,bootstrapped:s})};import{existsSync as Di}from"node:fs";import{chmod as Bi}from"node:fs/promises";import jl from"node:os";import Hn from"node:path";var Ul=(e,t)=>e.reduce((n,r)=>r<n?r:n,t);var Ol=1e5,Zo=null,_l=Promise.resolve(),en=e=>{let t=_l.then(e,e);return _l=t.then(()=>{},()=>{}),t},Fi=e=>{let t=_e(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Ui=e=>{let t=Fi(e);return d(t)?t:Re({repoRoot:t.value})},at=()=>{if(!Wt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:Zo}},Oi=(e,t)=>{let n=new Map,r=new Set,o=i=>{let c=new Set,l=i;for(;l&&!c.has(l);){if(r.has(l))return l;c.add(l),l=n.get(l)}return null},s=[];for(let i of e){let c=i.payload,l=c?.id;l&&(i.action==="add.board"&&r.add(l),c.parent&&n.set(l,c.parent),(l===t||o(l)===t)&&s.push(i))}return s},Wl=async(e={})=>{let t=Ui(e.repoRoot);if(d(t))return a(t.message);let n=je(t.value);if(d(n))return a(n.message);let o=(e.boardId?Oi(n.value,e.boardId):n.value).map(zt).filter(g=>g!==null),s=Date.now(),i=e.end??s,c=e.start??Ul(o,i);if(i<=c)return u("Empty time window",{bucketMs:0,buckets:[],earliest:c,latest:i});let l=o.filter(g=>g>=c&&g<i).sort((g,I)=>g-I),m=Math.max(1,Math.ceil((i-c)/Ol)),p=new Map;for(let g of l){let I=Math.min(Ol-1,Math.floor((g-c)/m)),S=c+I*m;p.set(S,(p.get(S)??0)+1)}let f=[...p.entries()].sort(([g],[I])=>g-I).map(([g,I])=>({t:g,count:I}));return u("Computed event timeline",{bucketMs:m,buckets:f,earliest:c,latest:i})},Ar="",$l="",Vl=async(e={})=>{let t=Fi(e.repoRoot);if(d(t))return a(t.message);let n=ut(t.value);if(d(n))return a(n.message);let r=await F({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=${$l}%H${Ar}%at${Ar}%an${Ar}%s`]});if(d(r))return a(r.message);let o=r.value.stdout.split($l).filter(s=>s.trim().length>0).map(s=>{let[i,...c]=s.split(`
|
|
59
|
-
`),[l,m,p,...f]=(i??"").split(
|
|
60
|
-
`).map(f=>f.trim()).filter(Boolean);if(o.length===0)return a("No changed files found for this commit");if(o.length>Xv)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Hn.join(jl.tmpdir(),"epiq","commit-diffs",t),i=await Promise.all(o.map(async(f,g)=>{let[I,S]=await Promise.all([Hl(e,`${t}~1`,f),Hl(e,t,f)]),R=Hn.basename(f),A=Hn.join(s,String(g),"before",R),P=Hn.join(s,String(g),"after",R);return Di(A)||(be.writeToFile(A,I),await Bi(A,292)),Di(P)||(be.writeToFile(P,S),await Bi(P,292)),{beforePath:A,afterPath:P}})),[c,...l]=i;if(!c)return a("No changed files found for this commit");let m=await Si(n,c.beforePath,c.afterPath,"new");if(d(m)||l.length===0)return m;await new Promise(f=>setTimeout(f,Jv));let p=await Promise.all(l.map(({beforePath:f,afterPath:g})=>Si(n,f,g,"reuse")));for(let f of p)d(f)&&logger.error(`Failed to open an additional diff tab for ${t}: ${f.message}`);return m},Gl=async e=>{if(!qv(e.sha))return a("Invalid commit sha");let t=Fi(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=$o()[0];if(r&&Ei(r)){let o=await Qv(n,e.sha,r);if(!d(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return Yv(n,e.sha)},Kl=e=>{let t=je(e);if(d(t))return a(t.message);let n=it();if(d(n))return a(n.message);Zo=null;let o=st(t.value).filter(d);return o.length>0?a(o.map(s=>s.message).join(", ")):(C({readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},Zv=(e,t)=>{Zo=null;let n=Kl(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},zl=e=>en(async()=>{let t=Ui(e.repoRoot);if(d(t))return a(t.message);let n=uo(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=it();if(d(s))return s;let c=st(r).filter(d);return c.length>0?Zv(t.value,c.map(l=>l.message).join(", ")):(C({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),Zo=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),ql=(e={})=>en(async()=>{let t=Ui(e.repoRoot);if(d(t))return a(t.message);let n=Kl(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});var _i=()=>{let e=Ft();return d(e)?xt:e.value.attachmentMaxKb??xt},$i=e=>{let t=_e(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Ne=async(e,t)=>{let n=$i(e);if(d(n))return n;let r=Re({repoRoot:n.value});if(d(r))return a(r.message);let o=Sn(),s=await cn({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.stateBranch});if(d(s))return a(s.message);if(t?.pull??!1){let l=await F({cwd:r.value,args:["pull","--ff-only"]});d(l)&&se.info(3,l.message)}let i=je(r.value);if(d(i))return a(i.message);let c=pn(i.value);return d(c)?a(c.message):u("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:r.value})},Ae=()=>{let e=Ft();return d(e)?a(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},Fe=()=>{let e=We();return d(e)?a(e.message):e},Xl=e=>(e.props.tags??[]).map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ue(t.name)})),Hi=()=>{let e=We(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},Jl=(e,t)=>{let n=new Map(e);for(let r of Object.values(t)){if(r.tombstoned){n.set(r.id,r.name);continue}n.set(r.id,Fn(r.name,n.get(r.id))??r.name)}return n},Ql=(e,t=new Map)=>(e.props.assignees??[]).map(n=>E.getContributor(n)).filter(n=>n!=null).map(n=>{let r=n.tombstoned?n.name:Fn(n.name,t.get(n.id))??n.name;return{id:n.id,name:r,color:ue(r)}});var Zl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Fe();if(d(n))return n;let r=n.value.nodes,o=Hi(),s=Object.values(r).filter(T).filter(i=>!i.isDeleted).filter(i=>e.includeClosed||i.parentNodeId!==ve).filter(i=>e.boardId?(i.parentNodeId?r[i.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(i=>({id:i.id,ref:He(i.id),title:Ze(i.title),description:i.props.description??"",parentNodeId:i.parentNodeId,isClosed:i.parentNodeId===ve,readonly:!!i.readonly,tags:Xl(i),assignees:Ql(i,o)}));return u("Listed issues",s)},eu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=Pn(e.parentId,n.value,t.value.stateBranchRoot);if(d(o))return o;let s=jo({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(d(s))return s;let i=[...s.value],c=i.find(f=>f.action==="add.issue")?.payload.id;if(!c)return a("Unable to determine created issue id");e.description&&i.push({id:q(),...n.value,action:"edit.description",payload:{id:c,md:e.description}});let l=[];for(let f of e.tagNames??[]){let g=Ze(f).trim();if(!g||l.some(R=>R.name===g))continue;let I=Object.values(r.value.tags).find(R=>R.name===g),S=I?.id??q();I||i.push({id:q(),...n.value,action:"create.tag",payload:{id:S,name:g}}),i.push({id:q(),...n.value,action:"add.issue.tag",payload:{id:c,tag:S}}),l.push({id:S,name:g})}let m=[];for(let f of e.assigneeNames??[]){let g=Ze(f).trim();if(!g||m.some(R=>R.name===g))continue;let I=Object.values(r.value.contributors).find(R=>R.name===g),S=I?.id??q();I||i.push({id:q(),...n.value,action:"create.contributor",payload:{id:S,name:g}}),i.push({id:q(),...n.value,action:"add.issue.assignee",payload:{id:c,assignee:S}}),m.push({id:S,name:g})}let p=U(i,t.value.stateBranchRoot);return d(p)?a(p.message):u("Created issue",{id:c,title:e.title,parentId:e.parentId,description:e.description??"",tags:l,assignees:m})},tu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=mn(ve,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:q(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ve,rank:r.value}},s=U([o],t.value.stateBranchRoot);return d(s)?a(s.message):u("Closed issue",{id:e.issueId})},nu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Target node is not issue");if(o.parentNodeId!==ve)return a("Issue is not closed");let s=Oo(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ve)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=mn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let l={id:q(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=U([l],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,parentId:i.id})},ru=async e=>{let t=$i(e.repoRoot);if(d(t))return t;let n=Ae();if(d(n))return n;let r=Re({repoRoot:t.value});if(d(r))return r;let o=je(r.value);if(d(o))return o;let s=pn(o.value);if(d(s))return s;let i=mn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:q(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},l=U([c],r.value);return d(l)?a(l.message):u("Moved issue",{id:e.issueId,parentId:e.parentId})};var es=async(e={})=>{Jo();let t=$i(e.repoRoot);if(d(t))return a("Sync failed");let n=Ae();if(d(n))return n;let r=await yo({cwd:t.value,ownEventFileName:un(n.value)});return d(r)?(ki(r.message),r):(Qo(),u("Synced",r.value))};var Tr=()=>{let e=Fe();if(d(e))return e;let t=at(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(g=>Zr(g)&&!g.isDeleted),s=Hi(),i=new Map,c=new Map;for(let g of r)if(!g.isDeleted){if(_t(g)&&g.parentNodeId){let I=i.get(g.parentNodeId)??[];I.push(g),i.set(g.parentNodeId,I)}if(T(g)&&g.parentNodeId){let I=c.get(g.parentNodeId)??[];I.push(g),c.set(g.parentNodeId,I)}}let l=Ft();if(d(l))return l;let m={};for(let g of r.filter(T))g.isDeleted||(m[g.id]=E.getCommentsByIssue(g.id).map(I=>{let S=E.getContributor(I.authorId);return{id:I.id,issueId:I.issue,body:I.md,author:{id:I.authorId,name:S?.name??"Unknown",color:ue(S?.name??I.authorId)},createdAt:Yl(I.id)}}));let p=new Map;for(let g of e.value.eventLog)g.action==="add.issue.attachment"&&p.set(g.payload.id,g.payload.author);let f={};for(let g of r.filter(T))g.isDeleted||(f[g.id]=E.getAttachmentsByIssue(g.id).map(I=>({id:I.id,issueId:I.issue,name:I.name,fileName:kn(I.hash,I.ext),bytes:I.bytes,createdAt:Yl(I.id),canDelete:p.get(I.id)===l.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((g,I)=>g.rank.localeCompare(I.rank)).map(g=>({id:g.id,ref:He(g.id),title:g.title,swimlanes:(i.get(g.id)??[]).sort((I,S)=>I.rank.localeCompare(S.rank)).map(I=>({id:I.id,title:I.title,readonly:!!I.readonly||n,issues:(c.get(I.id)??[]).sort((S,R)=>S.rank.localeCompare(R.rank)).map(S=>({id:S.id,ref:He(S.id),title:Ze(S.title),description:S.props.description??"",readonly:!!S.readonly||n,tags:Xl(S),assignees:Ql(S,s),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===ve})),parentNodeId:I.parentNodeId}))})),tags:Object.values(e.value.tags).map(g=>({...g,color:ue(g.name)})),contributors:Object.values(e.value.contributors).map(g=>({...g,color:ue(g.name)})),user:{name:l.value.userName??"",id:l.value.userId??"",color:ue(l.value.userName??"")},commentsByIssueId:m,attachmentsByIssueId:f,attachmentMaxKb:_i(),timeTravel:t})},dt=async(e={})=>{if(at().mode!=="live")return Tr();let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:Tr()},ou=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return u("No changes made",{id:e.issueId,description:s});let i={id:q(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,description:e.description})},su=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Ze(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return u("No changes made",{id:e.issueId,title:s});let i={id:q(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,title:s})},iu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Ze(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??q(),l=[...i?[]:[{id:q(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:q(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=U(l,t.value.stateBranchRoot);return d(m)?a(m.message):u("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},au=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:q(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,tagId:e.tagId})},du=async(e,t)=>{let n=je(e);if(d(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},cu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let R=r.value.contributors[s],A=R?void 0:await du(t.value.stateBranchRoot,s);if(!R&&!A)return a("Unknown assignee id");let P=R??A,_=[...R?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:P.id,name:P.name}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:P.id}}],w=U(_,t.value.stateBranchRoot);return d(w)?a(w.message):u("Added issue assignee",{id:e.issueId,assignee:{id:P.id,name:P.name}})}let i=Ze(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=[...Jl(Hi(),r.value.contributors).entries()].filter(([,R])=>R===i);if(l.length>1)return a(`"${i}" matches ${l.length} contributors (${l.map(([R])=>R).join(", ")}). Assign by assigneeId to choose.`);let m=l[0];if(!m&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[p=q(),f=i]=m??[],I=[...!!r.value.contributors[p]?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:p,name:f}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],S=U(I,t.value.stateBranchRoot);return d(S)?a(S.message):u("Added issue assignee",{id:e.issueId,assignee:{id:p,name:f}})},lu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await du(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:q(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=U(i,t.value.stateBranchRoot);return d(c)?a(c.message):u("Tombstoned contributor",{id:e.contributorId,name:to})};var uu=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=je(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Oi(o.value,e.boardId):o.value,i=new Map,c=new Set,l=new Set;for(let g of o.value)g.userId&&l.add(g.userId);for(let g of s)g.userId&&(i.set(g.userId,g.userName??""),c.add(g.userId));let m=r.value.contributors,f=[...Jl(i,m).entries()].map(([g,I])=>({id:g,name:I,color:ue(I),isSelf:g===n.value.userId,isExternal:!c.has(g),isRemoved:m[g]?.tombstoned===!0,hasAuthoredAnywhere:l.has(g)}));return u("Listed board contributors",f)},mu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:q(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},ts=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=q(),c={id:q(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},ns=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},pu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=qd(t.value.stateBranchRoot,s,_i());if(d(i))return i;let c=Ze(e.name??"").trim()||"image",l=q(),m={id:q(),...n.value,action:"add.issue.attachment",payload:{id:l,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=U([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Added issue attachment",{id:l,issueId:e.issueId,fileName:kn(i.value.hash,i.value.ext),bytes:i.value.bytes})},fu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return a("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return a("You can only delete your own attachments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Attachment target must be an issue");if(s.readonly)return a("Cannot delete attachment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},gu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:Yd(t.value.stateBranchRoot,e.fileName,_i())};var vu=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=rr();if(d(p))return se.error(p.message);let{autoSync:f,userName:g,preferredEditor:I}=p.value;return!!(f&&g&&I)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await en(async()=>{at().mode==="live"&&(await es({repoRoot:e.repoRoot}),Ut({type:"state",payload:await dt({repoRoot:e.repoRoot})}))})}finally{o=!1,s&&(s=!1,c())}}},l=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=rr();if(d(p))return se.error(p.message);let{autoSyncDebounceMs:f}=p.value;i()&&(t=setTimeout(()=>{c(),m()},f??15e3))};return m(),{scheduleSync:l,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as ey}from"ws";var ty=new Set(["sync","issues:create","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]),yu=()=>{let e=Tr();Ut({type:"state",payload:e})},de=(e,t)=>{e.send(JSON.stringify(t))},rs=async(e,t)=>de(e,{type:"state",payload:await dt({repoRoot:t})}),ny=async(e,t)=>{let n=()=>de(e,{type:"state",payload:Tr()});if(at().mode!=="live")return n();let r=await dt({repoRoot:t});return at().mode!=="live"?n():de(e,{type:"state",payload:r})},ct=async(e,t,n,r,o)=>{if(de(e,{type:r,payload:o}),d(o))return de(e,{type:"failed",payload:o.message});n(),ny(e,t)},hu=(e,t,{onStateChanged:n})=>{new ey({server:e,path:"/ws"}).on("connection",o=>{Oa(o),o.on("message",async s=>{let i=async c=>{let{type:l}=c;if(l==="timeline:get"){let{requestId:m,...p}=c.payload??{};return de(o,{type:"timeline",requestId:m,payload:await Wl({repoRoot:t,...p})})}if(l==="commits:get"){let{requestId:m,...p}=c.payload??{};return de(o,{type:"commits",requestId:m,payload:await Vl({repoRoot:t,...p})})}if(l==="commit:inspect")return de(o,{type:"commit:inspect:result",payload:await Gl({repoRoot:t,sha:c.payload.sha})});if(l==="time-travel:scrub"){let m=await zl({repoRoot:t,targetTime:c.payload.targetTime});return de(o,{type:"time-travel:result",payload:m}),d(m)?void 0:yu()}if(l==="time-travel:live"){let m=await ql({repoRoot:t});return de(o,{type:"time-travel:result",payload:m}),d(m)?void 0:yu()}if(l==="state:get")return rs(o,t);if(l==="sync"){let m=await es({repoRoot:t});return de(o,{type:"sync:result",payload:m}),n(),rs(o,t)}if(l==="issue:comment:add"){let m=await ts({repoRoot:t,...c.payload});return ct(o,t,n,"issue:comment:add:result",m)}if(l==="issue:comment:delete"){let m=await ns({repoRoot:t,...c.payload});return de(o,{type:"issue:comment:delete:result",payload:m}),d(m)?de(o,{type:"failed",payload:m.message}):(n(),rs(o,t))}if(l==="issue:edit:description"){let m=await ou({repoRoot:t,...c.payload});return ct(o,t,n,"issue:edit:description:result",m)}if(l==="issue:edit:title"){let m=await su({repoRoot:t,...c.payload});return ct(o,t,n,"issue:edit:title:result",m)}if(l==="issue:tag:add"){let m=await iu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:tag:add:result",m)}if(l==="issue:tag:remove"){let m=await au({repoRoot:t,...c.payload});return ct(o,t,n,"issue:tag:remove:result",m)}if(l==="contributor:remove"){let m=await lu({repoRoot:t,...c.payload});return ct(o,t,n,"contributor:remove:result",m)}if(l==="contributors:get")return de(o,{type:"contributors",payload:await uu({repoRoot:t,...c.payload})});if(l==="issue:assignee:add"){let m=await cu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:assignee:add:result",m)}if(l==="issue:assignee:remove"){let m=await mu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:assignee:remove:result",m)}if(l==="issues:list")return de(o,{type:"issues",payload:await Zl({repoRoot:t})});if(l==="issues:create"){let m=await eu({...c.payload,repoRoot:t});return de(o,{type:"issues:create:result",payload:m}),d(m)?Ut({type:"failed",payload:m.message}):(Ut({type:"issue:created",payload:m.value}),n(),rs(o,t))}if(l==="issues:move"){if(!c.payload.position)return de(o,{type:"error",message:"Missing move position"});let m=await ru({...c.payload,repoRoot:t});return ct(o,t,n,"issues:move:result",m)}if(l==="issue:close"){if(!c.payload.issueId)return de(o,{type:"error",message:"Missing issueId"});let m=await tu({repoRoot:t,issueId:c.payload.issueId});return ct(o,t,n,"issue:close:result",m)}if(l==="issue:reopen"){if(!c.payload.issueId)return de(o,{type:"error",message:"Missing issueId"});let m=await nu({repoRoot:t,issueId:c.payload.issueId});return ct(o,t,n,"issue:reopen:result",m)}return de(o,{type:"error",message:"Unknown message type"})};try{let c=JSON.parse(s.toString());return ty.has(c.type)?await en(async()=>at().mode!=="live"?de(o,{type:"failed",payload:"Read-only while viewing history"}):i(c)):await i(c)}catch(c){return de(o,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var sy=En.dirname(oy(import.meta.url)),iy=process.env.IS_LOCAL==="true"?En.resolve(process.cwd(),"dist/gui"):En.join(sy,"gui"),os,ay=async()=>(os===void 0&&(os=await import("node:sea").catch(()=>null)),os?.isSea()?os:null),fe=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},dy=e=>fe(e,409,{isError:!0,message:"Read-only while viewing history"}),ss=(e,t)=>en(async()=>at().mode!=="live"?dy(e):t()),xu=async(e,t=1024*1024)=>new Promise((n,r)=>{let o="",s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),cy=2*1024*1024,ly={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},uy=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",bu=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=En.resolve(iy),o=En.resolve(r,n),s=En.relative(r,o);if(s.startsWith("..")||En.isAbsolute(s))return fe(t,403,{isError:!0,message:"Forbidden"});let i=await ay();try{let c=i?Buffer.from(i.getAsset(`gui/${s}`)):await Iu(o);return t.writeHead(200,{"content-type":uy(o)}),t.end(c)}catch{return fe(t,404,{isError:!0,message:`Not found: ${n}`})}},my=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=l=>{if(e.off("listening",c),l.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(l)},c=()=>{e.off("error",i);let l=e.address();if(!l||typeof l=="string"){r(new Error("Unable to resolve address"));return}n(l.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Eu=async e=>{let t=ry.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return fe(s,200,await dt({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await xu(o);if(!c.issueId||!c.body?.trim())return fe(s,400,{isError:!0,message:"Missing issueId or body"});let l=c.issueId,m=c.body;return await ss(s,async()=>{let p=await ts({repoRoot:e.repoRoot,issueId:l,body:m});return d(p)?fe(s,400,{isError:!0,message:p.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await xu(o,cy);if(!c.issueId||!c.dataBase64)return fe(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let l=c.issueId,m=c.dataBase64,p=c.name??"";return await ss(s,async()=>{let f=await pu({repoRoot:e.repoRoot,issueId:l,name:p,dataBase64:m});return d(f)?fe(s,400,{isError:!0,message:f.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));return c?ss(s,async()=>{let l=await fu({repoRoot:e.repoRoot,attachmentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing attachment id"})}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),l=await gu({repoRoot:e.repoRoot,fileName:c});if(d(l))return fe(s,404,{isError:!0,message:l.message});try{let m=await Iu(l.value.filePath);return s.writeHead(200,{"content-type":ly[l.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return fe(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));return c?ss(s,async()=>{let l=await ns({repoRoot:e.repoRoot,commentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing comment id"})}return i.pathname.startsWith("/board/")?bu("/",s):bu(i.pathname,s)});try{await my(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=vu({repoRoot:e.repoRoot});hu(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Su=async e=>{let t=Ft();Q(t)&&Me(t.value);let n=await Eu({...e,boardId:""});if(d(n))return n;let{url:r}=n.value;return console.log(`Epiq GUI running at ${py.cyan(r)}`),La(r),u("Started GUI",{url:r})};import{Box as sn}from"ink";import ce from"react";import{Box as ji,Text as wr}from"ink";import lt,{useEffect as fy,useMemo as gy}from"react";import{ulid as vy}from"ulid";var Cu=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return lt.createElement(wr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?lt.createElement(wr,{color:n,dimColor:o},e):lt.createElement(wr,{color:n,dimColor:o},e.slice(0,c),lt.createElement(wr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Nu=vy(),yy=e=>`${e}`,hy=e=>{let{pendingNavTarget:t}=Jt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(ae(b.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(b))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==b.PALETTE).map(i=>{let c=wo(i),l=zo.find(m=>m.intent===c);return{command:i,description:l?.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))},xy=e=>ee.text({id:Nu,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),by=(e,t,n)=>ee.text({id:yy(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Wi=[],Iy=e=>{Ru();let t=E.createNode(xy(v().rootNodeId));d(t)||!Ot(t.value)||(Wi=[t.value,...e.map((n,r)=>by(n,r,Nu)).map(E.createNode).filter(Q).map(({value:n})=>n).filter(Ot)],M.navigate({contextNode:t.value,selectedIndex:0}))},Ru=()=>{let e=Wi.map(t=>t.id);Wi=[];for(let t of e)E.deleteNode(t)};function Au({width:e,height:t}){let r=gc().value.trim().toLowerCase(),o=gy(()=>hy(r),[r]);fy(()=>(Iy(o),()=>{Ru()}),[o]);let s=v().selectedIndex;return lt.createElement(ji,{flexDirection:"column",width:e,height:t-2},lt.createElement(tt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let l=c===s,m=i.isAvailable?h.accent:h.secondary2,p=i.isAvailable?"":"[unavailable] ";return lt.createElement(ji,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},lt.createElement(wr,{color:m,dimColor:!i.isAvailable},l?"\u276F ":" ",lt.createElement(Cu,{text:Va(i.command),match:r,color:m,dimColor:!i.isAvailable})),lt.createElement(ji,{paddingLeft:2},lt.createElement(Cu,{text:p+i.description,match:r.length>=2?r:"",color:l&&i.isAvailable?h.primary:h.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Oy}from"ink";import ds from"react";import Pr from"chalk";import{Box as Vi,Text as Tu}from"ink";import Mr,{useEffect as Ey,useMemo as Sy,useState as Cy}from"react";var wu=Pr.hex(h.secondary),Ny=Pr.inverse,Ry=Pr.inverse.hex(h.secondary2),Ay={hint:"",hints:[],overlap:0,remainder:""},Pu=({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}},Ty=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ue(t);return{bg:r=>Pr.bgHex(n).black(r),bgCursor:r=>Pr.bgHex(n).inverse.black(r)}}return zs(t)},wy=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Pu({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}},Mu=()=>({value:Le.value,cursorPosition:Le.cursorPosition,commandIsPending:Le.commandIsPending,autoCompletion:Le.commandMeta.autoCompletion??Ay,infoMessage:Le.commandMeta.infoMessage,validationStatus:Le.commandMeta.validity,command:Le.commandMeta.command,inputString:Le.commandMeta.inputString,modifier:Le.commandMeta.modifier}),My=(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,Lu=({width:e,mode:t})=>{let[n,r]=Cy(Mu());Ey(()=>{let S=()=>{let A=Mu();r(P=>My(P,A)?P:A)},R=li(S);return S(),()=>{R()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:l,command:m,modifier:p,validationStatus:f}=n,g=c&&f===bt.Invalid,I=Sy(()=>{let S=Math.max(0,Math.min(s,o.length)),R=Pu({value:o,command:m}),A=wy({value:o,command:m,modifier:p}),P=m?zs(m):null,_=Ty({command:m,modifier:p}),w=(ge,me)=>{let Gn=R&&me>=R.start&&me<R.end,Kn=A&&me>=A.start&&me<A.end;return Gn&&P?P.fg(ge):Kn&&_?_.bg(ge):ge},W=(ge,me)=>{let Gn=R&&me>=R.start&&me<R.end,Kn=A&&me>=A.start&&me<A.end;return Gn&&P?P.fgCursor(ge):Kn&&_?_.bgCursor(ge):Ny(ge)},H=o.slice(0,S),D=o[S]??" ",$=S<o.length?o.slice(S+1):"",Ye=Array.from(H).map((ge,me)=>w(ge,me)).join(""),we=W(D,S),Xe=Array.from($).map((ge,me)=>w(ge,S+1+me)).join("");if(l.hint){let ge=l.hint[l.overlap]??D;we=Ry(ge),Xe=wu(l.remainder.slice(1)+$)}return wu(t===y.PALETTE?"?":":")+Ye+we+Xe},[o,s,l,m,p]);return Mr.createElement(Vi,{flexDirection:"column",justifyContent:"flex-start"},Mr.createElement(Vi,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},Mr.createElement(Vi,null,Mr.createElement(Tu,null,I),i&&Mr.createElement(Tu,{wrap:"truncate",color:g?h.red:h.secondary2},` ${i} `))))};import{Box as Py,Text as Ly}from"ink";import ku from"react";var ky=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Du=({width:e,availableHints:t})=>{let n=ky(t,e).join(" | ");return ku.createElement(Py,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},ku.createElement(Ly,{color:h.secondary2},n.length?n:"\xA0"))};import{Box as Dy,Text as is}from"ink";import Lr,{useEffect as By,useRef as jn,useState as Fy}from"react";var Uy=40,as=.3,Gi="\u2500",Bu=1,Fu=16,Uu=({width:e})=>{let{replay:t}=j(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Bu,[c,l]=Fy(0),m=jn(r);m.current=r;let p=jn(0),f=jn(0),g=jn(0),I=jn(0),S=jn(0);if(By(()=>{if(!n){p.current=0,g.current=0,I.current=0,S.current=0,l(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let w=setInterval(()=>{let W=Date.now(),H=m.current;if(H!==g.current){let Xe=H-g.current,ge=W-f.current;if(Xe<0)I.current=0,S.current=0;else if(Xe>0&&ge>0){let me=Xe/ge;I.current=I.current===0?me:I.current*(1-as)+me*as,S.current=S.current===0?Xe:S.current*(1-as)+Xe*as}p.current=H,f.current=W,g.current=H}let D=W-f.current,$=Math.min(S.current,I.current*D),Ye=Math.min(1,p.current+$),we=Math.round(Ye*i);l(Xe=>Xe===we?Xe:we)},Uy);return()=>clearInterval(w)},[n,i]),!t)return null;let R=w=>{let W=s>1?w/(s-1):0,H=Math.round(W*(Fu-1))/(Fu-1);return no(H)},A=Math.min(s,Math.floor(c/Bu)),P=[];for(let w=0;w<A;w++){let W=R(w),H=P[P.length-1];H&&H.color===W?H.text+=Gi:P.push({text:Gi,color:W})}let _=Gi.repeat(Math.max(0,s-A));return Lr.createElement(Dy,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1,columnGap:1},Lr.createElement(is,{color:h.secondary2},"\u25B6"),Lr.createElement(is,null,P.map((w,W)=>Lr.createElement(is,{key:W,color:w.color},w.text)),Lr.createElement(is,{color:h.secondary,dimColor:!0},_)))};var kr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=j(),o=t===y.COMMAND_LINE||t===y.PALETTE;return ds.createElement(Oy,null,o?ds.createElement(Lu,{width:e,mode:t}):r==="replay"?ds.createElement(Uu,{width:e}):ds.createElement(Du,{width:e,mode:t,availableHints:n}))};import{Box as tn,Text as Wn}from"ink";import Oe,{useEffect as _y,useMemo as $y}from"react";import{ulid as Ou}from"ulid";var ls=Ou(),Hy=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),jy=e=>ee.text({id:ls,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Wy=(e,t,n)=>ee.text({id:Ou(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),cs=[],_u=()=>{let e=cs.filter(n=>n.id!==ls).map(n=>n.id),t=cs.filter(n=>n.id===ls).map(n=>n.id);cs=[];for(let n of[...e,...t])E.deleteNode(n)},Vy=e=>{_u();let t=E.createNode(jy(v().rootNodeId));if(d(t)||!Ot(t.value))return logger.error("Could not attach help nodes");cs=[t.value,...e.map((n,r)=>Wy(n,r,ls)).map(E.createNode).filter(Q).map(({value:n})=>n).filter(Ot)],M.navigate({contextNode:t.value,selectedIndex:0})},$u=({width:e,height:t})=>{let n=$y(()=>Hy(),[]);_y(()=>(Vy(n),()=>{_u()}),[n]);let r=v().selectedIndex;return Oe.createElement(tn,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},Oe.createElement(tn,{paddingX:1,justifyContent:"center"},Oe.createElement(Wn,{color:h.accent},"Help"),Oe.createElement(Wn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Oe.createElement(tn,{paddingX:1,marginTop:1},Oe.createElement(tn,{width:20,justifyContent:"flex-end"},Oe.createElement(Wn,{color:h.secondary},"Key(s)")),Oe.createElement(tn,{flexGrow:1,width:40,paddingLeft:2},Oe.createElement(Wn,{color:h.secondary},"Action"))),Oe.createElement(tt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Oe.createElement(tn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Oe.createElement(tn,{width:20,justifyContent:"flex-end"},Oe.createElement(Wn,{color:h.accent},o)),Oe.createElement(tn,{flexGrow:1,width:40,paddingLeft:2},Oe.createElement(Wn,{color:c?h.primary:h.secondary2},s)))})))};import Gy from"chalk";import{Box as us,Text as Dt}from"ink";import qe from"react";var Hu=({width:e,height:t})=>qe.createElement(us,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},qe.createElement(Dt,{color:h.accent,bold:!0},"Initialize project"),qe.createElement(Dt,null,`This folder is not an ${Gy.hex(h.accent)("epiq")} project yet.`),qe.createElement(Dt,{color:h.primary},"To start tracking issues here, we need to initialize a new",qe.createElement(Dt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),qe.createElement(us,{marginTop:1,flexDirection:"column"},qe.createElement(us,null,qe.createElement(Dt,{color:h.accent}," "),qe.createElement(Dt,{color:h.primary},"Type "),qe.createElement(Dt,{backgroundColor:h.secondary}," :init "))),qe.createElement(us,{marginTop:1},qe.createElement(Dt,{color:h.secondary2},"This will create, commit and push "),qe.createElement(Dt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as ms,Text as Ct}from"ink";import Te from"react";var Ky=({isDone:e,command:t,value:n})=>Te.createElement(ms,null,Te.createElement(Ct,{color:h.accent,dimColor:e},e?" \u2714 ":" "),Te.createElement(Ct,{dimColor:e},"Type "),Te.createElement(Ct,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&Te.createElement(Te.Fragment,null,Te.createElement(Ct,{dimColor:e}," "),Te.createElement(Ct,{color:h.secondary,dimColor:e},"<"+n+">"))),zy=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Ki({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Vt(),l=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=l.findIndex(f=>!f.done),p=m===-1?void 0:l[m];return Te.createElement(ms,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Te.createElement(Ct,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),Te.createElement(Ct,null,"Let's get you started - it's a breeze."),Te.createElement(Ct,{color:h.secondary2},"Remember - you can always search available commands by typing:",Te.createElement(Ct,{color:h.accent}," ? ")),p&&Te.createElement(Ct,{color:h.secondary2},p.message),Te.createElement(ms,{flexDirection:"column"},l.map((f,g)=>m===-1||g<=m?Te.createElement(ms,{key:f.key,marginBottom:1},Te.createElement(Ky,{isDone:f.done,command:f.command,value:f.done?zy(f.value):void 0})):null)))}import ys from"chalk";import{Box as Br,Text as Vn}from"ink";import xe from"react";import{Box as ps,Text as ju}from"ink";import nn from"react";import qy from"chalk";var Yy=e=>(E.getTag(e)?.name??"").length+3,Xy=e=>{let t=E.getContributor(e);return(t?qt(e,t.name):"").length+3},Wu=({width:e})=>{let{viewMode:t}=K(),n=j(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],l=At(c?.id??o.id,"TICKET"),m=Q(l)?l.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],g=m?.parentNodeId?!Vs(o.id,m.parentNodeId)&&t==="dense":!1,I=r.map((H,D)=>{let $=D===r.length-1,Ye=Y(H.id),we=$?Ye?.[s]?.title:void 0;return`${D?" / ":""}${H.title??""}${we?` \u25B8 ${we}`:""}`}).join(""),S=m?E.getCommentsByIssue(m.id):[],R=S.length?String(S.length).length+11:0,A=g?p.reduce((H,D)=>H+Yy(D),0)+f.reduce((H,D)=>H+Xy(D),0)+R:0,P=c?.id!=null&&!(t==="wide"&&T(c)),_=Math.max(0,e-A),w=I.substring(0,_)+(P?qy.hex(h.secondary2).dim(` ${He(c.id)}`):""),W=g?[...p.map(H=>nn.createElement(ps,{key:`tag-${H}`,paddingLeft:1},nn.createElement(Un,{id:H}))),...f.map(H=>nn.createElement(ps,{key:`assignee-${H}`,paddingLeft:1},nn.createElement(Yt,{id:H}))),S.length?nn.createElement(ps,{key:"comments",paddingLeft:1},nn.createElement(ju,{color:h.accent},"[",S.length," comment",S.length===1?"":"s","]")):null]:[];return nn.createElement(ps,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},nn.createElement(ju,{color:h.secondary2},w),W)};import{Box as Jy,Text as Vu}from"ink";import fs from"react";var Qy=({filters:e})=>fs.createElement(Jy,{columnGap:1},fs.createElement(Vu,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>fs.createElement(Vu,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Gu=fs.memo(Qy);import{Box as Zy,Text as gs}from"ink";import Dr from"react";function Ku(){let{eventLog:e,unappliedEvents:t}=j(),n=e.at(-1)?.id,r=Co(n??""),o=Q(r)?io(r.value):"INVALID DATE";return Dr.createElement(Zy,{paddingLeft:1},Dr.createElement(gs,{backgroundColor:h.accent,color:h.secondary}," Readonly "),Dr.createElement(gs,{color:h.accent}," "+t.length+" edits ago at "+o+"."),Dr.createElement(gs,{color:h.accent}," Resume with "),Dr.createElement(gs,{backgroundColor:h.accent,color:h.secondary}," ",":peek now"," "))}import{Box as eh,Text as zi}from"ink";import vs from"react";function zu(){let{replay:e}=j();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return vs.createElement(eh,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},vs.createElement(zi,{backgroundColor:h.accent,color:h.secondary}," \u25B6 REPLAY "),vs.createElement(zi,{color:h.secondary2},io(new Date(r))),vs.createElement(zi,{color:h.accent},`${t}/${n} edits`))}import qi from"chalk";import{Box as th,Text as qu}from"ink";import Yi,{useEffect as nh,useState as rh}from"react";var oh=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],sh=150,Yu=12,ih=.36,Xu=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)}},ah=({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)}`},dh=(e,t,n)=>{let r=Xu(e),o=Xu(t);return ah({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},ch=(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 dh(s,i,o)};function Ju({syncStatus:e,autoSync:t}){let[n,r]=rh(0);nh(()=>{if(e.status!=="syncing"){r(0);return}let c=0,l=setInterval(()=>{c+=1;let m=(Math.sin(c*ih)+1)/2,p=Math.round(m*(Yu-1));r(f=>f===p?f:p)},sh);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:ch(oh,n/(Yu-1))??""}[e.status];return Yi.createElement(th,null,Yi.createElement(qu,null,qi.hex(h.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Yi.createElement(qu,null,qi.hex(i)("\u25CF")+qi.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import nm from"chalk";import{Text as rm}from"ink";import om,{useEffect as ph,useState as fh}from"react";var rn="1.4.1";import Xi from"chalk";var lh="https://registry.npmjs.org/epiq/latest",Ji=null,Qu=0,uh=1e3*60*60*24,Zu=e=>e.replace(/^v/,""),mh=(e,t)=>{let n=Zu(e).split(".").map(Number),r=Zu(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},em=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Ji&&Date.now()-Qu<uh)return Ji;try{let t=await fetch(lh);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?mh(r,e)>0:!1};return Ji=o,Qu=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},tm=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Xi.hex(h.accent).dim(s):Xi.hex(h.secondary).dim(s)).join(Xi.hex(h.secondary2).dim("."))};function sm(){let[e,t]=fh({current:rn,latest:null,updateAvailable:!1});return ph(()=>{let n=!0;return em(rn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?om.createElement(rm,{dimColor:!0,color:h.secondary2},rn+" "):om.createElement(rm,null,nm.hex(h.secondary2).dim(rn),nm.hex(h.accent).dim(" \u2197 "),tm(rn,e.latest))}function Fr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=j(),{userName:i,preferredEditor:c,autoSync:l}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?ln(s.currentLabel,Math.max(0,p)):"";return xe.createElement(Br,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?xe.createElement(Br,{paddingLeft:1},xe.createElement(Vn,{color:h.secondary2},g)):f?xe.createElement(Vn,null," "):o===y.PALETTE?xe.createElement(Br,null,xe.createElement(Vn,{color:h.accent},"Command Palette"),xe.createElement(Vn,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):xe.createElement(Br,{paddingLeft:1},e.length>0?xe.createElement(Gu,{filters:e}):xe.createElement(Wu,{width:p})),n==="live"?xe.createElement(Br,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},xe.createElement(Ju,{autoSync:!!l,syncStatus:r}),xe.createElement(Vn,null,ys.hex(h.secondary2).dim("Mode: ")+ys.hex(h.secondary2).dim(o.padEnd(8," "))," "),xe.createElement(im,{icon:"@",value:i}),xe.createElement(im,{icon:"\u276F",value:c}),xe.createElement(sm,null)):"",n==="peek"?xe.createElement(Ku,null):"",n==="replay"?xe.createElement(zu,null):"")}function im({icon:e,value:t}){return xe.createElement(Vn,null,ys.dim(e)+ys.hex(h.accent)(` ${t??"-"} `))}import{Box as gh,Text as vh}from"ink";import Ur from"react";import{Box as hs,Text as Qi}from"ink";import on from"react";function Zi(){let e=j(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?z(t?.id):[];return on.createElement(hs,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:s},on.createElement(hs,{padding:1,paddingTop:0,paddingBottom:0},on.createElement(Qi,null,"Select a board:")),on.createElement(hs,{padding:1,flexDirection:"column"},i.map((c,l)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===l,f=z(c.id).flatMap(({id:g})=>Y(g)).length;return on.createElement(hs,{key:c.id??l},on.createElement(Qi,{color:m?h.accent:h.secondary2},on.createElement(ke,{isSelected:m})),on.createElement(Qi,{color:m?h.accent:h.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var yh=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=j(),l=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Ur.createElement(gh,{flexDirection:"row"},e.context==="WORKSPACE"?Ur.createElement(Zi,null):l?Ur.createElement(Uo,{height:f,width:i,swimlanes:(c[l.id]??[]).filter(g=>g!==void 0&&_t(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Ur.createElement(vh,null))},am=Ur.memo(yh);import{useEffect as hh}from"react";var xh=e=>{hh(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:l}=v();l==="default"&&!c&&ho(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},dm=({autoSync:e})=>(xh(e),null);function ea({width:e,height:t}){let n=j(),{autoSync:r,viewMode:o}=Pa(),s=n.filters;if(n.mode===y.HELP)return ce.createElement(sn,{flexDirection:"column"},ce.createElement($u,{width:e,height:t}));if(n.mode===y.PALETTE)return ce.createElement(sn,{flexDirection:"column"},ce.createElement(Fr,{filters:s}),ce.createElement(Au,{width:e,height:t-2}),ce.createElement(kr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Vt(),c=!i,l=i&&!n.hasProjectDefinition;if(c)return ce.createElement(sn,{flexDirection:"column"},ce.createElement(sn,{flexDirection:"column"},ce.createElement(Fr,{hideBreadCrumb:!0,filters:s}),ce.createElement(Ki,{height:t,width:e})),ce.createElement(kr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(l)return ce.createElement(sn,{flexDirection:"column"},ce.createElement(sn,{flexDirection:"column"},ce.createElement(Fr,{hideBreadCrumb:!0,filters:s}),ce.createElement(Hu,{height:t,width:e})),ce.createElement(kr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Ue(n.breadCrumb??[],"BOARD");if(Q(m)){let p=m.value.id,f=z(p).length,g=3,I=Math.floor(e/g),S=Math.floor(e/Math.max(f,1));e=Math.min(S,I)*Math.max(f,g)}return ce.createElement(sn,{flexDirection:"column"},ce.createElement(dm,{autoSync:r}),ce.createElement(sn,{flexDirection:"column"},ce.createElement(Fr,{filters:s}),ce.createElement(am,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ce.createElement(kr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import bh from"readline";var xs,bs,Nt,Ih=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.Yank,x.InitCommandLine,x.InitCommandPalette,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Eh=new Set([x.NavPreviousItem,x.NavNextItem,x.NavToPreviousContainer,x.NavToNextContainer,x.Confirm,x.Exit,x.InitCommandPalette,x.InitMove,x.MoveNextItem,x.MovePreviousItem,x.MoveToNextContainer,x.MoveToPreviousContainer,x.Delete,x.AddItem,x.EditTitle,x.EditDescription,x.ConfirmMove,x.Edit,x.ViewHelp,x.Yank]),cm=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=yc(e,n);if(!s||r&&!Ih.has(s)||o==="replay"&&n===y.DEFAULT&&Eh.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},Sh=()=>async function(t,n){n.name!=="escape"&&(Nt&&(clearTimeout(Nt),Nt=void 0),await cm(n))},Ch=()=>async function(t){if(t.length===1&&t[0]===27){Nt&&clearTimeout(Nt),Nt=setTimeout(()=>{cm({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Nt=void 0},25);return}Nt&&(clearTimeout(Nt),Nt=void 0)};function lm(){xs&&process.stdin.removeListener("keypress",xs),bs&&process.stdin.removeListener("data",bs),xs=Sh(),bs=Ch(),bh.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",bs),process.stdin.on("keypress",xs)}async function um(){try{let e=Ft();Q(e)&&Me(e.value);let t=_e(process.cwd()),n=[];if(Q(t)){let s=Re({repoRoot:t.value});if(d(s))return fn(3,s.message);let i=Sn(),c=await cn({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return fn(3,c.message);let l=await F({cwd:s.value,args:["pull","--ff-only"]});d(l)&&logger.info(3,l.message);let m=je(s.value);if(d(m))return fn(3,m.message);n=m.value}let r=pn(n);if(d(r))return fn(4,r.message);C({hasProjectDefinition:Q(t),hasInitializingEvents:!!n.length});let o=ta();return d(o)?fn(6,o.message):(lm(),u("Booted Epiq",void 0))}catch(e){return fn(0,go(e))}}Wc();var Th=`${an.bold("Epiq CLI")}
|
|
57
|
+
`,Ni.writeFileSync(t,n,"utf8"),ce.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var xv=async e=>{let t=await F({cwd:e,args:["status","--porcelain"]});return d(t)?t:u("Checked git diff",t.value.stdout.trim().length>0)},ne=(e,t)=>a(`[${e}] ${t}`),Zc=async()=>{V("");let e=Cn(),t=await gt(process.cwd());if(d(t))return ne(1,t.message);let n=t.value,r=await Hr(n);if(d(r))return ne(2,r.message);if(r.value)return ne(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await xv(n);if(d(o))return ne(2.5,o.message);if(o.value)return ne(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Bs(n))return ne(4,"Epiq project already initialized");let s=Gt();if(!s.isSetupDone||!s.userName)return ne(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=K(),c=i.userName,l=i.userId;if(!l||!c)return ne(5,"Missing Epiq user id");let m=e.stateBranch,p=await Wr({repoRoot:n,branch:m});if(d(p))return ne(6,p.message);if(p.value)return ne(6,`State branch already exists: ${m}`);let f=await Hs({repoRoot:n,stateBranchName:m});if(d(f))return ne(6,f.message);let g=Kr();if(d(g))return ne(7,g.message);let I=Qc.join(Gr(),e.projectId),S=await ln({repoRoot:n,stateBranchRoot:I,stateBranchName:m});if(d(S))return ne(8,S.message);let R=Qc.join(I,".epiq");hv.mkdirSync(R,{recursive:!0});let A=Md({userId:l,userName:c});if(d(A))return ne(9,A.message);for(let Ss of A.value){let ra=mo({event:Ss,rootDir:I});if(d(ra))return ne(9,ra.message)}let P=await Jr({stateBranchRoot:I,eventFileName:mn({userId:l,userName:c})});if(d(P))return ne(10,P.message);let _=await Rn({cwd:I,message:"[epiq:init]"});if(d(_))return ne(10,_.message);let w=await Jc(n);if(d(w))return ne(11,w.message);let W=sa({repoRoot:n,fileContents:e});if(d(W))return ne(12,W.message);let H=await le.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(H))return ne(13,H.message);let D=await le.commit({cwd:n,message:"[epiq:init-project]"});if(d(D))return ne(13,D.message);let $="Project initialized!",Ye=await F({cwd:n,args:["push","-u","origin","HEAD"]});d(Ye)&&($+=` Warn: [init:14] ${Ye.message}`);let we=await or({repoRoot:n,stateBranchRoot:I});d(we)&&($+=` Warn: [init:15] ${we.message}`);let ge=st(A.value).filter(d);if(ge.length>0)return ne(16,ge.map(Ss=>Ss.message).join(`
|
|
58
|
+
`));let me=We();if(d(me))return ne(16,me.message);let{rootNodeId:Gn,nodes:Kn}=me.value,na=Kn[Gn];return na?(M.navigate({contextNode:na,selectedIndex:0}),C({hasProjectDefinition:!0,mode:y.DEFAULT}),u($,null)):ne(16,"Unable to resolve initialized root node")};import{ulid as Iv}from"ulid";import{ulid as bv}from"ulid";var el=null,en=()=>structuredClone(el),Sr=e=>{el=e},tl=()=>{let{contextNode:e,selectedIndex:t}=v(),r=Y(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},Ri=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Y(t).filter(o=>o.id!==e);return po(r,n)},nl=({id:e,parentId:t,position:n={at:"end"}})=>{let r=se();if(d(r))return a("Unable to resolve user ID");let o=Ri({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:bv(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},rl=e=>{Sr(e);let t=Wt(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function Ai(e){let t=tl();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=Y(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let l=nl({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(l)?l:rl(l.value)}function Ti(e){let t=tl();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),s=Y(n.id)[r+e];if(!s)return a("Missing sibling node");let i=nl({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:rl(i.value)}var ol=()=>{let e=en();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=Y(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Ho=(e,t="Moved preview")=>{if(d(e))return e;let n=ol();return d(n)?n:(C({mode:y.MOVE}),u(t,null))},sl=async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=X().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=Y(n.id)[r];if(!o)return C({mode:y.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=Y(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],l=s[i+1],m=l!=null?{at:"before",sibling:l.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Ri({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Sr({id:Iv(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:y.MOVE}),u("Move initialized",null))}if(t==="next")return Ho(Ti(1));if(t==="previous")return Ho(Ti(-1));if(t==="to-next")return Ho(Ai(1));if(t==="to-previous")return Ho(Ai(-1));if(t==="confirm"){let s=en();if(!s)return a("No pending move to confirm");let i=await yt();if(d(i))return i;let c=U([s],i.value);if(d(c))return c;let l=ol();return d(l)?l:(Sr(null),C({mode:y.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Sr(null),C({mode:y.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Wo}from"ulid";import{monotonicFactory as Ev,ulid as Sv}from"ulid";var Cv=Ev(),jo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Cv();return u("Created issue events",[{id:Sv(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var il=async(e,t)=>{let n=se();if(d(n))return a("Unable to resolve user ID");let r=await yt();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=v(),l=m=>{let p=U([m],o);if(d(p))return p;let f=E.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=E.getNode(f.parentNodeId);return g?(M.navigate({contextNode:g,selectedIndex:E.getSiblings(f.parentNodeId).findIndex(({id:I})=>I===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=E.getNode(m);if(!p)return a("Workspace not found");let f=Ln(p.id,n.value,o);return d(f)?f:l({id:Wo(),action:"add.board",payload:{id:Wo(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Oe(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Ln(m.value.id,n.value,o);return d(p)?p:l({id:Wo(),action:"add.swimlane",payload:{id:Wo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=z(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let _=Oe(s,"SWIMLANE");return d(_)?null:_.value})();if(!p)return a("Unable to add issue in this context");let f=Ln(p.id,n.value,o);if(d(f))return f;let g=jo({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let I=g.value,S=U([...I],o);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let P=I.find(_=>_.action==="add.issue")?.payload.id;return P?(M.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:_})=>_===P)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};var Vo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=uo(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,l=it();if(d(l))return l;let p=st(i).filter(d);if(p.length>0)return it(),C(o),a(p.map(g=>g.message).join(", "));let f=v().nodes[e];return f?(M.navigate({contextNode:f,selectedIndex:r}),u("",{unappliedEvents:c})):(it(),C(o),a("Board did not exist at that date"))};var Nv=20,Rv=16,Av=150,Go=null,Ko=null;var In=()=>{Go!==null&&(clearInterval(Go),Go=null),Ko!==null&&(clearTimeout(Ko),Ko=null)},al=()=>{In(),C({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Tv=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)},dl=({events:e,startTime:t,durationMs:n})=>{In();let r=e.length,o=e.map(f=>qt(f)??t),s=o[r-1]??Date.now(),i=Tv(o),c=Math.max(1,Math.round(n*Nv/1e3)),l=Math.max(Math.round(n/c),Rv),m=0,p=0;C({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Go=setInterval(()=>{m++;let f=m/c,g=[],I;for(;p<r&&i[p]<=f;){let R=e[p],A=Wt(R);if(d(A)){al();return}g.push(...qs(R)),I=R,p++}if(p>=r||m>=c){for(;p<r;p++){let A=Wt(e[p]);if(d(A))break}let R=v().replay;C({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),In(),Ko=setTimeout(al,Av);return}let S=v().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:I?qt(I)??S?.currentTime??t:S?.currentTime??t,currentLabel:I?cd(I):S?.currentLabel??"",flashNodeIds:I?[...new Set(g)]:S?.flashNodeIds??[]}})},l)};var cl=async()=>{let e=Oe(v().breadCrumb,"BOARD");if(d(e))return e;let t=await gt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta;if(In(),r==="now"){let c=je(n.value);if(d(c))return a(c.message);let l=it();if(d(l))return l;let p=st(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(C({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"){let c=v().eventLog.at(-1),l=qt(c);if(l===null)return a("No previous event to peek");s=l}else if(r==="next"){let c=v().unappliedEvents.at(0),l=qt(c);if(l===null)return a("No next event to peek");s=l+1}else{let c=vn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Vo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var ll=async()=>{let e=Oe(v().breadCrumb,"BOARD");if(d(e))return e;let t=await gt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta,{dateInput:s,durationInput:i}=Eo(r,o);if(In(),v().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=vn(s);if(!c)return a("Invalid replay date");let l=i?Io(i):15e3;if(l===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=v(),f=Vo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(it(),C(p),u("Nothing to replay from that point",!0)):(dl({events:g,startTime:m,durationMs:l}),u("Replaying board history",!0))};import Mv from"zod";var ul=()=>{let e=X().commandMeta.inputString,t=Mv.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=Qe({autoSyncDebounceMs:t.data});return d(n)?n:(Me({autoSyncIntervalMs:t.data}),C({mode:y.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var ml=()=>{let e=X().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ud(e),n=Qe({autoSync:t});return d(n)?n:(Me({autoSync:t}),C({mode:y.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var pl=()=>{let e=X().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Qe({logLevel:e});return d(n)?n:(Me({logLevel:e}),C({mode:y.DEFAULT}),u(`Auto sync set to "${e}"`,null))};import{spawn as Pv}from"node:child_process";var Lv=()=>{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"]}}},fl=async e=>new Promise(t=>{let{command:n,args:r}=Lv();try{let o=Pv(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var Cr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await fl(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},gl=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=pr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case ye.REF:return Cr(He(o.id),"ref");case ye.TITLE:return Cr(o.title,"title");case ye.DESCRIPTION:return r?Cr(r.props?.description??"","description"):a("No issue in scope");case ye.TAGS:{if(!r)return a("No issue in scope");let s=Kt(r).map(({name:i})=>i);return Cr(s.join(", "),"tags")}case ye.ASSIGNEES:{if(!r)return a("No issue in scope");let s=zt(r).map(({name:i})=>i);return Cr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var vl=async()=>{V(""),C({mode:y.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await vo();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var kv=e=>e.action==="add.issue.comment",yl=e=>Object.values(v().tags).find(t=>t.name===e),hl=()=>{let{eventLog:e=[],contributors:t}=v(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t)){if(o.tombstoned){n.set(o.id,o.name);continue}n.set(o.id,Fn(o.name,n.get(o.id))??o.name)}return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},Dt=async()=>{let e=await yt();return d(e)?e:u("Resolved persist root",e.value)},zo=[{systemOnly:!0,intent:k.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:sl},{intent:k.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await Dt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=T(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!T(c))return a("Unable to resolve comment issue");let l=c.log?.filter(kv).find(m=>m.payload.id===s);return l?l.payload.author!==e.value.userId?a("You can only delete your own comments"):U([{id:Be(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return U([{id:Be(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=X().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>ie(b.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),u("Filter updated",null)}},{intent:k.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return Zt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:y.HELP}),u("Viewing help",null)}},{intent:k.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!T(r))return a("Cannot close in this context");let o=v().nodes[ve];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await Dt();if(d(s))return s;let i=s.value,c=pn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let l=U([{id:Be(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(l)?l:u("Issue closed",null)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):At(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=v().nodes[ve];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!T(s))return a("Target node is not issue");let c=Oo(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let l=v().nodes[c];if(!l)return a("Previous parent no longer exists");let m=await Dt();if(d(m))return m;let p=m.value,f=pn(l.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=U([{id:Be(),action:"reopen.issue",payload:{id:s.id,parent:l.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:Zc},{intent:k.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:il,onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=vc();if(!o)return a("Provide a title");let s=await Dt();return d(s)?s:U([{id:Be(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=yl(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return a("Invalid untag target");let i=At(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!T(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await Dt();return d(m)?m:U([{id:Be(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let s=At(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=await Dt();if(d(c))return c;let l=yl(r),m=l?.id??Be();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):U([...l?[]:[{id:Be(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Be(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),l=z(c.id)[i];if(!l)return a("Invalid assign target");let m=At(l.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!T(p))return a("Target node is not issue");let f=await Dt();if(d(f))return f;let g=hl(),I=!o&&s.toLowerCase()==="me",S,R;if(I)S=e.value.userId,R=g.find(_=>_.id===S)?.name??e.value.userName;else{let _=g.filter(W=>W.name===s);if(_.length>1)return a(`"${s}" matches ${_.length} contributors (${_.map(W=>W.id).join(", ")}). Assign from the GUI to choose by id.`);let w=_[0];if(!w&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);S=w?.id??Be(),R=w?.name??s}if((p.props.assignees??[]).includes(S))return a("Assignee already assigned");let P=!!v().contributors[S];return U([...P?[]:[{id:Be(),action:"create.contributor",payload:{id:S,name:R},...e.value}],{id:Be(),action:"add.issue.assignee",payload:{id:p.id,assignee:S},...e.value}],f.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=se();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return a("Invalid unassign target");let s=At(o.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=i.props.assignees??[],l=r.toLowerCase()==="me",m=l?c.filter(g=>g===e.value.userId):hl().filter(g=>g.name===r&&c.includes(g.id)).map(g=>g.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(l?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Dt();return d(f)?f:U([{id:Be(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>4e3)return a(`Cannot exceed ${4e3} characters`);let r=se();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=v(),i=Oe([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let l=c.context==="TICKET"?u("Resolved ticket",c):At(c.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let m=l.value;if(!T(m))return a("Target node is not issue");let p=await Dt();return d(p)?p:U([{id:Be(),action:"add.issue.comment",payload:{id:Be(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:vl},{intent:k.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:cl},{intent:k.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:ll},{intent:k.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await Hc();return d(e)?e:(C({mode:y.DEFAULT}),u("Export successful",!0))}},{intent:k.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(M.exit(),u("Exit successful",!0))},{intent:k.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>Xc(t),onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>gl(t),onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case re.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??Be();if(!i||!c)return a("Unable to resolve user name or id");let l=Qe({userName:i,userId:c,preferredEditor:o??""});return d(l)?l:(Me({userName:i,userId:c}),C({mode:y.DEFAULT}),u(`Username set to "${i}"`,null))}case re.EDITOR:{if(!n)return a("No editor provided");let r=Qe({preferredEditor:n});return d(r)?r:(Me({preferredEditor:n}),C({mode:y.DEFAULT}),u(`Editor configuration set to "${n}"`,null))}case re.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Qe({viewMode:n});return d(r)?r:(Me({viewMode:n}),C({mode:y.DEFAULT}),u(`View set to "${n}"`,null))}case re.AUTOSYNC:return ml();case re.LOG_LEVEL:return pl();case re.SYNC_DEBOUNCE_MS:return ul();case re.ATTACHMENT_MAX_KB:return Xd();default:return a("Unknown config command")}}},{intent:k.Coffee,description:"Sponsor the development of Epiq!",mode:y.COMMAND_LINE,action:()=>{let e=X().commandMeta.modifier;return e==="custom"?Er("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Er(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),V(""),u("Thanks you!",null)}}];var Dv=new Set(["peek","replay","filter","view-help","yank"]),St=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=X();if(!t)return a("No command to confirm");if(!e&&n===bt.Invalid)return a("Invalid command");let s=wo(t);uc();let{readOnly:i}=v();if(i&&!Dv.has(s))return yr({status:Ft.Fail,message:"Command not available in readonly state",value:null});let c=zo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return yr({status:Ft.Fail,message:"Command not found",value:null});let l;try{l=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return yr({status:Ft.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(l)?yr(l):(mc({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&ho(),l)};var qo=[{intent:x.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:y.COMMAND_LINE}),V("move cancel"),St({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:y.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:y.COMMAND_LINE}),V("move start"),St({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:y.MOVE,action:()=>(C({mode:y.COMMAND_LINE}),V("move confirm"),St({isForceExecutedBySystem:!0}))}],Yo=[{intent:x.MovePreviousItem,mode:y.MOVE,action:()=>en()?(C({mode:y.COMMAND_LINE}),V("move previous"),St({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveNextItem,mode:y.MOVE,action:()=>en()?(C({mode:y.COMMAND_LINE}),V("move next"),St({isForceExecutedBySystem:!0})):a("No pending move")}],xl=[{intent:x.MoveToNextContainer,mode:y.MOVE,action:()=>en()?(C({mode:y.COMMAND_LINE}),V("move to-next"),St({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveToPreviousContainer,mode:y.MOVE,action:()=>en()?(C({mode:y.COMMAND_LINE}),V("move to-previous"),St({isForceExecutedBySystem:!0})):a("No pending move")}];var bl={[B.WORKSPACE]:[...qo,...Yo],[B.BOARD]:[...qo,...Yo],[B.SWIMLANE]:[...qo,...Yo,...xl],[B.TICKET]:[],[B.FIELD]:[],[B.FIELD_LIST]:[],[B.TEXT]:[],[B.COMMENT]:[]};import Bv from"node:fs";import Fv from"node:path";var Il=e=>{let t=$e(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Re({repoRoot:t.value});if(d(n))return a(n.message);let r=Dn(e.hash,e.ext),o=Fv.join(nr(n.value),r);return Bv.existsSync(o)?(Er(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var El=()=>{V("");let{pendingNavTarget:e}=Qt();C({mode:y.DEFAULT}),e&&M.navigate(e),Zt({pendingNavTarget:void 0})},Sl=[{intent:x.ExitCommandLine,mode:y.HELP,action:()=>(El(),u("Exiting help",null))},{intent:x.Exit,mode:y.HELP,action:()=>(El(),u("Closed help",null))},{intent:x.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:x.NavNextItem,mode:y.HELP,action:()=>(M.navigateToNextItem(),u("Navigating to next help item",null))},{intent:x.NavToPreviousContainer,mode:y.HELP,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:x.NavToNextContainer,mode:y.HELP,action:()=>(M.navigateToNextContainer(),u("Navigating to next help container",null))}];var Uv=e=>{C({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=Qt();t&&M.navigate(t),Zt({pendingNavTarget:void 0}),V(`${e} `)},Cl=()=>{V("");let{pendingNavTarget:e}=Qt();e&&M.navigate(e),Zt({pendingNavTarget:void 0}),C({mode:y.DEFAULT})},Nl=[{intent:x.InitCommandPalette,mode:y.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{V("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return Zt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:y.PALETTE}),u("Opening command palette",null)}},{intent:x.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!_t(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Uv(t),u("Selected command",t)):u("No command selected",null)}},{intent:x.ExitCommandLine,mode:y.PALETTE,action:()=>(Cl(),u("Exiting palette",null))},{intent:x.Exit,mode:y.PALETTE,action:()=>(Cl(),u("Closed command palette",null))},{intent:x.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:y.PALETTE,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:y.PALETTE,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:y.PALETTE,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var Rl=[...Sl,...Nl,{intent:x.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.NEW} `),u("Adding new item",null))},{intent:x.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.DELETE} `),u("Deleting item",null))},{intent:x.InitCommandLine,mode:y.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:y.COMMAND_LINE}),V(""),u("Entering command line mode",null))},{intent:x.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Y(e?.id??"")?.length){let r=e?E.getAttachment(e.id):void 0;if(r)return Il(r);if(e?.title===Z.DESCRIPTION)return C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Propose command",!0);if(e?.title===Z.ASSIGNEES)return C({mode:y.COMMAND_LINE}),V(`${b.ASSIGN} `),u("Propose command",!0);if(e?.title===Z.TAGS)return C({mode:y.COMMAND_LINE}),V(`${b.TAG} `),u("Propose command",!0);if(t.title===Z.DESCRIPTION&&e?.context==="TEXT")return C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Propose command",!0)}return M.enterChildNode(),u("Entering context",null)}},{intent:x.Yank,mode:y.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=v(),t=e?.title===Z.DESCRIPTION?ye.DESCRIPTION:e?.title===Z.TAGS?ye.TAGS:e?.title===Z.ASSIGNEES?ye.ASSIGNEES:ye.REF,r=ie(b.YANK).includes(t)?t:ye.REF;return C({mode:y.COMMAND_LINE}),V(`${b.YANK} ${r}`),u("Propose command",!0)}},{intent:x.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:x.EditDescription,mode:y.DEFAULT,description:"[e] edit description",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Exiting context",null))},{intent:x.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),u("Exiting context",null))},{intent:x.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:y.DEFAULT,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:y.DEFAULT,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var Ov=500,_v=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Al=e=>{let t=_v(e);t&&To(n=>(n+t).slice(0,Ov))};var $v=[y.COMMAND_LINE,y.PALETTE],Hv=e=>[{intent:x.MoveCursorLeft,mode:e,action:()=>(ui(-1),u("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:e,action:()=>(ui(1),u("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:e,action:()=>(mi("left"),u("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:e,action:()=>(mi("right"),u("Moving cursor right of word",null))},{intent:x.AutoCompleteCommand,mode:e,action:()=>(To((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=v().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:x.CaptureInput,mode:e,action:(t,{sequence:n})=>(Al(n??""),u("Capturing input",null))},{intent:x.EraseInput,mode:e,action:()=>(cc(),u("Erasing input",null))},{intent:x.EraseInputWord,mode:e,action:()=>(lc(),u("Erasing input word",null))}],Tl=[{intent:x.Confirm,mode:y.COMMAND_LINE,action:()=>(St(),u("Executing command",null))},{intent:x.ViewHelp,mode:y.DEFAULT,action:()=>(C({mode:y.HELP}),u("Viewing help",null))},...$v.flatMap(Hv),{intent:x.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(C({mode:y.DEFAULT}),u("Exiting command line",null))},{intent:x.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(pc(),u("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(fc(),u("Getting next command from history",null))}];import Pl from"chalk";var Xo=Pl.dim.hex(h.secondary2)(": for command line"),wl="q to exit",Ml=`${Pl.hex(h.accent)("m")} to confirm`,wi={[B.WORKSPACE]:[Xo],[B.BOARD]:[Xo],[B.BOARD+y.COMMAND_LINE]:[Xo],[B.SWIMLANE]:[Xo],[B.TICKET+y.HELP]:[wl],[B.SWIMLANE+y.HELP]:[wl],[B.TICKET]:[],[B.FIELD]:[],[B.SWIMLANE+y.MOVE]:[Ml],[B.TICKET+y.MOVE]:[Ml]};var Nr=e=>e.trim().toLocaleLowerCase(),jv=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Wv=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?Yt(n,r.name):void 0}).filter(n=>!!n)},Ll=(e,t)=>{let n=Nr(t.value);if(!n)return!0;switch(t.target){case"title":return Nr(e.title??"").includes(n);case"description":return Nr(e.props.description??"").includes(n);case"tag":return jv(e).map(Nr).some(o=>o.includes(n));case"assignee":return Wv(e).map(Nr).some(o=>o.includes(n));case"ref":return Za(e.id,t.value);default:return!0}};function kl(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Dl=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 En,Mi,Pi=new Set,Bl=()=>{for(let e of Pi)e()},Gv=e=>(Pi.add(e),()=>Pi.delete(e));function Fl(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let l=kl(t,o,r);if(d(l))return logger.error(l.message),l;let m=l.value,{context:p}=c,f=wi[p+n]??wi[p]??[],g=[...Rl,...bl[p]??[],...Tl],I=Dl(g),S=Kv(o,s),R=S[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:g,actionIndex:I,selectedNode:R,renderedChildrenIndex:S})}var v=()=>{if(!En)throw new Error("State not initialized. Call initWorkspaceState() first.");return En},We=()=>En?u("Retrieved state",En):a("State not initialized. Call initWorkspaceState() first.");function dr(e){Mi=e;let t=$e(process.cwd()),n=!1;if(!d(t)){let s=ut(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=Fl(r);return d(o)?o:(En=o.value,Bl(),u("State initialized",null))}function pe(e){let t=v(),n=e(t),r=Fl(n);return d(r)?a(r.message??"Unable to update state"):(En=r.value,Bl(),u("State updated",null))}var C=e=>pe(t=>({...t,...e}));var j=()=>Vv(Gv,v,v),Kv=(e,t)=>{let n={};for(let r of Object.values(e))T(r)&&t.length>0&&!t.every(o=>Ll(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},z=e=>v()?.renderedChildrenIndex[e]??[],it=()=>Mi?dr(Mi):a("Cannot reset state: no initial workspace found"),Vt=()=>En!==void 0;var Li=e=>{Vt()&&(C({syncStatus:e}),Ot({type:"sync-status",payload:e}))},Jo=(e="Syncing...")=>{Li({status:"syncing",msg:e})},Qo=(e="Synced")=>{Li({status:"synced",msg:e})},ki=e=>{Li({status:"failed",msg:e})},et=e=>(ki(e),a(e));import{decodeTime as MD}from"ulid";var zv=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=J("getRepoRootDir",await gt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=J("getStateBranchRoot",Re({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=J("ensureInitialCommit",await Da(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=J("bootstrapStateBranchStorage",await Ua({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=J("hasInProgressGitOperation(stateBranchRoot)",await Hr(s));if(d(l))return a(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=J("ensureStateBranchLayout",Ia(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},qv=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=J("stageStateBranchOwnEventFile",await Jr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=J("stageStateBranchMediaFiles",await Ba({stateBranchRoot:t}));if(d(o))return a(o.message);let s=J("hasStagedChanges(after stage)",await fa(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=J("createStateBranchSyncCommit",await Fa({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),u("Committed own event file",{createdCommit:!0,commitSha:i.value}))},yo=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Jo();let n=J("ensureSyncReady",await zv({cwd:e,ensureUpstream:!0}));if(d(n))return et(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=J("isDetachedHead(stateBranchRoot)",await ga(o));if(d(i))return et(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return et("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,l,m=!1,p=!1,f=J("getStateBranch",Nn(r));if(d(f))return et(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let I=J("commitOwnEventFileToStateBranch",await qv({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(I))return et(I.message);c=I.value.createdCommit,l=I.value.commitSha;let S=J("pullBranchRebaseIfPresent",await Ps({cwd:o,branch:g}));if(d(S))return et(S.message);if(m=S.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let R=J("pushStateBranch",await or({stateBranchRoot:o,repoRoot:r}));if(d(R)&&pa(R.message)){let A=J("pullBranchRebaseIfPresent(retry)",await Ps({cwd:o,branch:g}));if(d(A))return et(A.message);m=m||A.value,R=J("pushStateBranch(retry)",await or({stateBranchRoot:o,repoRoot:r}))}if(d(R))return et(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let R=J("git rev-parse HEAD",await F({args:["rev-parse","HEAD"],cwd:o}));if(d(R))return et(R.message);l=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",l)}return Qo(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:l,pulled:m,pushed:p,bootstrapped:s})};import{existsSync as Di}from"node:fs";import{chmod as Bi}from"node:fs/promises";import jl from"node:os";import Hn from"node:path";var Ul=(e,t)=>e.reduce((n,r)=>r<n?r:n,t);var Ol=1e5,Zo=null,_l=Promise.resolve(),tn=e=>{let t=_l.then(e,e);return _l=t.then(()=>{},()=>{}),t},Fi=e=>{let t=$e(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Ui=e=>{let t=Fi(e);return d(t)?t:Re({repoRoot:t.value})},at=()=>{if(!Vt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:Zo}},Oi=(e,t)=>{let n=new Map,r=new Set,o=i=>{let c=new Set,l=i;for(;l&&!c.has(l);){if(r.has(l))return l;c.add(l),l=n.get(l)}return null},s=[];for(let i of e){let c=i.payload,l=c?.id;l&&(i.action==="add.board"&&r.add(l),c.parent&&n.set(l,c.parent),(l===t||o(l)===t)&&s.push(i))}return s},Wl=async(e={})=>{let t=Ui(e.repoRoot);if(d(t))return a(t.message);let n=je(t.value);if(d(n))return a(n.message);let o=(e.boardId?Oi(n.value,e.boardId):n.value).map(qt).filter(g=>g!==null),s=Date.now(),i=e.end??s,c=e.start??Ul(o,i);if(i<=c)return u("Empty time window",{bucketMs:0,buckets:[],earliest:c,latest:i});let l=o.filter(g=>g>=c&&g<i).sort((g,I)=>g-I),m=Math.max(1,Math.ceil((i-c)/Ol)),p=new Map;for(let g of l){let I=Math.min(Ol-1,Math.floor((g-c)/m)),S=c+I*m;p.set(S,(p.get(S)??0)+1)}let f=[...p.entries()].sort(([g],[I])=>g-I).map(([g,I])=>({t:g,count:I}));return u("Computed event timeline",{bucketMs:m,buckets:f,earliest:c,latest:i})},Rr="",$l="",Vl=async(e={})=>{let t=Fi(e.repoRoot);if(d(t))return a(t.message);let n=ut(t.value);if(d(n))return a(n.message);let r=await F({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=${$l}%H${Rr}%at${Rr}%an${Rr}%s`]});if(d(r))return a(r.message);let o=r.value.stdout.split($l).filter(s=>s.trim().length>0).map(s=>{let[i,...c]=s.split(`
|
|
59
|
+
`),[l,m,p,...f]=(i??"").split(Rr);if(!l||!m)return null;let g=c.join(" "),I=Number(/(\d+) insertion/.exec(g)?.[1]??0),S=Number(/(\d+) deletion/.exec(g)?.[1]??0);return{sha:l,time:Number(m)*1e3,author:p??"unknown",subject:f.join(Rr),linesChanged:I+S}}).filter(s=>s!==null);return u("Computed commit timeline",o)},Yv=e=>/^[0-9a-f]{7,40}$/i.test(e),Xv=async(e,t)=>{let n=await F({cwd:e,args:["show",t]});if(d(n))return a(n.message);let r=Hn.join(jl.tmpdir(),"epiq","commit-diffs");be.mkDir(r);let o=Hn.join(r,`${t}.diff`);return Di(o)||(be.writeToFile(o,n.value.stdout),await Bi(o,292)),Yc(o)},Jv=12,Qv=800,Hl=async(e,t,n)=>{let r=await F({cwd:e,args:["show",`${t}:${n}`]});return d(r)?"":r.value.stdout},Zv=async(e,t,n)=>{let r=await F({cwd:e,args:["diff-tree","--no-commit-id","--name-only","-r",t]});if(d(r))return a(r.message);let o=r.value.stdout.split(`
|
|
60
|
+
`).map(f=>f.trim()).filter(Boolean);if(o.length===0)return a("No changed files found for this commit");if(o.length>Jv)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Hn.join(jl.tmpdir(),"epiq","commit-diffs",t),i=await Promise.all(o.map(async(f,g)=>{let[I,S]=await Promise.all([Hl(e,`${t}~1`,f),Hl(e,t,f)]),R=Hn.basename(f),A=Hn.join(s,String(g),"before",R),P=Hn.join(s,String(g),"after",R);return Di(A)||(be.writeToFile(A,I),await Bi(A,292)),Di(P)||(be.writeToFile(P,S),await Bi(P,292)),{beforePath:A,afterPath:P}})),[c,...l]=i;if(!c)return a("No changed files found for this commit");let m=await Si(n,c.beforePath,c.afterPath,"new");if(d(m)||l.length===0)return m;await new Promise(f=>setTimeout(f,Qv));let p=await Promise.all(l.map(({beforePath:f,afterPath:g})=>Si(n,f,g,"reuse")));for(let f of p)d(f)&&logger.error(`Failed to open an additional diff tab for ${t}: ${f.message}`);return m},Gl=async e=>{if(!Yv(e.sha))return a("Invalid commit sha");let t=Fi(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=$o()[0];if(r&&Ei(r)){let o=await Zv(n,e.sha,r);if(!d(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return Xv(n,e.sha)},Kl=e=>{let t=je(e);if(d(t))return a(t.message);let n=it();if(d(n))return a(n.message);Zo=null;let o=st(t.value).filter(d);return o.length>0?a(o.map(s=>s.message).join(", ")):(C({readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},ey=(e,t)=>{Zo=null;let n=Kl(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},zl=e=>tn(async()=>{let t=Ui(e.repoRoot);if(d(t))return a(t.message);let n=uo(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=it();if(d(s))return s;let c=st(r).filter(d);return c.length>0?ey(t.value,c.map(l=>l.message).join(", ")):(C({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),Zo=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),ql=(e={})=>tn(async()=>{let t=Ui(e.repoRoot);if(d(t))return a(t.message);let n=Kl(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});var _i=()=>{let e=Ut();return d(e)?xt:e.value.attachmentMaxKb??xt},$i=e=>{let t=$e(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Ne=async(e,t)=>{let n=$i(e);if(d(n))return n;let r=Re({repoRoot:n.value});if(d(r))return a(r.message);let o=Cn(),s=await ln({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.stateBranch});if(d(s))return a(s.message);if(t?.pull??!1){let l=await F({cwd:r.value,args:["pull","--ff-only"]});d(l)&&ce.info(3,l.message)}let i=je(r.value);if(d(i))return a(i.message);let c=fn(i.value);return d(c)?a(c.message):u("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:r.value})},Ae=()=>{let e=Ut();return d(e)?a(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},Fe=()=>{let e=We();return d(e)?a(e.message):e},Xl=e=>(e.props.tags??[]).map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ue(t.name)})),Hi=()=>{let e=We(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},Jl=(e,t)=>{let n=new Map(e);for(let r of Object.values(t)){if(r.tombstoned){n.set(r.id,r.name);continue}n.set(r.id,Fn(r.name,n.get(r.id))??r.name)}return n},Ql=(e,t=new Map)=>(e.props.assignees??[]).map(n=>E.getContributor(n)).filter(n=>n!=null).map(n=>{let r=n.tombstoned?n.name:Fn(n.name,t.get(n.id))??n.name;return{id:n.id,name:r,color:ue(r)}});var Zl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Fe();if(d(n))return n;let r=n.value.nodes,o=Hi(),s=Object.values(r).filter(T).filter(i=>!i.isDeleted).filter(i=>e.includeClosed||i.parentNodeId!==ve).filter(i=>e.boardId?(i.parentNodeId?r[i.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(i=>({id:i.id,ref:He(i.id),title:Ze(i.title),description:i.props.description??"",parentNodeId:i.parentNodeId,isClosed:i.parentNodeId===ve,readonly:!!i.readonly,tags:Xl(i),assignees:Ql(i,o)}));return u("Listed issues",s)},eu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=Ln(e.parentId,n.value,t.value.stateBranchRoot);if(d(o))return o;let s=jo({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(d(s))return s;let i=[...s.value],c=i.find(f=>f.action==="add.issue")?.payload.id;if(!c)return a("Unable to determine created issue id");e.description&&i.push({id:q(),...n.value,action:"edit.description",payload:{id:c,md:e.description}});let l=[];for(let f of e.tagNames??[]){let g=Ze(f).trim();if(!g||l.some(R=>R.name===g))continue;let I=Object.values(r.value.tags).find(R=>R.name===g),S=I?.id??q();I||i.push({id:q(),...n.value,action:"create.tag",payload:{id:S,name:g}}),i.push({id:q(),...n.value,action:"add.issue.tag",payload:{id:c,tag:S}}),l.push({id:S,name:g})}let m=[];for(let f of e.assigneeNames??[]){let g=Ze(f).trim();if(!g||m.some(R=>R.name===g))continue;let I=Object.values(r.value.contributors).find(R=>R.name===g),S=I?.id??q();I||i.push({id:q(),...n.value,action:"create.contributor",payload:{id:S,name:g}}),i.push({id:q(),...n.value,action:"add.issue.assignee",payload:{id:c,assignee:S}}),m.push({id:S,name:g})}let p=U(i,t.value.stateBranchRoot);return d(p)?a(p.message):u("Created issue",{id:c,title:e.title,parentId:e.parentId,description:e.description??"",tags:l,assignees:m})},tu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=pn(ve,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:q(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ve,rank:r.value}},s=U([o],t.value.stateBranchRoot);return d(s)?a(s.message):u("Closed issue",{id:e.issueId})},nu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Target node is not issue");if(o.parentNodeId!==ve)return a("Issue is not closed");let s=Oo(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ve)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=pn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let l={id:q(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=U([l],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,parentId:i.id})},ru=async e=>{let t=$i(e.repoRoot);if(d(t))return t;let n=Ae();if(d(n))return n;let r=Re({repoRoot:t.value});if(d(r))return r;let o=je(r.value);if(d(o))return o;let s=fn(o.value);if(d(s))return s;let i=pn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:q(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},l=U([c],r.value);return d(l)?a(l.message):u("Moved issue",{id:e.issueId,parentId:e.parentId})};var es=async(e={})=>{Jo();let t=$i(e.repoRoot);if(d(t))return a("Sync failed");let n=Ae();if(d(n))return n;let r=await yo({cwd:t.value,ownEventFileName:mn(n.value)});return d(r)?(ki(r.message),r):(Qo(),u("Synced",r.value))};var Ar=()=>{let e=Fe();if(d(e))return e;let t=at(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(g=>Zr(g)&&!g.isDeleted),s=Hi(),i=new Map,c=new Map;for(let g of r)if(!g.isDeleted){if($t(g)&&g.parentNodeId){let I=i.get(g.parentNodeId)??[];I.push(g),i.set(g.parentNodeId,I)}if(T(g)&&g.parentNodeId){let I=c.get(g.parentNodeId)??[];I.push(g),c.set(g.parentNodeId,I)}}let l=Ut();if(d(l))return l;let m={};for(let g of r.filter(T))g.isDeleted||(m[g.id]=E.getCommentsByIssue(g.id).map(I=>{let S=E.getContributor(I.authorId);return{id:I.id,issueId:I.issue,body:I.md,author:{id:I.authorId,name:S?.name??"Unknown",color:ue(S?.name??I.authorId)},createdAt:Yl(I.id)}}));let p=new Map;for(let g of e.value.eventLog)g.action==="add.issue.attachment"&&p.set(g.payload.id,g.payload.author);let f={};for(let g of r.filter(T))g.isDeleted||(f[g.id]=E.getAttachmentsByIssue(g.id).map(I=>({id:I.id,issueId:I.issue,name:I.name,fileName:Dn(I.hash,I.ext),bytes:I.bytes,createdAt:Yl(I.id),canDelete:p.get(I.id)===l.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((g,I)=>g.rank.localeCompare(I.rank)).map(g=>({id:g.id,ref:He(g.id),title:g.title,swimlanes:(i.get(g.id)??[]).sort((I,S)=>I.rank.localeCompare(S.rank)).map(I=>({id:I.id,title:I.title,readonly:!!I.readonly||n,issues:(c.get(I.id)??[]).sort((S,R)=>S.rank.localeCompare(R.rank)).map(S=>({id:S.id,ref:He(S.id),title:Ze(S.title),description:S.props.description??"",readonly:!!S.readonly||n,tags:Xl(S),assignees:Ql(S,s),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===ve})),parentNodeId:I.parentNodeId}))})),tags:Object.values(e.value.tags).map(g=>({...g,color:ue(g.name)})),contributors:Object.values(e.value.contributors).map(g=>({...g,color:ue(g.name)})),user:{name:l.value.userName??"",id:l.value.userId??"",color:ue(l.value.userName??"")},commentsByIssueId:m,attachmentsByIssueId:f,attachmentMaxKb:_i(),timeTravel:t})},dt=async(e={})=>{if(at().mode!=="live")return Ar();let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:Ar()},ou=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return u("No changes made",{id:e.issueId,description:s});let i={id:q(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,description:e.description})},su=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Ze(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return u("No changes made",{id:e.issueId,title:s});let i={id:q(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,title:s})},iu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Ze(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??q(),l=[...i?[]:[{id:q(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:q(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=U(l,t.value.stateBranchRoot);return d(m)?a(m.message):u("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},au=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:q(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,tagId:e.tagId})},du=async(e,t)=>{let n=je(e);if(d(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},cu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let R=r.value.contributors[s],A=R?void 0:await du(t.value.stateBranchRoot,s);if(!R&&!A)return a("Unknown assignee id");let P=R??A,_=[...R?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:P.id,name:P.name}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:P.id}}],w=U(_,t.value.stateBranchRoot);return d(w)?a(w.message):u("Added issue assignee",{id:e.issueId,assignee:{id:P.id,name:P.name}})}let i=Ze(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=[...Jl(Hi(),r.value.contributors).entries()].filter(([,R])=>R===i);if(l.length>1)return a(`"${i}" matches ${l.length} contributors (${l.map(([R])=>R).join(", ")}). Assign by assigneeId to choose.`);let m=l[0];if(!m&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[p=q(),f=i]=m??[],I=[...!!r.value.contributors[p]?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:p,name:f}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],S=U(I,t.value.stateBranchRoot);return d(S)?a(S.message):u("Added issue assignee",{id:e.issueId,assignee:{id:p,name:f}})},lu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await du(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:q(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=U(i,t.value.stateBranchRoot);return d(c)?a(c.message):u("Tombstoned contributor",{id:e.contributorId,name:to})};var uu=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=je(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Oi(o.value,e.boardId):o.value,i=new Map,c=new Set,l=new Set;for(let g of o.value)g.userId&&l.add(g.userId);for(let g of s)g.userId&&(i.set(g.userId,g.userName??""),c.add(g.userId));let m=r.value.contributors,f=[...Jl(i,m).entries()].map(([g,I])=>({id:g,name:I,color:ue(I),isSelf:g===n.value.userId,isExternal:!c.has(g),isRemoved:m[g]?.tombstoned===!0,hasAuthoredAnywhere:l.has(g)}));return u("Listed board contributors",f)},mu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:q(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},ts=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=q(),c={id:q(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},ns=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},pu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=qd(t.value.stateBranchRoot,s,_i());if(d(i))return i;let c=Ze(e.name??"").trim()||"image",l=q(),m={id:q(),...n.value,action:"add.issue.attachment",payload:{id:l,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=U([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Added issue attachment",{id:l,issueId:e.issueId,fileName:Dn(i.value.hash,i.value.ext),bytes:i.value.bytes})},fu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return a("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return a("You can only delete your own attachments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Attachment target must be an issue");if(s.readonly)return a("Cannot delete attachment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},gu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:Yd(t.value.stateBranchRoot,e.fileName,_i())};var ty=15e3,vu=e=>{let t,n=!1,r=!1,o=0,s=()=>{let p=Yr();return d(p)?(ce.error(p.message),null):p.value},i=()=>{let p=s();if(!p)return!1;let{autoSync:f,userName:g,preferredEditor:I}=p;return!!(f&&g&&I)},c=()=>{let p=s()?.autoSyncDebounceMs??ty;return Math.max(0,p-(Date.now()-o))},l=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await tn(async()=>{if(at().mode!=="live")return;let p=await es({repoRoot:e.repoRoot});if(d(p))return;let{pulled:f,createdCommit:g,bootstrapped:I}=p.value;!f&&!g&&!I||Ot({type:"state",payload:await dt({repoRoot:e.repoRoot})})})}finally{r=!1,m()}}};function m(){n||!i()||r||t||(t=setTimeout(()=>{t=void 0,l()},c()))}return m(),{queueSync:m,dispose:()=>{n=!0,t&&clearTimeout(t)}}};import{WebSocketServer as ny}from"ws";var yu=new Set(["sync","issues:create","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var hu=()=>{let e=Ar();Ot({type:"state",payload:e})},ae=(e,t)=>{e.send(JSON.stringify(t))},rs=async(e,t)=>ae(e,{type:"state",payload:await dt({repoRoot:t})}),ry=async(e,t)=>{let n=()=>ae(e,{type:"state",payload:Ar()});if(at().mode!=="live")return n();let r=await dt({repoRoot:t});return at().mode!=="live"?n():ae(e,{type:"state",payload:r})},ct=async(e,t,n,r,o)=>{if(ae(e,{type:r,payload:o}),d(o))return ae(e,{type:"failed",payload:o.message});n(),ry(e,t)},xu=(e,t,{onStateChanged:n})=>{new ny({server:e,path:"/ws"}).on("connection",o=>{Oa(o),o.on("message",async s=>{let i=async c=>{let{type:l}=c;if(l==="timeline:get"){let{requestId:m,...p}=c.payload??{};return ae(o,{type:"timeline",requestId:m,payload:await Wl({repoRoot:t,...p})})}if(l==="commits:get"){let{requestId:m,...p}=c.payload??{};return ae(o,{type:"commits",requestId:m,payload:await Vl({repoRoot:t,...p})})}if(l==="commit:inspect")return ae(o,{type:"commit:inspect:result",payload:await Gl({repoRoot:t,sha:c.payload.sha})});if(l==="time-travel:scrub"){let m=await zl({repoRoot:t,targetTime:c.payload.targetTime});return ae(o,{type:"time-travel:result",payload:m}),d(m)?void 0:hu()}if(l==="time-travel:live"){let m=await ql({repoRoot:t});return ae(o,{type:"time-travel:result",payload:m}),d(m)?void 0:hu()}if(l==="state:get")return rs(o,t);if(l==="sync"){let m=await es({repoRoot:t});return ae(o,{type:"sync:result",payload:m}),n(),rs(o,t)}if(l==="issue:comment:add"){let m=await ts({repoRoot:t,...c.payload});return ct(o,t,n,"issue:comment:add:result",m)}if(l==="issue:comment:delete"){let m=await ns({repoRoot:t,...c.payload});return ae(o,{type:"issue:comment:delete:result",payload:m}),d(m)?ae(o,{type:"failed",payload:m.message}):(n(),rs(o,t))}if(l==="issue:edit:description"){let m=await ou({repoRoot:t,...c.payload});return ct(o,t,n,"issue:edit:description:result",m)}if(l==="issue:edit:title"){let m=await su({repoRoot:t,...c.payload});return ct(o,t,n,"issue:edit:title:result",m)}if(l==="issue:tag:add"){let m=await iu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:tag:add:result",m)}if(l==="issue:tag:remove"){let m=await au({repoRoot:t,...c.payload});return ct(o,t,n,"issue:tag:remove:result",m)}if(l==="contributor:remove"){let m=await lu({repoRoot:t,...c.payload});return ct(o,t,n,"contributor:remove:result",m)}if(l==="contributors:get")return ae(o,{type:"contributors",payload:await uu({repoRoot:t,...c.payload})});if(l==="issue:assignee:add"){let m=await cu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:assignee:add:result",m)}if(l==="issue:assignee:remove"){let m=await mu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:assignee:remove:result",m)}if(l==="issues:list")return ae(o,{type:"issues",payload:await Zl({repoRoot:t})});if(l==="issues:create"){let m=await eu({...c.payload,repoRoot:t});return ae(o,{type:"issues:create:result",payload:m}),d(m)?Ot({type:"failed",payload:m.message}):(Ot({type:"issue:created",payload:m.value}),n(),rs(o,t))}if(l==="issues:move"){if(!c.payload.position)return ae(o,{type:"error",message:"Missing move position"});let m=await ru({...c.payload,repoRoot:t});return ct(o,t,n,"issues:move:result",m)}if(l==="issue:close"){if(!c.payload.issueId)return ae(o,{type:"error",message:"Missing issueId"});let m=await tu({repoRoot:t,issueId:c.payload.issueId});return ct(o,t,n,"issue:close:result",m)}if(l==="issue:reopen"){if(!c.payload.issueId)return ae(o,{type:"error",message:"Missing issueId"});let m=await nu({repoRoot:t,issueId:c.payload.issueId});return ct(o,t,n,"issue:reopen:result",m)}return ae(o,{type:"error",message:"Unknown message type"})};try{let c=JSON.parse(s.toString());return yu.has(c.type)?await tn(async()=>at().mode!=="live"?ae(o,{type:"failed",payload:"Read-only while viewing history"}):i(c)):await i(c)}catch(c){return ae(o,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var iy=Sn.dirname(sy(import.meta.url)),ay=process.env.IS_LOCAL==="true"?Sn.resolve(process.cwd(),"dist/gui"):Sn.join(iy,"gui"),os,dy=async()=>(os===void 0&&(os=await import("node:sea").catch(()=>null)),os?.isSea()?os:null),fe=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},cy=e=>fe(e,409,{isError:!0,message:"Read-only while viewing history"}),ss=(e,t)=>tn(async()=>at().mode!=="live"?cy(e):t()),bu=async(e,t=1024*1024)=>new Promise((n,r)=>{let o="",s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),ly=2*1024*1024,uy={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},my=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",Iu=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=Sn.resolve(ay),o=Sn.resolve(r,n),s=Sn.relative(r,o);if(s.startsWith("..")||Sn.isAbsolute(s))return fe(t,403,{isError:!0,message:"Forbidden"});let i=await dy();try{let c=i?Buffer.from(i.getAsset(`gui/${s}`)):await Eu(o);return t.writeHead(200,{"content-type":my(o)}),t.end(c)}catch{return fe(t,404,{isError:!0,message:`Not found: ${n}`})}},py=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=l=>{if(e.off("listening",c),l.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(l)},c=()=>{e.off("error",i);let l=e.address();if(!l||typeof l=="string"){r(new Error("Unable to resolve address"));return}n(l.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Su=async e=>{let t=oy.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return fe(s,200,await dt({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await bu(o);if(!c.issueId||!c.body?.trim())return fe(s,400,{isError:!0,message:"Missing issueId or body"});let l=c.issueId,m=c.body;return await ss(s,async()=>{let p=await ts({repoRoot:e.repoRoot,issueId:l,body:m});return d(p)?fe(s,400,{isError:!0,message:p.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await bu(o,ly);if(!c.issueId||!c.dataBase64)return fe(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let l=c.issueId,m=c.dataBase64,p=c.name??"";return await ss(s,async()=>{let f=await pu({repoRoot:e.repoRoot,issueId:l,name:p,dataBase64:m});return d(f)?fe(s,400,{isError:!0,message:f.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));return c?ss(s,async()=>{let l=await fu({repoRoot:e.repoRoot,attachmentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing attachment id"})}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),l=await gu({repoRoot:e.repoRoot,fileName:c});if(d(l))return fe(s,404,{isError:!0,message:l.message});try{let m=await Eu(l.value.filePath);return s.writeHead(200,{"content-type":uy[l.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return fe(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));return c?ss(s,async()=>{let l=await ns({repoRoot:e.repoRoot,commentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing comment id"})}return i.pathname.startsWith("/board/")?Iu("/",s):Iu(i.pathname,s)});try{await py(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=vu({repoRoot:e.repoRoot});xu(t,e.repoRoot,{onStateChanged:()=>n.queueSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Cu=async e=>{let t=Ut();Q(t)&&Me(t.value);let n=await Su({...e,boardId:""});if(d(n))return n;let{url:r}=n.value;return console.log(`Epiq GUI running at ${fy.cyan(r)}`),La(r),u("Started GUI",{url:r})};import{Box as an}from"ink";import de from"react";import{Box as ji,Text as Tr}from"ink";import lt,{useEffect as gy,useMemo as vy}from"react";import{ulid as yy}from"ulid";var Nu=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return lt.createElement(Tr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?lt.createElement(Tr,{color:n,dimColor:o},e):lt.createElement(Tr,{color:n,dimColor:o},e.slice(0,c),lt.createElement(Tr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Ru=yy(),hy=e=>`${e}`,xy=e=>{let{pendingNavTarget:t}=Qt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(ie(b.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(b))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==b.PALETTE).map(i=>{let c=wo(i),l=zo.find(m=>m.intent===c);return{command:i,description:l?.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))},by=e=>ee.text({id:Ru,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Iy=(e,t,n)=>ee.text({id:hy(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Wi=[],Ey=e=>{Au();let t=E.createNode(by(v().rootNodeId));d(t)||!_t(t.value)||(Wi=[t.value,...e.map((n,r)=>Iy(n,r,Ru)).map(E.createNode).filter(Q).map(({value:n})=>n).filter(_t)],M.navigate({contextNode:t.value,selectedIndex:0}))},Au=()=>{let e=Wi.map(t=>t.id);Wi=[];for(let t of e)E.deleteNode(t)};function Tu({width:e,height:t}){let r=gc().value.trim().toLowerCase(),o=vy(()=>xy(r),[r]);gy(()=>(Ey(o),()=>{Au()}),[o]);let s=v().selectedIndex;return lt.createElement(ji,{flexDirection:"column",width:e,height:t-2},lt.createElement(tt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let l=c===s,m=i.isAvailable?h.accent:h.secondary2,p=i.isAvailable?"":"[unavailable] ";return lt.createElement(ji,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},lt.createElement(Tr,{color:m,dimColor:!i.isAvailable},l?"\u276F ":" ",lt.createElement(Nu,{text:Va(i.command),match:r,color:m,dimColor:!i.isAvailable})),lt.createElement(ji,{paddingLeft:2},lt.createElement(Nu,{text:p+i.description,match:r.length>=2?r:"",color:l&&i.isAvailable?h.primary:h.secondary2,dimColor:!i.isAvailable})))})))}import{Box as _y}from"ink";import ds from"react";import Mr from"chalk";import{Box as Vi,Text as wu}from"ink";import wr,{useEffect as Sy,useMemo as Cy,useState as Ny}from"react";var Mu=Mr.hex(h.secondary),Ry=Mr.inverse,Ay=Mr.inverse.hex(h.secondary2),Ty={hint:"",hints:[],overlap:0,remainder:""},Lu=({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}},wy=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ue(t);return{bg:r=>Mr.bgHex(n).black(r),bgCursor:r=>Mr.bgHex(n).inverse.black(r)}}return zs(t)},My=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Lu({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}},Pu=()=>({value:Le.value,cursorPosition:Le.cursorPosition,commandIsPending:Le.commandIsPending,autoCompletion:Le.commandMeta.autoCompletion??Ty,infoMessage:Le.commandMeta.infoMessage,validationStatus:Le.commandMeta.validity,command:Le.commandMeta.command,inputString:Le.commandMeta.inputString,modifier:Le.commandMeta.modifier}),Py=(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,ku=({width:e,mode:t})=>{let[n,r]=Ny(Pu());Sy(()=>{let S=()=>{let A=Pu();r(P=>Py(P,A)?P:A)},R=li(S);return S(),()=>{R()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:l,command:m,modifier:p,validationStatus:f}=n,g=c&&f===bt.Invalid,I=Cy(()=>{let S=Math.max(0,Math.min(s,o.length)),R=Lu({value:o,command:m}),A=My({value:o,command:m,modifier:p}),P=m?zs(m):null,_=wy({command:m,modifier:p}),w=(ge,me)=>{let Gn=R&&me>=R.start&&me<R.end,Kn=A&&me>=A.start&&me<A.end;return Gn&&P?P.fg(ge):Kn&&_?_.bg(ge):ge},W=(ge,me)=>{let Gn=R&&me>=R.start&&me<R.end,Kn=A&&me>=A.start&&me<A.end;return Gn&&P?P.fgCursor(ge):Kn&&_?_.bgCursor(ge):Ry(ge)},H=o.slice(0,S),D=o[S]??" ",$=S<o.length?o.slice(S+1):"",Ye=Array.from(H).map((ge,me)=>w(ge,me)).join(""),we=W(D,S),Xe=Array.from($).map((ge,me)=>w(ge,S+1+me)).join("");if(l.hint){let ge=l.hint[l.overlap]??D;we=Ay(ge),Xe=Mu(l.remainder.slice(1)+$)}return Mu(t===y.PALETTE?"?":":")+Ye+we+Xe},[o,s,l,m,p]);return wr.createElement(Vi,{flexDirection:"column",justifyContent:"flex-start"},wr.createElement(Vi,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},wr.createElement(Vi,null,wr.createElement(wu,null,I),i&&wr.createElement(wu,{wrap:"truncate",color:g?h.red:h.secondary2},` ${i} `))))};import{Box as Ly,Text as ky}from"ink";import Du from"react";var Dy=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Bu=({width:e,availableHints:t})=>{let n=Dy(t,e).join(" | ");return Du.createElement(Ly,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},Du.createElement(ky,{color:h.secondary2},n.length?n:"\xA0"))};import{Box as By,Text as is}from"ink";import Pr,{useEffect as Fy,useRef as jn,useState as Uy}from"react";var Oy=40,as=.3,Gi="\u2500",Fu=1,Uu=16,Ou=({width:e})=>{let{replay:t}=j(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Fu,[c,l]=Uy(0),m=jn(r);m.current=r;let p=jn(0),f=jn(0),g=jn(0),I=jn(0),S=jn(0);if(Fy(()=>{if(!n){p.current=0,g.current=0,I.current=0,S.current=0,l(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let w=setInterval(()=>{let W=Date.now(),H=m.current;if(H!==g.current){let Xe=H-g.current,ge=W-f.current;if(Xe<0)I.current=0,S.current=0;else if(Xe>0&&ge>0){let me=Xe/ge;I.current=I.current===0?me:I.current*(1-as)+me*as,S.current=S.current===0?Xe:S.current*(1-as)+Xe*as}p.current=H,f.current=W,g.current=H}let D=W-f.current,$=Math.min(S.current,I.current*D),Ye=Math.min(1,p.current+$),we=Math.round(Ye*i);l(Xe=>Xe===we?Xe:we)},Oy);return()=>clearInterval(w)},[n,i]),!t)return null;let R=w=>{let W=s>1?w/(s-1):0,H=Math.round(W*(Uu-1))/(Uu-1);return no(H)},A=Math.min(s,Math.floor(c/Fu)),P=[];for(let w=0;w<A;w++){let W=R(w),H=P[P.length-1];H&&H.color===W?H.text+=Gi:P.push({text:Gi,color:W})}let _=Gi.repeat(Math.max(0,s-A));return Pr.createElement(By,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1,columnGap:1},Pr.createElement(is,{color:h.secondary2},"\u25B6"),Pr.createElement(is,null,P.map((w,W)=>Pr.createElement(is,{key:W,color:w.color},w.text)),Pr.createElement(is,{color:h.secondary,dimColor:!0},_)))};var Lr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=j(),o=t===y.COMMAND_LINE||t===y.PALETTE;return ds.createElement(_y,null,o?ds.createElement(ku,{width:e,mode:t}):r==="replay"?ds.createElement(Ou,{width:e}):ds.createElement(Bu,{width:e,mode:t,availableHints:n}))};import{Box as nn,Text as Wn}from"ink";import _e,{useEffect as $y,useMemo as Hy}from"react";import{ulid as _u}from"ulid";var ls=_u(),jy=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Wy=e=>ee.text({id:ls,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Vy=(e,t,n)=>ee.text({id:_u(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),cs=[],$u=()=>{let e=cs.filter(n=>n.id!==ls).map(n=>n.id),t=cs.filter(n=>n.id===ls).map(n=>n.id);cs=[];for(let n of[...e,...t])E.deleteNode(n)},Gy=e=>{$u();let t=E.createNode(Wy(v().rootNodeId));if(d(t)||!_t(t.value))return logger.error("Could not attach help nodes");cs=[t.value,...e.map((n,r)=>Vy(n,r,ls)).map(E.createNode).filter(Q).map(({value:n})=>n).filter(_t)],M.navigate({contextNode:t.value,selectedIndex:0})},Hu=({width:e,height:t})=>{let n=Hy(()=>jy(),[]);$y(()=>(Gy(n),()=>{$u()}),[n]);let r=v().selectedIndex;return _e.createElement(nn,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},_e.createElement(nn,{paddingX:1,justifyContent:"center"},_e.createElement(Wn,{color:h.accent},"Help"),_e.createElement(Wn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),_e.createElement(nn,{paddingX:1,marginTop:1},_e.createElement(nn,{width:20,justifyContent:"flex-end"},_e.createElement(Wn,{color:h.secondary},"Key(s)")),_e.createElement(nn,{flexGrow:1,width:40,paddingLeft:2},_e.createElement(Wn,{color:h.secondary},"Action"))),_e.createElement(tt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return _e.createElement(nn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},_e.createElement(nn,{width:20,justifyContent:"flex-end"},_e.createElement(Wn,{color:h.accent},o)),_e.createElement(nn,{flexGrow:1,width:40,paddingLeft:2},_e.createElement(Wn,{color:c?h.primary:h.secondary2},s)))})))};import Ky from"chalk";import{Box as us,Text as Bt}from"ink";import qe from"react";var ju=({width:e,height:t})=>qe.createElement(us,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},qe.createElement(Bt,{color:h.accent,bold:!0},"Initialize project"),qe.createElement(Bt,null,`This folder is not an ${Ky.hex(h.accent)("epiq")} project yet.`),qe.createElement(Bt,{color:h.primary},"To start tracking issues here, we need to initialize a new",qe.createElement(Bt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),qe.createElement(us,{marginTop:1,flexDirection:"column"},qe.createElement(us,null,qe.createElement(Bt,{color:h.accent}," "),qe.createElement(Bt,{color:h.primary},"Type "),qe.createElement(Bt,{backgroundColor:h.secondary}," :init "))),qe.createElement(us,{marginTop:1},qe.createElement(Bt,{color:h.secondary2},"This will create, commit and push "),qe.createElement(Bt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as ms,Text as Ct}from"ink";import Te from"react";var zy=({isDone:e,command:t,value:n})=>Te.createElement(ms,null,Te.createElement(Ct,{color:h.accent,dimColor:e},e?" \u2714 ":" "),Te.createElement(Ct,{dimColor:e},"Type "),Te.createElement(Ct,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&Te.createElement(Te.Fragment,null,Te.createElement(Ct,{dimColor:e}," "),Te.createElement(Ct,{color:h.secondary,dimColor:e},"<"+n+">"))),qy=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Ki({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Gt(),l=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=l.findIndex(f=>!f.done),p=m===-1?void 0:l[m];return Te.createElement(ms,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Te.createElement(Ct,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),Te.createElement(Ct,null,"Let's get you started - it's a breeze."),Te.createElement(Ct,{color:h.secondary2},"Remember - you can always search available commands by typing:",Te.createElement(Ct,{color:h.accent}," ? ")),p&&Te.createElement(Ct,{color:h.secondary2},p.message),Te.createElement(ms,{flexDirection:"column"},l.map((f,g)=>m===-1||g<=m?Te.createElement(ms,{key:f.key,marginBottom:1},Te.createElement(zy,{isDone:f.done,command:f.command,value:f.done?qy(f.value):void 0})):null)))}import ys from"chalk";import{Box as Dr,Text as Vn}from"ink";import xe from"react";import{Box as ps,Text as Wu}from"ink";import rn from"react";import Yy from"chalk";var Xy=e=>(E.getTag(e)?.name??"").length+3,Jy=e=>{let t=E.getContributor(e);return(t?Yt(e,t.name):"").length+3},Vu=({width:e})=>{let{viewMode:t}=K(),n=j(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],l=At(c?.id??o.id,"TICKET"),m=Q(l)?l.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],g=m?.parentNodeId?!Vs(o.id,m.parentNodeId)&&t==="dense":!1,I=r.map((H,D)=>{let $=D===r.length-1,Ye=Y(H.id),we=$?Ye?.[s]?.title:void 0;return`${D?" / ":""}${H.title??""}${we?` \u25B8 ${we}`:""}`}).join(""),S=m?E.getCommentsByIssue(m.id):[],R=S.length?String(S.length).length+11:0,A=g?p.reduce((H,D)=>H+Xy(D),0)+f.reduce((H,D)=>H+Jy(D),0)+R:0,P=c?.id!=null&&!(t==="wide"&&T(c)),_=Math.max(0,e-A),w=I.substring(0,_)+(P?Yy.hex(h.secondary2).dim(` ${He(c.id)}`):""),W=g?[...p.map(H=>rn.createElement(ps,{key:`tag-${H}`,paddingLeft:1},rn.createElement(Un,{id:H}))),...f.map(H=>rn.createElement(ps,{key:`assignee-${H}`,paddingLeft:1},rn.createElement(Xt,{id:H}))),S.length?rn.createElement(ps,{key:"comments",paddingLeft:1},rn.createElement(Wu,{color:h.accent},"[",S.length," comment",S.length===1?"":"s","]")):null]:[];return rn.createElement(ps,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},rn.createElement(Wu,{color:h.secondary2},w),W)};import{Box as Qy,Text as Gu}from"ink";import fs from"react";var Zy=({filters:e})=>fs.createElement(Qy,{columnGap:1},fs.createElement(Gu,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>fs.createElement(Gu,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ku=fs.memo(Zy);import{Box as eh,Text as gs}from"ink";import kr from"react";function zu(){let{eventLog:e,unappliedEvents:t}=j(),n=e.at(-1)?.id,r=Co(n??""),o=Q(r)?io(r.value):"INVALID DATE";return kr.createElement(eh,{paddingLeft:1},kr.createElement(gs,{backgroundColor:h.accent,color:h.secondary}," Readonly "),kr.createElement(gs,{color:h.accent}," "+t.length+" edits ago at "+o+"."),kr.createElement(gs,{color:h.accent}," Resume with "),kr.createElement(gs,{backgroundColor:h.accent,color:h.secondary}," ",":peek now"," "))}import{Box as th,Text as zi}from"ink";import vs from"react";function qu(){let{replay:e}=j();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return vs.createElement(th,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},vs.createElement(zi,{backgroundColor:h.accent,color:h.secondary}," \u25B6 REPLAY "),vs.createElement(zi,{color:h.secondary2},io(new Date(r))),vs.createElement(zi,{color:h.accent},`${t}/${n} edits`))}import qi from"chalk";import{Box as nh,Text as Yu}from"ink";import Yi,{useEffect as rh,useState as oh}from"react";var sh=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],ih=150,Xu=12,ah=.36,Ju=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)}},dh=({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)}`},ch=(e,t,n)=>{let r=Ju(e),o=Ju(t);return dh({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},lh=(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 ch(s,i,o)};function Qu({syncStatus:e,autoSync:t}){let[n,r]=oh(0);rh(()=>{if(e.status!=="syncing"){r(0);return}let c=0,l=setInterval(()=>{c+=1;let m=(Math.sin(c*ah)+1)/2,p=Math.round(m*(Xu-1));r(f=>f===p?f:p)},ih);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:lh(sh,n/(Xu-1))??""}[e.status];return Yi.createElement(nh,null,Yi.createElement(Yu,null,qi.hex(h.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Yi.createElement(Yu,null,qi.hex(i)("\u25CF")+qi.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import rm from"chalk";import{Text as om}from"ink";import sm,{useEffect as fh,useState as gh}from"react";var on="1.4.2";import Xi from"chalk";var uh="https://registry.npmjs.org/epiq/latest",Ji=null,Zu=0,mh=1e3*60*60*24,em=e=>e.replace(/^v/,""),ph=(e,t)=>{let n=em(e).split(".").map(Number),r=em(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},tm=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Ji&&Date.now()-Zu<mh)return Ji;try{let t=await fetch(uh);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?ph(r,e)>0:!1};return Ji=o,Zu=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},nm=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Xi.hex(h.accent).dim(s):Xi.hex(h.secondary).dim(s)).join(Xi.hex(h.secondary2).dim("."))};function im(){let[e,t]=gh({current:on,latest:null,updateAvailable:!1});return fh(()=>{let n=!0;return tm(on).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?sm.createElement(om,{dimColor:!0,color:h.secondary2},on+" "):sm.createElement(om,null,rm.hex(h.secondary2).dim(on),rm.hex(h.accent).dim(" \u2197 "),nm(on,e.latest))}function Br({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=j(),{userName:i,preferredEditor:c,autoSync:l}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?un(s.currentLabel,Math.max(0,p)):"";return xe.createElement(Dr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?xe.createElement(Dr,{paddingLeft:1},xe.createElement(Vn,{color:h.secondary2},g)):f?xe.createElement(Vn,null," "):o===y.PALETTE?xe.createElement(Dr,null,xe.createElement(Vn,{color:h.accent},"Command Palette"),xe.createElement(Vn,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):xe.createElement(Dr,{paddingLeft:1},e.length>0?xe.createElement(Ku,{filters:e}):xe.createElement(Vu,{width:p})),n==="live"?xe.createElement(Dr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},xe.createElement(Qu,{autoSync:!!l,syncStatus:r}),xe.createElement(Vn,null,ys.hex(h.secondary2).dim("Mode: ")+ys.hex(h.secondary2).dim(o.padEnd(8," "))," "),xe.createElement(am,{icon:"@",value:i}),xe.createElement(am,{icon:"\u276F",value:c}),xe.createElement(im,null)):"",n==="peek"?xe.createElement(zu,null):"",n==="replay"?xe.createElement(qu,null):"")}function am({icon:e,value:t}){return xe.createElement(Vn,null,ys.dim(e)+ys.hex(h.accent)(` ${t??"-"} `))}import{Box as vh,Text as yh}from"ink";import Fr from"react";import{Box as hs,Text as Qi}from"ink";import sn from"react";function Zi(){let e=j(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?z(t?.id):[];return sn.createElement(hs,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:s},sn.createElement(hs,{padding:1,paddingTop:0,paddingBottom:0},sn.createElement(Qi,null,"Select a board:")),sn.createElement(hs,{padding:1,flexDirection:"column"},i.map((c,l)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===l,f=z(c.id).flatMap(({id:g})=>Y(g)).length;return sn.createElement(hs,{key:c.id??l},sn.createElement(Qi,{color:m?h.accent:h.secondary2},sn.createElement(ke,{isSelected:m})),sn.createElement(Qi,{color:m?h.accent:h.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var hh=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=j(),l=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Fr.createElement(vh,{flexDirection:"row"},e.context==="WORKSPACE"?Fr.createElement(Zi,null):l?Fr.createElement(Uo,{height:f,width:i,swimlanes:(c[l.id]??[]).filter(g=>g!==void 0&&$t(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Fr.createElement(yh,null))},dm=Fr.memo(hh);import{useEffect as xh}from"react";var bh=e=>{xh(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:l}=v();l==="default"&&!c&&ho(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},cm=({autoSync:e})=>(bh(e),null);function ea({width:e,height:t}){let n=j(),{autoSync:r,viewMode:o}=Pa(),s=n.filters;if(n.mode===y.HELP)return de.createElement(an,{flexDirection:"column"},de.createElement(Hu,{width:e,height:t}));if(n.mode===y.PALETTE)return de.createElement(an,{flexDirection:"column"},de.createElement(Br,{filters:s}),de.createElement(Tu,{width:e,height:t-2}),de.createElement(Lr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Gt(),c=!i,l=i&&!n.hasProjectDefinition;if(c)return de.createElement(an,{flexDirection:"column"},de.createElement(an,{flexDirection:"column"},de.createElement(Br,{hideBreadCrumb:!0,filters:s}),de.createElement(Ki,{height:t,width:e})),de.createElement(Lr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(l)return de.createElement(an,{flexDirection:"column"},de.createElement(an,{flexDirection:"column"},de.createElement(Br,{hideBreadCrumb:!0,filters:s}),de.createElement(ju,{height:t,width:e})),de.createElement(Lr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Oe(n.breadCrumb??[],"BOARD");if(Q(m)){let p=m.value.id,f=z(p).length,g=3,I=Math.floor(e/g),S=Math.floor(e/Math.max(f,1));e=Math.min(S,I)*Math.max(f,g)}return de.createElement(an,{flexDirection:"column"},de.createElement(cm,{autoSync:r}),de.createElement(an,{flexDirection:"column"},de.createElement(Br,{filters:s}),de.createElement(dm,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),de.createElement(Lr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Ih from"readline";var xs,bs,Nt,Eh=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.Yank,x.InitCommandLine,x.InitCommandPalette,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Sh=new Set([x.NavPreviousItem,x.NavNextItem,x.NavToPreviousContainer,x.NavToNextContainer,x.Confirm,x.Exit,x.InitCommandPalette,x.InitMove,x.MoveNextItem,x.MovePreviousItem,x.MoveToNextContainer,x.MoveToPreviousContainer,x.Delete,x.AddItem,x.EditTitle,x.EditDescription,x.ConfirmMove,x.Edit,x.ViewHelp,x.Yank]),lm=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=yc(e,n);if(!s||r&&!Eh.has(s)||o==="replay"&&n===y.DEFAULT&&Sh.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},Ch=()=>async function(t,n){n.name!=="escape"&&(Nt&&(clearTimeout(Nt),Nt=void 0),await lm(n))},Nh=()=>async function(t){if(t.length===1&&t[0]===27){Nt&&clearTimeout(Nt),Nt=setTimeout(()=>{lm({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Nt=void 0},25);return}Nt&&(clearTimeout(Nt),Nt=void 0)};function um(){xs&&process.stdin.removeListener("keypress",xs),bs&&process.stdin.removeListener("data",bs),xs=Ch(),bs=Nh(),Ih.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",bs),process.stdin.on("keypress",xs)}async function mm(){try{let e=Ut();Q(e)&&Me(e.value);let t=$e(process.cwd()),n=[];if(Q(t)){let s=Re({repoRoot:t.value});if(d(s))return gn(3,s.message);let i=Cn(),c=await ln({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return gn(3,c.message);let l=await F({cwd:s.value,args:["pull","--ff-only"]});d(l)&&logger.info(3,l.message);let m=je(s.value);if(d(m))return gn(3,m.message);n=m.value}let r=fn(n);if(d(r))return gn(4,r.message);C({hasProjectDefinition:Q(t),hasInitializingEvents:!!n.length});let o=ta();return d(o)?gn(6,o.message):(um(),u("Booted Epiq",void 0))}catch(e){return gn(0,go(e))}}Wc();var wh=`${dn.bold("Epiq CLI")}
|
|
61
61
|
|
|
62
|
-
${
|
|
63
|
-
${
|
|
62
|
+
${dn.dim("Boot in directory:")}
|
|
63
|
+
${dn.cyan("$ epiq")}
|
|
64
64
|
|
|
65
|
-
${
|
|
66
|
-
${
|
|
67
|
-
`,
|
|
68
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
65
|
+
${dn.dim("Launch GUI:")}
|
|
66
|
+
${dn.cyan("$ epiq gui")}
|
|
67
|
+
`,Mh=Ah(wh,{importMeta:import.meta,version:on,flags:{init:{type:"boolean",default:!1}}}),Is=Mh.input[0];Is&&Is!=="gui"&&(console.error(dn.red(`Unknown command: ${Is}`)),process.exit(1));var pm=process.stdout.columns||120,fm=process.stdout.rows||20,Es=null,Ph=e=>{try{return Es?(Es.rerender(e),u("Rerendered app",void 0)):(Es=Rh(e),u("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${go(t)}`)}},ta=()=>Ph(Th.createElement(ea,{width:pm,height:fm}));process.stdout.on("resize",()=>{if(pm=process.stdout.columns||120,fm=process.stdout.rows||20,!Es)return;let e=ta();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(Is==="gui"){let e=await Cu({repoRoot:process.cwd()});d(e)&&(console.error(dn.red(`Failed to start Epiq GUI:
|
|
68
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await mm();d(e)&&(logger.info(e.message),console.error(dn.red(`Failed to boot Epiq:
|
|
69
69
|
${e.message}`)),process.exitCode=1)}export{ta as renderApp};
|